1 import { Worker, isMainThread } from 'worker_threads';
2 import { wrt } from '../browser/wrt';
7 let workers: WorkerMap = {};
10 Object.defineProperty(global, 'serviceType', {
11 value: wrt.getServiceModel(),
15 function createWorker(id: string, startService: string, filename: string) {
19 workers[id] = new Worker(startService, {
25 workers[id].on('message', (message: string) => {
26 if (message === 'will-terminate') {
27 workers[id].terminate();
30 workers[id].on('exit', (code: number) => {
32 let runningServices = Object.keys(workers).length;
33 console.log(`exit code(${code}), remain services(${runningServices})`);
37 function terminateWorker(id: string, delay: number) {
39 console.log(`This worker is already terminated. ${id}`);
42 console.log(`${id} will shutdown after ${delay}ms`);
43 workers[id].postMessage({ type: 'stop', delay });
46 export function startService(id: string, filename: string) {
47 console.log(`startService - ${id}`);
48 if (global['serviceType'] === 'STANDALONE') {
49 let ids = id.split(':');
50 let serviceId = ids[0];
51 let packageId = serviceId.split('.')[0];
52 wrt.security?.dropThreadPrivilege(packageId, serviceId);
54 let startService = `${__dirname}/service_runner.js`;
55 createWorker(id, startService, filename);
58 export function stopService(id: string) {
59 console.log(`stopService - ${id}`);
60 terminateWorker(id, 500);
63 export function handleBuiltinService(serviceId: string, serviceName: string) {
67 let need_stop = (serviceName.substr(0, 5) === 'stop_');
69 console.log(`${serviceName} will be terminated.`);
70 workers[serviceId].terminate();
72 console.log(`Builtin service is ${serviceName}`);
73 let startService = `${__dirname}/../service/builtins/${serviceName}.js`;
74 createWorker(serviceId, startService, '');