@cardinali-studio/adminkit 2.2.48 → 2.2.50
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/dist/app/App.js +6 -6
- package/dist/app/app.css +67 -1
- package/dist/app/delivery.js +7 -7
- package/dist/app/guide/TransferGuide.js +1 -1
- package/dist/app/lib/deliveries.d.ts +6 -0
- package/dist/app/lib/delivery-capabilities.d.ts +31 -0
- package/dist/app/lib/delivery-capabilities.js +115 -0
- package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
- package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
- package/dist/app/lib/delivery-finalize.d.ts +21 -0
- package/dist/app/lib/delivery-finalize.js +42 -0
- package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
- package/dist/app/lib/delivery-multipart-large.js +28 -0
- package/dist/app/lib/delivery-network.d.ts +7 -1
- package/dist/app/lib/delivery-network.js +85 -18
- package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
- package/dist/app/lib/delivery-part-pipeline.js +270 -0
- package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
- package/dist/app/lib/delivery-upload-coordinator.js +229 -0
- package/dist/app/lib/delivery-upload.d.ts +19 -3
- package/dist/app/lib/delivery-upload.js +226 -29
- package/dist/app/lib/upload-queue.d.ts +5 -0
- package/dist/app/lib/upload-queue.js +54 -29
- package/dist/app/routes/Deliveries.d.ts +9 -3
- package/dist/app/routes/Deliveries.js +299 -164
- package/dist/app/routes/DeliveryDashboard.js +1 -1
- package/dist/app/routes/DeliveryEmail.d.ts +8 -1
- package/dist/app/routes/DeliveryEmail.js +63 -23
- package/dist/app/routes/Overview.js +5 -5
- package/dist/app/routes/UploadDock.js +4 -3
- package/dist/form/media/MediaGrid.js +1 -1
- package/dist/functions/_shared/b2.js +108 -19
- package/dist/functions/_shared/delivery-activation.js +98 -0
- package/dist/functions/_shared/delivery-download-bundle.js +280 -0
- package/dist/functions/_shared/delivery-email.js +92 -13
- package/dist/functions/_shared/delivery-file-names.js +19 -0
- package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
- package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
- package/dist/functions/_shared/delivery-manifest-free.js +74 -0
- package/dist/functions/_shared/delivery-manifest.js +277 -20
- package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
- package/dist/functions/_shared/delivery-request.js +74 -0
- package/dist/functions/_shared/delivery-storage-access.js +14 -0
- package/dist/functions/_shared/delivery-upload-admission.js +221 -0
- package/dist/functions/_shared/delivery-upload-contract.js +44 -0
- package/dist/functions/_shared/delivery-upload-free.js +80 -0
- package/dist/functions/_shared/delivery-upload-policy.js +64 -0
- package/dist/functions/_shared/delivery-upload-session.js +365 -0
- package/dist/functions/_shared/delivery-work-budget.js +49 -0
- package/dist/functions/_shared/diagnostics.js +59 -0
- package/dist/functions/api/deliveries.js +61 -17
- package/dist/functions/api/delivery/multipart.js +156 -16
- package/dist/functions/delivery-public/assets/client.js +59 -54
- package/dist/functions/delivery-public/assets/delivery.css +6 -2
- package/dist/functions/delivery-public/index.js +43 -15
- package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
- package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
- package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
- package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
- package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
- package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
- package/dist/functions/index.js +3 -1
- package/dist/theme.css +2 -1
- package/package.json +1 -1
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { deliveryCapabilities } from './delivery-upload-policy.js';
|
|
2
|
+
import { reserveUploadBudget, consumeUploadBudget, acquireUploadSlot, releaseUploadSlot, assertUploadBudgetFresh, UPLOAD_BUDGET_RESOURCES } from './delivery-upload-admission.js';
|
|
3
|
+
import { deliveryStorageRoot } from './delivery-storage-scope.js';
|
|
4
|
+
import { sha256 } from './delivery-crypto.js';
|
|
5
|
+
import { DELIVERY_PART_BYTES, DELIVERY_MAX_ARCHIVE_BYTES, validateDeliverySourceBytes } from './delivery-limits.js';
|
|
6
|
+
import { opaqueUploadId as validId, canonicalUploadJson as canonical, uploadSessionError as error,
|
|
7
|
+
uploadSessionMarker, withUploadSessionInvocation } from './delivery-upload-contract.js';
|
|
8
|
+
import { claimManifestWriter, assertManifestWriter, manifestStatus, manifestDraftPage, ingestManifest,
|
|
9
|
+
ingestReplayManifest, saveManifestCheckpoint, saveAsyncManifestCheckpoint, asyncManifestStatus, finalizeManifestStepCommon } from './delivery-manifest.js';
|
|
10
|
+
import { finalizeManifestPaid } from './delivery-finalization-paid.js';
|
|
11
|
+
import { activateDeliveryMinimal } from './delivery-activation.js';
|
|
12
|
+
import { invokeMultipartUploadUnit } from '../api/delivery/multipart.js';
|
|
13
|
+
import { createFreeUploadWork, FREE_UPLOAD_UNIT, needsPaid } from './delivery-upload-free.js';
|
|
14
|
+
|
|
15
|
+
export const UPLOAD_SESSION_ROLLOUT_ENABLED = false;
|
|
16
|
+
const bytes = v => new TextEncoder().encode(v).byteLength;
|
|
17
|
+
const changed = () => error('upload_capability_changed', 'Rileggi il contratto della stessa sessione di upload');
|
|
18
|
+
const unknown = () => error('upload_budget_unknown', 'Inviluppo, costi o budget account non verificati');
|
|
19
|
+
const uncertain = () => error('upload_unit_uncertain', 'Esito non dimostrato: sessione conservata, nessuna operazione ripetuta alla cieca');
|
|
20
|
+
const canRecover = e => e.retryable!==false && (e.status===undefined||e.status>=500);
|
|
21
|
+
function replayResult(json) {
|
|
22
|
+
const result=JSON.parse(json);
|
|
23
|
+
if(result.ok!==true)throw error(result.code||'upload_capability_changed',result.error||'Unità respinta',result.status||409);
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
const integer = n => Number.isSafeInteger(n) && n >= 0;
|
|
27
|
+
const manifestHandlers = { manifestClaim: claimManifestWriter, manifestStatus, manifestDraftPage,
|
|
28
|
+
manifestBatch: ingestManifest, manifestReplayBatch: ingestReplayManifest, manifestCheckpoint: saveManifestCheckpoint,
|
|
29
|
+
asyncCheckpoint: saveAsyncManifestCheckpoint, asyncCheckpointStatus: asyncManifestStatus,
|
|
30
|
+
segmentedFinalize: finalizeManifestStepCommon, coalescedFinalize: finalizeManifestPaid };
|
|
31
|
+
const multipartActions = new Set(['create','presign','record','reconcile','complete','presignBatch','recordBatch','multipartVerifyStep','completePaid']);
|
|
32
|
+
const recoverable = new Set(['manifestClaim','manifestStatus','manifestDraftPage','presign','record','complete','presignBatch','recordBatch',
|
|
33
|
+
'manifestBatch','manifestReplayBatch','manifestCheckpoint','asyncCheckpoint','asyncCheckpointStatus','completePaid',
|
|
34
|
+
'segmentedFinalize','coalescedFinalize','minimalActivate']);
|
|
35
|
+
const requiredFeature = { presignBatch:'presignBatch',recordBatch:'recordBatch',manifestReplayBatch:'asyncCheckpoint',
|
|
36
|
+
asyncCheckpoint:'asyncCheckpoint',asyncCheckpointStatus:'asyncCheckpoint',segmentedFinalize:'segmentedFinalize',
|
|
37
|
+
coalescedFinalize:'coalescedFinalize',minimalActivate:'minimalActivate' };
|
|
38
|
+
function costVector(v) {
|
|
39
|
+
if (!v || Object.keys(v).length !== UPLOAD_BUDGET_RESOURCES.length || UPLOAD_BUDGET_RESOURCES.some(k=>!integer(v[k]))) throw unknown();
|
|
40
|
+
return v;
|
|
41
|
+
}
|
|
42
|
+
function selection(input) {
|
|
43
|
+
if (!input || input.pipelineContractVersion!==undefined&&input.pipelineContractVersion!==1 || !validId(input.id) || !validId(input.sessionId) || typeof input.sourceFingerprint !== 'string' ||
|
|
44
|
+
!input.sourceFingerprint || bytes(input.sourceFingerprint)>512 || !integer(input.fileCount) || input.fileCount<1 || input.fileCount>100000 ||
|
|
45
|
+
!['webp','jpg',undefined].includes(input.webFormat)) throw changed();
|
|
46
|
+
const sourceBytes = validateDeliverySourceBytes(input.sourceBytes);
|
|
47
|
+
if (typeof input.label !== 'string' || bytes(input.label)>1024) throw changed();
|
|
48
|
+
return { sourceFingerprint:input.sourceFingerprint,fileCount:input.fileCount,sourceBytes,
|
|
49
|
+
label:input.label,galleryEnabled:!!input.galleryEnabled,webEnabled:!!input.webEnabled,webFormat:input.webFormat||'webp' };
|
|
50
|
+
}
|
|
51
|
+
function validatePolicy(env,p,s) {
|
|
52
|
+
const c=p?.capabilities?.uploadPipeline, e=p?.envelope;
|
|
53
|
+
if (env.DELIVERY_MANIFEST_V2!=='true' || !c || c.schemaVersion!==1 || c.protocolVersion!==1 || !/^[a-f0-9]{64}$/.test(c.revision||'') ||
|
|
54
|
+
!['free','paid'].includes(env.DELIVERY_UPLOAD_PROFILE) || c.profile!==env.DELIVERY_UPLOAD_PROFILE) throw unknown();
|
|
55
|
+
if (c.certification?.status!=='certified' || !validId(c.certification.reportId) || c.provenance?.verified!==true ||
|
|
56
|
+
!/^[a-f0-9]{64}$/.test(c.provenance.consumerBuildId||'') || !c.features?.segmentedFinalize || !c.features?.minimalActivate || !c.limits) throw changed();
|
|
57
|
+
if(c.admission?.status!=='available' || !validId(c.admission.budgetRevision)) throw error(c.admission?.status==='exhausted'?'upload_quota_exhausted':'upload_budget_unknown','Ammissione non disponibile',c.admission?.status==='exhausted'?429:409);
|
|
58
|
+
// A partial operation report is insufficient to admit a full upload. This
|
|
59
|
+
// trusted provider must qualify the entire selected envelope, including costs.
|
|
60
|
+
if(!e || e.complete!==true || !validId(e.id) || !integer(e.maxFiles) || s.fileCount>e.maxFiles ||
|
|
61
|
+
!integer(e.maxSourceBytes) || s.sourceBytes>e.maxSourceBytes || !integer(e.maxArchiveBytes) ||
|
|
62
|
+
e.maxArchiveBytes<22 || e.maxArchiveBytes>DELIVERY_MAX_ARCHIVE_BYTES || !e.profiles?.includes(c.profile) ||
|
|
63
|
+
(s.webEnabled||s.galleryEnabled)&&e.variants!==true) throw error('upload_profile_required','Carico completo non qualificato per questo profilo');
|
|
64
|
+
costVector(e.cost);
|
|
65
|
+
if(!integer(e.maxMetadataBytes)||e.maxMetadataBytes<1||e.maxMetadataBytes>64*1024*1024)throw unknown();
|
|
66
|
+
const required=['manifestClaim','manifestStatus','manifestDraftPage','create','presign','record','reconcile','complete',
|
|
67
|
+
'manifestBatch','manifestCheckpoint','segmentedFinalize','minimalActivate'];
|
|
68
|
+
if(UPLOAD_BUDGET_RESOURCES.some(k=>e.cost[k]<1) || !p.operations || required.some(action=>!p.operations[action]?.profiles?.includes(c.profile))) throw unknown();
|
|
69
|
+
if(c.profile==='free'&&(e.maxFiles>32||!integer(e.maxMetadataBytes)||e.maxMetadataBytes>32768)) {
|
|
70
|
+
throw error('upload_profile_required','Inviluppo completo fuori dal percorso Free limitato; conserva la sessione e usa un profilo qualificato');
|
|
71
|
+
}
|
|
72
|
+
if(s.webFormat==='jpg'&&s.webEnabled&&env.DELIVERY_JPEG_ENABLED!=='true') throw changed();
|
|
73
|
+
return c;
|
|
74
|
+
}
|
|
75
|
+
async function realDispatch(env,body,context) {
|
|
76
|
+
if(env.DELIVERY_UPLOAD_PROFILE==='free')env=createFreeUploadWork(env).env;
|
|
77
|
+
const handler=Object.hasOwn(manifestHandlers,body.action)&&manifestHandlers[body.action];
|
|
78
|
+
const result=handler?await handler(env,body):body.action==='minimalActivate'?await activateDeliveryMinimal(env,body,context):await invokeMultipartUploadUnit(env,body);
|
|
79
|
+
return {ok:true,...result};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Server-owned installation boundary. Default discovery is disabled/unverified;
|
|
83
|
+
* there is NO env switch, client-supplied tariff, report or SQL callback. Tests
|
|
84
|
+
* supply a synthetic policy provider to exercise the same internal coordinator.
|
|
85
|
+
* Public routes always instantiate the default boundary behind the false gate. */
|
|
86
|
+
export function createUploadSessionCoordinator(env, { readPolicy=async()=>({capabilities:await deliveryCapabilities(env)}),
|
|
87
|
+
dispatch=realDispatch, clock=()=>Date.now(), context={} }={}) {
|
|
88
|
+
async function load(input) {
|
|
89
|
+
if(!validId(input.id)||!validId(input.sessionId)) throw changed();
|
|
90
|
+
const row=await env.DB.prepare(`SELECT s.*,a.contract_json,a.remaining_json,a.state admission_state,
|
|
91
|
+
a.lease_owner,a.lease_token,a.lease_until,p.manifest_json,p.state package_state,p.storage_prefix,
|
|
92
|
+
p.file_count,p.source_bytes,p.source_fingerprint,p.gallery_enabled,p.web_enabled,p.web_format,
|
|
93
|
+
d.status delivery_status,d.files_expires_at FROM delivery_upload_sessions s
|
|
94
|
+
JOIN delivery_upload_admissions a ON a.session_id=s.session_id
|
|
95
|
+
JOIN delivery_packages p ON p.id=s.session_id AND p.delivery_id=s.delivery_id
|
|
96
|
+
JOIN deliveries d ON d.id=s.delivery_id WHERE s.session_id=? AND s.delivery_id=?`).bind(input.sessionId,input.id).first();
|
|
97
|
+
if(!row) return null;
|
|
98
|
+
row.contract=JSON.parse(row.contract_json);
|
|
99
|
+
if(await sha256(canonical(row.contract))!==row.contract_hash || uploadSessionMarker({...row,id:row.session_id})?.contractHash!==row.contract_hash ||
|
|
100
|
+
row.contract.sessionId!==row.session_id || row.contract.deliveryId!==row.delivery_id || row.contract.storagePrefix!==row.storage_prefix ||
|
|
101
|
+
row.contract.selection.fileCount!==row.file_count || row.contract.selection.sourceBytes!==row.source_bytes ||
|
|
102
|
+
row.contract.selection.sourceFingerprint!==row.source_fingerprint || row.contract.selection.galleryEnabled!==!!row.gallery_enabled ||
|
|
103
|
+
row.contract.selection.webEnabled!==!!row.web_enabled || row.contract.selection.webFormat!==row.web_format) throw changed();
|
|
104
|
+
return row;
|
|
105
|
+
}
|
|
106
|
+
async function policy(row) {
|
|
107
|
+
const p=structuredClone(await readPolicy(env,structuredClone(row.contract.selection)));
|
|
108
|
+
const c=validatePolicy(env,p,row.contract.selection);
|
|
109
|
+
await assertUploadBudgetFresh(env,clock(),c.admission.budgetRevision);
|
|
110
|
+
for(const key of ['maxArchiveBytes','maxMetadataBytes','maxFiles','maxSourceBytes']) {
|
|
111
|
+
const accepted=row.contract.envelope?.[key];
|
|
112
|
+
if(!integer(accepted))throw changed();
|
|
113
|
+
p.envelope[key]=Math.min(p.envelope[key],accepted);
|
|
114
|
+
}
|
|
115
|
+
const persisted=await env.DB.prepare(`SELECT s.metadata_bytes,
|
|
116
|
+
EXISTS(SELECT 1 FROM delivery_uploads u WHERE u.package_id=s.package_id AND (u.bytes>?
|
|
117
|
+
OR EXISTS(SELECT 1 FROM delivery_upload_parts part WHERE part.upload_id=u.id AND part.part_number>? LIMIT 1))) outside_archive
|
|
118
|
+
FROM delivery_manifest_state s WHERE s.package_id=?`)
|
|
119
|
+
.bind(p.envelope.maxArchiveBytes,Math.ceil(p.envelope.maxArchiveBytes/DELIVERY_PART_BYTES),row.session_id).first();
|
|
120
|
+
if(!persisted||persisted.metadata_bytes>p.envelope.maxMetadataBytes||persisted.outside_archive)throw error('upload_profile_required','Lo stato persistito richiede un inviluppo qualificato più ampio');
|
|
121
|
+
for(const [group,values] of Object.entries(c.limits))for(const [key,value] of Object.entries(values)) {
|
|
122
|
+
const accepted=row.contract.effectiveLimits[group]?.[key];
|
|
123
|
+
if(!integer(value)||value<1||!integer(accepted)||accepted<1)throw unknown();
|
|
124
|
+
values[key]=Math.min(value,accepted);
|
|
125
|
+
}
|
|
126
|
+
return p;
|
|
127
|
+
}
|
|
128
|
+
async function snapshot(row,input,p) {
|
|
129
|
+
let blocked=null;
|
|
130
|
+
if(!p)try{p=await policy(row);}catch(e){blocked=e.code||'upload_budget_unknown';}
|
|
131
|
+
if(row.admission_state!=='reserved')blocked='upload_quota_exhausted';
|
|
132
|
+
if(row.delivery_status==='deleted'||!['uploading','ready'].includes(row.package_state)||row.files_expires_at&&Date.parse(row.files_expires_at)<=clock())blocked='upload_capability_changed';
|
|
133
|
+
const c=p?.capabilities?.uploadPipeline;
|
|
134
|
+
const pending=await env.DB.prepare(`SELECT sequence,action,digest,state,recovery_allowed FROM delivery_upload_units
|
|
135
|
+
WHERE session_id=? AND state IN ('running','uncertain') LIMIT 1`).bind(row.session_id).first();
|
|
136
|
+
const receipt=integer(input.sequence)?await env.DB.prepare(`SELECT sequence,action,digest,state,
|
|
137
|
+
CASE WHEN length(CAST(result_json AS BLOB))<=${env.DELIVERY_UPLOAD_PROFILE==='paid'?32768:12288} THEN result_json ELSE NULL END result_json,
|
|
138
|
+
COALESCE(length(CAST(result_json AS BLOB)),0)>${env.DELIVERY_UPLOAD_PROFILE==='paid'?32768:12288} resultRequiresProfile FROM delivery_upload_units
|
|
139
|
+
WHERE session_id=? AND sequence=?`).bind(row.session_id,input.sequence).first():null;
|
|
140
|
+
const progress=await env.DB.prepare(`SELECT s.state,s.cursor,s.page_count,s.metadata_bytes,
|
|
141
|
+
CASE WHEN length(CAST(c.checkpoint_json AS BLOB))<=4096 THEN c.checkpoint_json ELSE NULL END checkpoint_json,
|
|
142
|
+
COALESCE(length(CAST(c.checkpoint_json AS BLOB)),0)>4096 checkpointRequiresRead
|
|
143
|
+
FROM delivery_manifest_state s LEFT JOIN delivery_checkpoints c ON c.package_id=s.package_id WHERE s.package_id=?`).bind(row.session_id).first();
|
|
144
|
+
const result={schemaVersion:1,id:row.delivery_id,packageId:row.session_id,contract:row.contract,contractHash:row.contract_hash,
|
|
145
|
+
nextSequence:row.next_sequence,profile:env.DELIVERY_UPLOAD_PROFILE||'unknown',blocked,
|
|
146
|
+
negotiation:{pipelineContractVersion:1,capabilityRevision:c?.revision||row.contract.capabilityRevision,effectiveLimits:c?.limits||row.contract.effectiveLimits},
|
|
147
|
+
remaining:JSON.parse(row.remaining_json),packageState:row.package_state,
|
|
148
|
+
progress:progress?{state:progress.state,cursor:progress.cursor,pageCount:progress.page_count,metadataBytes:progress.metadata_bytes,checkpoint:progress.checkpoint_json?JSON.parse(progress.checkpoint_json):null,checkpointRequiresRead:!!progress.checkpointRequiresRead}:null,
|
|
149
|
+
pending:pending?{sequence:pending.sequence,action:pending.action,digest:pending.digest,state:pending.state,recoverable:!!pending.recovery_allowed}:null,
|
|
150
|
+
receipt:receipt?{...receipt,resultRequiresProfile:!!receipt.resultRequiresProfile,result:receipt.result_json?JSON.parse(receipt.result_json):null,result_json:undefined}:null,
|
|
151
|
+
slot:row.lease_owner===input.writerToken&&row.lease_until>clock()?{token:row.lease_token,expiresAt:row.lease_until}:null};
|
|
152
|
+
if(bytes(JSON.stringify(result))>(env.DELIVERY_UPLOAD_PROFILE==='paid'?278528:32768))throw needsPaid();
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
async function status(input) {
|
|
156
|
+
const row=await load(input);if(!row)throw changed();return snapshot(row,input);
|
|
157
|
+
}
|
|
158
|
+
async function admit(input) {
|
|
159
|
+
const s=selection(input);
|
|
160
|
+
const previous=await load(input);
|
|
161
|
+
if(previous) {
|
|
162
|
+
if(canonical(previous.contract.selection)!==canonical(s))throw changed();
|
|
163
|
+
return snapshot(previous,input);
|
|
164
|
+
}
|
|
165
|
+
const p=await readPolicy(env,s), c=validatePolicy(env,p,s), now=clock();
|
|
166
|
+
const schema=await env.DB.prepare(`SELECT COUNT(*) n FROM sqlite_master WHERE type='table'
|
|
167
|
+
AND name IN ('delivery_manifest_read_work','delivery_manifest_read_fragments')`).first();
|
|
168
|
+
if(schema?.n!==2)throw error('upload_capability_changed','Migrazione dei micro-passi necessaria prima dell’ammissione',503);
|
|
169
|
+
if(input.capabilityRevision!==undefined&&input.capabilityRevision!==c.revision)throw changed();
|
|
170
|
+
if(typeof input.writerToken!=='string'||!/^[a-zA-Z0-9-]{16,80}$/.test(input.writerToken))throw changed();
|
|
171
|
+
const sid=input.sessionId,prefix=`${deliveryStorageRoot(env)}/${input.id}/${sid}/v1`;
|
|
172
|
+
const contract={pipelineContractVersion:1,capabilityRevision:c.revision,budgetRevision:c.admission.budgetRevision,
|
|
173
|
+
profile:c.profile,envelopeId:p.envelope.id,effectiveLimits:structuredClone(c.limits),sessionId:sid,deliveryId:input.id,
|
|
174
|
+
storagePrefix:prefix,selection:s,format:{manifestVersion:2,zipFormat:'store-header-v1',partBytes:DELIVERY_PART_BYTES,pagePacking:'common-v1'},
|
|
175
|
+
envelope:Object.fromEntries(['maxArchiveBytes','maxMetadataBytes','maxFiles','maxSourceBytes'].map(key=>[key,p.envelope[key]])),
|
|
176
|
+
reportId:c.certification.reportId,consumerBuildId:c.provenance.consumerBuildId};
|
|
177
|
+
// Claim common-v1 at admission, before even the first metadata/ZIP unit.
|
|
178
|
+
// Compatible older finalizers must not adopt this session as legacy.
|
|
179
|
+
const hash=await sha256(canonical(contract)), marker=JSON.stringify({version:2,generation:sid,finalizationProtocol:'common-v1',uploadSession:{version:1,id:sid,contractHash:hash}});
|
|
180
|
+
// SELECT guards + a final constraint make missing/deleted parents rollback
|
|
181
|
+
// the reservation too. An uncertain response is recovered by the same sid.
|
|
182
|
+
await reserveUploadBudget(env,sid,p.envelope.cost,contract,now,({token,guard,args})=>[
|
|
183
|
+
env.DB.prepare(`INSERT INTO delivery_packages(id,delivery_id,label,position,gallery_enabled,web_enabled,web_format,state,storage_prefix,
|
|
184
|
+
source_fingerprint,file_count,source_bytes,manifest_json,created_at,updated_at)
|
|
185
|
+
SELECT ?,?,?,(SELECT COALESCE(MAX(position),-1)+1 FROM delivery_packages WHERE delivery_id=?),?,?,?,'uploading',?,?,?,?,?,?,?
|
|
186
|
+
FROM deliveries d WHERE d.id=? AND d.status!='deleted' AND (d.files_expires_at IS NULL OR d.files_expires_at>?) AND ${guard}`)
|
|
187
|
+
.bind(sid,input.id,s.label,input.id,+s.galleryEnabled,+s.webEnabled,s.webFormat,prefix,s.sourceFingerprint,s.fileCount,s.sourceBytes,marker,
|
|
188
|
+
new Date(now).toISOString(),new Date(now).toISOString(),input.id,new Date(now).toISOString(),...args),
|
|
189
|
+
env.DB.prepare(`INSERT INTO delivery_manifest_state(package_id,created_at,writer_token,writer_until)
|
|
190
|
+
SELECT ?,?,?,? WHERE ${guard} AND EXISTS(SELECT 1 FROM delivery_packages WHERE id=?)`)
|
|
191
|
+
.bind(sid,new Date(now).toISOString(),input.writerToken,now+65*60000,...args,sid),
|
|
192
|
+
env.DB.prepare(`INSERT INTO delivery_upload_sessions(session_id,delivery_id,contract_hash,created_at)
|
|
193
|
+
SELECT ?,?,?,? WHERE ${guard} AND EXISTS(SELECT 1 FROM delivery_manifest_state WHERE package_id=?)`)
|
|
194
|
+
.bind(sid,input.id,hash,now,...args,sid),
|
|
195
|
+
env.DB.prepare(`INSERT INTO delivery_upload_budget_guards(token,ok) SELECT ?,CASE WHEN EXISTS(SELECT 1 FROM delivery_upload_sessions WHERE session_id=? AND contract_hash=?) THEN 1 ELSE 0 END WHERE ${guard}`).bind(token,sid,hash,...args),
|
|
196
|
+
env.DB.prepare('DELETE FROM delivery_upload_budget_guards WHERE token=?').bind(token),
|
|
197
|
+
]);
|
|
198
|
+
const saved=await load(input);if(!saved)throw changed();return snapshot(saved,input,p);
|
|
199
|
+
}
|
|
200
|
+
async function finish(row,request,token,result) {
|
|
201
|
+
const json=JSON.stringify(result);if(bytes(json)>32768)throw uncertain();
|
|
202
|
+
const guardToken=crypto.randomUUID();
|
|
203
|
+
await env.DB.batch([
|
|
204
|
+
env.DB.prepare(`UPDATE delivery_upload_units SET state='committed',result_json=?,payload_json=NULL
|
|
205
|
+
WHERE session_id=? AND sequence=? AND execution_token=? AND state='running'`).bind(json,row.session_id,request.sequence,token),
|
|
206
|
+
env.DB.prepare(`UPDATE delivery_upload_sessions SET next_sequence=next_sequence+1 WHERE session_id=? AND next_sequence=?
|
|
207
|
+
AND EXISTS(SELECT 1 FROM delivery_upload_units WHERE session_id=? AND sequence=? AND execution_token=? AND state='committed')`)
|
|
208
|
+
.bind(row.session_id,request.sequence,row.session_id,request.sequence,token),
|
|
209
|
+
env.DB.prepare('INSERT INTO delivery_upload_budget_guards(token,ok) VALUES (?,CASE WHEN changes()=1 THEN 1 ELSE 0 END)').bind(guardToken),
|
|
210
|
+
env.DB.prepare('DELETE FROM delivery_upload_budget_guards WHERE token=?').bind(guardToken),
|
|
211
|
+
]);
|
|
212
|
+
}
|
|
213
|
+
async function response(row,input,p,result,replay,slot) {
|
|
214
|
+
// A unit already returns its result. Do not repeat the same receipt inside
|
|
215
|
+
// the snapshot, especially when resuming an entry page/checkpoint.
|
|
216
|
+
const reply={result,session:await snapshot(row,{...input,sequence:undefined},p),replay,...(slot?{slot}:{})};
|
|
217
|
+
if(bytes(JSON.stringify(reply))>(env.DELIVERY_UPLOAD_PROFILE==='paid'?278528:32768))throw needsPaid();
|
|
218
|
+
return reply;
|
|
219
|
+
}
|
|
220
|
+
function bound(p,body,request) {
|
|
221
|
+
const c=p.capabilities.uploadPipeline, spec=p.operations[body.action];
|
|
222
|
+
if(!spec || !spec.profiles?.includes(c.profile))throw error('upload_profile_required','Unità non qualificata sul profilo corrente');
|
|
223
|
+
if(requiredFeature[body.action]&&!c.features[requiredFeature[body.action]])throw changed();
|
|
224
|
+
if(['coalescedFinalize','completePaid'].includes(body.action)&&c.profile!=='paid')throw error('upload_profile_required','Questa unità richiede Paid');
|
|
225
|
+
const maxBytes=Math.min(spec.maxRequestBytes,c.profile==='free'?40960:278528);
|
|
226
|
+
if(!integer(spec.maxRequestBytes)||spec.maxRequestBytes<1||spec.maxRequestBytes>278528||bytes(canonical(request))>maxBytes)throw error('upload_budget_exceeded','Richiesta oltre il budget qualificato',413);
|
|
227
|
+
if(Array.isArray(body.entries)) {
|
|
228
|
+
const limit=c.limits.manifestBatch;
|
|
229
|
+
if(!limit||body.entries.length>Math.min(limit.maxEntries,c.profile==='free'?32:200)||bytes(JSON.stringify(body.entries))>Math.min(limit.maxEntriesBytes,c.profile==='free'?32768:262144))throw error('upload_budget_exceeded','Batch metadati oltre il budget corrente',413);
|
|
230
|
+
}
|
|
231
|
+
if(Array.isArray(body.parts)&&body.parts.length>Math.min(4,c.limits.recordBatch?.maxParts||1) || Array.isArray(body.partNumbers)&&body.partNumbers.length>Math.min(4,c.limits.presignBatch?.maxParts||1))throw error('upload_budget_exceeded','Troppe parti nella stessa unità',413);
|
|
232
|
+
costVector(spec.cost);return spec;
|
|
233
|
+
}
|
|
234
|
+
async function unit(input) {
|
|
235
|
+
const row=await load(input);if(!row)throw changed();
|
|
236
|
+
const body=input.body;
|
|
237
|
+
if(!body || typeof body!=='object' || Array.isArray(body) || !integer(input.sequence) ||
|
|
238
|
+
!(Object.hasOwn(manifestHandlers,body.action)||multipartActions.has(body.action)||body.action==='minimalActivate') ||
|
|
239
|
+
['id','packageId','writerToken','pipelineContractVersion','capabilityRevision','uploadPipeline'].some(k=>Object.hasOwn(body,k)))throw changed();
|
|
240
|
+
const digest=await sha256(canonical(body));
|
|
241
|
+
const old=await env.DB.prepare(`SELECT action,digest,state,
|
|
242
|
+
CASE WHEN length(CAST(result_json AS BLOB))<=${env.DELIVERY_UPLOAD_PROFILE==='paid'?32768:12288} THEN result_json ELSE NULL END result_json
|
|
243
|
+
FROM delivery_upload_units WHERE session_id=? AND sequence=?`).bind(row.session_id,input.sequence).first();
|
|
244
|
+
if(old && (old.digest!==digest||old.action!==body.action))throw changed();
|
|
245
|
+
// Committed results can be read after a downgrade/closed gate; this never
|
|
246
|
+
// grants another operation. The writer is checked even on receipt replay.
|
|
247
|
+
if(body.action==='manifestClaim'&&!old) {
|
|
248
|
+
const writer=await env.DB.prepare('SELECT writer_token,writer_until FROM delivery_manifest_state WHERE package_id=?').bind(row.session_id).first();
|
|
249
|
+
if(writer?.writer_token!==input.writerToken&&writer?.writer_until>=clock())throw error('delivery_manifest','Writer ancora attivo');
|
|
250
|
+
} else {
|
|
251
|
+
const writer=await env.DB.prepare('SELECT writer_token FROM delivery_manifest_state WHERE package_id=?').bind(row.session_id).first();
|
|
252
|
+
if(!input.writerToken||writer?.writer_token!==input.writerToken)throw error('delivery_manifest','Identità del writer cambiata');
|
|
253
|
+
}
|
|
254
|
+
if(old?.state==='committed') {if(!old.result_json)throw needsPaid();return response(row,input,undefined,replayResult(old.result_json),true);}
|
|
255
|
+
if(old)throw uncertain();
|
|
256
|
+
const p=await policy(row),c=p.capabilities.uploadPipeline;
|
|
257
|
+
if(input.capabilityRevision!==c.revision||row.next_sequence!==input.sequence||row.admission_state!=='reserved')throw changed();
|
|
258
|
+
if(row.delivery_status==='deleted'||!['uploading','ready'].includes(row.package_state)||row.files_expires_at&&Date.parse(row.files_expires_at)<=clock())throw changed();
|
|
259
|
+
const spec=bound(p,body,input);
|
|
260
|
+
if(body.uploadId) {
|
|
261
|
+
const upload=await env.DB.prepare('SELECT id FROM delivery_uploads WHERE id=? AND package_id=? AND delivery_id=?').bind(body.uploadId,row.session_id,row.delivery_id).first();
|
|
262
|
+
if(!upload)throw changed();
|
|
263
|
+
}
|
|
264
|
+
if(body.variant&&!['originals',...(row.contract.selection.webEnabled||row.contract.selection.galleryEnabled?['web']:[]),...(row.contract.selection.galleryEnabled?['thumbs']:[])].includes(body.variant))throw changed();
|
|
265
|
+
const maxParts=Math.ceil(p.envelope.maxArchiveBytes/DELIVERY_PART_BYTES);
|
|
266
|
+
if(body.bytes!==undefined&&(!integer(body.bytes)||body.bytes>p.envelope.maxArchiveBytes)||body.partCount!==undefined&&(!integer(body.partCount)||body.partCount>maxParts))throw error('upload_budget_exceeded','Archivio fuori dall’inviluppo ammesso',413);
|
|
267
|
+
if([...(body.partNumbers||[]),...(body.parts||[]).map(p=>p.partNumber),...(body.partNumber==null?[]:[body.partNumber])].some(n=>!integer(n)||n<1||n>maxParts))throw error('upload_budget_exceeded','Parte fuori dall’inviluppo ammesso',413);
|
|
268
|
+
if(Array.isArray(body.entries)) {
|
|
269
|
+
const state=await env.DB.prepare('SELECT metadata_bytes FROM delivery_manifest_state WHERE package_id=?').bind(row.session_id).first();
|
|
270
|
+
const prior=await env.DB.prepare(`SELECT COALESCE(SUM(length(CAST(entry_json AS BLOB))),0) bytes FROM delivery_manifest_entries
|
|
271
|
+
WHERE package_id=? AND entry_id IN (SELECT json_extract(value,'$.index') FROM json_each(?))`).bind(row.session_id,JSON.stringify(body.entries)).first();
|
|
272
|
+
// Raw input includes wrappers and is a conservative upper bound on the
|
|
273
|
+
// normalized replacement. Replayed originals preserve existing variants.
|
|
274
|
+
if(state.metadata_bytes+Math.max(0,bytes(JSON.stringify(body.entries))-prior.bytes)>p.envelope.maxMetadataBytes)throw error('upload_budget_exceeded','Metadati oltre l’inviluppo ammesso',413);
|
|
275
|
+
}
|
|
276
|
+
const now=clock(),slot=await acquireUploadSlot(env,row.session_id,input.writerToken,now,{includeRunningUnits:true});
|
|
277
|
+
// Every new invocation is charged, including a duplicate attempt that races
|
|
278
|
+
// another. Tariffs must include adapter, receipt, lease, recovery and cleanup.
|
|
279
|
+
await consumeUploadBudget(env,row.session_id,'call-'+crypto.randomUUID(),spec.cost,now);
|
|
280
|
+
const token=crypto.randomUUID();
|
|
281
|
+
const baseline=await env.DB.prepare('SELECT state,cursor,page_count FROM delivery_manifest_state WHERE package_id=?').bind(row.session_id).first();
|
|
282
|
+
const acquired=await env.DB.prepare(`INSERT INTO delivery_upload_units(session_id,sequence,action,digest,payload_json,state,execution_token,created_at,baseline_json)
|
|
283
|
+
SELECT ?,?,?,?,?,'running',?,?,? WHERE EXISTS(SELECT 1 FROM delivery_upload_sessions WHERE session_id=? AND next_sequence=?)
|
|
284
|
+
AND NOT EXISTS(SELECT 1 FROM delivery_upload_units WHERE session_id=? AND state IN ('running','uncertain')) ON CONFLICT DO NOTHING`)
|
|
285
|
+
.bind(row.session_id,input.sequence,body.action,digest,canonical(body),token,now,JSON.stringify(baseline),row.session_id,input.sequence,row.session_id).run();
|
|
286
|
+
if(!acquired.meta?.changes)throw uncertain();
|
|
287
|
+
try {
|
|
288
|
+
const result=await withUploadSessionInvocation(env,row.session_id,local=>dispatch(local,{...body,id:row.delivery_id,packageId:row.session_id,writerToken:input.writerToken},context),input.sequence);
|
|
289
|
+
if(result?.ok!==true)throw uncertain();
|
|
290
|
+
if(c.profile==='free'&&bytes(JSON.stringify(result))>FREE_UPLOAD_UNIT.dataBytes)throw needsPaid();
|
|
291
|
+
await finish(row,input,token,result);
|
|
292
|
+
return response(await load(input),input,p,result,false,slot);
|
|
293
|
+
} catch(e) {
|
|
294
|
+
if(e.retryable===false&&e.status>=400&&e.status<500&&e.code!=='upload_unit_uncertain') {
|
|
295
|
+
// This receipt records the rejection, NOT a claim that no storage
|
|
296
|
+
// effect occurred. Manual resume still reconciles the same generation.
|
|
297
|
+
await finish(row,input,token,{ok:false,error:e.message,code:e.code,status:e.status}).catch(()=>{});
|
|
298
|
+
}
|
|
299
|
+
// Do not infer "not applied" from a timeout, process loss or failed receipt.
|
|
300
|
+
// Persist uncertainty; no lease expiry turns it into permission to rerun.
|
|
301
|
+
await env.DB.prepare(`UPDATE delivery_upload_units SET state='uncertain',recovery_allowed=? WHERE session_id=? AND sequence=? AND execution_token=? AND state='running'`)
|
|
302
|
+
.bind(+canRecover(e),row.session_id,input.sequence,token).run().catch(()=>{});
|
|
303
|
+
throw e;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function recover(input) {
|
|
307
|
+
const row=await load(input);if(!row||!integer(input.sequence))throw changed();
|
|
308
|
+
const pending=await env.DB.prepare(`SELECT sequence,action,digest,state,recovery_allowed,attempts,baseline_json,
|
|
309
|
+
CASE WHEN length(CAST(result_json AS BLOB))<=${env.DELIVERY_UPLOAD_PROFILE==='paid'?32768:12288} THEN result_json ELSE NULL END result_json,
|
|
310
|
+
CASE WHEN length(CAST(payload_json AS BLOB))<=${env.DELIVERY_UPLOAD_PROFILE==='paid'?278528:40960} THEN payload_json ELSE NULL END payload_json
|
|
311
|
+
FROM delivery_upload_units WHERE session_id=? AND sequence=?`).bind(row.session_id,input.sequence).first();
|
|
312
|
+
const writer=await env.DB.prepare('SELECT writer_token FROM delivery_manifest_state WHERE package_id=?').bind(row.session_id).first();
|
|
313
|
+
if(!input.writerToken||writer?.writer_token!==input.writerToken)throw error('delivery_manifest','Identità del writer cambiata');
|
|
314
|
+
if(pending?.state==='committed'){if(!pending.result_json)throw needsPaid();return response(row,input,undefined,replayResult(pending.result_json),true);}
|
|
315
|
+
// No timeout takeover of running work. An unknown process lifetime is not
|
|
316
|
+
// proof that storage effects have stopped. Unhandled actions stay reviewable.
|
|
317
|
+
if(!pending||pending.state!=='uncertain'||!pending.recovery_allowed||!recoverable.has(pending.action)||pending.attempts>=3)throw uncertain();
|
|
318
|
+
if(!pending.payload_json)throw needsPaid();
|
|
319
|
+
const body=JSON.parse(pending.payload_json);
|
|
320
|
+
if(await sha256(canonical(body))!==pending.digest||body.action!==pending.action||input.body!==undefined)throw changed();
|
|
321
|
+
const p=await policy(row),c=p.capabilities.uploadPipeline;
|
|
322
|
+
if(input.capabilityRevision!==c.revision||row.next_sequence!==input.sequence||row.admission_state!=='reserved'||
|
|
323
|
+
row.delivery_status==='deleted'||!['uploading','ready'].includes(row.package_state)||row.files_expires_at&&Date.parse(row.files_expires_at)<=clock())throw changed();
|
|
324
|
+
const spec=bound(p,body,{...input,body}),now=clock();
|
|
325
|
+
const slot=await acquireUploadSlot(env,row.session_id,input.writerToken,now,{includeRunningUnits:true});
|
|
326
|
+
await consumeUploadBudget(env,row.session_id,'recovery-'+crypto.randomUUID(),spec.cost,now);
|
|
327
|
+
const token=crypto.randomUUID();
|
|
328
|
+
const claimed=await env.DB.prepare(`UPDATE delivery_upload_units SET state='running',execution_token=?,attempts=attempts+1,recovery_allowed=0
|
|
329
|
+
WHERE session_id=? AND sequence=? AND state='uncertain' AND attempts=?`).bind(token,row.session_id,input.sequence,pending.attempts).run();
|
|
330
|
+
if(!claimed.meta?.changes)throw uncertain();
|
|
331
|
+
try {
|
|
332
|
+
let result;
|
|
333
|
+
if(['segmentedFinalize','coalescedFinalize'].includes(body.action)) {
|
|
334
|
+
const before=JSON.parse(pending.baseline_json),current=await env.DB.prepare('SELECT state,cursor FROM delivery_manifest_state WHERE package_id=?').bind(row.session_id).first();
|
|
335
|
+
if(current&&before&&(current.state!==before.state||current.cursor>before.cursor)) {
|
|
336
|
+
if(current.cursor<before.cursor)throw uncertain();
|
|
337
|
+
if(current.state==='ready') {
|
|
338
|
+
const proof=await env.DB.prepare(`SELECT o.verified,o.digest,o.object_key,p.manifest_json,p.file_count FROM delivery_manifest_objects o
|
|
339
|
+
JOIN delivery_packages p ON p.id=o.package_id WHERE o.package_id=? AND o.page_number=-1`).bind(row.session_id).first();
|
|
340
|
+
const marker=JSON.parse(proof?.manifest_json||'{}');
|
|
341
|
+
if(!proof?.verified||proof.digest!==marker.digest||proof.object_key!==marker.root)throw uncertain();
|
|
342
|
+
}
|
|
343
|
+
result={ok:true,done:current.state==='ready',phase:current.state==='ready'?'verified':current.cursor?'pages':'sealed',cursor:current.cursor,total:row.contract.selection.fileCount};
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if(!result)result=await withUploadSessionInvocation(env,row.session_id,local=>dispatch(local,{...body,id:row.delivery_id,packageId:row.session_id,writerToken:input.writerToken},context),input.sequence);
|
|
347
|
+
if(result?.ok!==true)throw uncertain();
|
|
348
|
+
if(c.profile==='free'&&bytes(JSON.stringify(result))>FREE_UPLOAD_UNIT.dataBytes)throw needsPaid();
|
|
349
|
+
await finish(row,input,token,result);
|
|
350
|
+
return response(await load(input),input,p,result,true,slot);
|
|
351
|
+
}catch(e){
|
|
352
|
+
if(e.retryable===false&&e.status>=400&&e.status<500&&e.code!=='upload_unit_uncertain')await finish(row,input,token,{ok:false,error:e.message,code:e.code,status:e.status}).catch(()=>{});
|
|
353
|
+
await env.DB.prepare("UPDATE delivery_upload_units SET state='uncertain',recovery_allowed=? WHERE session_id=? AND sequence=? AND execution_token=? AND state='running'").bind(+canRecover(e),row.session_id,input.sequence,token).run().catch(()=>{});throw e;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
async function pause(input) {
|
|
357
|
+
const row=await load(input);if(!row)throw changed();
|
|
358
|
+
await assertManifestWriter(env,row.session_id,input.writerToken);
|
|
359
|
+
const pending=await env.DB.prepare(`SELECT sequence FROM delivery_upload_units WHERE session_id=? AND state IN ('running','uncertain') LIMIT 1`).bind(row.session_id).first();
|
|
360
|
+
if(pending)throw uncertain();
|
|
361
|
+
// A supplied stale slot token never releases a newer owner/lease.
|
|
362
|
+
return {released:await releaseUploadSlot(env,row.session_id,input.writerToken,input.slotToken)};
|
|
363
|
+
}
|
|
364
|
+
return {admit,status,unit,pause,recover};
|
|
365
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Internal request accounting. Never populate these limits from an HTTP body.
|
|
2
|
+
import { inheritUploadSessionInvocation } from './delivery-upload-contract.js';
|
|
3
|
+
export const DELIVERY_WORK_BUDGET = Symbol('delivery work budget');
|
|
4
|
+
export const PAID_FINALIZE_LIMITS = Object.freeze({
|
|
5
|
+
units: 4, metadataBytes: 1024 * 1024, d1Calls: 192, externalCalls: 48, betweenUnitsMs: 2000,
|
|
6
|
+
});
|
|
7
|
+
export const policyError = (code, message, status = 409) => Object.assign(new Error(message), { code, status, retryable: false });
|
|
8
|
+
export function requirePaidUpload(env) {
|
|
9
|
+
if (env.DELIVERY_UPLOAD_PROFILE !== 'paid') throw policyError('upload_profile_required', 'Questo passo richiede il profilo Workers Paid; lo stato del caricamento è conservato.');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function createDeliveryWorkBudget(env, now = () => performance.now()) {
|
|
13
|
+
const limits = PAID_FINALIZE_LIMITS, started = now();
|
|
14
|
+
const used = { units: 0, metadataBytes: 0, d1Calls: 0, statements: 0, externalCalls: 0 };
|
|
15
|
+
const overflow = () => policyError('upload_budget_exceeded', 'Budget della richiesta esaurito; riprendi dal cursore persistito.', 413);
|
|
16
|
+
const charge = (key, n) => { if (used[key] + n > limits[key]) throw overflow(); used[key] += n; };
|
|
17
|
+
const read = result => { charge('metadataBytes', new TextEncoder().encode(JSON.stringify(result ?? null)).length); return result; };
|
|
18
|
+
const raw = Symbol('statement');
|
|
19
|
+
const wrap = statement => ({
|
|
20
|
+
[raw]: statement,
|
|
21
|
+
bind(...args) { return wrap(statement.bind(...args)); },
|
|
22
|
+
async first(...args) { charge('d1Calls', 1); used.statements++; return read(await statement.first(...args)); },
|
|
23
|
+
async all(...args) { charge('d1Calls', 1); used.statements++; const result = await statement.all(...args); read(result.results || []); return result; },
|
|
24
|
+
async run() { charge('d1Calls', 1); used.statements++; return statement.run(); },
|
|
25
|
+
});
|
|
26
|
+
const budget = {
|
|
27
|
+
used,
|
|
28
|
+
canRead(bytes) { return bytes + 4096 <= limits.metadataBytes - used.metadataBytes; },
|
|
29
|
+
external() { charge('externalCalls', 1); },
|
|
30
|
+
stopReason() {
|
|
31
|
+
if (used.units >= limits.units) return 'units';
|
|
32
|
+
if (now() - started >= limits.betweenUnitsMs) return 'wall';
|
|
33
|
+
if (limits.d1Calls - used.d1Calls < 32 || limits.externalCalls - used.externalCalls < 6) return 'calls';
|
|
34
|
+
// Leave room for the next unit's small state/size queries before its
|
|
35
|
+
// exact entry-json preflight. Finishing a current unit needs only 4 KiB.
|
|
36
|
+
if (limits.metadataBytes - used.metadataBytes < 16384) return 'metadata';
|
|
37
|
+
return null;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
const scoped = Object.create(env);
|
|
41
|
+
Object.defineProperties(scoped, {
|
|
42
|
+
DB: { value: {
|
|
43
|
+
prepare(sql) { return wrap(env.DB.prepare(sql)); },
|
|
44
|
+
async batch(statements) { charge('d1Calls', 1); used.statements += statements.length; return env.DB.batch(statements.map(s => s[raw])); },
|
|
45
|
+
} },
|
|
46
|
+
[DELIVERY_WORK_BUDGET]: { value: budget },
|
|
47
|
+
});
|
|
48
|
+
return { env: inheritUploadSessionInvocation(env, scoped), budget };
|
|
49
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Request-local technical traces. Never retain request bodies, bind values or headers.
|
|
2
|
+
export const DIAGNOSTICS = Symbol.for('cardinali.request.diagnostics');
|
|
3
|
+
const uuid = value => typeof value === 'string' && /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(value) ? value : null;
|
|
4
|
+
const word = value => typeof value === 'string' && /^[A-Za-z][A-Za-z0-9_.:-]{0,79}$/.test(value) ? value : null;
|
|
5
|
+
export function redact(value, env = {}) {
|
|
6
|
+
let text = String(value ?? '').slice(0, 12000);
|
|
7
|
+
for (const [key, secret] of Object.entries(env)) if (/secret|token|password|application_key|api_key/i.test(key) && typeof secret === 'string' && secret.length >= 4) text = text.split(secret).join('[redacted]');
|
|
8
|
+
return text.replace(/https?:\/\/[^\s<>"']+/gi, '[url]')
|
|
9
|
+
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[email]')
|
|
10
|
+
.replace(/(?:Bearer\s+|(?:authorization|password|secret|token|api[_-]?key)\s*[:=]\s*)[^\s,;]+/gi, '[credential]')
|
|
11
|
+
.replace(/(["'`])[^\n]*?\1/g, '[value]')
|
|
12
|
+
.replace(/[A-Za-z0-9_+/=-]{32,}/g, '[redacted]')
|
|
13
|
+
.replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '').slice(0, 1200);
|
|
14
|
+
}
|
|
15
|
+
const now = () => performance.now();
|
|
16
|
+
export function requestDiagnostics(env, requestId) {
|
|
17
|
+
if (env[DIAGNOSTICS]) return env;
|
|
18
|
+
const trace = { requestId: uuid(requestId) ?? crypto.randomUUID(), started: now(), steps: [], total: 0 };
|
|
19
|
+
const record = step => { trace.total++; trace.steps.push(step); if (trace.steps.length > 12) trace.steps.shift(); };
|
|
20
|
+
const originals = new WeakMap();
|
|
21
|
+
const tracked = (binding, name) => {
|
|
22
|
+
const wrap = (statement, sql) => { const proxy = new Proxy(statement, { get(target, property) {
|
|
23
|
+
if (property === 'bind') return (...values) => wrap(target.bind(...values), sql);
|
|
24
|
+
const fn = target[property];
|
|
25
|
+
if (!['run', 'all', 'first', 'raw'].includes(property) || typeof fn !== 'function') return typeof fn === 'function' ? fn.bind(target) : fn;
|
|
26
|
+
return async (...args) => { const started = now(); try { const result = await fn.apply(target, args); record({ component: name, operation: property, query: redact(sql, env).slice(0, 320), durationMs: Math.round(now() - started), ok: true }); return result; }
|
|
27
|
+
catch (error) { record({ component: name, operation: property, query: redact(sql, env).slice(0, 320), durationMs: Math.round(now() - started), ok: false }); throw error; } };
|
|
28
|
+
}}); originals.set(proxy, statement); return proxy; };
|
|
29
|
+
return new Proxy(binding, { get(target, property) {
|
|
30
|
+
if (property === 'prepare') return sql => wrap(target.prepare(sql), sql);
|
|
31
|
+
if (property === 'batch') return async statements => { const started = now(); try { const result = await target.batch(statements.map(statement => originals.get(statement) ?? statement)); record({ component: name, operation: 'batch', count: statements.length, durationMs: Math.round(now() - started), ok: true }); return result; }
|
|
32
|
+
catch (error) { record({ component: name, operation: 'batch', count: statements.length, durationMs: Math.round(now() - started), ok: false }); throw error; } };
|
|
33
|
+
const fn = target[property]; return typeof fn === 'function' ? fn.bind(target) : fn;
|
|
34
|
+
}});
|
|
35
|
+
};
|
|
36
|
+
const local = { ...env, [DIAGNOSTICS]: { trace, record } };
|
|
37
|
+
for (const name of ['DB', 'CONTENT_DB']) if (env[name]?.prepare) local[name] = tracked(env[name], name);
|
|
38
|
+
return local;
|
|
39
|
+
}
|
|
40
|
+
export async function technicalDiagnostic(error, { env = {}, operation, version, body = {} } = {}) {
|
|
41
|
+
const trace = env[DIAGNOSTICS]?.trace;
|
|
42
|
+
const causes = [], seen = new Set();
|
|
43
|
+
for (let current = error; current && !seen.has(current) && causes.length < 3; current = current.cause) {
|
|
44
|
+
seen.add(current);
|
|
45
|
+
const frames = String(current.stack ?? '').split('\n').slice(1, 25).flatMap(line => {
|
|
46
|
+
const match = line.match(/(?:^|[\/\s(])([A-Za-z0-9_.-]+\.(?:[cm]?js|ts)):(\d+):(\d+)\)?$/);
|
|
47
|
+
return match ? [{ file: match[1], line: Number(match[2]), column: Number(match[3]) }] : [];
|
|
48
|
+
}).slice(0, 6);
|
|
49
|
+
causes.push({ type: word(current.name) ?? 'Error', code: word(current.code), message: redact(current.message ?? current, env).slice(0, 600), frames });
|
|
50
|
+
}
|
|
51
|
+
const context = {};
|
|
52
|
+
for (const key of ['id', 'packageId', 'sessionId']) if (uuid(body?.[key])) context[key] = body[key];
|
|
53
|
+
for (const key of ['cursor', 'offset', 'sequence', 'partNumber']) if (Number.isSafeInteger(body?.[key]) && body[key] >= 0) context[key] = body[key];
|
|
54
|
+
if (['originals', 'web', 'thumbs'].includes(body?.variant)) context.variant = body.variant;
|
|
55
|
+
const steps = trace?.steps ?? [];
|
|
56
|
+
const signature = JSON.stringify([word(operation), causes.map(c => [c.type, c.code, c.message, c.frames]), steps.filter(s => !s.ok).map(s => [s.component, s.operation, s.query])]);
|
|
57
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(signature));
|
|
58
|
+
return { version: 1, capture: 'exception', operation: word(operation) ?? 'unknown', backendVersion: /^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?$/i.test(version ?? '') ? version : 'unknown', requestId: trace?.requestId ?? crypto.randomUUID(), durationMs: trace ? Math.round(now() - trace.started) : null, stepCount: trace?.total ?? 0, steps, context, causes, fingerprint: Array.from(new Uint8Array(digest), x => x.toString(16).padStart(2, '0')).join('') };
|
|
59
|
+
}
|