@tnunamak/dalan 0.0.0-stage → 0.6.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/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {openSync,closeSync,fstatSync,readSync,constants} from 'node:fs';
|
|
2
|
+
import {createArtifactJournal,artifactBytesDigest} from './artifact-journal.mjs';
|
|
3
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
4
|
+
function inspectNative(store,params,query) {
|
|
5
|
+
const row=store.db.prepare("SELECT * FROM artifacts WHERE id=? AND request_id=? AND claim_id=? AND kind='upload'").get(query.reference,query.job,params.claimId);
|
|
6
|
+
if(!row||!Number.isSafeInteger(row.size)||row.size<0||row.size>8*1024*1024)fail('artifact_integrity_mismatch');
|
|
7
|
+
const fd=openSync(row.path,constants.O_RDONLY|constants.O_NOFOLLOW);
|
|
8
|
+
let bytes;
|
|
9
|
+
try {
|
|
10
|
+
const stat=fstatSync(fd);if(!stat.isFile()||stat.size!==row.size)fail('artifact_integrity_mismatch');
|
|
11
|
+
bytes=Buffer.alloc(row.size);let position=0;
|
|
12
|
+
while(position<bytes.length){const n=readSync(fd,bytes,position,bytes.length-position,position);if(!n)fail('artifact_integrity_mismatch');position+=n;}
|
|
13
|
+
if(fstatSync(fd).size!==row.size)fail('artifact_integrity_mismatch');
|
|
14
|
+
} finally {closeSync(fd);}
|
|
15
|
+
return {reference:row.id,size:row.size,sha256:artifactBytesDigest(bytes),
|
|
16
|
+
chunkSha256:query.offset===undefined?undefined:artifactBytesDigest(bytes.subarray(query.offset,query.offset+query.chunkSize))};
|
|
17
|
+
}
|
|
18
|
+
export function protocolArtifactChunk(store,workspace,params,ctx) {
|
|
19
|
+
const {requestId,claimId,subject,worker,artifactId,offset,base64,connectionId=null}=params;
|
|
20
|
+
const final=params.final??false,expected=params.expected??null,expectedSize=params.expectedSize??null;
|
|
21
|
+
if(typeof final!=='boolean')fail('invalid_final');
|
|
22
|
+
return store.transaction(()=>{
|
|
23
|
+
const receipt=store.protocolMutationInTransaction(requestId,claimId,subject,worker,
|
|
24
|
+
{...ctx,operation:final?'seal':'upload',
|
|
25
|
+
args:{requestId,claimId,subject,worker,artifactId,offset,base64,final,expected,expectedSize}},()=>{
|
|
26
|
+
const value=workspace.chunkInTransaction(requestId,claimId,subject,artifactId,offset,base64,final,expected,worker,event=>{
|
|
27
|
+
if(event.duplicate)fail('artifact_exists');
|
|
28
|
+
if(final&&expectedSize!==null&&(!Number.isSafeInteger(expectedSize)||expectedSize<0||expectedSize!==event.size))
|
|
29
|
+
fail('artifact_size_mismatch');
|
|
30
|
+
const claim=store.assertClaim(requestId,claimId,subject,worker);
|
|
31
|
+
if(event.row.origin_claim_id!==claimId||event.row.origin_epoch!==claim.epoch)
|
|
32
|
+
fail('artifact_binding_mismatch');
|
|
33
|
+
const journal=createArtifactJournal({db:store.db,
|
|
34
|
+
authorize:c=>{
|
|
35
|
+
const live=store.assertClaim(c.job,c.claim,c.subject,c.worker);
|
|
36
|
+
const status=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(c.job)?.status;
|
|
37
|
+
return c.job===requestId&&c.claim===claimId&&c.subject===subject&&c.worker===worker&&
|
|
38
|
+
c.epoch===live.epoch&&status==='claimed';
|
|
39
|
+
},
|
|
40
|
+
inspect:q=>inspectNative(store,params,q)});
|
|
41
|
+
const operation=final?(event.chunkSize>0||!journal.get(requestId,artifactId)?'upload_seal':'seal'):'upload';
|
|
42
|
+
journal.record({job:requestId,artifact:artifactId,key:ctx.key,subject,worker,claim:claimId,epoch:claim.epoch,
|
|
43
|
+
operation,reference:event.reference,size:event.size,sha256:event.sha256,
|
|
44
|
+
...(operation!=='seal'?{offset:event.offset,chunkSize:event.chunkSize,chunkSha256:event.chunkSha256}:{})});
|
|
45
|
+
store.protocolEventInTransaction(requestId,final?'sealed':'uploaded',
|
|
46
|
+
{artifact_id:artifactId,reference:event.reference,size:event.size,sha256:event.sha256},claim.epoch);
|
|
47
|
+
});
|
|
48
|
+
return value;
|
|
49
|
+
},connectionId);
|
|
50
|
+
return {...receipt.value,revision:receipt.revision};
|
|
51
|
+
});
|
|
52
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
3
|
+
const text=x=>typeof x==='string'&&x.length>0&&x.length<=512;
|
|
4
|
+
function canonical(x) {
|
|
5
|
+
if(x===null||typeof x==='string'||typeof x==='boolean')return x;
|
|
6
|
+
if(typeof x==='number'&&Number.isFinite(x))return x;
|
|
7
|
+
if(Array.isArray(x))return x.map(canonical);
|
|
8
|
+
if(x&&Object.getPrototypeOf(x)===Object.prototype)return Object.fromEntries(Object.keys(x).sort().map(k=>[k,canonical(x[k])]));
|
|
9
|
+
fail('invalid_input');
|
|
10
|
+
}
|
|
11
|
+
const json=x=>JSON.stringify(canonical(x));
|
|
12
|
+
const digest=x=>createHash('sha256').update(json(x)).digest('hex');
|
|
13
|
+
function closed(x,keys) {
|
|
14
|
+
if(!x||Object.getPrototypeOf(x)!==Object.prototype||Object.keys(x).length!==keys.length||
|
|
15
|
+
keys.some(k=>!Object.hasOwn(x,k)||!text(x[k])))fail('invalid_input');
|
|
16
|
+
}
|
|
17
|
+
export function migrateProtocolDelivery(db) {
|
|
18
|
+
if(!db.isTransaction)fail('transaction_required');
|
|
19
|
+
db.exec(`
|
|
20
|
+
CREATE TABLE IF NOT EXISTS protocol_delivery_attempts (
|
|
21
|
+
delivery_id TEXT PRIMARY KEY REFERENCES durable_waiter_deliveries(delivery_id),
|
|
22
|
+
binding TEXT NOT NULL, state TEXT NOT NULL, attempt TEXT NOT NULL);
|
|
23
|
+
CREATE TABLE IF NOT EXISTS protocol_delivery_receipts (
|
|
24
|
+
job TEXT NOT NULL, principal TEXT NOT NULL, operation TEXT NOT NULL,
|
|
25
|
+
command_key TEXT NOT NULL, identity TEXT NOT NULL,
|
|
26
|
+
reply TEXT NOT NULL, PRIMARY KEY(job,principal,operation,command_key));
|
|
27
|
+
`);
|
|
28
|
+
}
|
|
29
|
+
// Private runtime interface: transport evidence is independently resolved by
|
|
30
|
+
// the injected trusted transport, never accepted from input.outcome alone.
|
|
31
|
+
export function createProtocolDeliveryDriver(store,{authorize,transport}={}) {
|
|
32
|
+
if(typeof authorize!=='function'||!transport||
|
|
33
|
+
['begin','result','reconcile'].some(k=>typeof transport[k]!=='function'))fail('callbacks_required');
|
|
34
|
+
const db=store.db;
|
|
35
|
+
function auth(job,action,authority) {
|
|
36
|
+
if(!text(job))fail('invalid_job');
|
|
37
|
+
const principal=authorize({job,action,authority});
|
|
38
|
+
if(!text(principal))fail('unauthorized');
|
|
39
|
+
store.assertProtocolAvailable(job);
|
|
40
|
+
if(!store.isProtocolJob(job))fail('protocol_required');
|
|
41
|
+
return principal;
|
|
42
|
+
}
|
|
43
|
+
function native(job,delivery) {
|
|
44
|
+
const row=db.prepare('SELECT * FROM durable_waiter_deliveries WHERE delivery_id=? AND job=?').get(delivery,job);
|
|
45
|
+
if(!row)fail('delivery_not_found');
|
|
46
|
+
const p=store.getProtocol(job);
|
|
47
|
+
if(!p||!text(p.destination))fail('invalid_destination');
|
|
48
|
+
const b={job,delivery,owner:row.owner,waiter:row.waiter,eventId:row.event_id,eventSeq:row.event_seq,
|
|
49
|
+
destination:p.destination,bodyDigest:digest(JSON.parse(row.fact))};
|
|
50
|
+
const side=db.prepare('SELECT * FROM protocol_delivery_attempts WHERE delivery_id=?').get(delivery);
|
|
51
|
+
if(side&&side.binding!==json(b))fail('delivery_binding_mismatch');
|
|
52
|
+
return {row,b,side,state:row.acknowledged_at!==null?'acknowledged':side?.state??'pending'};
|
|
53
|
+
}
|
|
54
|
+
function receipt(job,key,identity) {
|
|
55
|
+
const {principal,action}=JSON.parse(identity);
|
|
56
|
+
const r=db.prepare('SELECT identity,reply FROM protocol_delivery_receipts WHERE job=? AND principal=? AND operation=? AND command_key=?').get(job,principal,action,key);
|
|
57
|
+
if(!r)return null;
|
|
58
|
+
if(r.identity!==identity)fail('command_conflict');
|
|
59
|
+
return JSON.parse(r.reply);
|
|
60
|
+
}
|
|
61
|
+
function save(job,key,identity,reply) {
|
|
62
|
+
const {principal,action}=JSON.parse(identity);
|
|
63
|
+
db.prepare('INSERT INTO protocol_delivery_receipts VALUES(?,?,?,?,?,?)').run(job,principal,action,key,identity,json(reply));
|
|
64
|
+
return reply;
|
|
65
|
+
}
|
|
66
|
+
function prepare(job,authority,input,action) {
|
|
67
|
+
const principal=auth(job,action,authority),n=native(job,input.delivery);
|
|
68
|
+
const identity=json({job,principal,action,input,binding:n.b});
|
|
69
|
+
return {...n,principal,identity,replay:receipt(job,input.key,identity)};
|
|
70
|
+
}
|
|
71
|
+
function currentQuestion(envelope) {
|
|
72
|
+
const row=db.prepare('SELECT fact FROM durable_waiter_deliveries WHERE delivery_id=?').get(envelope.delivery);
|
|
73
|
+
const fact=JSON.parse(row.fact);
|
|
74
|
+
if(fact.type!=='questioned')return;
|
|
75
|
+
const claim=db.prepare('SELECT * FROM claims WHERE request_id=?').get(envelope.job);
|
|
76
|
+
const status=db.prepare('SELECT status FROM assignments WHERE request_id=?').get(envelope.job)?.status;
|
|
77
|
+
if(!claim||claim.epoch!==fact.epoch||claim.state!=='active'||status!=='claimed'||store.leaseExpired(claim))fail('stale_delivery_epoch');
|
|
78
|
+
}
|
|
79
|
+
async function dispatch(job,authority,input) {
|
|
80
|
+
closed(input,['key','delivery']);
|
|
81
|
+
const start=store.transaction(()=>{
|
|
82
|
+
const p=prepare(job,authority,input,'dispatch');
|
|
83
|
+
if(p.replay)return {reply:p.replay};
|
|
84
|
+
currentQuestion(p.b);
|
|
85
|
+
if(p.state==='unknown')fail('DELIVERY_UNKNOWN');
|
|
86
|
+
if(p.state!=='pending')fail('DELIVERY_STATE');
|
|
87
|
+
const attempt=randomUUID(),envelope={...p.b,attempt};
|
|
88
|
+
db.prepare('INSERT INTO protocol_delivery_attempts VALUES(?,?,?,?) ON CONFLICT(delivery_id) DO UPDATE SET binding=excluded.binding,state=excluded.state,attempt=excluded.attempt')
|
|
89
|
+
.run(input.delivery,json(p.b),'sending',attempt);
|
|
90
|
+
const reply=save(job,input.key,p.identity,{delivery:input.delivery,state:'sending'});
|
|
91
|
+
return {reply,envelope};
|
|
92
|
+
});
|
|
93
|
+
if(!start.envelope)return start.reply;
|
|
94
|
+
try {
|
|
95
|
+
// Recheck immediately before the external boundary. A concurrent owner
|
|
96
|
+
// ACK is never overwritten, and this call holds no SQLite transaction.
|
|
97
|
+
const ready=store.transaction(()=>{
|
|
98
|
+
auth(job,'dispatch',authority);
|
|
99
|
+
const p=native(job,input.delivery);
|
|
100
|
+
currentQuestion(p.b);
|
|
101
|
+
return p.state==='sending'&&p.side.attempt===start.envelope.attempt;
|
|
102
|
+
});
|
|
103
|
+
if(ready)await transport.begin(Object.freeze({...start.envelope}));
|
|
104
|
+
} catch {
|
|
105
|
+
// Once sending commits, exceptions cannot establish definitely-not-sent.
|
|
106
|
+
store.transaction(()=>{
|
|
107
|
+
const p=native(job,input.delivery);
|
|
108
|
+
if(p.state==='sending'&&p.side.attempt===start.envelope.attempt)
|
|
109
|
+
db.prepare("UPDATE protocol_delivery_attempts SET state='unknown' WHERE delivery_id=? AND attempt=? AND state='sending'").run(input.delivery,start.envelope.attempt);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return start.reply;
|
|
113
|
+
}
|
|
114
|
+
async function applyEvidence(job,authority,input,action) {
|
|
115
|
+
closed(input,['key','delivery','outcome','receipt']);
|
|
116
|
+
const allowed=action==='delivery_result'?['acknowledged','not_sent','unknown']:['found','not_found','unknown'];
|
|
117
|
+
if(!allowed.includes(input.outcome))fail('invalid_input');
|
|
118
|
+
const first=store.transaction(()=>{
|
|
119
|
+
const p=prepare(job,authority,input,action);
|
|
120
|
+
if(p.replay)return p;
|
|
121
|
+
if(!p.side)fail('DELIVERY_STATE');
|
|
122
|
+
if(p.state==='acknowledged')return p;
|
|
123
|
+
if(action==='delivery_result'&&!['sending','unknown'].includes(p.state))fail('DELIVERY_STATE');
|
|
124
|
+
if(action==='reconcile'&&p.state!=='unknown')fail('DELIVERY_STATE');
|
|
125
|
+
return p;
|
|
126
|
+
});
|
|
127
|
+
if(first.replay)return first.replay;
|
|
128
|
+
const envelope={...first.b,attempt:first.side.attempt};
|
|
129
|
+
let resolved=null;
|
|
130
|
+
if(first.state!=='acknowledged') {
|
|
131
|
+
const resolve=action==='delivery_result'?transport.result:transport.reconcile;
|
|
132
|
+
const value=await resolve.call(transport,Object.freeze({...envelope}),input.receipt);
|
|
133
|
+
resolved=value===undefined?null:canonical(value);
|
|
134
|
+
}
|
|
135
|
+
return store.transaction(()=>{
|
|
136
|
+
const p=prepare(job,authority,input,action);
|
|
137
|
+
if(p.replay)return p.replay;
|
|
138
|
+
if(!p.side||p.side.attempt!==envelope.attempt||json(p.b)!==json(first.b))fail('stale_delivery_attempt');
|
|
139
|
+
// A real owner ACK dominates an in-flight lookup, including not_sent.
|
|
140
|
+
if(p.state==='acknowledged')return save(job,input.key,p.identity,{delivery:input.delivery,state:'acknowledged'});
|
|
141
|
+
if(action==='delivery_result'&&!['sending','unknown'].includes(p.state))fail('DELIVERY_STATE');
|
|
142
|
+
if(action==='reconcile'&&p.state!=='unknown')fail('DELIVERY_STATE');
|
|
143
|
+
if(!resolved||json(resolved.envelope)!==json(envelope)||resolved.outcome!==input.outcome||
|
|
144
|
+
resolved.receipt!==input.receipt||resolved.authoritative!==true)fail('delivery_evidence_invalid');
|
|
145
|
+
const state=['acknowledged','found'].includes(input.outcome)?'acknowledged':
|
|
146
|
+
['not_sent','not_found'].includes(input.outcome)?'pending':'unknown';
|
|
147
|
+
if(state==='acknowledged') {
|
|
148
|
+
const at=store.nowMs();if(!Number.isSafeInteger(at)||at<0)fail('invalid_clock');
|
|
149
|
+
db.prepare('UPDATE durable_waiter_deliveries SET acknowledged_at=? WHERE delivery_id=? AND acknowledged_at IS NULL').run(at,input.delivery);
|
|
150
|
+
}
|
|
151
|
+
db.prepare('UPDATE protocol_delivery_attempts SET state=? WHERE delivery_id=? AND attempt=?').run(state,input.delivery,envelope.attempt);
|
|
152
|
+
return save(job,input.key,p.identity,{delivery:input.delivery,state});
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
function recover() {
|
|
156
|
+
// Private startup operation, no transport effect. Owner ACK remains dominant.
|
|
157
|
+
return store.transaction(()=>db.prepare("UPDATE protocol_delivery_attempts SET state='unknown' WHERE state='sending' AND delivery_id IN (SELECT delivery_id FROM durable_waiter_deliveries WHERE acknowledged_at IS NULL)").run().changes);
|
|
158
|
+
}
|
|
159
|
+
function deliveryState(deliveryId) {
|
|
160
|
+
const row=db.prepare('SELECT job FROM durable_waiter_deliveries WHERE delivery_id=?').get(deliveryId);
|
|
161
|
+
if(!row)return null;
|
|
162
|
+
store.assertProtocolAvailable(row.job);
|
|
163
|
+
return {delivery:deliveryId,state:native(row.job,deliveryId).state};
|
|
164
|
+
}
|
|
165
|
+
return {dispatch,deliveryResult:(...args)=>applyEvidence(...args,'delivery_result'),
|
|
166
|
+
reconcile:(...args)=>applyEvidence(...args,'reconcile'),recover,deliveryState};
|
|
167
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import {openSync,closeSync,fstatSync,readSync,constants} from 'node:fs';
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {createResultBindings} from './result-binding.mjs';
|
|
4
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
5
|
+
function canonical(value) {
|
|
6
|
+
if(value===null||typeof value==='string'||typeof value==='boolean')return value;
|
|
7
|
+
if(typeof value==='number'&&Number.isFinite(value))return value;
|
|
8
|
+
if(Array.isArray(value))return value.map(canonical);
|
|
9
|
+
if(value&&Object.getPrototypeOf(value)===Object.prototype)
|
|
10
|
+
return Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])]));
|
|
11
|
+
fail('invalid_command');
|
|
12
|
+
}
|
|
13
|
+
const json=value=>JSON.stringify(canonical(value));
|
|
14
|
+
const nat=n=>Number.isSafeInteger(n)&&n>=0;
|
|
15
|
+
function nativeArtifact(store,job,claimId,epoch,selectedId) {
|
|
16
|
+
const row=store.db.prepare("SELECT * FROM artifacts WHERE request_id=? AND COALESCE(client_artifact_id,id)=? AND kind='upload' AND claim_id=? AND sealed=1").get(job,selectedId,claimId);
|
|
17
|
+
if(!row||row.origin_claim_id!==claimId||row.origin_epoch!==epoch||!nat(row.size)||row.size>8*1024*1024||!row.origin_claim_id||
|
|
18
|
+
!nat(row.origin_epoch)||row.origin_epoch<1||!/^[a-f0-9]{64}$/.test(row.sha256??''))fail('invalid_sealed_artifact');
|
|
19
|
+
const fd=openSync(row.path,constants.O_RDONLY|constants.O_NOFOLLOW);
|
|
20
|
+
try {
|
|
21
|
+
const stat=fstatSync(fd);
|
|
22
|
+
if(!stat.isFile()||stat.size!==row.size)fail('artifact_integrity_failure');
|
|
23
|
+
const bytes=Buffer.alloc(row.size);
|
|
24
|
+
let offset=0;
|
|
25
|
+
while(offset<bytes.length){const count=readSync(fd,bytes,offset,bytes.length-offset,offset);if(!count)fail('artifact_integrity_failure');offset+=count;}
|
|
26
|
+
if(fstatSync(fd).size!==row.size||createHash('sha256').update(bytes).digest('hex')!==row.sha256)
|
|
27
|
+
fail('artifact_integrity_failure');
|
|
28
|
+
} finally {closeSync(fd);}
|
|
29
|
+
return {id:row.id,origin_claim:row.origin_claim_id,origin_epoch:row.origin_epoch,sha256:row.sha256,size:row.size};
|
|
30
|
+
}
|
|
31
|
+
export function finishProtocol(store,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence=null,connectionId=null) {
|
|
32
|
+
// Parent never routes cancelled native finishes back here. Native finish owns
|
|
33
|
+
// its late-evidence transaction and throws only after that audit commits.
|
|
34
|
+
if(store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status==='cancelled')
|
|
35
|
+
return store.finish(id,claimId,outcome,summary,result,subject,evidence,worker,null,null,connectionId);
|
|
36
|
+
const rollback=[];
|
|
37
|
+
try {return store.transaction(()=>{
|
|
38
|
+
const claim=store.assertFinishClaim(id,claimId,subject,worker);
|
|
39
|
+
// Commit-time authority gates both a fresh finish and a stored receipt replay.
|
|
40
|
+
store.assertMutationConnection(id,claim,connectionId);
|
|
41
|
+
if(!store.isProtocolJob(id))fail('protocol_required');
|
|
42
|
+
if(!ctx||typeof ctx.key!=='string'||!ctx.key||ctx.key.length>512||!nat(ctx.revision)||
|
|
43
|
+
ctx.epoch!==undefined&&(!nat(ctx.epoch)||ctx.epoch!==claim.epoch))fail('stale_authority');
|
|
44
|
+
const ids=ctx.args?.artifact_ids;
|
|
45
|
+
if(!Array.isArray(ids)||ids.some(x=>typeof x!=='string'||!x)||new Set(ids).size!==ids.length)
|
|
46
|
+
fail('invalid_artifact_ids');
|
|
47
|
+
// Snapshot evidence is server-derived and may be absent on receipt replay.
|
|
48
|
+
// The key binds caller intent; the original report retains its own evidence.
|
|
49
|
+
const args={outcome,summary,result,artifact_ids:ids};
|
|
50
|
+
const command={job:id,subject,worker,claim:claimId,epoch:claim.epoch,key:ctx.key,
|
|
51
|
+
expectedRevision:ctx.revision,operation:'finish',args};
|
|
52
|
+
const identity=json(command);
|
|
53
|
+
const prior=store.db.prepare('SELECT identity,result FROM claim_command_receipts WHERE job=? AND command_key=?').get(id,ctx.key);
|
|
54
|
+
if(prior) {
|
|
55
|
+
if(prior.identity!==identity)fail('command_conflict');
|
|
56
|
+
const report=store.db.prepare('SELECT receipt_id,claim_id,worker FROM reports WHERE request_id=?').get(id);
|
|
57
|
+
const binding=store.db.prepare('SELECT receipt FROM immutable_result_bindings WHERE job=?').get(id);
|
|
58
|
+
const saved=JSON.parse(prior.result);
|
|
59
|
+
if(!report||!binding||report.claim_id!==claimId||report.worker!==worker||
|
|
60
|
+
saved.value?.receipt_id!==report.receipt_id||JSON.parse(binding.receipt).receipt_id!==report.receipt_id)
|
|
61
|
+
fail('retained_receipt_required');
|
|
62
|
+
return {...saved.value,revision:saved.revision};
|
|
63
|
+
}
|
|
64
|
+
if(store.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(id))fail('original_finish_key_required');
|
|
65
|
+
let parsed;try{parsed=JSON.parse(result);}catch{fail('invalid_result_json');}
|
|
66
|
+
if(!parsed||typeof parsed!=='object'||Array.isArray(parsed)||
|
|
67
|
+
typeof parsed.source!=='string'||typeof parsed.policy!=='string')fail('binding_mismatch');
|
|
68
|
+
const receipt=store.protocolMutationInTransaction(id,claimId,subject,worker,
|
|
69
|
+
{...ctx,operation:'finish',args},()=>{
|
|
70
|
+
const refs=ids.map(selected=>nativeArtifact(store,id,claimId,claim.epoch,selected));
|
|
71
|
+
const byId=new Map(refs.map(ref=>[ref.id,ref]));
|
|
72
|
+
if(byId.size!==refs.length)fail('duplicate_artifact_reference');
|
|
73
|
+
const bindings=createResultBindings({db:store.db,
|
|
74
|
+
authorize:c=>{
|
|
75
|
+
const current=store.assertFinishClaim(id,claimId,subject,worker);
|
|
76
|
+
return c.job===id&&c.subject===subject&&c.worker===worker&&c.claim===claimId&&c.epoch===current.epoch;
|
|
77
|
+
},
|
|
78
|
+
readIntent:job=>store.getProtocol(job),
|
|
79
|
+
readArtifact:({job,id:artifactId})=>{
|
|
80
|
+
const ref=byId.get(artifactId);
|
|
81
|
+
return ref&&job===id?{...ref,job,sealed:true}:null;
|
|
82
|
+
},
|
|
83
|
+
readTerminal:job=>{
|
|
84
|
+
const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(job);
|
|
85
|
+
return row?{status:row.status,late:false,compute_stopped:false}:null;
|
|
86
|
+
}});
|
|
87
|
+
const bound=bindings.bind({job:id,subject,worker,claim:claimId,epoch:claim.epoch,
|
|
88
|
+
source:parsed.source,policy:parsed.policy,outcome,summary,result,artifacts:refs},()=>{
|
|
89
|
+
// A newly committed report cannot already have an owner decision.
|
|
90
|
+
store.assertQuestionsResolved(id,claimId,outcome);
|
|
91
|
+
const captured=captureEvidence?captureEvidence(cleanup=>rollback.push(cleanup)):evidence;
|
|
92
|
+
const native={...store.finishOnce(id,claimId,outcome,summary,result,subject,captured,worker,null,connectionId),acceptance:'unreviewed'};
|
|
93
|
+
store.protocolEventInTransaction(id,'finished',{receipt_id:native.receipt_id,outcome},claim.epoch);
|
|
94
|
+
return native;
|
|
95
|
+
});
|
|
96
|
+
return bound;
|
|
97
|
+
},connectionId);
|
|
98
|
+
return {...receipt.value,revision:receipt.revision};
|
|
99
|
+
});} catch(error) {for(const cleanup of rollback)cleanup();throw error;}
|
|
100
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
2
|
+
function canonical(value) {
|
|
3
|
+
if(value===null||typeof value==='string'||typeof value==='boolean') return value;
|
|
4
|
+
if(typeof value==='number'&&Number.isFinite(value)) return value;
|
|
5
|
+
if(Array.isArray(value)) return value.map(canonical);
|
|
6
|
+
if(value&&Object.getPrototypeOf(value)===Object.prototype) return Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])]));
|
|
7
|
+
fail('invalid_command');
|
|
8
|
+
}
|
|
9
|
+
const json=value=>JSON.stringify(canonical(value));
|
|
10
|
+
|
|
11
|
+
// One private owner mutation, receipt and revision in the caller's transaction.
|
|
12
|
+
// The raw capability is authenticated here and never enters the receipt table.
|
|
13
|
+
export function executeProtocolOwnerCommand(store,job,token,command,mutate) {
|
|
14
|
+
const {db}=store;
|
|
15
|
+
if(!db.isTransaction) fail('transaction_required');
|
|
16
|
+
store.owner(job,token);
|
|
17
|
+
if(!store.isProtocolJob(job)) fail('protocol_job_required');
|
|
18
|
+
store.assertProtocolAvailable(job);
|
|
19
|
+
const {key,revision,operation,args}=command??{};
|
|
20
|
+
if(typeof key!=='string'||!key.length||key.length>512||!Number.isSafeInteger(revision)||revision<0||typeof operation!=='string'||!operation||typeof mutate!=='function') fail('invalid_command');
|
|
21
|
+
const owner=db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(job).owner_hash;
|
|
22
|
+
const identity=json({job,owner,key,expectedRevision:revision,operation,args});
|
|
23
|
+
const prior=db.prepare('SELECT identity,result FROM claim_command_receipts WHERE job=? AND command_key=?').get(job,key);
|
|
24
|
+
if(prior) {
|
|
25
|
+
if(prior.identity!==identity) fail('command_conflict');
|
|
26
|
+
return JSON.parse(prior.result);
|
|
27
|
+
}
|
|
28
|
+
if(store.protocolRevision(job)!==revision) fail('revision_conflict');
|
|
29
|
+
const next=store.advanceProtocolRevisionInTransaction(job);
|
|
30
|
+
const value=mutate();
|
|
31
|
+
if(value&&typeof value.then==='function') fail('async_mutation_forbidden');
|
|
32
|
+
const result={value,revision:next};
|
|
33
|
+
db.prepare('INSERT INTO claim_command_receipts(job,command_key,identity,result) VALUES(?,?,?,?)').run(job,key,identity,json(result));
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {executeProtocolOwnerCommand} from './protocol-owner-command.mjs';
|
|
2
|
+
|
|
3
|
+
const flatten=receipt=>({...receipt.value,revision:receipt.revision});
|
|
4
|
+
export function answerProtocolQuestion(store,id,questionId,text,ownerToken,ctx) {
|
|
5
|
+
return store.transaction(()=>flatten(executeProtocolOwnerCommand(store,id,ownerToken,
|
|
6
|
+
{...ctx,operation:'answer',args:{questionId,text}},()=>{
|
|
7
|
+
const value=store.answerQuestionInTransaction(id,questionId,text);
|
|
8
|
+
store.protocolEventInTransaction(id,'answered',{question_id:questionId});
|
|
9
|
+
return value;
|
|
10
|
+
})));
|
|
11
|
+
}
|
|
12
|
+
export function cancelProtocolJob(store,id,reason,ownerToken,ctx) {
|
|
13
|
+
return store.transaction(()=>flatten(executeProtocolOwnerCommand(store,id,ownerToken,
|
|
14
|
+
{...ctx,operation:'cancel',args:{reason}},()=>{
|
|
15
|
+
const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
16
|
+
if(!row||['finished','cancelled'].includes(row.status))
|
|
17
|
+
throw Object.assign(new Error('TERMINAL: assignment is terminal'),{code:'TERMINAL'});
|
|
18
|
+
const value=store.cancelInTransaction(id,reason);
|
|
19
|
+
store.protocolEventInTransaction(id,'cancelled',{reason});
|
|
20
|
+
return value;
|
|
21
|
+
})));
|
|
22
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import {createDurableWaiters,migrateDurableWaiters} from './durable-waiters.mjs';
|
|
2
|
+
import {executeProtocolOwnerCommand} from './protocol-owner-command.mjs';
|
|
3
|
+
|
|
4
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
5
|
+
const text=value=>typeof value==='string'&&value.length>0&&value.length<=512;
|
|
6
|
+
const natural=value=>Number.isSafeInteger(value)&&value>=0;
|
|
7
|
+
// Called only by the Store's versioned migration, never by an HTTP request.
|
|
8
|
+
export function migrateProtocolOwnerWaiters(db) {
|
|
9
|
+
migrateDurableWaiters(db);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Private owner operations. Worker tools and notification ACKs do not use this ledger. */
|
|
13
|
+
export function createProtocolOwnerWaiters(store) {
|
|
14
|
+
const {db}=store;
|
|
15
|
+
const driverInstalled=!!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='protocol_delivery_attempts'").get();
|
|
16
|
+
function authorize(job,token) {
|
|
17
|
+
store.owner(job,token);
|
|
18
|
+
if(!store.isProtocolJob(job)) fail('protocol_job_required');
|
|
19
|
+
store.assertProtocolAvailable(job);
|
|
20
|
+
// The raw owner capability is transient. Persist only the existing hash.
|
|
21
|
+
return db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(job).owner_hash;
|
|
22
|
+
}
|
|
23
|
+
const waiters=createDurableWaiters({
|
|
24
|
+
db,clock:()=>store.nowMs(),
|
|
25
|
+
authorize:({job,owner})=>store.isProtocolJob(job)&&db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(job)?.owner_hash===owner,
|
|
26
|
+
readEvents:({job,afterSeq})=>store.protocolFacts(job).filter(event=>event.seq>afterSeq).map(event=>({
|
|
27
|
+
...event,id:`${job}:${event.seq}`,job,type:event.type??event.event_type,
|
|
28
|
+
})),
|
|
29
|
+
predicates:{terminal:event=>['finished','cancelled'].includes(event.type),input:event=>event.type==='questioned',any:()=>true},
|
|
30
|
+
});
|
|
31
|
+
function register(job,token,input) { return store.transaction(()=>{
|
|
32
|
+
const owner=authorize(job,token);
|
|
33
|
+
const {key,revision,waiter,predicate,afterSeq,expiresAt}=input??{};
|
|
34
|
+
if(!text(key)||!natural(revision)||!text(waiter)||!natural(afterSeq)||!natural(expiresAt)||!['terminal','input','any'].includes(predicate)) fail('invalid_registration');
|
|
35
|
+
const receipt=executeProtocolOwnerCommand(store,job,token,{key,revision,operation:'wait',args:{waiter,predicate,afterSeq,expiresAt}},()=>{
|
|
36
|
+
waiters.register({job,owner,waiter,key,predicate,afterSeq,expiresAt});
|
|
37
|
+
store.protocolEventInTransaction(job,'waiter_registered',{waiter,predicate});
|
|
38
|
+
waiters.materialize({job,owner,waiter});
|
|
39
|
+
return {waiter,delivery:waiters.inbox({job,owner,waiter})[0]?.delivery??null};
|
|
40
|
+
});
|
|
41
|
+
return {...receipt.value,revision:receipt.revision};
|
|
42
|
+
}); }
|
|
43
|
+
function inbox(job,token,waiter) { return store.transaction(()=>{
|
|
44
|
+
const owner=authorize(job,token);
|
|
45
|
+
if(!text(waiter)) fail('invalid_waiter');
|
|
46
|
+
waiters.materialize({job,owner,waiter});
|
|
47
|
+
const epoch=db.prepare('SELECT epoch FROM claims WHERE request_id=?').get(job)?.epoch;
|
|
48
|
+
return {deliveries:waiters.inbox({job,owner,waiter}).filter(row=>row.fact.type!=='questioned'||row.fact.epoch===epoch).map(row=>({
|
|
49
|
+
delivery:row.delivery,waiter,job,event:row.eventId,
|
|
50
|
+
state:driverInstalled?db.prepare('SELECT state FROM protocol_delivery_attempts WHERE delivery_id=?').get(row.delivery)?.state??'pending':'pending',receipt:null,
|
|
51
|
+
}))};
|
|
52
|
+
}); }
|
|
53
|
+
function ack(job,token,waiter,delivery) { return store.transaction(()=>{
|
|
54
|
+
const owner=authorize(job,token);
|
|
55
|
+
const result=waiters.ack({job,owner,waiter,delivery});
|
|
56
|
+
return {delivery:result.delivery,state:'acknowledged'};
|
|
57
|
+
}); }
|
|
58
|
+
function materializeAll(job) {
|
|
59
|
+
if(!db.isTransaction)fail('transaction_required');
|
|
60
|
+
for(const row of db.prepare('SELECT owner,waiter FROM durable_waiters WHERE job=?').all(job))
|
|
61
|
+
waiters.materialize({job,owner:row.owner,waiter:row.waiter});
|
|
62
|
+
}
|
|
63
|
+
return {register,inbox,ack,materializeAll};
|
|
64
|
+
}
|
|
65
|
+
// Called by the native event transaction, so a committed result always carries
|
|
66
|
+
// its durable wake obligation even when nobody has polled the owner's inbox.
|
|
67
|
+
export const materializeProtocolWaiters=(store,job)=>createProtocolOwnerWaiters(store).materializeAll(job);
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {createJobRetention} from './job-retention.mjs';
|
|
2
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
3
|
+
const transaction=store=>{if(!store.db.isTransaction)fail('transaction_required');};
|
|
4
|
+
// Internal helpers: callers authenticate their native owner/worker boundary first.
|
|
5
|
+
function binding(store,id,requirePolicy=true) {
|
|
6
|
+
if(!store.isProtocolJob(id))return null;
|
|
7
|
+
const row=store.db.prepare('SELECT owner_hash,target_worker,status FROM assignments WHERE request_id=?').get(id);
|
|
8
|
+
const deadline=store.getProtocol(id)?.retain_until_ms;
|
|
9
|
+
if(!row?.owner_hash||!row.target_worker||!Number.isSafeInteger(deadline)||deadline<0)
|
|
10
|
+
fail('invalid_retention_binding');
|
|
11
|
+
const policy=store.db.prepare('SELECT * FROM job_retention_policy WHERE job=?').get(id);
|
|
12
|
+
if(requirePolicy&&!policy)fail('retention_not_found');
|
|
13
|
+
if(policy&&(policy.owner!==row.owner_hash||policy.worker!==row.target_worker||policy.retain_until!==deadline))
|
|
14
|
+
fail('retention_conflict');
|
|
15
|
+
return {job:id,owner:row.owner_hash,worker:row.target_worker,retainUntil:deadline};
|
|
16
|
+
}
|
|
17
|
+
function component(store,b) {
|
|
18
|
+
return createJobRetention({db:store.db,clock:()=>store.nowMs(),
|
|
19
|
+
authorize:c=>c.job===b.job&&c.owner===b.owner&&c.worker===b.worker,
|
|
20
|
+
readState:job=>{
|
|
21
|
+
const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(job);
|
|
22
|
+
return row?{status:row.status,compute_stopped:false}:null;
|
|
23
|
+
},
|
|
24
|
+
fence:()=>{
|
|
25
|
+
const row=store.db.prepare('SELECT * FROM job_retention_tombstones WHERE job=?').get(b.job);
|
|
26
|
+
return !!row&&row.owner===b.owner&&row.worker===b.worker&&
|
|
27
|
+
row.retain_until===b.retainUntil&&row.purge_pending===1;
|
|
28
|
+
},
|
|
29
|
+
purge:()=>fail('physical_purge_forbidden')});
|
|
30
|
+
}
|
|
31
|
+
export function defineProtocolRetentionInTransaction(store,id) {
|
|
32
|
+
transaction(store);
|
|
33
|
+
const b=binding(store,id,false);
|
|
34
|
+
return b?component(store,b).define(b):null;
|
|
35
|
+
}
|
|
36
|
+
export function expireProtocolRetentionInTransaction(store,id) {
|
|
37
|
+
transaction(store);
|
|
38
|
+
const b=binding(store,id);
|
|
39
|
+
return b?component(store,b).expire(b):{deleted:false};
|
|
40
|
+
}
|
|
41
|
+
export function assertProtocolAvailable(store,id) {
|
|
42
|
+
const b=binding(store,id);
|
|
43
|
+
if(!b)return true;
|
|
44
|
+
if(store.nowMs()>=b.retainUntil) {
|
|
45
|
+
// With an outer transaction, its later throw rolls the tombstone back.
|
|
46
|
+
// The immutable policy nevertheless fences access on every invocation.
|
|
47
|
+
if(store.db.isTransaction)expireProtocolRetentionInTransaction(store,id);
|
|
48
|
+
else store.transaction(()=>expireProtocolRetentionInTransaction(store,id));
|
|
49
|
+
}
|
|
50
|
+
// Outside a caller transaction expiry is committed before this throws.
|
|
51
|
+
return component(store,b).assertAvailable(b);
|
|
52
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import {createHmac,timingSafeEqual} from 'node:crypto';
|
|
2
|
+
import {createProtocolDeliveryDriver} from './protocol-delivery-driver.mjs';
|
|
3
|
+
import {createProtocolStopObserver} from './protocol-stop-observer.mjs';
|
|
4
|
+
import {readVerifiedHostStop} from './host-budget-receipts.mjs';
|
|
5
|
+
|
|
6
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
7
|
+
export function protocolServiceCapability(operatorKey,role) {
|
|
8
|
+
if(!['dispatcher','observer'].includes(role)||typeof operatorKey!=='string'||!operatorKey)fail('invalid_service_role');
|
|
9
|
+
return createHmac('sha256',operatorKey).update('dot-bridge:protocol-v0:'+role).digest('hex');
|
|
10
|
+
}
|
|
11
|
+
function same(a,b) {
|
|
12
|
+
return typeof a==='string'&&/^[a-f0-9]{64}$/.test(a)&&timingSafeEqual(Buffer.from(a,'hex'),Buffer.from(b,'hex'));
|
|
13
|
+
}
|
|
14
|
+
function closed(body,keys) {
|
|
15
|
+
if(!body||Object.getPrototypeOf(body)!==Object.prototype||Object.keys(body).length!==keys.length||
|
|
16
|
+
keys.some(key=>!Object.hasOwn(body,key)))fail('invalid_input');
|
|
17
|
+
}
|
|
18
|
+
// The receiver for owner-inbox is the native durable inbox itself. Only its
|
|
19
|
+
// owner's persisted ACK proves acceptance; absence of that ACK proves nothing.
|
|
20
|
+
function inboxTransport(store) {
|
|
21
|
+
function proof(envelope,label,kind) {
|
|
22
|
+
const row=store.db.prepare('SELECT acknowledged_at FROM durable_waiter_deliveries WHERE job=? AND delivery_id=?').get(envelope.job,envelope.delivery);
|
|
23
|
+
if(!row)return null;
|
|
24
|
+
return {envelope,outcome:row.acknowledged_at!==null?(kind==='result'?'acknowledged':'found'):'unknown',receipt:label,authoritative:true};
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
begin(envelope) {if(envelope.destination!=='owner-inbox')fail('unsupported_protocol_destination');},
|
|
28
|
+
result:(e,label)=>proof(e,label,'result'),reconcile:(e,label)=>proof(e,label,'reconcile'),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export function createProtocolServices(store,{operatorKey,receiptDir,transport,resolveStopEvidence}={}) {
|
|
32
|
+
const dispatchKey=protocolServiceCapability(operatorKey,'dispatcher');
|
|
33
|
+
const observerKey=protocolServiceCapability(operatorKey,'observer');
|
|
34
|
+
const authorize=(role,key)=>({authority})=>same(authority,key)?'service:'+role:null;
|
|
35
|
+
const delivery=createProtocolDeliveryDriver(store,{authorize:authorize('dispatcher',dispatchKey),transport:transport??inboxTransport(store)});
|
|
36
|
+
const resolveHostStop=(binding,label)=>{
|
|
37
|
+
if(!receiptDir||!binding.scope.startsWith('host-check:'))return null;
|
|
38
|
+
const checkRunId=binding.scope.slice('host-check:'.length);
|
|
39
|
+
if(label!==checkRunId)return null;
|
|
40
|
+
const job=store.db.prepare('SELECT request_id,claim_id FROM check_jobs WHERE id=?').get(checkRunId);
|
|
41
|
+
if(!job||job.request_id!==binding.job||job.claim_id!==binding.claim)return null;
|
|
42
|
+
const receipt=readVerifiedHostStop({receiptDir,checkRunId,invocationId:binding.invocation});
|
|
43
|
+
return receipt?{binding,verified:true,stopped:true,remaining_pids:receipt.remaining_pids}:null;
|
|
44
|
+
};
|
|
45
|
+
const observer=createProtocolStopObserver(store,{authorize:authorize('observer',observerKey),resolveEvidence:resolveStopEvidence??resolveHostStop});
|
|
46
|
+
delivery.recover();
|
|
47
|
+
async function invoke(operation,authority,body) {
|
|
48
|
+
const fields={dispatch:['key','delivery'],'delivery-result':['key','delivery','outcome','receipt'],
|
|
49
|
+
reconcile:['key','delivery','outcome','receipt'],enroll:['execution'],
|
|
50
|
+
'observe-stop':['key','revision','stop','evidence']}[operation];
|
|
51
|
+
if(!fields)fail('invalid_input');
|
|
52
|
+
closed(body,['id',...fields]);
|
|
53
|
+
const {id,...input}=body;
|
|
54
|
+
if(operation==='dispatch')return delivery.dispatch(id,authority,input);
|
|
55
|
+
if(operation==='delivery-result')return delivery.deliveryResult(id,authority,input);
|
|
56
|
+
if(operation==='reconcile')return delivery.reconcile(id,authority,input);
|
|
57
|
+
if(operation==='enroll')return observer.enroll(id,authority,input.execution);
|
|
58
|
+
return observer.observeStop(id,authority,input);
|
|
59
|
+
}
|
|
60
|
+
return {invoke,observation:job=>observer.getObservation(job),deliveryState:id=>delivery.deliveryState(id)};
|
|
61
|
+
}
|