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) {
17 workers[id].postMessage({ type: 'wake' });
21 workers[id] = new Worker(startService, {
27 workers[id].on('message', (message: string) => {
28 if (message === 'will-terminate') {
29 workers[id].terminate();
32 workers[id].on('exit', (code: number) => {
34 let runningServices = Object.keys(workers).length;
35 console.log(`exit code(${code}), remain services(${runningServices})`);
39 function terminateWorker(id: string, delay: number) {
41 console.log(`This worker is already terminated. ${id}`);
44 console.log(`${id} will shutdown after ${delay}ms`);
45 workers[id].postMessage({ type: 'stop', delay });
48 export function startService(id: string, filename: string) {
49 console.log(`startService - ${id}`);
50 if (global['serviceType'] === 'STANDALONE') {
51 let ids = id.split(':');
52 let serviceId = ids[0];
53 let packageId = serviceId.split('.')[0];
54 wrt.security?.dropThreadPrivilege(packageId, serviceId);
56 let startService = `${__dirname}/service_runner.js`;
57 createWorker(id, startService, filename);
60 export function stopService(id: string) {
61 console.log(`stopService - ${id}`);
62 terminateWorker(id, 500);
65 export function handleBuiltinService(serviceId: string, serviceName: string) {
69 let need_stop = (serviceName.substr(0, 5) === 'stop_');
71 console.log(`${serviceName} will be terminated.`);
72 workers[serviceId].terminate();
74 console.log(`Builtin service is ${serviceName}`);
75 let startService = `${__dirname}/../service/builtins/${serviceName}.js`;
76 createWorker(serviceId, startService, '');