rig-review 0.16.0 → 0.17.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/docs/WORKFLOWS.md +12 -5
- package/package.json +1 -1
- package/src/bones-check.ts +1 -1
- package/src/cli.ts +5 -2
- package/src/compare-server.ts +27 -5
- package/src/front.ts +44 -8
- package/src/live-lifecycle.ts +351 -0
- package/src/open.ts +10 -8
- package/src/rebuild.ts +1 -1
- package/src/server.ts +28 -5
- package/web/compare.ts +2 -1
- package/web/live-connection.ts +110 -0
- package/web/main.ts +2 -0
package/docs/WORKFLOWS.md
CHANGED
|
@@ -160,10 +160,17 @@ rig-review strip /absolute/output --reference-video /absolute/original.mp4 --ani
|
|
|
160
160
|
Only tool-owned instances with matching content, canonical input locations, tool
|
|
161
161
|
fingerprint and a private capability handshake are reused. The URL hash is
|
|
162
162
|
checked before serving the app; a stale link never selects another instance's
|
|
163
|
-
package. Input hashes are freshly computed, not trusted from mtime caches.
|
|
164
|
-
open
|
|
165
|
-
|
|
166
|
-
|
|
163
|
+
package. Input hashes are freshly computed, not trusted from mtime caches. In both
|
|
164
|
+
`open` and foreground `review` / `review compare`, each open window holds a live
|
|
165
|
+
WebSocket connection (`/api/live`); once the last window closes and stays at zero connections
|
|
166
|
+
for the 3-second grace period, or if no window ever connects within 30 minutes
|
|
167
|
+
(reusing a windowless worker via `open` gives it a fresh 30-minute unopened window),
|
|
168
|
+
the server finishes any in-flight request or Apply, flushes state, prints one line
|
|
169
|
+
stating why it exited, and exits `0`. A browser that unloads a background tab to
|
|
170
|
+
save memory looks the same as a closed tab, so the server stops; saved feedback
|
|
171
|
+
survives and `open` brings it back. Their
|
|
172
|
+
private registry, requests and logs live beside feedback under
|
|
173
|
+
`~/.local/state/rig-c-review/open/`; nothing is written into supplied folders. `RIG_REVIEW_STATE_DIR` selects another state root
|
|
167
174
|
outside all input packages, judged by its canonical location (symlinks in the path
|
|
168
175
|
and its existing ancestors resolved). Existing foreground review commands still work.
|
|
169
176
|
|
|
@@ -216,7 +223,7 @@ request, and refuses an unknown, expired or replaced instance by name
|
|
|
216
223
|
(`FRONT_INSTANCE_UNKNOWN`, `FRONT_INSTANCE_EXPIRED`, `FRONT_INSTANCE_REPLACED`).
|
|
217
224
|
Worker error text is not passed through; failures become named `FRONT_*` codes.
|
|
218
225
|
Package assets keep their `sandbox` CSP through the front. It never reads packages.
|
|
219
|
-
Idle fronts exit after
|
|
226
|
+
Idle fronts exit after the 3-second grace period once no live instance remains.
|
|
220
227
|
|
|
221
228
|
If another listener holds the front port, `open` fails with
|
|
222
229
|
`FRONT_PORT_BUSY: 127.0.0.1:4318 is held by another listener; use --direct` and
|
package/package.json
CHANGED
package/src/bones-check.ts
CHANGED
|
@@ -89,7 +89,7 @@ export function createBonesCheck(p: ReviewPackage, options: { stateDir: string;
|
|
|
89
89
|
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
|
-
return { run };
|
|
92
|
+
return { run, running: () => running };
|
|
93
93
|
}
|
|
94
94
|
|
|
95
95
|
/** `propose --from-config` on the scratch config, or the line naming the missing source painting. */
|
package/src/cli.ts
CHANGED
|
@@ -112,7 +112,9 @@ export async function main(args:string[],options:{stateDir?:string}={}){
|
|
|
112
112
|
const p=await loadCompare({a,b,reference,animation});
|
|
113
113
|
if(command==='feedback'){printFeedback(await readFeedbackCompareSession(p,options.stateDir));return;}
|
|
114
114
|
if(command==='check'){console.log(`Comparison valid: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nAnimation: ${animation}\nReference SHA-256: ${p.response.reference.sha256}\nPlayback: two compiled models present`);return;}
|
|
115
|
-
const capability=randomBytes(32).toString('hex'),server=await startCompareServer(p,{port,stateDir:options.stateDir,capability
|
|
115
|
+
const capability=randomBytes(32).toString('hex'),server=await startCompareServer(p,{port,stateDir:options.stateDir,capability,exitOnClose:true});
|
|
116
|
+
const stop=(sig:string)=>{server.stop(true);console.log(`review compare: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
|
|
117
|
+
console.log(`Compare ready: http://127.0.0.1:${server.port}/#cap=${capability}\nComparison: ${p.response.title}\nSource SHA-256: ${p.response.sourceHash}\nPress Ctrl+C to stop.`);return;
|
|
116
118
|
}
|
|
117
119
|
const input=args.shift();if(!input)throw new Error(usage);let port=4317;let checkpoint:string|undefined,reference:string|undefined,compare:string|undefined,animation:string|undefined;const handoff:OpenInputs={input};
|
|
118
120
|
while(args.length){const flag=args.shift();const value=args.shift();if(!value)throw new Error(`Missing value for ${flag}`);if(handoffOption(flag!)){handoff[handoffOption(flag!)!]=value;continue;}if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0…65535');}else if(flag==='--checkpoint')checkpoint=value;else if(flag==='--reference')reference=value;else if(flag==='--compare')compare=value;else if(flag==='--animation')animation=value;else throw new Error(`Unknown option ${flag}\n${usage}`);}
|
|
@@ -123,7 +125,8 @@ export async function main(args:string[],options:{stateDir?:string}={}){
|
|
|
123
125
|
const selection=animation!==undefined||fromReport?selectAnimation([{label:'single',catalog:p.feedbackCatalog,report:p.report}],animation,true):null;const initialAnimation=selection?.name;if(command==='feedback'){const saved=await readFeedbackSession(p,options.stateDir);await assertReviewUnchanged(p);printFeedback(saved);return;}if(command==='check'){console.log(`Package valid: ${p.manifest.title}\nRevision: ${p.manifest.revision}\nSource SHA-256: ${p.sourceHash}\nDeclared files: ${p.files.size}\nPlayback: ${p.manifest.model?'compiled model present':'unavailable (no model)'}`);return;}
|
|
124
126
|
if(checkpoint&&!p.manifest.checkpoints.some(v=>v.id===checkpoint))throw new Error(`Unknown checkpoint ${checkpoint}`);
|
|
125
127
|
// Foreground serving uses the same `#cap=` fragment handoff as open: the printed link alone can submit.
|
|
126
|
-
const capability=randomBytes(32).toString('hex'),server=await startServer(p,{port,stateDir:options.stateDir,initialAnimation,capability});const url=new URL(`http://127.0.0.1:${server.port}/`);if(checkpoint)url.searchParams.set('checkpoint',checkpoint);url.hash='cap='+capability;
|
|
128
|
+
const capability=randomBytes(32).toString('hex'),server=await startServer(p,{port,stateDir:options.stateDir,initialAnimation,capability,exitOnClose:true});const url=new URL(`http://127.0.0.1:${server.port}/`);if(checkpoint)url.searchParams.set('checkpoint',checkpoint);url.hash='cap='+capability;
|
|
129
|
+
const stop=(sig:string)=>{server.stop(true);console.log(`review: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
|
|
127
130
|
if(fromReport&&selection)console.error(animationDiagnostic(selection));
|
|
128
131
|
console.log(`Review ready: ${url}\nPackage: ${p.manifest.title} (${p.manifest.revision})\nSource SHA-256: ${p.sourceHash}\nPress Ctrl+C to stop.`);
|
|
129
132
|
}
|
package/src/compare-server.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {createControlServer,type ControlIdentity} from './control-server.ts';
|
|
2
|
-
import {openGate,staleOpenStatus,accessGate,openNonceGate,stampOpen,type OpenIdentity} from './open-protocol.ts';
|
|
2
|
+
import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
|
|
3
3
|
import { readFile } from 'node:fs/promises';
|
|
4
4
|
import { appRoot, buildWeb } from './build.ts';
|
|
5
5
|
import { packagePath, safeFile } from './manifest.ts';
|
|
@@ -8,6 +8,7 @@ import { serveReference } from './reference.ts';
|
|
|
8
8
|
import {referenceFrameIndex} from './reference-frame-index.ts';
|
|
9
9
|
import { exportCompareStrip, stripJson } from './strip-export.ts';
|
|
10
10
|
import { readCompareSession, saveCompareSession } from './compare-session.ts';
|
|
11
|
+
import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
|
|
11
12
|
|
|
12
13
|
const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
|
|
13
14
|
const json=(value:unknown,status=200)=>Response.json(value,{status,headers});
|
|
@@ -29,16 +30,33 @@ function serveAsset(req:Request,path:string):Response{
|
|
|
29
30
|
return new Response(req.method==='HEAD'?null:file,{headers:{...assetHeaders,'Content-Length':String(size)}});
|
|
30
31
|
}
|
|
31
32
|
/** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it. */
|
|
32
|
-
export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string}={}){
|
|
33
|
+
export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
|
|
33
34
|
const bundle=await buildWeb('compare');
|
|
34
35
|
const frames=referenceFrameIndex(p.referencePath,p.response.binding.reference.sha256,p.response.sourceHash);
|
|
35
36
|
const control=options.control?createControlServer({identity:options.control,sourceHash:p.response.sourceHash,mode:'compare',unchanged:()=>assertCompareUnchanged(p),activity:options.activity}):null;
|
|
36
|
-
|
|
37
|
+
let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
|
|
38
|
+
const live=createLiveLifecycle({
|
|
39
|
+
label:'review compare',
|
|
40
|
+
graceMs:options.graceMs,
|
|
41
|
+
unopenedTimeoutMs:options.unopenedTimeoutMs,
|
|
42
|
+
exitOnClose:options.exitOnClose,
|
|
43
|
+
onClose:options.onClose,
|
|
44
|
+
log:options.log,
|
|
45
|
+
stopServer:()=>{rawStop?.(true);},
|
|
46
|
+
});
|
|
47
|
+
const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try{
|
|
37
48
|
const url=new URL(req.url),origin=`http://127.0.0.1:${port}`;
|
|
38
49
|
if(url.origin!==origin)return json({error:'Loopback host required'},403);
|
|
39
50
|
const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!control);if(refused)return refused;
|
|
51
|
+
if(req.method==='GET'&&url.pathname===LIVE_PATH){
|
|
52
|
+
const fromFront=Boolean(options.open&&sameSecret(req.headers.get(openNonceHeader),options.open.nonce)&&req.headers.get('origin')===null);
|
|
53
|
+
if(!fromFront&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
|
|
54
|
+
options.activity?.();return live.upgrade(req,srv,headers,options.open?.key);
|
|
55
|
+
}
|
|
56
|
+
live.onRequestStart(url.pathname);
|
|
57
|
+
try {
|
|
40
58
|
const controlled=await control?.(req,origin);if(controlled)return controlled;
|
|
41
|
-
options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}}return gate;}
|
|
59
|
+
options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
|
|
42
60
|
if(req.method==='PUT'&&url.pathname==='/api/compare/session'){
|
|
43
61
|
if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
|
|
44
62
|
return json(await saveCompareSession(p,await bodyJson(req),options.stateDir));
|
|
@@ -58,6 +76,10 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
|
|
|
58
76
|
if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
|
|
59
77
|
if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/compare.css'),{headers:{...headers,'Content-Type':'text/css'}});
|
|
60
78
|
return json({error:'Not found'},404);
|
|
79
|
+
} finally { live.onRequestEnd(url.pathname); }
|
|
61
80
|
}catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
|
|
62
|
-
|
|
81
|
+
const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:live.websocket,async fetch(req,srv){const res=await handle(req,srv.port,srv);if(!res)return undefined as unknown as Response;return stampOpen(req,res,options.open);}});
|
|
82
|
+
rawStop=server.stop.bind(server);
|
|
83
|
+
server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
|
|
84
|
+
return Object.assign(server,{live});
|
|
63
85
|
}
|
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??
|
|
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;
|
|
@@ -91,9 +94,15 @@ async function instanceRecord(control:string,key:string):Promise<RecordFile|null
|
|
|
91
94
|
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
95
|
const responseHeaders=['content-type','content-length','content-range','accept-ranges','content-disposition','cache-control','content-security-policy','x-content-type-options','referrer-policy'];
|
|
93
96
|
export const maximumUpstreamStreams=32;
|
|
97
|
+
interface FrontLiveRelay {upstream:WebSocket;client:ServerWebSocket<FrontLiveRelay>|null}
|
|
94
98
|
export function startFront(options:{control:string;port:number;nonce:string;fingerprint:string}){
|
|
95
99
|
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,
|
|
100
|
+
const server=Bun.serve<FrontLiveRelay>({hostname:'127.0.0.1',port:options.port,websocket:{
|
|
101
|
+
idleTimeout:0,
|
|
102
|
+
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{}},
|
|
103
|
+
message(ws,msg){last=performance.now();try{ws.data.upstream.send(msg);}catch{}},
|
|
104
|
+
close(ws){last=performance.now();try{ws.data.upstream.close();}catch{}},
|
|
105
|
+
},async fetch(req,srv){
|
|
97
106
|
last=performance.now();
|
|
98
107
|
try{
|
|
99
108
|
const url=new URL(req.url);if(url.origin!==origin)return refuse('FRONT_LOOPBACK_REQUIRED',403);
|
|
@@ -104,6 +113,33 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
|
|
|
104
113
|
const record=await instanceRecord(options.control,key);if(!record)return refuse('FRONT_INSTANCE_UNKNOWN: reopen with rig-review open',404);
|
|
105
114
|
const route=frontRoute(record.mode,req.method,path);if(!route)return refuse('FRONT_ROUTE_REFUSED',404);
|
|
106
115
|
const landing=path==='/'||path==='/index.html';if(!landing&&url.search)return refuse('FRONT_QUERY_REFUSED',400);
|
|
116
|
+
if(route.live){
|
|
117
|
+
if(sentOrigin!==origin)return refuse('FRONT_SAME_ORIGIN_REQUIRED',403);
|
|
118
|
+
if(req.headers.get('upgrade')?.toLowerCase()!=='websocket')return refuse('FRONT_UPGRADE_REQUIRED',426);
|
|
119
|
+
const upstreamWs=new WebSocket(record.origin.replace(/^http/,'ws')+path,{headers:{[openNonceHeader]:record.nonce}} as unknown as string[]);
|
|
120
|
+
const outcome=await new Promise<'ok'|'replaced'|'timeout'|'closed'>(resolve=>{
|
|
121
|
+
const timer=setTimeout(()=>resolve('timeout'),route.timeoutMs);
|
|
122
|
+
const finish=(result:'ok'|'replaced'|'timeout'|'closed')=>{clearTimeout(timer);resolve(result);};
|
|
123
|
+
req.signal.addEventListener('abort',()=>finish('closed'),{once:true});
|
|
124
|
+
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');}};
|
|
125
|
+
upstreamWs.onerror=()=>finish('closed');
|
|
126
|
+
upstreamWs.onclose=()=>finish('closed');
|
|
127
|
+
});
|
|
128
|
+
if(outcome!=='ok'){
|
|
129
|
+
try{upstreamWs.close();}catch{}
|
|
130
|
+
if(outcome==='timeout'&&!req.signal.aborted)return refuse('FRONT_UPSTREAM_TIMEOUT',504);
|
|
131
|
+
if(outcome==='replaced')return refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410);
|
|
132
|
+
const probe=await fetch(record.origin+'/api/access',{headers:{[openNonceHeader]:record.nonce},redirect:'manual',signal:AbortSignal.timeout(1500)}).catch(()=>null);
|
|
133
|
+
void probe?.body?.cancel().catch(()=>{});
|
|
134
|
+
return probe?refuse('FRONT_INSTANCE_REPLACED: reopen with rig-review open',410):refuse('FRONT_INSTANCE_EXPIRED: reopen with rig-review open',410);
|
|
135
|
+
}
|
|
136
|
+
const relay:FrontLiveRelay={upstream:upstreamWs,client:null};
|
|
137
|
+
upstreamWs.onmessage=ev=>{try{relay.client?.send(String(ev.data));}catch{}};
|
|
138
|
+
upstreamWs.onerror=()=>{try{relay.client?.close();}catch{}};
|
|
139
|
+
upstreamWs.onclose=()=>{try{relay.client?.close();}catch{}};
|
|
140
|
+
if(!srv.upgrade(req,{data:relay,headers:noStore})){try{upstreamWs.close();}catch{}return refuse('FRONT_UPGRADE_FAILED',400);}
|
|
141
|
+
return undefined as unknown as Response;
|
|
142
|
+
}
|
|
107
143
|
let body:ArrayBuffer|undefined;
|
|
108
144
|
if(route.mutation){
|
|
109
145
|
// Never rewrite Origin without this instance's capability; the worker compares it again itself.
|
|
@@ -124,7 +160,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
|
|
|
124
160
|
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
161
|
const out=new Headers();for(const name of responseHeaders){const value=upstream.headers.get(name);if(value!==null)out.set(name,value);}
|
|
126
162
|
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();
|
|
163
|
+
if(timer)clearTimeout(timer);const reader=upstream.body.getReader();
|
|
128
164
|
// Media/model streams stay counted until finished or cancelled by the browser.
|
|
129
165
|
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
166
|
return new Response(stream,{status:upstream.status,headers:out});
|
|
@@ -132,7 +168,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
|
|
|
132
168
|
}});
|
|
133
169
|
return {origin,stop:()=>server.stop(true),idleMs:()=>performance.now()-last,active:()=>active};
|
|
134
170
|
}
|
|
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;}
|
|
171
|
+
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
172
|
export async function runFront(requestPath:string):Promise<void>{
|
|
137
173
|
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
174
|
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 +177,8 @@ export async function runFront(requestPath:string):Promise<void>{
|
|
|
141
177
|
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
178
|
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
179
|
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);};
|
|
180
|
+
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
181
|
// 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()
|
|
147
|
-
process.on('SIGTERM',()=>{void stop();});process.on('SIGINT',()=>{void stop();});
|
|
182
|
+
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));
|
|
183
|
+
process.on('SIGTERM',()=>{void stop('received SIGTERM');});process.on('SIGINT',()=>{void stop('received SIGINT');});
|
|
148
184
|
}
|
|
@@ -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??
|
|
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
|
|
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);
|
|
151
|
-
|
|
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. */
|
package/src/rebuild.ts
CHANGED
|
@@ -1524,5 +1524,5 @@ export function createRebuilds(p: ReviewPackage, options: RebuildOptions) {
|
|
|
1524
1524
|
return safeFile(await realpath(join(rebuildDir(options.stateDir, p.sourceHash, id), 'build')), packagePath(name));
|
|
1525
1525
|
}
|
|
1526
1526
|
|
|
1527
|
-
return { describe, start, read, file, running: () => running, baseline: settledBaseline, inspectedCheck: settledInspectedCheck, latest, undo, history, startStrip, readStrip, stripJob, closeStrip, stripFile };
|
|
1527
|
+
return { describe, start, read, file, running: () => running, busy: () => busy() !== null, baseline: settledBaseline, inspectedCheck: settledInspectedCheck, latest, undo, history, startStrip, readStrip, stripJob, closeStrip, stripFile };
|
|
1528
1528
|
}
|
package/src/server.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { appRoot, buildWeb } from './build.ts';
|
|
|
4
4
|
import { packagePath, safeFile, type ReviewPackage } from './manifest.ts';
|
|
5
5
|
import { exportReviewStrip, stripJson } from './strip-export.ts';
|
|
6
6
|
import {assertReviewUnchanged,referenceBinding,selectedReference,safeSelectedReference,serveReference} from './reference.ts';
|
|
7
|
-
import {openGate,staleOpenStatus,accessGate,openNonceGate,stampOpen,type OpenIdentity} from './open-protocol.ts';
|
|
7
|
+
import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
|
|
8
8
|
import { readSession, saveSession } from './session.ts';
|
|
9
9
|
import { createRebuilds, RebuildError } from './rebuild.ts';
|
|
10
10
|
import { DENSITY_STRIP_LIMIT } from './density-strip.ts';
|
|
@@ -14,6 +14,7 @@ import { BONES_CHECK_LIMIT, createBonesCheck } from './bones-check.ts';
|
|
|
14
14
|
import { createRequirementsCheck } from './requirements-run.ts';
|
|
15
15
|
import { REQUIREMENTS_LIMIT, RequirementsError } from './requirements.ts';
|
|
16
16
|
import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError } from './environment-check.ts';
|
|
17
|
+
import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
|
|
17
18
|
import { homedir } from 'node:os';
|
|
18
19
|
import { join } from 'node:path';
|
|
19
20
|
const headers={ 'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
|
|
@@ -29,7 +30,7 @@ async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceed
|
|
|
29
30
|
}
|
|
30
31
|
/** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it.
|
|
31
32
|
* `cwd` is where the producer is looked for after the package's own directories (review's working directory by default). */
|
|
32
|
-
export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number}={}){
|
|
33
|
+
export async function startServer(p:ReviewPackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;initialAnimation?:string;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
|
|
33
34
|
const bundle=await buildWeb();
|
|
34
35
|
const unchanged=()=>assertReviewUnchanged(p);
|
|
35
36
|
const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review'),starts=[p.root,options.cwd??process.cwd()];
|
|
@@ -43,12 +44,30 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
|
|
|
43
44
|
// Check under this world (#112): the exported schedule written into scratch; the installed producer's check --environment reads it.
|
|
44
45
|
const environmentCheck=createEnvironmentCheck(p,{stateDir,starts,unchanged,latest:rebuilds.latest});
|
|
45
46
|
const control=options.control?createControlServer({identity:options.control,sourceHash:p.sourceHash,mode:'single',unchanged,activity:options.activity}):null;
|
|
46
|
-
|
|
47
|
+
let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
|
|
48
|
+
const live=createLiveLifecycle({
|
|
49
|
+
label:'review',
|
|
50
|
+
graceMs:options.graceMs,
|
|
51
|
+
unopenedTimeoutMs:options.unopenedTimeoutMs,
|
|
52
|
+
exitOnClose:options.exitOnClose,
|
|
53
|
+
onClose:options.onClose,
|
|
54
|
+
log:options.log,
|
|
55
|
+
busy:()=>Boolean(rebuilds.busy()||readings.running()||requirements.running()||environmentCheck.running()||bonesCheck.running()),
|
|
56
|
+
stopServer:()=>{rawStop?.(true);},
|
|
57
|
+
});
|
|
58
|
+
const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try {
|
|
47
59
|
const url=new URL(req.url);const origin=`http://127.0.0.1:${port}`;
|
|
48
60
|
if(url.origin!==origin)return json({error:'Loopback host required'},403);
|
|
49
61
|
const refused=openNonceGate(req,options.open)??accessGate(req,options.capability,!!control);if(refused)return refused;
|
|
62
|
+
if(req.method==='GET'&&url.pathname===LIVE_PATH){
|
|
63
|
+
const fromFront=Boolean(options.open&&sameSecret(req.headers.get(openNonceHeader),options.open.nonce)&&req.headers.get('origin')===null);
|
|
64
|
+
if(!fromFront&&req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
|
|
65
|
+
options.activity?.();return live.upgrade(req,srv,headers,options.open?.key);
|
|
66
|
+
}
|
|
67
|
+
live.onRequestStart(url.pathname);
|
|
68
|
+
try {
|
|
50
69
|
const controlled=await control?.(req,origin);if(controlled)return controlled;
|
|
51
|
-
options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}}return gate;}
|
|
70
|
+
options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await unchanged();}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
|
|
52
71
|
if(req.method==='PUT'&&url.pathname==='/api/session'){
|
|
53
72
|
if(req.headers.get('origin')!==origin)return json({error:'Same-origin Origin required'},403);
|
|
54
73
|
const input=await bodyJson(req);await unchanged();return json(await saveSession(p,input,options.stateDir));
|
|
@@ -148,6 +167,10 @@ export async function startServer(p:ReviewPackage,options:{port?:number;stateDir
|
|
|
148
167
|
if(url.pathname==='/'||url.pathname==='/index.html')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/index.html'),{headers:{...headers,'Content-Type':'text/html; charset=utf-8'}});
|
|
149
168
|
if(url.pathname==='/styles.css')return new Response(req.method==='HEAD'?null:await readFile(appRoot+'web/styles.css'),{headers:{...headers,'Content-Type':'text/css'}});
|
|
150
169
|
return json({error:'Not found'},404);
|
|
170
|
+
} finally { live.onRequestEnd(url.pathname); }
|
|
151
171
|
}catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
|
|
152
|
-
|
|
172
|
+
const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:live.websocket,async fetch(req,srv){const res=await handle(req,srv.port,srv);if(!res)return undefined as unknown as Response;return stampOpen(req,res,options.open);}});
|
|
173
|
+
rawStop=server.stop.bind(server);
|
|
174
|
+
server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
|
|
175
|
+
return Object.assign(server,{live});
|
|
153
176
|
}
|
package/web/compare.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {bindAppearance,bindPan,bindStageLayout,bindInspectorTabs,syncStageLayout
|
|
|
17
17
|
import {RigOverlays} from './rig-overlays.ts';
|
|
18
18
|
import {bindWorkspaceUI,type WorkspaceUI} from './workspace-ui.ts';
|
|
19
19
|
import {connectControl} from './control.ts';
|
|
20
|
+
import {connectLiveWindow} from './live-connection.ts';
|
|
20
21
|
import {pageInstanceAccess,readOnlyReason} from './instance-access.ts';
|
|
21
22
|
import {controlComparison,type ControlCommand,type ControlInspection,type ControlView} from '../src/control.ts';
|
|
22
23
|
import {pairEligibility,type InputState,type PairDomain} from '../src/comparison-eligibility.ts';
|
|
@@ -56,7 +57,7 @@ const layers={images:true,mesh:false,bones:false,meshOpacity:.65};
|
|
|
56
57
|
let stripBusy = false;
|
|
57
58
|
let persistence:PersistenceConnection|null=null,submittedBaseline:CompareSession|null=null,draftConflict=false;
|
|
58
59
|
// First, before any URL use: take the `#cap=` handoff into memory/session storage and strip it.
|
|
59
|
-
const access=pageInstanceAccess();let readOnly:string|null=null;
|
|
60
|
+
const access=pageInstanceAccess();connectLiveWindow(access);let readOnly:string|null=null;
|
|
60
61
|
/** Whether this instance serves agent control (`/api/access`); a plain open is never probed for it (#164). */
|
|
61
62
|
let controlServed=true;
|
|
62
63
|
let referenceFrames:VideoInfo|null=null;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { LIVE_PATH } from '../src/live-lifecycle.ts';
|
|
2
|
+
import type { InstanceAccess } from './instance-access.ts';
|
|
3
|
+
|
|
4
|
+
const RECONNECT_DELAY_MS = 200;
|
|
5
|
+
const MAX_RECONNECT_ATTEMPTS = 20;
|
|
6
|
+
|
|
7
|
+
function toWebSocketUrl(routePath: string): string {
|
|
8
|
+
if (/^wss?:\/\//i.test(routePath)) return routePath;
|
|
9
|
+
if (/^https?:\/\//i.test(routePath)) return routePath.replace(/^http/i, 'ws');
|
|
10
|
+
const base = typeof location !== 'undefined' ? location.href : 'http://127.0.0.1/';
|
|
11
|
+
const resolved = new URL(routePath, base);
|
|
12
|
+
resolved.protocol = resolved.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
13
|
+
return resolved.href;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Holds one persistent WebSocket connection (`/api/live`) per open review or compare window (#236).
|
|
18
|
+
* WebSockets sit outside the browser's six-connection HTTP/1.1 pool per origin (shared by all managed front
|
|
19
|
+
* instances on `127.0.0.1:4318`) and report drops immediately via `onclose`/`onerror` so the window can
|
|
20
|
+
* reconnect well inside the 3-second close grace period. Closing a tab or killing the browser (`SIGKILL`)
|
|
21
|
+
* tears down the loopback TCP socket in the OS kernel immediately without `pagehide` or `sendBeacon`.
|
|
22
|
+
*/
|
|
23
|
+
export function connectLiveWindow(access: Pick<InstanceAccess, 'route'>): () => void {
|
|
24
|
+
if (typeof WebSocket === 'undefined') return () => {};
|
|
25
|
+
const wsUrl = toWebSocketUrl(access.route(LIVE_PATH));
|
|
26
|
+
let socket: WebSocket | null = null;
|
|
27
|
+
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
28
|
+
let attempts = 0;
|
|
29
|
+
let disposed = false;
|
|
30
|
+
|
|
31
|
+
const clearReconnect = () => {
|
|
32
|
+
if (reconnectTimer !== null) {
|
|
33
|
+
clearTimeout(reconnectTimer);
|
|
34
|
+
reconnectTimer = null;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const scheduleReconnect = () => {
|
|
39
|
+
if (disposed || reconnectTimer !== null) return;
|
|
40
|
+
if (attempts >= MAX_RECONNECT_ATTEMPTS) return;
|
|
41
|
+
attempts += 1;
|
|
42
|
+
reconnectTimer = setTimeout(open, RECONNECT_DELAY_MS);
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const open = () => {
|
|
46
|
+
if (disposed) return;
|
|
47
|
+
clearReconnect();
|
|
48
|
+
const prev = socket;
|
|
49
|
+
socket = null;
|
|
50
|
+
if (prev) {
|
|
51
|
+
prev.onopen = null;
|
|
52
|
+
prev.onclose = null;
|
|
53
|
+
prev.onerror = null;
|
|
54
|
+
try {
|
|
55
|
+
prev.close();
|
|
56
|
+
} catch {}
|
|
57
|
+
}
|
|
58
|
+
let ws: WebSocket;
|
|
59
|
+
try {
|
|
60
|
+
ws = new WebSocket(wsUrl);
|
|
61
|
+
} catch {
|
|
62
|
+
scheduleReconnect();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
socket = ws;
|
|
66
|
+
let disconnected = false;
|
|
67
|
+
const onDisconnect = () => {
|
|
68
|
+
if (disposed || disconnected || socket !== ws) return;
|
|
69
|
+
disconnected = true;
|
|
70
|
+
scheduleReconnect();
|
|
71
|
+
};
|
|
72
|
+
ws.onopen = () => {
|
|
73
|
+
if (disposed || socket !== ws) return;
|
|
74
|
+
attempts = 0;
|
|
75
|
+
};
|
|
76
|
+
ws.onerror = onDisconnect;
|
|
77
|
+
ws.onclose = onDisconnect;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const onVisibilityChange = () => {
|
|
81
|
+
if (disposed || document.visibilityState !== 'visible') return;
|
|
82
|
+
if (!socket || socket.readyState === WebSocket.CLOSED || socket.readyState === WebSocket.CLOSING) {
|
|
83
|
+
attempts = 0;
|
|
84
|
+
open();
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
reconnectTimer = setTimeout(open, 0);
|
|
89
|
+
if (typeof document !== 'undefined') {
|
|
90
|
+
document.addEventListener('visibilitychange', onVisibilityChange);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return () => {
|
|
94
|
+
disposed = true;
|
|
95
|
+
clearReconnect();
|
|
96
|
+
if (typeof document !== 'undefined') {
|
|
97
|
+
document.removeEventListener('visibilitychange', onVisibilityChange);
|
|
98
|
+
}
|
|
99
|
+
const prev = socket;
|
|
100
|
+
socket = null;
|
|
101
|
+
if (prev) {
|
|
102
|
+
prev.onopen = null;
|
|
103
|
+
prev.onclose = null;
|
|
104
|
+
prev.onerror = null;
|
|
105
|
+
try {
|
|
106
|
+
prev.close();
|
|
107
|
+
} catch {}
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
package/web/main.ts
CHANGED
|
@@ -32,6 +32,7 @@ import {chestRegionsBinding,cropWorldMapping,type CropWorldMapping} from '../src
|
|
|
32
32
|
import {bindWorkspaceUI,selectedInspector,type WorkspaceUI} from './workspace-ui.ts';
|
|
33
33
|
import {bindInspectorBlocks,activeBlocksUI,restoreActiveBlocksUI,type InspectorBlocks} from './inspector-blocks.ts';
|
|
34
34
|
import {connectControl} from './control.ts';
|
|
35
|
+
import {connectLiveWindow} from './live-connection.ts';
|
|
35
36
|
import {pageInstanceAccess,readOnlyReason} from './instance-access.ts';
|
|
36
37
|
import {controlComparison,type ControlCommand,type ControlInspection,type ControlView} from '../src/control.ts';
|
|
37
38
|
import {singleEligibility,videoReferenceAt,type InputState,type SingleLayout} from '../src/comparison-eligibility.ts';
|
|
@@ -82,6 +83,7 @@ const option = (value: string, label: string) => { const item = document.createE
|
|
|
82
83
|
const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
|
|
83
84
|
// First, before any URL use: take the `#cap=` handoff into memory/session storage and strip it.
|
|
84
85
|
const access = pageInstanceAccess();
|
|
86
|
+
connectLiveWindow(access);
|
|
85
87
|
let readOnly: string | null = null;
|
|
86
88
|
let data: ReviewResponse;
|
|
87
89
|
let session: ReviewSession;
|