odant-work 1.0.102 → 1.0.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat-task.js +17 -6
- package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +24 -2
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +31 -8
- package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +32 -0
- package/$server/$folder/lib/consultant/consultant.js +80 -3
- package/$server/$folder/lib/tree/tree.js +2 -2
- package/autostart.bat +28 -0
- package/autostart.sh +17 -0
- package/package.json +1 -1
- package/run.mjs +19 -0
- package/scripts/autostart.mjs +281 -0
- package/scripts/watchdog.mjs +496 -0
- package/sources/client.js +122 -2
- package/sources/host/auth-methods.js +2 -0
- package/sources/host/auto-updater.js +23 -1
- package/sources/host/http-server.js +5 -3
- package/sources/host/push.js +43 -14
- package/sources/host/websocket.js +52 -3
- package/sources/modules/agent/index.js +26 -14
- package/sources/modules/agent/session.js +38 -8
- package/sources/modules/user-profile/user-profile.js +129 -0
- package/sources/server/access/gateway.js +2 -1
- package/sources/server/class/feed.js +6 -0
- package/sources/server/server.js +50 -1
- package/sources/server/user.js +45 -0
- package/start.bat +25 -0
- package/start.sh +27 -0
- package/stop.bat +25 -0
- package/stop.sh +16 -0
- package/sw.js +3 -11
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Фоновый супервизор (watchdog) процесса ODANT-WORK:
|
|
4
|
+
* - --start : запустить watchdog в фоне (detached, без консоли) и дождаться порта WORK
|
|
5
|
+
* - --stop : поставить маркер ручной остановки (#system/work.stopped), остановить сервис/задачу ОС, watchdog и сервер
|
|
6
|
+
* - --run : цикл супервизора (перезапуск при падении с backoff, поддержка #system/restart-request.json)
|
|
7
|
+
* - --boot : запуск супервизора из автозагрузки ОС (сбрасывает старый маркер остановки)
|
|
8
|
+
* - --status : вывести статус процесса, watchdog и порта
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import net from 'node:net';
|
|
13
|
+
import http from 'node:http';
|
|
14
|
+
import childProcess from 'node:child_process';
|
|
15
|
+
import { pathToFileURL } from 'node:url';
|
|
16
|
+
|
|
17
|
+
export const RESTART_EXIT_CODE = 75;
|
|
18
|
+
const MAX_LOG_BYTES = 10 * 1024 * 1024;
|
|
19
|
+
const BACKOFF_MS = [3000, 5000, 10000, 20000, 30000];
|
|
20
|
+
const HEALTHY_RUN_MS = 60_000;
|
|
21
|
+
|
|
22
|
+
export function resolveWorkRoot(explicitRoot = '') {
|
|
23
|
+
if (explicitRoot)
|
|
24
|
+
return path.resolve(explicitRoot);
|
|
25
|
+
return path.resolve(process.cwd());
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function resolveEntryScript(workRoot) {
|
|
29
|
+
const localRun = path.join(workRoot, 'run.mjs');
|
|
30
|
+
if (fs.existsSync(localRun))
|
|
31
|
+
return localRun;
|
|
32
|
+
const pkgRun = path.resolve(import.meta.dirname, '..', 'run.mjs');
|
|
33
|
+
if (fs.existsSync(pkgRun))
|
|
34
|
+
return pkgRun;
|
|
35
|
+
const nmRun = path.join(workRoot, 'node_modules', 'odant-work', 'run.mjs');
|
|
36
|
+
if (fs.existsSync(nmRun))
|
|
37
|
+
return nmRun;
|
|
38
|
+
return localRun;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function resolveWorkPort(workRoot, env = process.env) {
|
|
42
|
+
try {
|
|
43
|
+
const cfgFile = path.join(workRoot, 'config.json');
|
|
44
|
+
if (fs.existsSync(cfgFile)) {
|
|
45
|
+
const cfg = JSON.parse(fs.readFileSync(cfgFile, 'utf8'));
|
|
46
|
+
const p = Number(cfg?.PORT);
|
|
47
|
+
if (Number.isInteger(p) && p > 0)
|
|
48
|
+
return p;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch { /* ignore */ }
|
|
52
|
+
const envPort = Number(env.WORK_PORT);
|
|
53
|
+
return (Number.isInteger(envPort) && envPort > 0) ? envPort : 8001;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function pathsOf(workRoot) {
|
|
57
|
+
const sysDir = path.join(workRoot, '#system');
|
|
58
|
+
return {
|
|
59
|
+
sysDir,
|
|
60
|
+
watchdogPid: path.join(sysDir, 'watchdog.pid'),
|
|
61
|
+
runPid: path.join(sysDir, 'run.pid'),
|
|
62
|
+
stoppedMarker: path.join(sysDir, 'work.stopped'),
|
|
63
|
+
restartRequest: path.join(sysDir, 'restart-request.json'),
|
|
64
|
+
logFile: path.join(sysDir, 'work-server.log'),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function isPidAlive(pid) {
|
|
69
|
+
const n = Number(pid);
|
|
70
|
+
if (!Number.isInteger(n) || n <= 0)
|
|
71
|
+
return false;
|
|
72
|
+
try {
|
|
73
|
+
process.kill(n, 0);
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
return err?.code === 'EPERM';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function readPidFile(filePath) {
|
|
82
|
+
try {
|
|
83
|
+
if (!fs.existsSync(filePath))
|
|
84
|
+
return 0;
|
|
85
|
+
const raw = fs.readFileSync(filePath, 'utf8').trim();
|
|
86
|
+
if (!raw)
|
|
87
|
+
return 0;
|
|
88
|
+
if (raw.startsWith('{')) {
|
|
89
|
+
const parsed = JSON.parse(raw);
|
|
90
|
+
const pid = Number(parsed?.pid);
|
|
91
|
+
return Number.isInteger(pid) && pid > 0 ? pid : 0;
|
|
92
|
+
}
|
|
93
|
+
const pid = Number(raw);
|
|
94
|
+
return Number.isInteger(pid) && pid > 0 ? pid : 0;
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function isPortOpen(port, host = '127.0.0.1', timeoutMs = 1000) {
|
|
102
|
+
return new Promise((resolve) => {
|
|
103
|
+
const sock = net.createConnection({ host, port });
|
|
104
|
+
let done = false;
|
|
105
|
+
const finish = (v) => {
|
|
106
|
+
if (done)
|
|
107
|
+
return;
|
|
108
|
+
done = true;
|
|
109
|
+
try { sock.destroy(); } catch { /* ignore */ }
|
|
110
|
+
resolve(v);
|
|
111
|
+
};
|
|
112
|
+
sock.setTimeout(timeoutMs);
|
|
113
|
+
sock.once('connect', () => finish(true));
|
|
114
|
+
sock.once('timeout', () => finish(false));
|
|
115
|
+
sock.once('error', () => finish(false));
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function checkHttpReady(port, host = '127.0.0.1', timeoutMs = 1500) {
|
|
120
|
+
return new Promise((resolve) => {
|
|
121
|
+
const req = http.get({ host, port, path: '/favicon.ico', timeout: timeoutMs }, (res) => {
|
|
122
|
+
res.resume();
|
|
123
|
+
resolve(res.statusCode > 0 && res.statusCode < 500);
|
|
124
|
+
});
|
|
125
|
+
req.on('timeout', () => { req.destroy(); resolve(false); });
|
|
126
|
+
req.on('error', () => resolve(false));
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function rotateLogIfNeeded(logFile) {
|
|
131
|
+
try {
|
|
132
|
+
if (!fs.existsSync(logFile))
|
|
133
|
+
return;
|
|
134
|
+
const st = fs.statSync(logFile);
|
|
135
|
+
if (st.size < MAX_LOG_BYTES)
|
|
136
|
+
return;
|
|
137
|
+
const prev = logFile + '.1';
|
|
138
|
+
try { fs.rmSync(prev, { force: true }); } catch { /* ignore */ }
|
|
139
|
+
fs.renameSync(logFile, prev);
|
|
140
|
+
}
|
|
141
|
+
catch { /* ignore */ }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function appendLog(logFile, msg) {
|
|
145
|
+
try {
|
|
146
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
147
|
+
rotateLogIfNeeded(logFile);
|
|
148
|
+
fs.appendFileSync(logFile, `[${new Date().toISOString()}] ${msg}\n`, 'utf8');
|
|
149
|
+
}
|
|
150
|
+
catch { /* ignore */ }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function listPortListeningPids(port) {
|
|
154
|
+
const outPids = new Set();
|
|
155
|
+
if (!port)
|
|
156
|
+
return outPids;
|
|
157
|
+
try {
|
|
158
|
+
if (process.platform === 'win32') {
|
|
159
|
+
const out = childProcess.execSync(`netstat -ano | findstr :${port}`, {
|
|
160
|
+
encoding: 'utf8',
|
|
161
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
162
|
+
});
|
|
163
|
+
for (const line of out.split(/\r?\n/)) {
|
|
164
|
+
const m = line.trim().match(new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+(\\d+)$`, 'i'));
|
|
165
|
+
const pid = m ? Number(m[1]) : 0;
|
|
166
|
+
if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)
|
|
167
|
+
outPids.add(pid);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
const cmds = [
|
|
172
|
+
`lsof -tiTCP:${port} -sTCP:LISTEN`,
|
|
173
|
+
`fuser ${port}/tcp`,
|
|
174
|
+
];
|
|
175
|
+
for (const cmd of cmds) {
|
|
176
|
+
try {
|
|
177
|
+
const out = childProcess.execSync(cmd, {
|
|
178
|
+
encoding: 'utf8',
|
|
179
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
180
|
+
});
|
|
181
|
+
for (const tok of out.split(/\s+/)) {
|
|
182
|
+
const pid = Number(tok.trim());
|
|
183
|
+
if (Number.isInteger(pid) && pid > 0 && pid !== process.pid)
|
|
184
|
+
outPids.add(pid);
|
|
185
|
+
}
|
|
186
|
+
if (outPids.size)
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
catch { /* try next */ }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch { /* ignore */ }
|
|
194
|
+
return outPids;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function terminatePid(pid, timeoutMs = 5000) {
|
|
198
|
+
if (!isPidAlive(pid) || pid === process.pid)
|
|
199
|
+
return true;
|
|
200
|
+
try {
|
|
201
|
+
process.kill(pid, 'SIGTERM');
|
|
202
|
+
}
|
|
203
|
+
catch { /* ignore */ }
|
|
204
|
+
const deadline = Date.now() + timeoutMs;
|
|
205
|
+
while (Date.now() < deadline) {
|
|
206
|
+
if (!isPidAlive(pid))
|
|
207
|
+
return true;
|
|
208
|
+
await new Promise(r => setTimeout(r, 150));
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
if (process.platform === 'win32')
|
|
212
|
+
childProcess.execSync(`taskkill /PID ${pid} /T /F`, { stdio: 'ignore' });
|
|
213
|
+
else
|
|
214
|
+
process.kill(pid, 'SIGKILL');
|
|
215
|
+
}
|
|
216
|
+
catch { /* ignore */ }
|
|
217
|
+
return !isPidAlive(pid);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function stopSystemAutostartUnitIfRunning() {
|
|
221
|
+
try {
|
|
222
|
+
if (process.platform === 'linux' && fs.existsSync('/run/systemd/system')) {
|
|
223
|
+
for (const cmd of [
|
|
224
|
+
'systemctl is-active --quiet odant-work && systemctl stop odant-work',
|
|
225
|
+
'systemctl --user is-active --quiet odant-work && systemctl --user stop odant-work',
|
|
226
|
+
]) {
|
|
227
|
+
try { childProcess.execSync(cmd, { stdio: 'ignore' }); } catch { /* ignore */ }
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
else if (process.platform === 'win32') {
|
|
231
|
+
try {
|
|
232
|
+
childProcess.execSync('schtasks /End /TN "ODANT-WORK"', { stdio: 'ignore' });
|
|
233
|
+
}
|
|
234
|
+
catch { /* ignore */ }
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch { /* ignore */ }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function backoffForAttempt(attempt) {
|
|
241
|
+
const idx = Math.max(0, Math.min(BACKOFF_MS.length - 1, attempt));
|
|
242
|
+
return BACKOFF_MS[idx];
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export async function runSupervisor({ workRoot = resolveWorkRoot(), boot = false } = {}) {
|
|
246
|
+
const p = pathsOf(workRoot);
|
|
247
|
+
fs.mkdirSync(p.sysDir, { recursive: true });
|
|
248
|
+
|
|
249
|
+
const existingWatchdog = readPidFile(p.watchdogPid);
|
|
250
|
+
if (existingWatchdog && existingWatchdog !== process.pid && isPidAlive(existingWatchdog)) {
|
|
251
|
+
appendLog(p.logFile, `[watchdog] уже запущен (pid=${existingWatchdog}), дубликат завершён.`);
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (boot || !fs.existsSync(p.stoppedMarker)) {
|
|
256
|
+
try { fs.rmSync(p.stoppedMarker, { force: true }); } catch { /* ignore */ }
|
|
257
|
+
}
|
|
258
|
+
try { fs.rmSync(p.restartRequest, { force: true }); } catch { /* ignore */ }
|
|
259
|
+
|
|
260
|
+
fs.writeFileSync(p.watchdogPid, JSON.stringify({
|
|
261
|
+
pid: process.pid,
|
|
262
|
+
cwd: workRoot,
|
|
263
|
+
startedAt: new Date().toISOString(),
|
|
264
|
+
}), 'utf8');
|
|
265
|
+
|
|
266
|
+
const cleanupPidFile = () => {
|
|
267
|
+
try {
|
|
268
|
+
if (readPidFile(p.watchdogPid) === process.pid)
|
|
269
|
+
fs.rmSync(p.watchdogPid, { force: true });
|
|
270
|
+
}
|
|
271
|
+
catch { /* ignore */ }
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
let currentChild = null;
|
|
275
|
+
let stopping = false;
|
|
276
|
+
const handleSignal = (sig) => {
|
|
277
|
+
stopping = true;
|
|
278
|
+
appendLog(p.logFile, `[watchdog] получен сигнал ${sig}, остановка сервера.`);
|
|
279
|
+
try {
|
|
280
|
+
fs.writeFileSync(p.stoppedMarker, JSON.stringify({ pid: process.pid, reason: sig, time: Date.now() }), 'utf8');
|
|
281
|
+
}
|
|
282
|
+
catch { /* ignore */ }
|
|
283
|
+
if (currentChild && !currentChild.killed) {
|
|
284
|
+
try { currentChild.kill('SIGTERM'); } catch { /* ignore */ }
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
process.on('SIGINT', () => handleSignal('SIGINT'));
|
|
288
|
+
process.on('SIGTERM', () => handleSignal('SIGTERM'));
|
|
289
|
+
|
|
290
|
+
const entryScript = resolveEntryScript(workRoot);
|
|
291
|
+
let nextExtraEnv = {};
|
|
292
|
+
let attempt = 0;
|
|
293
|
+
|
|
294
|
+
try {
|
|
295
|
+
while (!stopping) {
|
|
296
|
+
if (fs.existsSync(p.stoppedMarker)) {
|
|
297
|
+
appendLog(p.logFile, '[watchdog] найден маркер ручной остановки work.stopped, выход.');
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
rotateLogIfNeeded(p.logFile);
|
|
302
|
+
const logFd = fs.openSync(p.logFile, 'a');
|
|
303
|
+
const startedAt = Date.now();
|
|
304
|
+
const childEnv = {
|
|
305
|
+
...process.env,
|
|
306
|
+
...nextExtraEnv,
|
|
307
|
+
WORK_WATCHDOG: '1',
|
|
308
|
+
};
|
|
309
|
+
delete childEnv.NODE_OPTIONS;
|
|
310
|
+
nextExtraEnv = {};
|
|
311
|
+
|
|
312
|
+
appendLog(p.logFile, `[watchdog] старт сервера: ${entryScript} (attempt=${attempt})`);
|
|
313
|
+
|
|
314
|
+
let exitCode = 0;
|
|
315
|
+
let exitSignal = null;
|
|
316
|
+
try {
|
|
317
|
+
await new Promise((resolve) => {
|
|
318
|
+
const child = childProcess.spawn(process.execPath, [entryScript], {
|
|
319
|
+
cwd: workRoot,
|
|
320
|
+
env: childEnv,
|
|
321
|
+
windowsHide: true,
|
|
322
|
+
stdio: ['ignore', logFd, logFd],
|
|
323
|
+
});
|
|
324
|
+
currentChild = child;
|
|
325
|
+
child.once('exit', (code, sig) => {
|
|
326
|
+
exitCode = code ?? 1;
|
|
327
|
+
exitSignal = sig || null;
|
|
328
|
+
currentChild = null;
|
|
329
|
+
resolve();
|
|
330
|
+
});
|
|
331
|
+
child.once('error', (err) => {
|
|
332
|
+
appendLog(p.logFile, `[watchdog] ошибка запуска child: ${err?.message || err}`);
|
|
333
|
+
exitCode = 1;
|
|
334
|
+
currentChild = null;
|
|
335
|
+
resolve();
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
finally {
|
|
340
|
+
try { fs.closeSync(logFd); } catch { /* ignore */ }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
if (stopping || fs.existsSync(p.stoppedMarker)) {
|
|
344
|
+
appendLog(p.logFile, '[watchdog] остановка подтверждена (work.stopped).');
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Штатный запрос перезапуска из UI (restart_normal / version_update_restart)
|
|
349
|
+
if (fs.existsSync(p.restartRequest)) {
|
|
350
|
+
try {
|
|
351
|
+
const req = JSON.parse(fs.readFileSync(p.restartRequest, 'utf8'));
|
|
352
|
+
if (req?.env && typeof req.env === 'object')
|
|
353
|
+
nextExtraEnv = req.env;
|
|
354
|
+
}
|
|
355
|
+
catch { /* ignore */ }
|
|
356
|
+
try { fs.rmSync(p.restartRequest, { force: true }); } catch { /* ignore */ }
|
|
357
|
+
attempt = 0;
|
|
358
|
+
appendLog(p.logFile, `[watchdog] штатный перезапуск (code=${exitCode}, sig=${exitSignal || '-'})`);
|
|
359
|
+
await new Promise(r => setTimeout(r, 400));
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (exitCode === RESTART_EXIT_CODE) {
|
|
364
|
+
attempt = 0;
|
|
365
|
+
appendLog(p.logFile, `[watchdog] перезапуск по коду ${RESTART_EXIT_CODE}`);
|
|
366
|
+
await new Promise(r => setTimeout(r, 400));
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Если сервер вышел чисто с кодом 0 без restart-request (например, другой процесс перехватил порт или SIGTERM)
|
|
371
|
+
if (exitCode === 0 && !exitSignal) {
|
|
372
|
+
appendLog(p.logFile, '[watchdog] сервер завершился с кодом 0, watchdog останавливается.');
|
|
373
|
+
break;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const livedMs = Date.now() - startedAt;
|
|
377
|
+
if (livedMs >= HEALTHY_RUN_MS)
|
|
378
|
+
attempt = 0;
|
|
379
|
+
const waitMs = backoffForAttempt(attempt);
|
|
380
|
+
attempt++;
|
|
381
|
+
appendLog(p.logFile, `[watchdog] аварийное завершение (code=${exitCode}, sig=${exitSignal || '-'}, uptime=${Math.round(livedMs / 1000)}с). Перезапуск через ${Math.round(waitMs / 1000)}с...`);
|
|
382
|
+
await new Promise(r => setTimeout(r, waitMs));
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
finally {
|
|
386
|
+
cleanupPidFile();
|
|
387
|
+
}
|
|
388
|
+
return 0;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export async function startDetached({ workRoot = resolveWorkRoot(), timeoutMs = 35_000 } = {}) {
|
|
392
|
+
const p = pathsOf(workRoot);
|
|
393
|
+
const port = resolveWorkPort(workRoot);
|
|
394
|
+
fs.mkdirSync(p.sysDir, { recursive: true });
|
|
395
|
+
try { fs.rmSync(p.stoppedMarker, { force: true }); } catch { /* ignore */ }
|
|
396
|
+
|
|
397
|
+
const existingWatchdog = readPidFile(p.watchdogPid);
|
|
398
|
+
const existingServer = readPidFile(p.runPid);
|
|
399
|
+
if (existingWatchdog && isPidAlive(existingWatchdog) && existingServer && isPidAlive(existingServer) && await isPortOpen(port)) {
|
|
400
|
+
console.log(`ODANT-WORK уже запущен: http://localhost:${port}/ (watchdog PID ${existingWatchdog}, сервер PID ${existingServer})`);
|
|
401
|
+
return { alreadyRunning: true, port, watchdogPid: existingWatchdog, serverPid: existingServer };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const watchdogScript = path.resolve(import.meta.dirname, 'watchdog.mjs');
|
|
405
|
+
const child = childProcess.spawn(process.execPath, [watchdogScript, '--run', `--root=${workRoot}`], {
|
|
406
|
+
cwd: workRoot,
|
|
407
|
+
env: { ...process.env, WORK_WATCHDOG: '1' },
|
|
408
|
+
detached: true,
|
|
409
|
+
windowsHide: true,
|
|
410
|
+
stdio: 'ignore',
|
|
411
|
+
});
|
|
412
|
+
child.unref();
|
|
413
|
+
|
|
414
|
+
const deadline = Date.now() + timeoutMs;
|
|
415
|
+
while (Date.now() < deadline) {
|
|
416
|
+
await new Promise(r => setTimeout(r, 400));
|
|
417
|
+
if (await checkHttpReady(port)) {
|
|
418
|
+
const srvPid = readPidFile(p.runPid);
|
|
419
|
+
const wdPid = readPidFile(p.watchdogPid) || child.pid;
|
|
420
|
+
console.log(`ODANT-WORK запущен в фоне: http://localhost:${port}/ (сервер PID ${srvPid || '?'}, watchdog PID ${wdPid})`);
|
|
421
|
+
console.log(`Лог сервера: ${p.logFile}`);
|
|
422
|
+
return { alreadyRunning: false, port, watchdogPid: wdPid, serverPid: srvPid };
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
console.error(`ODANT-WORK не ответил на порту ${port} за ${Math.round(timeoutMs / 1000)}с. Проверьте лог: ${p.logFile}`);
|
|
426
|
+
return { alreadyRunning: false, timeout: true, port };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export async function stopWork({ workRoot = resolveWorkRoot() } = {}) {
|
|
430
|
+
const p = pathsOf(workRoot);
|
|
431
|
+
const port = resolveWorkPort(workRoot);
|
|
432
|
+
fs.mkdirSync(p.sysDir, { recursive: true });
|
|
433
|
+
fs.writeFileSync(p.stoppedMarker, JSON.stringify({ pid: process.pid, time: Date.now(), reason: 'stop-command' }), 'utf8');
|
|
434
|
+
try { fs.rmSync(p.restartRequest, { force: true }); } catch { /* ignore */ }
|
|
435
|
+
|
|
436
|
+
stopSystemAutostartUnitIfRunning();
|
|
437
|
+
|
|
438
|
+
const wdPid = readPidFile(p.watchdogPid);
|
|
439
|
+
if (wdPid && isPidAlive(wdPid))
|
|
440
|
+
await terminatePid(wdPid, 4000);
|
|
441
|
+
try { fs.rmSync(p.watchdogPid, { force: true }); } catch { /* ignore */ }
|
|
442
|
+
|
|
443
|
+
const srvPid = readPidFile(p.runPid);
|
|
444
|
+
if (srvPid && isPidAlive(srvPid))
|
|
445
|
+
await terminatePid(srvPid, 6000);
|
|
446
|
+
|
|
447
|
+
for (const pid of listPortListeningPids(port))
|
|
448
|
+
await terminatePid(pid, 4000);
|
|
449
|
+
|
|
450
|
+
try { fs.rmSync(p.runPid, { force: true }); } catch { /* ignore */ }
|
|
451
|
+
|
|
452
|
+
const stillBusy = await isPortOpen(port, '127.0.0.1', 500);
|
|
453
|
+
if (stillBusy) {
|
|
454
|
+
console.warn(`Предупреждение: порт ${port} всё ещё занят.`);
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
console.log(`ODANT-WORK остановлен (порт ${port} свободен).`);
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export async function printStatus({ workRoot = resolveWorkRoot() } = {}) {
|
|
462
|
+
const p = pathsOf(workRoot);
|
|
463
|
+
const port = resolveWorkPort(workRoot);
|
|
464
|
+
const wdPid = readPidFile(p.watchdogPid);
|
|
465
|
+
const srvPid = readPidFile(p.runPid);
|
|
466
|
+
const wdAlive = isPidAlive(wdPid);
|
|
467
|
+
const srvAlive = isPidAlive(srvPid);
|
|
468
|
+
const portOpen = await isPortOpen(port);
|
|
469
|
+
console.log(`Каталог WORK: ${workRoot}`);
|
|
470
|
+
console.log(`Порт ${port}: ${portOpen ? 'СЛУШАЕТ' : 'свободен'}`);
|
|
471
|
+
console.log(`Сервер (${p.runPid}): ${srvAlive ? `работает (PID ${srvPid})` : 'остановлен'}`);
|
|
472
|
+
console.log(`Watchdog (${p.watchdogPid}): ${wdAlive ? `работает (PID ${wdPid})` : 'остановлен'}`);
|
|
473
|
+
console.log(`Маркер остановки: ${fs.existsSync(p.stoppedMarker) ? 'да' : 'нет'}`);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
const isMain = process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
|
|
477
|
+
if (isMain) {
|
|
478
|
+
const args = process.argv.slice(2);
|
|
479
|
+
const rootArg = args.find(a => a.startsWith('--root='))?.slice(7) || '';
|
|
480
|
+
const workRoot = resolveWorkRoot(rootArg);
|
|
481
|
+
if (args.includes('--stop')) {
|
|
482
|
+
const ok = await stopWork({ workRoot });
|
|
483
|
+
process.exit(ok ? 0 : 1);
|
|
484
|
+
}
|
|
485
|
+
else if (args.includes('--status')) {
|
|
486
|
+
await printStatus({ workRoot });
|
|
487
|
+
}
|
|
488
|
+
else if (args.includes('--run') || args.includes('--boot')) {
|
|
489
|
+
const code = await runSupervisor({ workRoot, boot: args.includes('--boot') });
|
|
490
|
+
process.exit(code);
|
|
491
|
+
}
|
|
492
|
+
else {
|
|
493
|
+
const res = await startDetached({ workRoot });
|
|
494
|
+
process.exit(res?.timeout ? 1 : 0);
|
|
495
|
+
}
|
|
496
|
+
}
|
package/sources/client.js
CHANGED
|
@@ -438,6 +438,8 @@ WORK.login = async function(force = false){
|
|
|
438
438
|
WORK.credentials = window.top.WORK.credentials;
|
|
439
439
|
WORK.uid = window.top.WORK.uid || '';
|
|
440
440
|
WORK.USER = window.top.WORK.USER;
|
|
441
|
+
WORK.userSettings = window.top.WORK.userSettings || WORK.userSettings;
|
|
442
|
+
WORK._userSettingsLoaded = Boolean(window.top.WORK._userSettingsLoaded);
|
|
441
443
|
WORK._loginError = null;
|
|
442
444
|
return res;
|
|
443
445
|
}
|
|
@@ -485,6 +487,7 @@ WORK.login = async function(force = false){
|
|
|
485
487
|
WORK._anonExitSynced = false;
|
|
486
488
|
if (authChanged || !WORK.USER)
|
|
487
489
|
await WORK.syncAuthUI();
|
|
490
|
+
await WORK.loadUserSettings?.();
|
|
488
491
|
WORK.refreshChatUnread?.();
|
|
489
492
|
if (authChanged) {
|
|
490
493
|
WORK._authNotifiedOnce = true;
|
|
@@ -500,6 +503,8 @@ WORK.login = async function(force = false){
|
|
|
500
503
|
WORK._pushSyncedUid = '';
|
|
501
504
|
WORK._loginError = null;
|
|
502
505
|
WORK.USER = undefined;
|
|
506
|
+
WORK.userSettings = { chatSound: true, aiModel: '' };
|
|
507
|
+
WORK._userSettingsLoaded = false;
|
|
503
508
|
WORK.chatUnread = { total: 0, byThread: {}, byNode: {}, byPeer: {} };
|
|
504
509
|
if (hadAuth || !WORK._anonExitSynced) {
|
|
505
510
|
WORK._anonExitSynced = true;
|
|
@@ -592,12 +597,117 @@ WORK.getPublicVapid = async function () {
|
|
|
592
597
|
key = WORK.urlBase64ToUint8Array(key);
|
|
593
598
|
return WORK.arrayBufferToBase64(key);
|
|
594
599
|
}
|
|
600
|
+
function getPushDeviceId() {
|
|
601
|
+
try {
|
|
602
|
+
let id = globalThis.localStorage?.getItem('work.push.deviceId') || '';
|
|
603
|
+
if (!id) {
|
|
604
|
+
id = globalThis.crypto?.randomUUID?.() || (Date.now().toString(36) + '-' + Math.random().toString(36).slice(2));
|
|
605
|
+
globalThis.localStorage?.setItem('work.push.deviceId', id);
|
|
606
|
+
}
|
|
607
|
+
return id;
|
|
608
|
+
}
|
|
609
|
+
catch {
|
|
610
|
+
return '';
|
|
611
|
+
}
|
|
612
|
+
}
|
|
595
613
|
WORK.storePushSubscription = function (subscription) {
|
|
596
|
-
|
|
614
|
+
const sub = typeof subscription?.toJSON === 'function' ? subscription.toJSON() : { ...(subscription || {}) };
|
|
615
|
+
const deviceId = getPushDeviceId();
|
|
616
|
+
let replaceEndpoint = '';
|
|
617
|
+
try { replaceEndpoint = globalThis.localStorage?.getItem('work.push.endpoint') || ''; } catch {}
|
|
618
|
+
const payload = {
|
|
619
|
+
...sub,
|
|
620
|
+
...(deviceId ? { deviceId } : {}),
|
|
621
|
+
...(replaceEndpoint && replaceEndpoint !== sub.endpoint ? { replaceEndpoint } : {}),
|
|
622
|
+
};
|
|
623
|
+
try {
|
|
624
|
+
if (sub.endpoint)
|
|
625
|
+
globalThis.localStorage?.setItem('work.push.endpoint', sub.endpoint);
|
|
626
|
+
} catch {}
|
|
627
|
+
return WORK.fetch("/", 'store_push_subscription', {}, payload);
|
|
597
628
|
}
|
|
598
629
|
WORK.removePushSubscription = function (subscription) {
|
|
599
|
-
|
|
630
|
+
const sub = typeof subscription?.toJSON === 'function' ? subscription.toJSON() : { ...(subscription || {}) };
|
|
631
|
+
const deviceId = getPushDeviceId();
|
|
632
|
+
try { globalThis.localStorage?.removeItem('work.push.endpoint'); } catch {}
|
|
633
|
+
return WORK.fetch("/", 'remove_push_subscription', {}, { ...sub, ...(deviceId ? { deviceId } : {}) });
|
|
634
|
+
}
|
|
635
|
+
WORK.userSettings = { chatSound: true, aiModel: '' };
|
|
636
|
+
WORK._userSettingsLoaded = false;
|
|
637
|
+
WORK._applyUserSettings = function (next, { broadcast = false } = {}) {
|
|
638
|
+
if (!next || typeof next !== 'object')
|
|
639
|
+
return WORK.userSettings;
|
|
640
|
+
WORK.userSettings = {
|
|
641
|
+
...WORK.userSettings,
|
|
642
|
+
...next,
|
|
643
|
+
chatSound: next.chatSound !== false,
|
|
644
|
+
aiModel: typeof next.aiModel === 'string' ? next.aiModel : (WORK.userSettings?.aiModel || ''),
|
|
645
|
+
};
|
|
646
|
+
if (WORK.USER?.DATA)
|
|
647
|
+
WORK.USER.DATA.settings = { ...WORK.userSettings };
|
|
648
|
+
if (broadcast) {
|
|
649
|
+
try { WORK._settingsChannel?.postMessage?.(WORK.userSettings); } catch {}
|
|
650
|
+
}
|
|
651
|
+
try {
|
|
652
|
+
WORK.authEvents?.dispatchEvent?.(new CustomEvent('user-settings', { detail: WORK.userSettings }));
|
|
653
|
+
} catch {}
|
|
654
|
+
return WORK.userSettings;
|
|
655
|
+
};
|
|
656
|
+
if (typeof BroadcastChannel !== 'undefined') {
|
|
657
|
+
try {
|
|
658
|
+
WORK._settingsChannel ??= new BroadcastChannel('work-user-settings');
|
|
659
|
+
WORK._settingsChannel.addEventListener('message', (e) => {
|
|
660
|
+
if (e.data && typeof e.data === 'object')
|
|
661
|
+
WORK._applyUserSettings(e.data, { broadcast: false });
|
|
662
|
+
});
|
|
663
|
+
} catch {}
|
|
600
664
|
}
|
|
665
|
+
WORK.loadUserSettings = async function () {
|
|
666
|
+
if (!WORK.uid || typeof WORK.fetch !== 'function')
|
|
667
|
+
return WORK.userSettings;
|
|
668
|
+
try {
|
|
669
|
+
const res = await WORK.fetch('/', 'user_settings_get');
|
|
670
|
+
if (res && typeof res === 'object') {
|
|
671
|
+
WORK._userSettingsLoaded = true;
|
|
672
|
+
WORK._applyUserSettings(res, { broadcast: false });
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
catch { /* ignore */ }
|
|
676
|
+
return WORK.userSettings;
|
|
677
|
+
};
|
|
678
|
+
WORK.saveUserSettings = async function (patch = {}) {
|
|
679
|
+
if (!patch || typeof patch !== 'object')
|
|
680
|
+
return WORK.userSettings;
|
|
681
|
+
WORK._applyUserSettings(patch, { broadcast: true });
|
|
682
|
+
if (!WORK.uid || typeof WORK.fetch !== 'function')
|
|
683
|
+
return WORK.userSettings;
|
|
684
|
+
try {
|
|
685
|
+
const saved = await WORK.fetch('/', 'user_settings_save', {}, patch);
|
|
686
|
+
if (saved && typeof saved === 'object') {
|
|
687
|
+
WORK._userSettingsLoaded = true;
|
|
688
|
+
WORK._applyUserSettings(saved, { broadcast: true });
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
catch (err) {
|
|
692
|
+
console.warn('[user-settings] save', err?.message || err);
|
|
693
|
+
}
|
|
694
|
+
return WORK.userSettings;
|
|
695
|
+
};
|
|
696
|
+
WORK._visibleTasks = new Set();
|
|
697
|
+
WORK.setTaskPresence = function (taskPath, visible) {
|
|
698
|
+
const p = String(taskPath || '').replace(/\/+$/, '');
|
|
699
|
+
if (!p)
|
|
700
|
+
return;
|
|
701
|
+
if (visible)
|
|
702
|
+
WORK._visibleTasks.add(p);
|
|
703
|
+
else
|
|
704
|
+
WORK._visibleTasks.delete(p);
|
|
705
|
+
try {
|
|
706
|
+
if (WORK._ws?.readyState === 1)
|
|
707
|
+
WORK._ws.send(JSON.stringify({ type: 'task.presence', path: p, visible: Boolean(visible) }));
|
|
708
|
+
}
|
|
709
|
+
catch { /* ignore */ }
|
|
710
|
+
};
|
|
601
711
|
/** Перед выходом убрать подписку у прежнего uid, иначе следующий пользователь получит его push. */
|
|
602
712
|
WORK.removeCurrentPushSubscription = async function () {
|
|
603
713
|
if (!WORK.uid || !navigator.serviceWorker || typeof Notification === 'undefined' || Notification.permission !== 'granted')
|
|
@@ -650,11 +760,17 @@ class WebSocketEvents {
|
|
|
650
760
|
}
|
|
651
761
|
}
|
|
652
762
|
onopen(e) {
|
|
763
|
+
WORK._ws = this;
|
|
653
764
|
this.send(JSON.stringify(Object.keys(CORE.$item.ITEMS)));
|
|
765
|
+
for (const tp of WORK._visibleTasks || []) {
|
|
766
|
+
try { this.send(JSON.stringify({ type: 'task.presence', path: tp, visible: true })); } catch {}
|
|
767
|
+
}
|
|
654
768
|
WORK.connected = true;
|
|
655
769
|
WORK.login().catch(() => {});
|
|
656
770
|
}
|
|
657
771
|
onclose(e) {
|
|
772
|
+
if (WORK._ws === this)
|
|
773
|
+
WORK._ws = null;
|
|
658
774
|
WORK.connected = false;
|
|
659
775
|
WORK.wsid = '';
|
|
660
776
|
WORK._loginPromise = null;
|
|
@@ -680,6 +796,10 @@ class WebSocketEvents {
|
|
|
680
796
|
case 'connect':{
|
|
681
797
|
WORK.wsid = this.id = data.wsid
|
|
682
798
|
} break;
|
|
799
|
+
case 'user-settings': {
|
|
800
|
+
if (data.settings && (!WORK.uid || data.uid === WORK.uid))
|
|
801
|
+
WORK._applyUserSettings?.(data.settings, { broadcast: false });
|
|
802
|
+
} break;
|
|
683
803
|
case 'auth-changed': {
|
|
684
804
|
WORK.onAuthChanged(data);
|
|
685
805
|
} break;
|
|
@@ -300,6 +300,8 @@ export const authMethods = {
|
|
|
300
300
|
let $user_item = await $users._get_next_item(uid, CORE.$user);
|
|
301
301
|
credentials.keys = $user_item.keys || {};
|
|
302
302
|
credentials.keys[time] = publicKey;
|
|
303
|
+
if ($user_item.DATA?.settings && typeof $user_item.DATA.settings === 'object')
|
|
304
|
+
credentials.settings = $user_item.DATA.settings;
|
|
303
305
|
|
|
304
306
|
if (iconBytes)
|
|
305
307
|
credentials.icon = '/USERS//' + uid + '/$user/icon.png';
|