blob: 8285925ca48205b3a993b5bc8b141842480d82cd [file]
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
RuntimeHostProcessTerminationRequiredError,
type RuntimeHostKernel,
} from './host-kernel.js';
export interface RuntimeHostProcessLifecycleOptions {
closeOnDisconnect?: boolean;
onReady?: () => void;
}
export type RuntimeHostProcessLifecycleEnd = 'host_closed' | 'termination_requested';
export async function runRuntimeHostProcessLifecycle(
host: Pick<RuntimeHostKernel, 'close' | 'closed'> &
Partial<Pick<RuntimeHostKernel, 'shutdownReason'>>,
options: RuntimeHostProcessLifecycleOptions = {},
): Promise<RuntimeHostProcessLifecycleEnd> {
let closing = false;
const close = () => {
if (closing) return;
closing = true;
void host.close();
};
process.once('SIGINT', close);
process.once('SIGTERM', close);
if (options.closeOnDisconnect) process.once('disconnect', close);
try {
options.onReady?.();
await host.closed;
return closing ? 'termination_requested' : 'host_closed';
} catch (error) {
if (error instanceof RuntimeHostProcessTerminationRequiredError) {
process.exit(host.shutdownReason === 'retirement' ? 0 : 1);
}
throw error;
} finally {
process.off('SIGINT', close);
process.off('SIGTERM', close);
if (options.closeOnDisconnect) process.off('disconnect', close);
}
}