@rig-c/review 0.16.0 → 0.18.0

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/src/front.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Managed loopback front: one stable origin (127.0.0.1:4318 by default) routing `/instances/<key>/…` to the
2
2
  * worker named by that key's private open record. It is a router, not an authority: it never reads packages,
3
3
  * never serves or logs a capability, and forwards a mutation (rewriting Origin) only with the page capability. */
4
+ import type {ServerWebSocket} from 'bun';
4
5
  import {randomUUID} from 'node:crypto';
5
6
  import {spawn} from 'node:child_process';
6
7
  import {lstat,readFile,readdir,realpath,rename,unlink,writeFile,open as openFile} from 'node:fs/promises';
@@ -8,6 +9,7 @@ import {dirname,join} from 'node:path';
8
9
  import {fileURLToPath} from 'node:url';
9
10
  import {acquireClaim,alive,openFingerprint,readRecord,releaseClaim,running,smallJson,type RecordFile} from './open.ts';
10
11
  import {capabilityHeader,openKeyHeader,openNonceHeader,sameSecret} from './open-protocol.ts';
12
+ import {DEFAULT_CLOSE_GRACE_MS,LIVE_PATH} from './live-lifecycle.ts';
11
13
  export const defaultFrontPort=4318; // Foreground `review <dir>` keeps 4317.
12
14
  interface FrontRecord {schema:'rig-review-front/1';origin:string;port:number;nonce:string;fingerprint:string;pid:number}
13
15
  interface FrontRequest {schema:'rig-review-front-request/1';control:string;request:string;record:string;port:number;nonce:string;fingerprint:string;idleMs:number}
@@ -24,7 +26,7 @@ async function frontAlive(row:FrontRecord):Promise<boolean>{try{const response=a
24
26
  /** Ensure this state directory's front on `port`; reuse a verified live one. A front from another tool
25
27
  * build is ours (verified nonce) and is replaced. Any other listener is FRONT_PORT_BUSY, never a fallback. */
26
28
  export async function ensureFront(options:{control:string;port:number;fingerprint:string;idleMs?:number}):Promise<string>{
27
- const {control,port,fingerprint}=options,name=frontName(port),recordPath=join(control,name+'.json'),nonce=randomUUID(),deadline=performance.now()+20000,idleMs=options.idleMs??30*60*1000;
29
+ const {control,port,fingerprint}=options,name=frontName(port),recordPath=join(control,name+'.json'),nonce=randomUUID(),deadline=performance.now()+20000,idleMs=options.idleMs??DEFAULT_CLOSE_GRACE_MS;
28
30
  const reuse=async()=>{const row=await readFront(recordPath,port);if(!row||!await frontAlive(row))return null;if(row.fingerprint===fingerprint)return row;
29
31
  try{process.kill(row.pid,'SIGTERM');}catch{}for(let n=0;n<100&&await frontAlive(row);n++)await sleep(30);return null;};
30
32
  const ready=await reuse();if(ready)return ready.origin;
@@ -42,10 +44,11 @@ export async function ensureFront(options:{control:string;port:number;fingerprin
42
44
  throw new Error(`FRONT_TIMEOUT: front did not become ready; log ${log}`);
43
45
  }finally{if(child&&!handedOff&&child.exitCode===null&&child.signalCode===null)child.kill('SIGTERM');await releaseClaim(join(control,name+'.claim'),nonce);if(request)await unlink(request).catch(e=>{if(e.code!=='ENOENT')throw e;});}
44
46
  }
45
- interface Route {mutation:boolean;limit:number;timeoutMs:number;control:boolean}
47
+ interface Route {mutation:boolean;limit:number;timeoutMs:number;control:boolean;live?:boolean}
46
48
  /** Closed allowlist per method. Agent control endpoints, open-status and anything unlisted are refused. */
47
49
  export function frontRoute(mode:'single'|'compare',method:string,path:string):Route|null{
48
50
  const read=method==='GET'||method==='HEAD',get:Route={mutation:false,limit:0,timeoutMs:30000,control:false};
51
+ if(path===LIVE_PATH)return method==='GET'?{...get,live:true}:null;
49
52
  if(['/','/index.html','/main.js','/styles.css','/api/access'].includes(path))return read?get:null;
50
53
  if(path==='/api/control/config')return method==='GET'?{...get,control:true}:null;
51
54
  if(['/api/control/register','/api/control/poll','/api/control/ack','/api/control/close'].includes(path))return method==='POST'?{mutation:true,limit:16384,timeoutMs:10000,control:true}:null;
@@ -55,27 +58,23 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
55
58
  const reads=mode==='single'?['/api/review','/review-reference']:['/api/compare','/api/compare/reference-frames','/compare-reference'];
56
59
  if(reads.includes(path))return read?get:null;
57
60
  if((mode==='single'?/^\/assets\/[^/]/:/^\/compare-assets\/(a|b)\/[^/]/).test(path))return read?get:null;
58
- // Apply · Rebuild (single only): status, one typed request, a job's status and its served scratch build.
59
- if(mode==='single'&&path==='/api/rebuild')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
60
- // #166 (single only): the applied records, and undo of the last one ({from}).
61
- if(mode==='single'&&path==='/api/rebuild/history')return read?get:null;
62
- if(mode==='single'&&path==='/api/rebuild/undo')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
63
- if(mode==='single'&&(/^\/api\/rebuild\/[a-f0-9]{64}$/.test(path)||/^\/rebuild\/[a-f0-9]{64}\/[^/]/.test(path)))return read?get:null;
64
- // #173 (single only): a density strip (2–5 patches, 320 KiB), its status, a candidate's job, its served build, and closing it.
65
- if(mode==='single'&&path==='/api/density-strip')return read?get:method==='POST'?{mutation:true,limit:320*1024,timeoutMs:30000,control:false}:null;
66
- if(mode==='single'&&path==='/api/density-strip/close')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
67
- if(mode==='single'&&(/^\/api\/density-strip\/[a-f0-9]{64}(?:\/[a-f0-9]{64})?$/.test(path)||/^\/density-strip\/[a-f0-9]{64}\/[a-f0-9]{64}\/[^/]/.test(path)))return read?get:null;
68
- // Bones check (#109, single only): one typed request {ops, configHash}, answered in the response.
69
- if(mode==='single'&&path==='/api/bones-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:60000,control:false}:null;
70
- // Readings (#108, single only): one typed request, then its job's status.
71
- if(mode==='single'&&path==='/api/readings')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
72
- if(mode==='single'&&/^\/api\/readings\/[a-f0-9]{64}$/.test(path))return read?get:null;
73
- // Declared requirements (#113, single only): the stage's catalog, one typed request, then its job's status.
74
- if(mode==='single'&&path==='/api/requirements')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
75
- if(mode==='single'&&/^\/api\/requirements\/[a-f0-9]{64}$/.test(path))return read?get:null;
76
- // Check under this world (#112, single only): one typed request {build, schedule}, then its job's status.
77
- if(mode==='single'&&path==='/api/environment-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
78
- if(mode==='single'&&/^\/api\/environment-check\/[a-f0-9]{64}$/.test(path))return read?get:null;
61
+ // Apply · Rebuild and producer checks: un-prefixed in single mode, side-scoped (/api/compare/(a|b)/*, /compare-rebuild/(a|b)/*) in compare mode (#234).
62
+ const toolPath=mode==='compare'?path.replace(/^\/api\/compare\/(?:a|b)(?=\/)/,'/api').replace(/^\/compare-rebuild\/(?:a|b)\//,'/rebuild/').replace(/^\/compare-density-strip\/(?:a|b)\//,'/density-strip/'):path;
63
+ if(mode==='compare'&&toolPath===path)return null;
64
+ if(toolPath==='/api/rebuild')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
65
+ if(toolPath==='/api/rebuild/history')return read?get:null;
66
+ if(toolPath==='/api/rebuild/undo')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
67
+ if(/^\/api\/rebuild\/[a-f0-9]{64}$/.test(toolPath)||/^\/rebuild\/[a-f0-9]{64}\/[^/]/.test(toolPath))return read?get:null;
68
+ if(toolPath==='/api/density-strip')return read?get:method==='POST'?{mutation:true,limit:320*1024,timeoutMs:30000,control:false}:null;
69
+ if(toolPath==='/api/density-strip/close')return method==='POST'?{mutation:true,limit:1024,timeoutMs:30000,control:false}:null;
70
+ if(/^\/api\/density-strip\/[a-f0-9]{64}(?:\/[a-f0-9]{64})?$/.test(toolPath)||/^\/density-strip\/[a-f0-9]{64}\/[a-f0-9]{64}\/[^/]/.test(toolPath))return read?get:null;
71
+ if(toolPath==='/api/bones-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:60000,control:false}:null;
72
+ if(toolPath==='/api/readings')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
73
+ if(/^\/api\/readings\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
74
+ if(toolPath==='/api/requirements')return read?get:method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
75
+ if(/^\/api\/requirements\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
76
+ if(toolPath==='/api/environment-check')return method==='POST'?{mutation:true,limit:64*1024,timeoutMs:30000,control:false}:null;
77
+ if(/^\/api\/environment-check\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
79
78
  return null;
80
79
  }
81
80
  async function boundedBody(req:Request,limit:number,timeoutMs=10000):Promise<ArrayBuffer>{
@@ -91,9 +90,15 @@ async function instanceRecord(control:string,key:string):Promise<RecordFile|null
91
90
  const upstreamFailure:Record<number,string>={400:'FRONT_UPSTREAM_REJECTED',403:'FRONT_UPSTREAM_FORBIDDEN',404:'FRONT_UPSTREAM_NOT_FOUND',405:'FRONT_UPSTREAM_METHOD',409:'FRONT_UPSTREAM_CONFLICT'};
92
91
  const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
93
92
  export const maximumUpstreamStreams=32;
93
+ interface FrontLiveRelay {upstream:WebSocket;client:ServerWebSocket<FrontLiveRelay>|null}
94
94
  export function startFront(options:{control:string;port:number;nonce:string;fingerprint:string}){
95
95
  const origin=`http://127.0.0.1:${options.port}`;let active=0,last=performance.now();
96
- const server=Bun.serve({hostname:'127.0.0.1',port:options.port,async fetch(req){
96
+ const server=Bun.serve<FrontLiveRelay>({hostname:'127.0.0.1',port:options.port,websocket:{
97
+ idleTimeout:0,
98
+ open(ws){last=performance.now();ws.data.client=ws;if(ws.data.upstream.readyState!==WebSocket.OPEN){try{ws.close();}catch{}return;}try{ws.send('live');}catch{}},
99
+ message(ws,msg){last=performance.now();try{ws.data.upstream.send(msg);}catch{}},
100
+ close(ws){last=performance.now();try{ws.data.upstream.close();}catch{}},
101
+ },async fetch(req,srv){
97
102
  last=performance.now();
98
103
  try{
99
104
  const url=new URL(req.url);if(url.origin!==origin)return refuse('FRONT_LOOPBACK_REQUIRED',403);
@@ -104,6 +109,33 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
104
109
  const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
105
110
  const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
106
111
  const landing=path==='/'||path==='/index.html';if(!landing&&url.search)return refuse('FRONT_QUERY_REFUSED',400);
112
+ if(route.live){
113
+ if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
114
+ if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
115
+ const upstreamWs=new WebSocket(record.origin.replace(/^http/,'ws')+path,{headers:{[openNonceHeader]:record.nonce}} as unknown as string[]);
116
+ const outcome=await new Promise<'ok'|'replaced'|'timeout'|'closed'>(resolve=>{
117
+ const timer=setTimeout(()=>resolve('timeout'),route.timeoutMs);
118
+ const finish=(result:'ok'|'replaced'|'timeout'|'closed')=>{clearTimeout(timer);resolve(result);};
119
+ req.signal.addEventListener('abort',()=>finish('closed'),{once:true});
120
+ upstreamWs.onmessage=ev=>{try{const msg=JSON.parse(String(ev.data)) as {type?:string;key?:string};finish(msg?.type==='live'&&msg?.key===key?'ok':'replaced');}catch{finish('replaced');}};
121
+ upstreamWs.onerror=()=>finish('closed');
122
+ upstreamWs.onclose=()=>finish('closed');
123
+ });
124
+ if(outcome!=='ok'){
125
+ try{upstreamWs.close();}catch{}
126
+ if(outcome==='timeout'&&!req.signal.aborted)return refuse('FRONT_UPSTREAM_TIMEOUT',504);
127
+ if(outcome==='replaced')return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);
128
+ const probe=await fetch(record.origin+'/api/access',{headers:{[openNonceHeader]:record.nonce},redirect:'manual',signal:AbortSignal.timeout(1500)}).catch(()=>null);
129
+ void probe?.body?.cancel().catch(()=>{});
130
+ return probe?refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
131
+ }
132
+ const relay:FrontLiveRelay={upstream:upstreamWs,client:null};
133
+ upstreamWs.onmessage=ev=>{try{relay.client?.send(String(ev.data));}catch{}};
134
+ upstreamWs.onerror=()=>{try{relay.client?.close();}catch{}};
135
+ upstreamWs.onclose=()=>{try{relay.client?.close();}catch{}};
136
+ if(!srv.upgrade(req,{data:relay,headers:noStore})){try{upstreamWs.close();}catch{}return refuse('FRONT_UPGRADE_FAILED',400);}
137
+ return undefined as unknown as Response;
138
+ }
107
139
  let body:ArrayBuffer|undefined;
108
140
  if(route.mutation){
109
141
  // Never rewrite Origin without this instance's capability; the worker compares it again itself.
@@ -124,7 +156,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
124
156
  if(upstream.status>=400&&upstream.status!==416){void upstream.body?.cancel().catch(()=>{});release();const code=upstreamFailure[upstream.status];return refuse(code??'FRONT_UPSTREAM_FAILED',code?upstream.status:502);}
125
157
  const out=new Headers();for(const name of responseHeaders){const value=upstream.headers.get(name);if(value!==null)out.set(name,value);}
126
158
  if(!upstream.body||req.method==='HEAD'){void upstream.body?.cancel().catch(()=>{});release();return new Response(null,{status:upstream.status,headers:out});}
127
- clearTimeout(timer);const reader=upstream.body.getReader();
159
+ if(timer)clearTimeout(timer);const reader=upstream.body.getReader();
128
160
  // Media/model streams stay counted until finished or cancelled by the browser.
129
161
  const stream=new ReadableStream<Uint8Array>({async pull(controller){try{const next=await reader.read();if(next.done){controller.close();release();}else controller.enqueue(next.value);}catch(error){release();controller.error(error);}},cancel(reason){release();abort.abort();return reader.cancel(reason).catch(()=>{});}});
130
162
  return new Response(stream,{status:upstream.status,headers:out});
@@ -132,7 +164,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
132
164
  }});
133
165
  return {origin,stop:()=>server.stop(true),idleMs:()=>performance.now()-last,active:()=>active};
134
166
  }
135
- async function liveInstances(control:string):Promise<boolean>{for(const name of await readdir(control))if(/^[a-f0-9]{64}\.json$/.test(name)){const row=await readRecord(join(control,name),name.slice(0,64)).catch(()=>null);if(row&&running(row.pid))return true;}return false;}
167
+ async function liveInstances(control:string):Promise<boolean>{for(const name of await readdir(control)){if(/^[a-f0-9]{64}\.claim$/.test(name))return true;if(/^[a-f0-9]{64}\.json$/.test(name)){const row=await readRecord(join(control,name),name.slice(0,64)).catch(()=>null);if(row&&running(row.pid))return true;}}return false;}
136
168
  export async function runFront(requestPath:string):Promise<void>{
137
169
  const spec=await smallJson(requestPath) as FrontRequest;if(spec?.schema!=='rig-review-front-request/1'||!uuid.test(spec.nonce??'')||!hex64.test(spec.fingerprint??'')||!Number.isSafeInteger(spec.port)||spec.port<1||spec.port>65535||!Number.isSafeInteger(spec.idleMs)||spec.idleMs<100)throw new Error('front: invalid request');
138
170
  const control=await realpath(spec.control);if(dirname(await realpath(requestPath))!==control||spec.request!==requestPath||spec.record!==join(control,frontName(spec.port)+'.json'))throw new Error('front: invalid state locations');
@@ -141,8 +173,8 @@ export async function runFront(requestPath:string):Promise<void>{
141
173
  try{front=startFront({control,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint});}catch(error){if((error as NodeJS.ErrnoException).code==='EADDRINUSE'||/in use/i.test(error instanceof Error?error.message:''))throw new Error(`FRONT_PORT_BUSY: 127.0.0.1:${spec.port}`);throw error;}
142
174
  const record:FrontRecord={schema:'rig-review-front/1',origin:front.origin,port:spec.port,nonce:spec.nonce,fingerprint:spec.fingerprint,pid:process.pid},tmp=spec.record+'.'+spec.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.record);
143
175
  await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
144
- let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;clearInterval(timer);front.stop();const current=await readFront(spec.record,spec.port).catch(()=>null);if(current?.nonce===spec.nonce)await unlink(spec.record).catch(()=>{});process.exit(0);};
176
+ let stopped=false;const stop=async(reason:string)=>{if(stopped)return;stopped=true;clearInterval(timer);front.stop();const current=await readFront(spec.record,spec.port).catch(()=>null);if(current?.nonce===spec.nonce)await unlink(spec.record).catch(()=>{});console.log(`review front: exiting — ${reason}.`);process.exit(0);};
145
177
  // Idle exit only once no request arrived for idleMs and no live worker record remains.
146
- const timer=setInterval(()=>{if(front.idleMs()>=spec.idleMs&&front.active()===0)void liveInstances(control).then(live=>{if(!live)void stop();}).catch(()=>{});},Math.min(1000,spec.idleMs));
147
- process.on('SIGTERM',()=>{void stop();});process.on('SIGINT',()=>{void stop();});
178
+ const timer=setInterval(()=>{if(front.idleMs()>=spec.idleMs&&front.active()===0)void liveInstances(control).then(live=>{if(!live)void stop(`no live review instances remain (idle for ${spec.idleMs}ms)`)}).catch(()=>{});},Math.min(250,spec.idleMs));
179
+ process.on('SIGTERM',()=>{void stop('received SIGTERM');});process.on('SIGINT',()=>{void stop('received SIGINT');});
148
180
  }
@@ -0,0 +1,351 @@
1
+ /**
2
+ * Live review window WebSocket connection tracking and idle/close server lifecycle (#236).
3
+ *
4
+ * Each open review or compare page holds one WebSocket (`GET /api/live`) connection open.
5
+ * - Why WebSocket: all managed `open` instances share the front origin (`127.0.0.1:4318`). Browsers cap HTTP/1.1
6
+ * connections at six per host, so holding one HTTP stream per tab starves requests at six windows. WebSockets sit
7
+ * outside the six-connection HTTP/1.1 pool and notify `onclose` immediately on drop so the client can reconnect
8
+ * within a couple hundred milliseconds rather than waiting on browser stream retry timers.
9
+ * - Reload vs. close: closing a tab or killing the browser (`SIGKILL`) tears down the TCP socket immediately without
10
+ * needing `pagehide` or `sendBeacon`. A reload tears down the old socket and immediately issues document/API requests
11
+ * followed by a new `/api/live` WebSocket well within `DEFAULT_CLOSE_GRACE_MS` (measured 40-slot + video reload p50
12
+ * 127.3ms, max 148.9ms; dual 40-slot compare p50 83.6ms, max 106.0ms -> 3,000ms grace gives >20x headroom, and
13
+ * incoming requests during the grace window reset the zero-connection clock).
14
+ * - Second tab: each tab holds its own `/api/live` WebSocket (`connections === 2`); closing one leaves `connections === 1`.
15
+ * - Quiet socket & machine sleep / background tab freeze: `idleTimeout` is disabled (`0`) and periodic server keepalive
16
+ * frames keep quiet sockets open; liveness is bound to the kernel loopback TCP socket rather than client JS timer
17
+ * heartbeats, and wall-clock sleep jumps reset any pending countdown on wake.
18
+ * - Unopened server: if no page ever connects within `DEFAULT_UNOPENED_TIMEOUT_MS` (30 minutes, 1,800,000ms), or after
19
+ * an `open` reuse re-arms a windowless worker, the server exits 0.
20
+ * - In-flight work: an active HTTP request or producer Apply/rebuild delays exit until it finishes, then re-checks the
21
+ * live connection count before flushing state, stopping the listener, printing one reason line, and exiting 0.
22
+ */
23
+ import type { ServerWebSocket, WebSocketHandler } from 'bun';
24
+
25
+ export const LIVE_PATH = '/api/live';
26
+
27
+ /**
28
+ * Measured heavy-package full browser reload (40-slot + multi-PNG + 313 frames + video reference):
29
+ * single review p50 127.34ms / max 148.90ms; dual 40-slot compare p50 83.60ms / max 106.01ms.
30
+ * 3,000ms provides >20x headroom over the heaviest reload while closing promptly after the last window shuts.
31
+ */
32
+ export const DEFAULT_CLOSE_GRACE_MS = 3_000;
33
+
34
+ /**
35
+ * Time a server that has not received a `/api/live` page connection waits before exiting (30 minutes).
36
+ * Preserves links handed from `rig-review open` or foreground servers to a human who opens them minutes later,
37
+ * while reaping unopened servers before the 45-minute stale threshold.
38
+ */
39
+ export const DEFAULT_UNOPENED_TIMEOUT_MS = 30 * 60 * 1_000;
40
+
41
+ /** Wall-clock jump beyond the check interval that indicates machine sleep / process pause. */
42
+ const SLEEP_JUMP_THRESHOLD_MS = 2_000;
43
+ const KEEPALIVE_INTERVAL_MS = 5_000;
44
+
45
+ export type LiveExitReason = 'last-window-closed' | 'unopened-timeout';
46
+
47
+ export interface LiveExitInfo {
48
+ reason: LiveExitReason;
49
+ line: string;
50
+ }
51
+
52
+ export interface LiveSocketData {
53
+ key?: string;
54
+ release?: () => void;
55
+ }
56
+
57
+ export interface UpgradableServer {
58
+ upgrade(req: Request, options: { data: LiveSocketData; headers?: HeadersInit }): boolean;
59
+ }
60
+
61
+ export interface LiveLifecycleOptions {
62
+ label?: string;
63
+ graceMs?: number;
64
+ unopenedTimeoutMs?: number;
65
+ busy?: () => boolean;
66
+ flush?: () => void | Promise<void>;
67
+ stopServer?: () => void | Promise<void>;
68
+ onClose?: (info: LiveExitInfo) => void | Promise<void>;
69
+ exitOnClose?: boolean;
70
+ log?: (line: string) => void;
71
+ now?: () => number;
72
+ }
73
+
74
+ export interface LiveLifecycle {
75
+ upgrade(req: Request, srv: UpgradableServer, baseHeaders: Record<string, string>, key?: string): Response | undefined;
76
+ readonly websocket: WebSocketHandler<LiveSocketData>;
77
+ attachSocket(): { close(): void };
78
+ dropSockets(): number;
79
+ onRequestStart(pathname: string): void;
80
+ onRequestEnd(pathname: string): void;
81
+ rearmUnopened(): boolean;
82
+ stop(): void;
83
+ readonly connections: number;
84
+ readonly everConnected: boolean;
85
+ readonly exited: Promise<LiveExitInfo | null>;
86
+ }
87
+
88
+ function isIgnoredActivityPath(pathname: string): boolean {
89
+ return pathname === LIVE_PATH;
90
+ }
91
+
92
+ export function formatExitLine(label: string, reason: LiveExitReason, graceMs: number, unopenedTimeoutMs: number): string {
93
+ if (reason === 'last-window-closed') {
94
+ return `${label}: exiting — last review window closed (0 live connections for ${graceMs}ms).`;
95
+ }
96
+ return `${label}: exiting — no review window connected within ${unopenedTimeoutMs}ms.`;
97
+ }
98
+
99
+ export function createLiveLifecycle(options: LiveLifecycleOptions = {}): LiveLifecycle {
100
+ const label = options.label ?? 'review';
101
+ const graceMs = Math.max(10, options.graceMs ?? DEFAULT_CLOSE_GRACE_MS);
102
+ const unopenedTimeoutMs = Math.max(10, options.unopenedTimeoutMs ?? DEFAULT_UNOPENED_TIMEOUT_MS);
103
+ const now = options.now ?? (() => Date.now());
104
+ const log = options.log ?? ((line: string) => console.log(line));
105
+
106
+ let connections = 0;
107
+ let everConnected = false;
108
+ let inFlightRequests = 0;
109
+ let startedAt = now();
110
+ let zeroSince: number | null = null;
111
+ let stopped = false;
112
+ let closing = false;
113
+ let waitingForInFlight = false;
114
+ const activeSockets = new Set<ServerWebSocket<LiveSocketData>>();
115
+
116
+ let resolveExited!: (info: LiveExitInfo | null) => void;
117
+ const exited = new Promise<LiveExitInfo | null>(resolve => {
118
+ resolveExited = resolve;
119
+ });
120
+
121
+ const checkIntervalMs = Math.min(50, Math.max(10, Math.floor(Math.min(graceMs, unopenedTimeoutMs) / 4)));
122
+ let lastTickAt = now();
123
+
124
+ function isBusy(): boolean {
125
+ return inFlightRequests > 0 || Boolean(options.busy?.());
126
+ }
127
+
128
+ async function triggerExit(reason: LiveExitReason): Promise<void> {
129
+ if (stopped || closing) return;
130
+ closing = true;
131
+ const line = formatExitLine(label, reason, graceMs, unopenedTimeoutMs);
132
+ const info: LiveExitInfo = { reason, line };
133
+ try {
134
+ await options.flush?.();
135
+ } catch { /* best-effort state flush */ }
136
+ // Re-check connection count if a page connected or new work arrived while flushing.
137
+ if (connections > 0 || isBusy()) {
138
+ closing = false;
139
+ if (connections > 0) zeroSince = null;
140
+ return;
141
+ }
142
+ clearInterval(timer);
143
+ clearInterval(keepaliveTimer);
144
+ try {
145
+ await options.onClose?.(info);
146
+ } catch { /* best-effort close hook */ }
147
+ try {
148
+ await options.stopServer?.();
149
+ } catch { /* best-effort server stop */ }
150
+ stopped = true;
151
+ log(line);
152
+ resolveExited(info);
153
+ if (options.exitOnClose) {
154
+ process.exit(0);
155
+ }
156
+ }
157
+
158
+ function check(): void {
159
+ if (stopped || closing) return;
160
+ if (connections > 0) {
161
+ zeroSince = null;
162
+ waitingForInFlight = false;
163
+ return;
164
+ }
165
+ const current = now();
166
+ let reason: LiveExitReason | null = null;
167
+ if (everConnected) {
168
+ if (zeroSince === null) zeroSince = current;
169
+ if (current - zeroSince >= graceMs) reason = 'last-window-closed';
170
+ } else {
171
+ if (current - startedAt >= unopenedTimeoutMs) reason = 'unopened-timeout';
172
+ }
173
+ if (!reason) return;
174
+ if (isBusy()) {
175
+ waitingForInFlight = true;
176
+ return;
177
+ }
178
+ if (waitingForInFlight) {
179
+ waitingForInFlight = false;
180
+ // Re-check connection count right after in-flight work completes.
181
+ if (connections > 0) {
182
+ zeroSince = null;
183
+ return;
184
+ }
185
+ }
186
+ void triggerExit(reason);
187
+ }
188
+
189
+ const timer = setInterval(() => {
190
+ if (stopped || closing) return;
191
+ const current = now();
192
+ const delta = current - lastTickAt;
193
+ lastTickAt = current;
194
+ if (delta > checkIntervalMs + SLEEP_JUMP_THRESHOLD_MS) {
195
+ if (zeroSince !== null) zeroSince = current;
196
+ if (!everConnected) startedAt = current;
197
+ return;
198
+ }
199
+ check();
200
+ }, checkIntervalMs);
201
+ timer.unref?.();
202
+
203
+ const keepaliveTimer = setInterval(() => {
204
+ if (stopped || closing || activeSockets.size === 0) return;
205
+ for (const ws of [...activeSockets]) {
206
+ try {
207
+ ws.send('keepalive');
208
+ ws.ping?.();
209
+ } catch {
210
+ ws.data?.release?.();
211
+ }
212
+ }
213
+ }, KEEPALIVE_INTERVAL_MS);
214
+ keepaliveTimer.unref?.();
215
+
216
+ function attachSocket(): { close(): void } {
217
+ connections += 1;
218
+ everConnected = true;
219
+ zeroSince = null;
220
+ waitingForInFlight = false;
221
+ let released = false;
222
+ return {
223
+ close() {
224
+ if (released) return;
225
+ released = true;
226
+ connections = Math.max(0, connections - 1);
227
+ if (connections === 0 && !stopped && !closing) {
228
+ zeroSince = now();
229
+ check();
230
+ }
231
+ },
232
+ };
233
+ }
234
+
235
+ function upgrade(req: Request, srv: UpgradableServer, baseHeaders: Record<string, string>, key?: string): Response | undefined {
236
+ if (stopped || closing) {
237
+ return new Response('Server is closing', { status: 503, headers: baseHeaders });
238
+ }
239
+ if (req.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
240
+ return new Response('WebSocket upgrade required', { status: 426, headers: baseHeaders });
241
+ }
242
+ const upgraded = srv.upgrade(req, {
243
+ data: { key },
244
+ headers: baseHeaders,
245
+ });
246
+ if (upgraded) return undefined;
247
+ return new Response('WebSocket upgrade failed', { status: 400, headers: baseHeaders });
248
+ }
249
+
250
+ const websocket: WebSocketHandler<LiveSocketData> = {
251
+ idleTimeout: 0,
252
+ open(ws) {
253
+ if (stopped || closing) {
254
+ try { ws.close(); } catch {}
255
+ return;
256
+ }
257
+ const handle = attachSocket();
258
+ activeSockets.add(ws);
259
+ ws.data = {
260
+ ...ws.data,
261
+ release: () => {
262
+ activeSockets.delete(ws);
263
+ handle.close();
264
+ },
265
+ };
266
+ try {
267
+ ws.send(ws.data.key ? JSON.stringify({ type: 'live', key: ws.data.key }) : 'live');
268
+ } catch {
269
+ ws.data.release?.();
270
+ }
271
+ },
272
+ message() {},
273
+ close(ws) {
274
+ ws.data?.release?.();
275
+ },
276
+ };
277
+
278
+ function dropSockets(): number {
279
+ const list = [...activeSockets];
280
+ for (const ws of list) {
281
+ try {
282
+ ws.close(1012, 'dropped');
283
+ } catch {}
284
+ ws.data?.release?.();
285
+ }
286
+ return list.length;
287
+ }
288
+
289
+ function onRequestStart(pathname: string): void {
290
+ if (isIgnoredActivityPath(pathname)) return;
291
+ inFlightRequests += 1;
292
+ if (stopped || closing) return;
293
+ const current = now();
294
+ if (everConnected && connections === 0) {
295
+ zeroSince = current;
296
+ } else if (!everConnected) {
297
+ startedAt = current;
298
+ }
299
+ }
300
+
301
+ function onRequestEnd(pathname: string): void {
302
+ if (isIgnoredActivityPath(pathname)) return;
303
+ inFlightRequests = Math.max(0, inFlightRequests - 1);
304
+ if (inFlightRequests === 0 && !stopped && !closing) {
305
+ check();
306
+ }
307
+ }
308
+
309
+ function rearmUnopened(): boolean {
310
+ if (stopped || closing) return false;
311
+ const current = now();
312
+ startedAt = current;
313
+ waitingForInFlight = false;
314
+ if (connections === 0) {
315
+ everConnected = false;
316
+ zeroSince = null;
317
+ }
318
+ return true;
319
+ }
320
+
321
+ function stop(): void {
322
+ if (stopped) return;
323
+ stopped = true;
324
+ closing = false;
325
+ clearInterval(timer);
326
+ clearInterval(keepaliveTimer);
327
+ for (const ws of [...activeSockets]) {
328
+ try { ws.close(); } catch {}
329
+ }
330
+ activeSockets.clear();
331
+ resolveExited(null);
332
+ }
333
+
334
+ return {
335
+ upgrade,
336
+ websocket,
337
+ attachSocket,
338
+ dropSockets,
339
+ onRequestStart,
340
+ onRequestEnd,
341
+ rearmUnopened,
342
+ stop,
343
+ get connections() {
344
+ return connections;
345
+ },
346
+ get everConnected() {
347
+ return everConnected;
348
+ },
349
+ exited,
350
+ };
351
+ }
package/src/open.ts CHANGED
@@ -18,6 +18,7 @@ import {ensureFront,frontPort} from './front.ts';
18
18
  import {playPackagePath} from './versions.ts';
19
19
  import {HandoffError,HANDOFF_FLAGS,isBuildRoot,type HandoffFlags,type HandoffRecord} from './handoff.ts';
20
20
  import {stateDirInside,stateRoots} from './state-dir.ts';
21
+ import {DEFAULT_UNOPENED_TIMEOUT_MS} from './live-lifecycle.ts';
21
22
  /** #149: an opened rig-parts build check package — its canonical path and the handoff record (or the refusal line). */
22
23
  export interface BuildOpen {package:string;handoff:HandoffRecord|null;reason:string|null}
23
24
  /** The stderr diagnostic for {@link BuildOpen}: the package opened, then how the config was found, its package-relative path and full SHA-256. */
@@ -33,7 +34,7 @@ export type OpenPackage=({mode:'single';p:ReviewPackage;inputs:OpenInputs;conten
33
34
  /** Private 0600 record. `capability` is the 256-bit page write capability, handed out only in the printed `#cap=` fragment. */
34
35
  export interface RecordFile extends OpenIdentity {schema:'rig-review-open-instance/1';pid:number;origin:string;mode:'single'|'compare';capability:string;controlToken?:string}
35
36
  /** `cwd` is the launcher's working directory: the worker runs in the state directory, so Apply · Rebuild looks for the producer from here after the package's own directories. */
36
- interface WorkerRequest {schema:'rig-review-open-request/1';inputs:OpenInputs;identity:OpenIdentity;stateDir:string;registry:string;request:string;idleMs:number;controlToken?:string;cwd?:string}
37
+ interface WorkerRequest {schema:'rig-review-open-request/1';inputs:OpenInputs;identity:OpenIdentity;stateDir:string;registry:string;request:string;idleMs:number;graceMs?:number;controlToken?:string;cwd?:string}
37
38
  const appRoot=fileURLToPath(new URL('..',import.meta.url));
38
39
  const digest=(value:unknown)=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
39
40
  const sleep=(ms:number)=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));
@@ -105,7 +106,7 @@ async function openRefusal(error:unknown,inputs:OpenInputs):Promise<unknown>{
105
106
  }
106
107
  /** Managed is the default: the printed URL goes through the one loopback front (127.0.0.1:4318, or
107
108
  * RIG_REVIEW_FRONT_PORT) so browser storage keeps one origin across reopens. `direct` keeps the worker's own port. */
108
- export async function openReview(inputs:OpenInputs,options:{stateDir?:string;idleMs?:number;direct?:boolean;frontPort?:number;frontIdleMs?:number}={}):Promise<{url:string;reused:boolean;nonce:string;inputs:OpenInputs;selection:AnimationSelection|null;direct:boolean;build:BuildOpen|null}>{
109
+ export async function openReview(inputs:OpenInputs,options:{stateDir?:string;idleMs?:number;graceMs?:number;direct?:boolean;frontPort?:number;frontIdleMs?:number}={}):Promise<{url:string;reused:boolean;nonce:string;inputs:OpenInputs;selection:AnimationSelection|null;direct:boolean;build:BuildOpen|null}>{
109
110
  const direct=options.direct??inputs.direct??false,port=direct?0:frontPort(options.frontPort);
110
111
  for(const path of [inputs.input,...(inputs.compare!==undefined?[inputs.compare]:[])])await assertOpenInput(path);
111
112
  if(inputs.compare!==undefined&&!inputs.reference)throw new Error('OPEN_REFERENCE_REQUIRED: compare: explicit --reference required');
@@ -115,13 +116,13 @@ export async function openReview(inputs:OpenInputs,options:{stateDir?:string;idl
115
116
  const stateDir=await canonicalDestination(resolve(options.stateDir??defaultStateDir())),roots=p.mode==='single'?stateRoots(p.p):[...stateRoots(p.p.a),...stateRoots(p.p.b)];
116
117
  const inside=stateDirInside(stateDir,roots);if(inside)throw new Error(`OPEN_STATE_INSIDE_PACKAGE ${inside.kind}: the review state directory must be outside input packages; it is inside the ${inside.kind}; set RIG_REVIEW_STATE_DIR outside it`);
117
118
  const control=join(stateDir,'open');await mkdir(control,{recursive:true,mode:0o700});const canonicalControl=await realpath(control);if((await lstat(control)).isSymbolicLink())throw new Error('open.state: control directory cannot be a symlink');
118
- const worker=await ensureWorker(p,key,fingerprint,stateDir,canonicalControl,options.idleMs??30*60*1000);
119
+ const worker=await ensureWorker(p,key,fingerprint,stateDir,canonicalControl,options.idleMs??DEFAULT_UNOPENED_TIMEOUT_MS,options.graceMs);
119
120
  const url=direct?openUrl(worker.row):openUrl(worker.row,await ensureFront({control:canonicalControl,port,fingerprint,idleMs:options.frontIdleMs}));
120
121
  // #149: the check package of a rig-parts build root says which package it opened and which config the handoff took.
121
122
  const build=p.mode==='single'&&basename(p.p.root)==='check'&&await isBuildRoot(dirname(p.p.root))?{package:p.p.root,handoff:p.p.reviewedSource.handoff??null,reason:p.p.handoffReason}:null;
122
123
  return {url,reused:worker.reused,nonce:worker.row.nonce,inputs:p.inputs,selection:p.selection,direct,build};
123
124
  }
124
- async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir:string,canonicalControl:string,idleMs:number):Promise<{row:RecordFile;reused:boolean}>{
125
+ async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir:string,canonicalControl:string,idleMs:number,graceMs?:number):Promise<{row:RecordFile;reused:boolean}>{
125
126
  const registry=join(canonicalControl,key+'.json'),claim=join(canonicalControl,key+'.claim'),nonce=randomUUID(),deadline=performance.now()+20000;
126
127
  const reuse=async()=>{const row=await readRecord(registry,key);return row&&row.fingerprint===fingerprint&&row.contentHash===p.contentHash&&row.mode===p.mode&&await alive(row)?row:null;};
127
128
  const ready=await reuse();if(ready)return {row:ready,reused:true};
@@ -130,7 +131,7 @@ async function ensureWorker(p:OpenPackage,key:string,fingerprint:string,stateDir
130
131
  try{
131
132
  const row=await reuse();if(row)return {row,reused:true};
132
133
  const identity:OpenIdentity={key,contentHash:p.contentHash,nonce,fingerprint};request=join(canonicalControl,`${key}.${nonce}.request.json`);const log=join(canonicalControl,`${key}.${nonce}.log`);
133
- const spec:WorkerRequest={schema:'rig-review-open-request/1',inputs:p.inputs,identity,stateDir,registry,request,idleMs,cwd:process.cwd(),...(p.inputs.control?{controlToken:randomUUID()}:{} )};await writeFile(request,JSON.stringify(spec),{mode:0o600,flag:'wx'});
134
+ const spec:WorkerRequest={schema:'rig-review-open-request/1',inputs:p.inputs,identity,stateDir,registry,request,idleMs,...(graceMs!==undefined?{graceMs}:{}),cwd:process.cwd(),...(p.inputs.control?{controlToken:randomUUID()}:{} )};await writeFile(request,JSON.stringify(spec),{mode:0o600,flag:'wx'});
134
135
  const logHandle=await openFile(log,'a',0o600);let child;try{child=spawn(process.execPath,[join(appRoot,'src/open-worker.ts'),request],{cwd:canonicalControl,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});spawned=child;child.unref();}finally{await logHandle.close();}
135
136
  let exited:string|undefined;child.on('error',error=>{exited=error.message;});child.on('exit',(code,signal)=>{exited=`exit ${code} ${signal??''}`;});
136
137
  while(performance.now()<deadline){const record=await reuse();if(record){handedOff=true;return {row:record,reused:false};}if(exited)throw new Error(`OPEN_START: ${exited}; worker log ${log}`);await sleep(30);}throw new Error(`OPEN_TIMEOUT: worker did not become ready; log ${log}`);
@@ -142,13 +143,14 @@ export async function runOpenWorker(requestPath:string):Promise<void>{
142
143
  const p=await loadOpenPackage(spec.inputs),fingerprint=await openFingerprint();if(fingerprint!==spec.identity.fingerprint||openKey(p,fingerprint)!==spec.identity.key||p.contentHash!==spec.identity.contentHash)throw new Error('open worker: inputs changed before startup');
143
144
  if(spec.inputs.control&&(!spec.controlToken||!/^[a-f0-9-]{36}$/.test(spec.controlToken)))throw new Error('open control: invalid private capability');
144
145
  // The worker mints its own page capability; it lives only in this process and the private record.
145
- const capability=randomBytes(32).toString('hex');let last=performance.now();const options={port:0,stateDir:spec.stateDir,open:spec.identity,capability,activity:()=>{last=performance.now();},...(spec.inputs.control?{control:{token:spec.controlToken!,instanceKey:spec.identity.key}}:{})};
146
+ const removeRecord=async()=>{const current=await readRecord(spec.registry,spec.identity.key);if(current?.nonce===spec.identity.nonce)await unlink(spec.registry).catch(()=>{});};
147
+ const capability=randomBytes(32).toString('hex');const options={port:0,stateDir:spec.stateDir,open:spec.identity,capability,unopenedTimeoutMs:spec.idleMs,...(spec.graceMs!==undefined?{graceMs:spec.graceMs}:{}),exitOnClose:true,onClose:removeRecord,...(spec.inputs.control?{control:{token:spec.controlToken!,instanceKey:spec.identity.key}}:{})};
146
148
  const server=p.mode==='single'?await startServer(p.p,{...options,initialAnimation:p.selection?.name,...(typeof spec.cwd==='string'&&isAbsolute(spec.cwd)?{cwd:spec.cwd}:{})}):await startCompareServer(p.p,options);
147
149
  const check=()=>p.mode==='single'?assertReviewUnchanged(p.p):assertCompareUnchanged(p.p);
148
150
  await check();const record:RecordFile={schema:'rig-review-open-instance/1',...spec.identity,pid:process.pid,origin:`http://127.0.0.1:${server.port}`,mode:p.mode,capability,...(spec.inputs.control?{controlToken:spec.controlToken}:{})};const tmp=spec.registry+'.'+spec.identity.nonce+'.tmp';await writeFile(tmp,JSON.stringify(record),{mode:0o600,flag:'wx'});await rename(tmp,spec.registry);
149
151
  await unlink(requestPath).catch(e=>{if(e.code!=='ENOENT')throw e;});
150
- let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;server.stop(true);clearInterval(timer);const current=await readRecord(spec.registry,spec.identity.key);if(current?.nonce===spec.identity.nonce)await unlink(spec.registry).catch(()=>{});};
151
- const timer=setInterval(()=>{if(performance.now()-last>=spec.idleMs)void stop();},Math.min(1000,spec.idleMs));process.on('SIGTERM',()=>{void stop();});process.on('SIGINT',()=>{void stop();});
152
+ let stopped=false;const stop=async(signal:string)=>{if(stopped)return;stopped=true;await removeRecord();server.stop(true);console.log(`review: exiting — received ${signal}.`);process.exit(0);};
153
+ process.on('SIGTERM',()=>{void stop('SIGTERM');});process.on('SIGINT',()=>{void stop('SIGINT');});
152
154
  }
153
155
 
154
156
  /** Read/control an already running, explicitly opted-in exact binding. Never starts a worker. */