@lalalic/markcut 3.2.17 → 3.2.19
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/README.md +3 -2
- package/bin/markcut +7 -1
- package/package.json +1 -1
- package/skills/markcut/SKILL.md +4 -0
- package/skills/markcut/references/preview-troubleshooting.md +58 -0
- package/src/queue-cli.mjs +9 -2
- package/src/queue-worker.mjs +202 -0
- package/tests/queue-cli.test.ts +9 -1
package/README.md
CHANGED
|
@@ -373,10 +373,11 @@ export MARKCUT_VTT_CLI='my-video-backend --prompt "{prompt}" {input}'
|
|
|
373
373
|
|
|
374
374
|
### Global queue CLI template (opt-in)
|
|
375
375
|
|
|
376
|
-
|
|
376
|
+
By default, Markcut routes generation and vision CLI subprocesses through its built-in SQLite execution queue. The single worker is started automatically on first use; no Neo or PM2 setup is required. Set `MARKCUT_QUEUE_ENABLED=0` to opt out. An explicit `MARKCUT_QUEUE_CLI_TEMPLATE` may override the default. `{command}` is the shell-quoted original command; the queue wrapper sets `MARKCUT_QUEUE_ACTIVE=1` for descendants to prevent re-entrance.
|
|
377
377
|
|
|
378
378
|
```bash
|
|
379
|
-
|
|
379
|
+
markcut queue status
|
|
380
|
+
markcut queue list
|
|
380
381
|
```
|
|
381
382
|
|
|
382
383
|
The template must use an executable reachable from the process environment. To avoid ambiguity with shell quoting of `$HOME`, use a literal absolute path in production. If unset, execution is unchanged. Rendering cache continues to be managed by Markcut, not the queue. No service restart or Markcut-specific queue daemon is required.
|
package/bin/markcut
CHANGED
|
@@ -5,7 +5,13 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
|
|
6
6
|
const __filename = fileURLToPath(import.meta.url);
|
|
7
7
|
const __dirname = dirname(__filename);
|
|
8
|
-
const
|
|
8
|
+
const root = resolve(__dirname, "..");
|
|
9
|
+
if (process.argv[2] === "queue") {
|
|
10
|
+
const result = spawnSync(process.execPath, [resolve(root, "src", "queue-worker.mjs"), ...process.argv.slice(3)], { stdio: "inherit" });
|
|
11
|
+
if (result.error) console.error(result.error.message);
|
|
12
|
+
process.exit(result.status ?? 1);
|
|
13
|
+
}
|
|
14
|
+
const entry = resolve(root, "src", "render", "cli.mjs");
|
|
9
15
|
|
|
10
16
|
const result = spawnSync(process.execPath, [entry, ...process.argv.slice(2)], {
|
|
11
17
|
stdio: "inherit",
|
package/package.json
CHANGED
package/skills/markcut/SKILL.md
CHANGED
|
@@ -78,6 +78,10 @@ npx @lalalic/markcut spots --waypoints "lat,lng;lat,lng" # discover POIs along a
|
|
|
78
78
|
|
|
79
79
|
---
|
|
80
80
|
|
|
81
|
+
## Preview troubleshooting
|
|
82
|
+
|
|
83
|
+
For native previews, Maps, playback, audio/subtitles or hosted ChatGPT MCP iframe issues, load [Preview Troubleshooting](references/preview-troubleshooting.md). Treat native playback, MCP compilation and hosted iframe rendering as separate verification gates.
|
|
84
|
+
|
|
81
85
|
## MCP Video Preview and Human Review (Player v24)
|
|
82
86
|
|
|
83
87
|
Use the model-visible `markcut.preview({path})` tool when a human needs to **watch and review a Markcut video** in ChatGPT. It is a video player, **not** a generic Markdown renderer and not the same as the local `npx @lalalic/markcut preview <file>` command.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# Markcut native/MCP preview troubleshooting
|
|
2
|
+
|
|
3
|
+
Use for Markcut map, route, cinematic, playback, audio, subtitle, blank iframe and MCP App issues. **Do not equate compiled preview metadata with verified rendering.** Read the bound project's AGENTS/README and the Browser Workspace skill first; load XChat bootstrap only in XChat-managed sessions. For Relay-managed work, reuse the existing Job/Task/PR rather than creating duplicates.
|
|
4
|
+
|
|
5
|
+
## Workspace and native preview
|
|
6
|
+
|
|
7
|
+
All episode/demo files and evidence must stay in a named vlog run, e.g. PROJECT/vlog/runs/episode-preview-validation/{video.md,source-manifest.json,qa.md,assets/,output/,reviews/}. Avoid scattering templates. Keep original GPS private and distinguish observed photo stops from inferred connecting routes. Shared player changes belong in an isolated Markcut Git worktree.
|
|
8
|
+
|
|
9
|
+
Start native Markcut with the **same absolute video.md** used later for MCP:
|
|
10
|
+
|
|
11
|
+
cd <markcut-repo>
|
|
12
|
+
node src/render/cli.mjs preview <project-repo>/vlog/runs/<run>/video.md --port=3014 --no-browser
|
|
13
|
+
|
|
14
|
+
Use a managed shell session for long-running sessions; stop only the debug process you started. Avoid localhost:3000/Root: that is **Remotion Studio**, not the native Markcut player. Historically even "markcut preview --help" unexpectedly launched Studio.
|
|
15
|
+
|
|
16
|
+
Start a dedicated Browser Workspace session: webhelm session start --url http://localhost:3014/; use webhelm session exec <session-id> with page_info(), snapshot(), js(), and cdp(). Inspect **actual** visuals, play/pause/seek, Google tiles, markers, polyline, route movement and cinematic camera. For a 12-second route demo, inspect 6–9s for route and 9–12s for cinematic; for other videos use their actual scene boundaries. Save screenshots in the run's output/. Differences in pixels can support animation evidence but do not prove route correctness. Inspect VTT text, audio element readyState/paused/muted/currentTime and verify audible sound separately.
|
|
17
|
+
|
|
18
|
+
If time freezes, inspect document.visibilityState: background Chrome tabs may be throttled. Use cdp("Page.bringToFront") and retest. Inspect window.remotion_delayRenderHandles and remotion_renderReady, but do not infer deadlock from a hidden tab alone.
|
|
19
|
+
|
|
20
|
+
## Browser Workspace DevTools
|
|
21
|
+
|
|
22
|
+
Install a console capture **before navigating**, then check after the relevant scene loads:
|
|
23
|
+
|
|
24
|
+
cdp("Page.addScriptToEvaluateOnNewDocument", source="""
|
|
25
|
+
window.__markcutErrors=[];
|
|
26
|
+
for(const level of ['error','warn']) {
|
|
27
|
+
const original=console[level];
|
|
28
|
+
console[level]=function(...args) {
|
|
29
|
+
window.__markcutErrors.push({level,message:args.map(String).join(' ')});
|
|
30
|
+
return original.apply(this,args);
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
""")
|
|
34
|
+
goto_url("http://localhost:3014/")
|
|
35
|
+
print(js("window.__markcutErrors"))
|
|
36
|
+
|
|
37
|
+
Save these Python statements in a file and use webhelm session exec <id> --code-file <path> when quoting is difficult. For DevTools/Network use cdp() and sanitized resource entries; **never print Google key= query values**, access tokens, private coordinates or cookies.
|
|
38
|
+
|
|
39
|
+
Observed signatures:
|
|
40
|
+
- ApiNotActivatedMapError: confirm API key's Google Cloud project, enable Maps JavaScript API on that project; inspect billing/referrer permissions based on evidence.
|
|
41
|
+
- Legacy Directions Service not enabled + DIRECTIONS_ROUTE REQUEST_DENIED: modernize from DirectionsService to google.maps.routes.Route.computeRoutes and enable Routes API for the owning Cloud project. Routes API may incur costs. Check ComputeRoutes RPC status **and** actual rendered path. Cache identical requests across Remotion seek/remount to reduce bills.
|
|
42
|
+
- DirectionsService deprecated or Remotion license warning alone is not the root cause. HTTP 200 and a static image do not prove an animated route.
|
|
43
|
+
|
|
44
|
+
## MCP tool and fresh ChatGPT thread/turn
|
|
45
|
+
|
|
46
|
+
Only after native preview passes, call the **actual NeoY markcut.preview** on that same absolute run video.md. Confirm returned resource URI/player version, revision/content hash, scene duration, map props, audio/VTT. This is a **compilation/resource gate**, not hosted-player approval.
|
|
47
|
+
|
|
48
|
+
For fresh MCP verification, when available use the NeoY chatgpt.thread capability (synchronous platform CLI), record verified thread ID and URL; an existing thread can use chatgpt.turn when suitable. Tell the new thread to call markcut.preview, **describe the image and play/seek 6–12 seconds in its own embedded player**, report errors, and **not approve**. Use a new thread for stale preview resource/cache, iframe isolation, or version testing. A thread still generating or displaying "Connection interrupted" may not have mounted the MCP App. Never claim map failure when only a DIL iframe exists: record "hosted iframe not instantiated" and retry/reload conservatively.
|
|
49
|
+
|
|
50
|
+
Open the resulting ChatGPT URL in an **exclusive Browser Workspace session**. Confirm iframe[title="Markcut Preview"], not just localhost. Via cdp("Target.getTargets") identify the web-sandbox.oaiusercontent.com **iframe target**. The actual Markcut DOM can be in that target's nested same-origin about:blank iframe. Use js(expression,target_id=<iframe-target>) to inspect nestedFrame.contentDocument, its body, buttons, .gm-style, map tiles, VTT/audio and errors. Do not bypass cross-origin protections. Observe actual picture at 6–9 and 9–12 seconds, and real pause/seek, not just DOM metadata. Never click Approve or Request changes for a diagnostic.
|
|
51
|
+
|
|
52
|
+
Capture nested iframe Console errors and Network failure statuses. Inspect effective outer sandbox response/host CSP as well as nested document: no CSP meta in about:blank **does not** prove Google Maps is allowed.
|
|
53
|
+
|
|
54
|
+
**2026-10-15 observed MCP-only failure:** native player showed Google tiles and Route.computeRoutes HTTP 200, whereas fresh hosted iframe Console repeatedly said "The Google Maps JavaScript API failed to load. Error: The Google Maps JavaScript API could not load." At ~6–7s it showed zero map nodes/tiles and repeated Maps JS requests. The exact CSP/network rejection was **not proven**. Do not mark MCP fixed because native passes.
|
|
55
|
+
|
|
56
|
+
## Verification evidence and cleanup
|
|
57
|
+
|
|
58
|
+
Record native / MCP compiler / hosted iframe as independent PASS/FAIL/UNKNOWN gates in the run's qa.md. Include UTC/local timestamp, commit/build version, thread ID, session ID, source video.md, scene time range, screenshots, sanitized errors/status, tests, unresolved blockers. Keep private GPS and keys out of logs and public mounts. After a fix rebuild Markcut native player and MCP bundle, verify deployed resource/version, repeat browser checks in a fresh thread if cache persists. Relay still owns task review/completion and approval is separate. Always webhelm session stop <id>, close exclusive tabs, and stop only your debug process.
|
package/src/queue-cli.mjs
CHANGED
|
@@ -2,16 +2,23 @@
|
|
|
2
2
|
export function shellQuote(value) {
|
|
3
3
|
return "'" + String(value).replace(/'/g, "'\\''") + "'";
|
|
4
4
|
}
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { resolve, dirname } from "node:path";
|
|
7
|
+
const queueWorker = resolve(dirname(fileURLToPath(import.meta.url)), "queue-worker.mjs");
|
|
5
8
|
export function queueCommand(command, env = process.env) {
|
|
6
9
|
const template = env.MARKCUT_QUEUE_CLI_TEMPLATE;
|
|
7
|
-
if (
|
|
10
|
+
if (env.MARKCUT_QUEUE_ACTIVE === "1" || env.MARKCUT_QUEUE_ENABLED === "0") return command;
|
|
11
|
+
if (!template) {
|
|
12
|
+
// Default: own SQLite worker, started on demand by the queue runner.
|
|
13
|
+
return `${shellQuote(process.execPath)} ${shellQuote(queueWorker)} run --queue media-ai -- /bin/sh -c ${shellQuote(`MARKCUT_QUEUE_ACTIVE=1 ${command}`)}`;
|
|
14
|
+
}
|
|
8
15
|
if (!template.includes("{command}")) throw Error("MARKCUT_QUEUE_CLI_TEMPLATE must contain {command}");
|
|
9
16
|
// The worker runs a shell to execute the original CLI without re-entering the queue.
|
|
10
17
|
return template.replaceAll("{command}", shellQuote(`MARKCUT_QUEUE_ACTIVE=1 ${command}`));
|
|
11
18
|
}
|
|
12
19
|
export function queueArgv(command, argv, env = process.env) {
|
|
13
20
|
const template = env.MARKCUT_QUEUE_CLI_TEMPLATE;
|
|
14
|
-
if (
|
|
21
|
+
if (env.MARKCUT_QUEUE_ACTIVE === "1" || env.MARKCUT_QUEUE_ENABLED === "0") return { command, argv };
|
|
15
22
|
const cmd = [command, ...argv].map(shellQuote).join(" ");
|
|
16
23
|
return { command: "/bin/sh", argv: ["-c", queueCommand(cmd, env)] };
|
|
17
24
|
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { mkdirSync, readFileSync, writeFileSync, rmSync, existsSync, openSync, readSync, closeSync, unlinkSync } from 'node:fs';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { homedir, constants as osConstants } from 'node:os';
|
|
9
|
+
|
|
10
|
+
const root = process.env.MARKCUT_QUEUE_HOME || join(homedir(), '.markcut', 'execution-queue');
|
|
11
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
12
|
+
const db = new DatabaseSync(join(root, 'queue.sqlite'));
|
|
13
|
+
db.exec('PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY, queue TEXT NOT NULL, status TEXT NOT NULL, command TEXT NOT NULL, cwd TEXT NOT NULL, created INTEGER NOT NULL, started INTEGER, ended INTEGER, pid INTEGER, code INTEGER, signal TEXT, error TEXT, timeout INTEGER NOT NULL DEFAULT 300000, dedupe TEXT); CREATE INDEX IF NOT EXISTS jobs_next ON jobs(status,queue,created); CREATE UNIQUE INDEX IF NOT EXISTS jobs_dedupe ON jobs(queue,dedupe) WHERE dedupe IS NOT NULL AND status IN (\'queued\',\'running\');');
|
|
14
|
+
const columns=db.prepare('PRAGMA table_info(jobs)').all().map(row=>row.name);
|
|
15
|
+
if(!columns.includes('retries')) db.exec('ALTER TABLE jobs ADD COLUMN retries INTEGER NOT NULL DEFAULT 0');
|
|
16
|
+
if(!columns.includes('attempts')) db.exec('ALTER TABLE jobs ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0');
|
|
17
|
+
db.exec('CREATE TABLE IF NOT EXISTS waiters (job TEXT NOT NULL, token TEXT PRIMARY KEY, pid INTEGER NOT NULL)');
|
|
18
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
19
|
+
const logPath = (id, stream) => join(root, id + '.' + stream);
|
|
20
|
+
const get = id => db.prepare('SELECT * FROM jobs WHERE id=?').get(id);
|
|
21
|
+
const args = process.argv.slice(2);
|
|
22
|
+
// Markcut owns its queue worker. Start it on demand, with no PM2 or Neo dependency.
|
|
23
|
+
async function ensureWorker() {
|
|
24
|
+
const lock = join(root, 'worker.lock', 'pid');
|
|
25
|
+
const current = () => {
|
|
26
|
+
try { return Number(readFileSync(lock, 'utf8')); } catch { return 0; }
|
|
27
|
+
};
|
|
28
|
+
if (current() && alive(current())) return;
|
|
29
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'worker'], {
|
|
30
|
+
detached: true, stdio: 'ignore', env: process.env,
|
|
31
|
+
});
|
|
32
|
+
child.unref();
|
|
33
|
+
for (let n = 0; n < 100; n++) {
|
|
34
|
+
const pid = current();
|
|
35
|
+
if (pid && alive(pid)) return;
|
|
36
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
37
|
+
}
|
|
38
|
+
throw Error('Markcut queue worker did not become ready');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function flag(name, fallback) { const i=args.indexOf(name); return i<0 ? fallback : args[i+1]; }
|
|
42
|
+
function enqueue() {
|
|
43
|
+
const cut=args.indexOf('--');
|
|
44
|
+
if(cut<0 || !args[cut+1]) throw Error('Usage: markcut queue run|submit --queue NAME [--timeout MS] [--dedupe KEY] -- COMMAND [ARGS...]');
|
|
45
|
+
const queue=flag('--queue', 'media-ai'), timeout=Number(flag('--timeout','300000')), retries=Number(flag('--retries','0'));
|
|
46
|
+
if(!/^[a-z0-9][\w-]*$/.test(queue) || !Number.isSafeInteger(timeout) || timeout<1 || !Number.isSafeInteger(retries) || retries<0 || retries>10) throw Error('Invalid queue or timeout');
|
|
47
|
+
const id=randomUUID(), command=JSON.stringify(args.slice(cut+1));
|
|
48
|
+
const dedupe=flag('--dedupe',null);
|
|
49
|
+
const insert=db.prepare('INSERT INTO jobs (id,queue,status,command,cwd,created,timeout,dedupe,retries) VALUES (?,?,?,?,?,?,?,?,?)');
|
|
50
|
+
try { insert.run(id,queue,'queued',command,process.cwd(),Date.now(),timeout,dedupe,retries); return id; }
|
|
51
|
+
catch(e) { if(!dedupe) throw e; const old=db.prepare("SELECT id FROM jobs WHERE queue=? AND dedupe=? AND status IN ('queued','running')").get(queue,dedupe); if(!old) throw e; if(get(old.id).command!==command) throw Error('Deduplication key already bound to a different command'); return old.id; }
|
|
52
|
+
}
|
|
53
|
+
function cancel(id) {
|
|
54
|
+
const job=get(id); if(!job) throw Error('Unknown job');
|
|
55
|
+
if(job.status==='queued') db.prepare("UPDATE jobs SET status='cancelled',ended=? WHERE id=? AND status='queued'").run(Date.now(),id);
|
|
56
|
+
else if(job.status==='running') db.prepare("UPDATE jobs SET status='cancelling' WHERE id=? AND status='running'").run(id);
|
|
57
|
+
}
|
|
58
|
+
async function follow(id) {
|
|
59
|
+
let offsets={stdout:0,stderr:0}; let interrupted=false;
|
|
60
|
+
const token=randomUUID();
|
|
61
|
+
db.prepare('INSERT INTO waiters (job,token,pid) VALUES (?,?,?)').run(id,token,process.pid);
|
|
62
|
+
const detach=()=>{db.prepare('DELETE FROM waiters WHERE token=?').run(token);};
|
|
63
|
+
const stop=()=>{
|
|
64
|
+
interrupted=true;detach();
|
|
65
|
+
for(const w of db.prepare('SELECT token,pid FROM waiters WHERE job=?').all(id)) if(!alive(w.pid)) db.prepare('DELETE FROM waiters WHERE token=?').run(w.token);
|
|
66
|
+
if(db.prepare('SELECT count(*) AS n FROM waiters WHERE job=?').get(id).n===0) cancel(id);
|
|
67
|
+
};
|
|
68
|
+
process.once('SIGINT',stop); process.once('SIGTERM',stop);
|
|
69
|
+
for(;;) {
|
|
70
|
+
for(const stream of ['stdout','stderr']) {
|
|
71
|
+
const file=logPath(id,stream);
|
|
72
|
+
if(!existsSync(file)) continue;
|
|
73
|
+
const fd=openSync(file,'r'); const chunks=[]; const buffer=Buffer.alloc(65536);
|
|
74
|
+
try { let n; while((n=readSync(fd,buffer,0,buffer.length,offsets[stream]))>0) { offsets[stream]+=n; chunks.push(Buffer.from(buffer.subarray(0,n))); } }
|
|
75
|
+
finally { closeSync(fd); }
|
|
76
|
+
for(const chunk of chunks) (stream==='stdout'?process.stdout:process.stderr).write(chunk);
|
|
77
|
+
}
|
|
78
|
+
const job=get(id);
|
|
79
|
+
if(['completed','failed','cancelled'].includes(job.status)) {
|
|
80
|
+
detach();process.exitCode=job.code??(job.status==='cancelled'?130:1); return;
|
|
81
|
+
}
|
|
82
|
+
if(interrupted) { process.exitCode=130; return; }
|
|
83
|
+
await sleep(100);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function alive(pid){try {process.kill(pid,0);return true;}catch{return false;}}
|
|
87
|
+
function groupAlive(pid){try {process.kill(-pid,0);return true;}catch{return false;}}
|
|
88
|
+
async function reap(pid) {
|
|
89
|
+
if(!pid || !Number.isInteger(pid) || pid<=1) return;
|
|
90
|
+
try {process.kill(-pid,'SIGTERM');}catch{}
|
|
91
|
+
for(let i=0;i<20;i++){if(!groupAlive(pid)) return;await sleep(100);}
|
|
92
|
+
try{process.kill(-pid,'SIGKILL');}catch{}
|
|
93
|
+
for(let i=0;i<20;i++){if(!groupAlive(pid)) return;await sleep(100);}
|
|
94
|
+
throw Error('Unreaped child process group '+pid);
|
|
95
|
+
}
|
|
96
|
+
async function executeJob(job) {
|
|
97
|
+
const [program,...argv]=JSON.parse(job.command);
|
|
98
|
+
const out=openSync(logPath(job.id,'stdout'),'w',0o600), err=openSync(logPath(job.id,'stderr'),'w',0o600);
|
|
99
|
+
let child,code=1,signal=null,reason=null;
|
|
100
|
+
try {
|
|
101
|
+
child=spawn(program,argv,{cwd:job.cwd,stdio:['ignore',out,err],detached:true,env:process.env,shell:false});
|
|
102
|
+
await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});
|
|
103
|
+
db.prepare('UPDATE jobs SET pid=? WHERE id=?').run(child.pid,job.id);
|
|
104
|
+
const result=await new Promise(resolve=>{
|
|
105
|
+
child.once('close',(c,s)=>resolve({code:c,signal:s}));
|
|
106
|
+
const timer=setInterval(()=>{
|
|
107
|
+
const latest=get(job.id);
|
|
108
|
+
if(latest.status==='cancelling'||Date.now()-latest.started>=job.timeout) {
|
|
109
|
+
clearInterval(timer);
|
|
110
|
+
reason=latest.status==='cancelling'?'cancelled':'timeout';
|
|
111
|
+
try{process.kill(-child.pid,'SIGTERM');}catch{}
|
|
112
|
+
}
|
|
113
|
+
},100);
|
|
114
|
+
child.once('close',()=>clearInterval(timer));
|
|
115
|
+
});
|
|
116
|
+
code=reason==='cancelled'?130:reason==='timeout'?124:(result.code??(result.signal?128+(osConstants.signals[result.signal]??0):1));
|
|
117
|
+
signal=result.signal;
|
|
118
|
+
// Do not release a queue slot while descendants from the prior command survive.
|
|
119
|
+
try { await reap(child.pid); } catch(error) { reason=error.message;code=1; }
|
|
120
|
+
} catch(error){reason=error.message;}
|
|
121
|
+
finally {closeSync(out);closeSync(err);}
|
|
122
|
+
if(code!==0 && !reason && job.attempts<job.retries) {
|
|
123
|
+
db.prepare("UPDATE jobs SET status='queued',pid=NULL,started=NULL WHERE id=?").run(job.id);
|
|
124
|
+
} else {
|
|
125
|
+
db.prepare('UPDATE jobs SET status=?,ended=?,code=?,signal=?,error=? WHERE id=?').run(reason==='cancelled'?'cancelled':code===0?'completed':'failed',Date.now(),code,signal,reason,job.id);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function worker() {
|
|
129
|
+
const lock=join(root,'worker.lock');
|
|
130
|
+
try { mkdirSync(lock); }
|
|
131
|
+
catch {
|
|
132
|
+
const prior=Number(existsSync(join(lock,'pid'))?readFileSync(join(lock,'pid'),'utf8'):0);
|
|
133
|
+
if(prior && alive(prior)) throw Error('Queue worker already running');
|
|
134
|
+
rmSync(lock,{recursive:true,force:true});mkdirSync(lock);
|
|
135
|
+
}
|
|
136
|
+
writeFileSync(join(lock,'pid'),String(process.pid));
|
|
137
|
+
process.once('exit',()=>{try{rmSync(lock,{recursive:true});}catch{}});
|
|
138
|
+
|
|
139
|
+
const capacities=JSON.parse(process.env.NEO_QUEUE_CAPACITIES||'{}');
|
|
140
|
+
for(const [name,limit] of Object.entries(capacities)) {
|
|
141
|
+
if(!/^[a-z0-9][\w-]*$/.test(name) || !Number.isInteger(limit) || limit<1 || limit>8 || (name==='media-ai' && limit!==1)) throw Error('Invalid per-queue capacity: '+name);
|
|
142
|
+
}
|
|
143
|
+
const stale=db.prepare("SELECT * FROM jobs WHERE status IN ('running','cancelling')").all();
|
|
144
|
+
for(const job of stale) {
|
|
145
|
+
await reap(job.pid);
|
|
146
|
+
db.prepare("UPDATE jobs SET status='failed',ended=?,code=137,error='worker interrupted; prior process group reaped' WHERE id=?").run(Date.now(),job.id);
|
|
147
|
+
}
|
|
148
|
+
// Retain audit metadata but remove old terminal-job stream files.
|
|
149
|
+
const retentionDays=Number(process.env.NEO_QUEUE_LOG_RETENTION_DAYS??7);
|
|
150
|
+
if(!Number.isInteger(retentionDays)||retentionDays<1||retentionDays>365) throw Error('Invalid log retention days');
|
|
151
|
+
const pruneLogs=()=>{
|
|
152
|
+
const expired=db.prepare("SELECT id FROM jobs WHERE status IN ('completed','failed','cancelled') AND ended<?").all(Date.now()-retentionDays*86400000);
|
|
153
|
+
for(const row of expired) for(const stream of ['stdout','stderr']) {
|
|
154
|
+
try{unlinkSync(logPath(row.id,stream));}catch(error){if(error.code!=='ENOENT') console.error('Log cleanup:',error.message);}
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
let lastPrune=0;
|
|
158
|
+
const active=new Map();
|
|
159
|
+
let stopping=false;
|
|
160
|
+
const shutdown=async()=>{
|
|
161
|
+
if(stopping) return;
|
|
162
|
+
stopping=true;
|
|
163
|
+
const running=db.prepare("SELECT id,pid FROM jobs WHERE status IN ('running','cancelling')").all();
|
|
164
|
+
for(const job of running) {
|
|
165
|
+
try { await reap(job.pid); }
|
|
166
|
+
catch(error) {console.error('Unable to terminate child process group:',error.message);process.exitCode=1;}
|
|
167
|
+
db.prepare("UPDATE jobs SET status='failed',ended=?,code=143,error='worker stopped' WHERE id=? AND status IN ('running','cancelling')").run(Date.now(),job.id);
|
|
168
|
+
}
|
|
169
|
+
process.exit(process.exitCode??0);
|
|
170
|
+
};
|
|
171
|
+
process.once('SIGTERM',()=>{void shutdown();});
|
|
172
|
+
process.once('SIGINT',()=>{void shutdown();});
|
|
173
|
+
for(;!stopping;) {
|
|
174
|
+
if(Date.now()-lastPrune>60000){pruneLogs();lastPrune=Date.now();}
|
|
175
|
+
const queued=db.prepare("SELECT * FROM jobs WHERE status='queued' ORDER BY created,id").all();
|
|
176
|
+
for(const candidate of queued) {
|
|
177
|
+
const limit=candidate.queue==='media-ai'?1:(capacities[candidate.queue]??1);
|
|
178
|
+
if((active.get(candidate.queue)??0)>=limit) continue;
|
|
179
|
+
// Only one PM2-owned worker dispatches. This atomic UPDATE protects the claim.
|
|
180
|
+
const now=Date.now();
|
|
181
|
+
const claim=db.prepare("UPDATE jobs SET status='running',started=?,attempts=attempts+1 WHERE id=? AND status='queued'").run(now,candidate.id);
|
|
182
|
+
if(!claim.changes) continue;
|
|
183
|
+
const job={...candidate,started:now};
|
|
184
|
+
active.set(job.queue,(active.get(job.queue)??0)+1);
|
|
185
|
+
void executeJob(job).catch(error=>{
|
|
186
|
+
db.prepare("UPDATE jobs SET status='failed',ended=?,code=1,error=? WHERE id=?").run(Date.now(),String(error),job.id);
|
|
187
|
+
}).finally(()=>active.set(job.queue,(active.get(job.queue)??1)-1));
|
|
188
|
+
}
|
|
189
|
+
await sleep(100);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
try {
|
|
194
|
+
if(args[0]==='worker') await worker();
|
|
195
|
+
else if(args[0]==='run' || args[0]==='submit') {
|
|
196
|
+
await ensureWorker();
|
|
197
|
+
const id=enqueue();if(args[0]==='submit') console.log(id);else await follow(id);}
|
|
198
|
+
else if(args[0]==='status') console.log(JSON.stringify(db.prepare('SELECT queue,status,count(*) AS count FROM jobs GROUP BY queue,status').all(),null,2));
|
|
199
|
+
else if(args[0]==='list') console.log(JSON.stringify(db.prepare('SELECT id,queue,status,created,started,ended,code,error FROM jobs ORDER BY created DESC LIMIT 30').all(),null,2));
|
|
200
|
+
else if(args[0]==='cancel') { if(!args[1]) throw Error('cancel ID');cancel(args[1]);}
|
|
201
|
+
else throw Error('Commands: worker | run | submit | status | list | cancel ID');
|
|
202
|
+
} catch(e) { console.error(e.message);process.exitCode=1; }
|
package/tests/queue-cli.test.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
2
|
import { queueCommand, queueArgv } from "../src/queue-cli.mjs";
|
|
3
3
|
describe("global queue CLI template", () => {
|
|
4
|
-
it("
|
|
4
|
+
it("queues by default and allows explicit opt-out", () => {
|
|
5
|
+
expect(queueCommand("echo one", {})).toContain("queue-worker.mjs' run --queue media-ai");
|
|
6
|
+
expect(queueCommand("echo one", {MARKCUT_QUEUE_ENABLED:"0"})).toBe("echo one");
|
|
7
|
+
});
|
|
5
8
|
it("wraps a shell command with a recursion guard", () => {
|
|
6
9
|
const env = { MARKCUT_QUEUE_CLI_TEMPLATE: "node queue.mjs run --queue media-ai -- /bin/sh -c {command}" };
|
|
7
10
|
const result = queueCommand('echo "a b"', env);
|
|
@@ -14,4 +17,9 @@ describe("global queue CLI template", () => {
|
|
|
14
17
|
const r=queueArgv("python",["file with spaces", "quoted'word"],{MARKCUT_QUEUE_CLI_TEMPLATE:"queue run -- /bin/sh -c {command}"});
|
|
15
18
|
expect(r.command).toBe("/bin/sh");expect(r.argv[1]).toContain("MARKCUT_QUEUE_ACTIVE");
|
|
16
19
|
});
|
|
20
|
+
it("queues argv by default", () => {
|
|
21
|
+
const r = queueArgv("/bin/echo", ["one two"], {});
|
|
22
|
+
expect(r.command).toBe("/bin/sh");
|
|
23
|
+
expect(r.argv[1]).toContain("queue-worker.mjs");
|
|
24
|
+
});
|
|
17
25
|
});
|