File size: 10,086 Bytes
b39afbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/**
 * Copyright (c) 2023 MERCENARIES.AI PTE. LTD.
 * All rights reserved.
 */

const { fork, spawn, exec, execSync } = require('node:child_process');
const os = require('node:os');
const path = require('node:path');
const { assert } = require('console');
const { ensure } = require('./pocketdbutils.js');
const { sleep, checkGitForUpdates, omniCwd } = require('./utils.js');
const { ensureDirSync } = require('fs-extra');
const { update_build } = require('./updater.js');
const readline = require('node:readline');
const fs = require('node:fs');

const { copyFileSync, existsSync } = require('node:fs');
let args = process.argv.slice(2);

let server_entry = null;

const packagejson = JSON.parse(fs.readFileSync(path.join(omniCwd(), 'package.json'), { encoding: 'utf-8' }));
const { argv0 } = require('node:process');
const depjson = packagejson.dependenciesBin;
const platform = os.platform();
const arch = os.arch();

const IPC_CMD = 'cmd';
const IPC_CMD_restart = 'restart';
// move out of /setup/launcher.js where the mercs.yaml file exists
const project_abs_root = omniCwd();
const pocketbaseInstallPath = path.join(project_abs_root, depjson.root_dir, 'pocketbase');

let server_process = null;
let pretty_process_pid = [];
let child_processes = new Map();

function start_server(implicit_args) {
  assert(server_process === null);
  assert(server_entry !== null);

  // IMPORTANT: omnitool need to run from /mercs as root and launcher in setup/launcher.js
  const server_wd = path.join(project_abs_root, 'packages/omni-server');

  // derive the server entry file using absolute paths from launcher.js
  // this ensures we can also resolve whether clicking directy on .exe or launching from terminal
  const entrypath = path.join(server_wd, server_entry);
  console.log(`Server entry point resolved to ${entrypath}`);

  server_process = fork(entrypath, implicit_args.concat(args), { cwd: server_wd, execArgv: ['--inspect'] });
  pretty_process_pid.push(`|--OMNITOOL - Server PID ${server_process.pid}`);
  child_processes.set(server_process.pid, server_process);

  server_process.on('exit', (code) => {
    console.log(`Server exited with code ${code}`);
    process.exit(1);
  });
  server_process.on('error', (err) => {
    console.error(err);
    process.abort();
  });
  server_process.on('message', (message) => {
    switch (message[IPC_CMD]) {
      case IPC_CMD_restart:
        console.log('Server Restarting...');
        server_process.removeAllListeners('exit');
        server_process.kill();
        child_processes.delete(server_process.pid);
        server_process = null;
        // no need to re-open browser on restarts
        implicit_args = implicit_args.filter((e) => e !== '--openBrowser');
        args = args.filter((e) => e !== '--openBrowser');
        start_server(implicit_args);
        break;
    }
  });
}

function verifyConfig() {
  // check if dep version is defined
  if (packagejson.engines['pocketbase'] === undefined) {
    console.error(`Missing version definition for pocketbase DB in package.json engines`);
    return false;
  }
  // check if dep is defined
  if (depjson['pocketbase'] === undefined) {
    console.error(`Unable to find installer definition for pocketbase DB`);
    return false;
  }
  // check if there's an installer for the platform
  try {
    let zippath = depjson['pocketbase'].zipfile[platform][arch];
    if (zippath === undefined) {
      console.error(`Unable to find installer download URL for pocketbase DB`);
      return false;
    }
  } catch (e) {
    console.error(`Unable to find pocketbase installer definition for [${platform}][${arch}]`);
    return false;
  }
  return true;
}

function start_pocketbase() {
  const pocketDBProcess = spawn(path.join(pocketbaseInstallPath, 'pocketbase'), ['serve'], { stdio: 'inherit' });
  setup_listeners(pocketDBProcess, 'pocketbase');
  pretty_process_pid.push(`|--OMNITOOL - PocketBaseDB PID ${pocketDBProcess.pid}`);
  child_processes.set(pocketDBProcess.pid, pocketDBProcess);
}

function start_vite() {
  const viteProcess = exec('yarn frontend');
  viteProcess.stderr.pipe(process.stderr);
  viteProcess.stdout.pipe(process.stdout);
  setup_listeners(viteProcess, 'vite debugger');
  pretty_process_pid.push(`|--OMNITOOL - Vite PID ${viteProcess.pid}`);
  child_processes.set(viteProcess.pid, viteProcess);
}

async function user_confirmation(prompt) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  return new Promise((resolve) =>
    rl.question(prompt, (ans) => {
      rl.close();
      resolve(ans);
    })
  );
}

function setup_listeners(proc, name) {
  proc.on('uncaughtException', (err) => {
    console.err(err);
    user_confirmation('Oops something went wrong. Press any key to exit...').then(() => process.exit(1));
  });
  // terminate parent for whatever reason
  proc.on('exit', (code) => {
    console.log(`${name} ${proc.pid} exited with code ${code}`);
    process.exit(1);
  });
}

async function check_for_updates() {
  console.log('Checking for updates...');
  const result = await checkGitForUpdates();
  if (result.hasUpdates) {
    const input = await user_confirmation(
      `You are currently on ${result.local}.\nThere's a new version ${result.remote} available. Would you like to pull and update with git? [y/n]:`
    );
    if (input === 'y') {
      try {
        console.log('\nCalling git pull...');
        execSync('git pull', { cwd: omniCwd(), stdio: 'inherit' });
        console.log('Calling yarn install...');
        execSync('yarn', { cwd: omniCwd(), stdio: 'inherit' });
        console.log('\nUpdate complete. Please re-run the application with: yarn start');
        process.exit(0);  
      }
      catch(e) {
        console.error(e);
        console.warn(`Update failed. Please try running [yarn start] again.`);
        process.exit(1);
      }
    } else {
      console.log(`Continuing with current build ${result.local}...`);
    }
  }
  else{
    console.log(`You are currently on the latest version available ${result.local}.`);
  }
}

async function run_development(server_args) {
  const pocketready = await ensure(pocketbaseInstallPath);
  if (!pocketready) {
    console.error('Fatal error setting up PocketBase DB');
    process.exit(1);
  }
  start_vite();
  await sleep(1000);
  start_pocketbase();
  await sleep(1000);
  start_server(server_args);
  log_processes();
}

async function run_production(server_args) {
  const pocketready = await ensure(pocketbaseInstallPath);
  if (!pocketready) {
    console.error('Fatal error setting up PocketBase DB');
    process.exit(1);
  }
  start_pocketbase();
  await sleep(1000);
  start_server(server_args);
  log_processes();
}

async function run_runtime_executable() {
  const didupdate = await update_build();
  if (didupdate) {
    console.log('Omnitool has been patched with an update and needed to close.');
    console.log('Please re-run the application!');
    console.log('Press any key to exit...');

    process.stdin.setRawMode(true);
    process.stdin.resume();
    process.stdin.on('data', process.exit.bind(process, 0));
  } else {
    await run_production(['-l', '127.0.0.1', '--openBrowser']);
  }
}

function log_processes() {
  pretty_process_pid.forEach((e) => console.log(e));
}

async function ensure_wasm() {
  const { NodeProcessEnv } = await import('omni-shared');
  // --- Copy wasm models
  let wasmDir = null;
  switch (process.env.NODE_ENV) {
    case NodeProcessEnv.development:
      wasmDir = path.join(omniCwd(), 'packages/omni-server', 'config.local', 'wasm');
      break;
    case NodeProcessEnv.production:
      wasmDir = path.join(omniCwd(), 'packages/omni-server', 'dist');
      break;
  }
  assert(wasmDir !== null);
  ensureDirSync(wasmDir);
  if (!existsSync(path.join(wasmDir, 'tfjs-backend-wasm.wasm'))) {
    console.log('Installing WASM modules... nsfwjs/threaded/wasm');
    copyFileSync(
      path.join(omniCwd(), 'node_modules', '@tensorflow', 'tfjs-backend-wasm', 'dist', 'tfjs-backend-wasm.wasm'),
      path.join(wasmDir, 'tfjs-backend-wasm.wasm')
    );
  }
  if (!existsSync(path.join(wasmDir, 'tfjs-backend-wasm-simd.wasm'))) {
    console.log('Installing WASM modules... nsfwjs/threaded/simd ');
    copyFileSync(
      path.join(omniCwd(), 'node_modules', '@tensorflow', 'tfjs-backend-wasm', 'dist', 'tfjs-backend-wasm-simd.wasm'),
      path.join(wasmDir, 'tfjs-backend-wasm-simd.wasm')
    );
  }
}

if (!verifyConfig()) {
  process.exit(1);
}

process.on('exit', (code) => {
  child_processes.forEach((p) => p.kill());
  child_processes.clear();
});

process.on('uncaughtException', (err) => {
  console.error(err);
  user_confirmation(
    `Oops something went terribly wrong: \n\t ${err}\n\nPlease let us know!\n\nPress any key to exit...`
  ).then(() => process.exit(1));
});

pretty_process_pid.push(`OMNITOOL - Launcher PID ${process.pid}`);

// launched from omnitool executable - always production + updates
async function run() {
  const { NodeProcessEnv } = await import('omni-shared');
  const omnitool_exec = 'omnitool';
  if (argv0.includes(omnitool_exec)) {
    console.log('Runtime mode detected..launching');
    server_entry = 'dist/server.cjs';
    process.env.NODE_ENV ??= 'production';
    ensure_wasm();
    run_runtime_executable();
  } else {
    // detect help and just show that then exit
    if (args.includes('--help') || args.includes('-h')) {
      execSync('node dist/run.js --help', { cwd: 'packages/omni-server', stdio: 'inherit' });
      process.exit(0);
    }
    console.log(`OMNITOOL Environment ${process.env.NODE_ENV}`);
    switch (process.env.NODE_ENV) {
      case NodeProcessEnv.development:
        server_entry = `dist/run.js`;
        ensure_wasm();
        run_development([]);
        break;
      case NodeProcessEnv.production:
        server_entry = 'dist/run.js';
        await check_for_updates();
        ensure_wasm();
        run_production([]);
        break;
      default:
        throw new Error('Unhandled environment - ' + process.env.NODE_ENV);
    }
  }
}

run();