[Service] Move service files to service/ folder
[platform/framework/web/wrtjs.git] / wrt_app / service / service_manager.ts
1 import { Worker, isMainThread } from 'worker_threads';
2 import { wrt } from '../browser/wrt';
3
4 interface WorkerMap {
5   [id: string]: any;
6 }
7 let workers: WorkerMap = {};
8 let runner: any;
9
10 Object.defineProperty(global, 'serviceType', {
11   value: wrt.getServiceModel(),
12   writable: false
13 });
14
15 function createWorker(id: string, startService: string, filename: string) {
16   if (workers[id]) {
17     workers[id].postMessage({ type: 'wake' });
18     return;
19   }
20
21   workers[id] = new Worker(startService, {
22     workerData: {
23       id,
24       filename
25     }
26   });
27   workers[id].on('message', (message: string) => {
28     if (message === 'will-terminate') {
29       workers[id].terminate();
30     }
31   });
32   workers[id].on('exit', (code: number) => {
33     delete workers[id];
34     let runningServices = Object.keys(workers).length;
35     console.log(`exit code(${code}), remain services(${runningServices})`);
36   });
37 }
38
39 function terminateWorker(id: string, delay: number) {
40   if (!workers[id]) {
41     console.log(`This worker is already terminated. ${id}`);
42     return;
43   }
44   console.log(`${id} will shutdown after ${delay}ms`);
45   workers[id].postMessage({ type: 'stop', delay });
46 }
47
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);
55   }
56   let startService = `${__dirname}/service_runner.js`;
57   createWorker(id, startService, filename);
58 }
59
60 export function stopService(id: string) {
61   console.log(`stopService - ${id}`);
62   terminateWorker(id, 500);
63 }
64
65 export function handleBuiltinService(serviceId: string, serviceName: string) {
66   if (!serviceName) {
67     return;
68   }
69   let need_stop = (serviceName.substr(0, 5) === 'stop_');
70   if (need_stop) {
71     console.log(`${serviceName} will be terminated.`);
72     workers[serviceId].terminate();
73   } else {
74     console.log(`Builtin service is ${serviceName}`);
75     let startService = `${__dirname}/../service/builtins/${serviceName}.js`;
76     createWorker(serviceId, startService, '');
77   }
78 }