CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (push) Successful in 4s
masterplan-lock / check (pull_request) Successful in 5s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 16s
CI (SIAX Cloud) / security (pull_request) Successful in 35s
CI (SIAX Cloud) / integration (pull_request) Successful in 37s
CI (SIAX Cloud) / quality (pull_request) Successful in 43s
A client retry with the same idempotency key replayed the journal and got 'outcome_unknown' even when the first upload had succeeded, because the verified DOC0 receipt was never persisted. Store document/version/checksum/ stage on the attempt (sql/021) and return it on replay; only a missing receipt falls back to observation. No second POST, no duplicate document.
161 lines
7.2 KiB
TypeScript
161 lines
7.2 KiB
TypeScript
import type { RepositorySql } from '../repositories/db';
|
|
import type postgres from 'postgres';
|
|
|
|
/** All scope values must come from authenticated and project-authorized context. */
|
|
export interface UploadAttemptIdentity {
|
|
tenantId: string;
|
|
projectId: string;
|
|
actorId: string;
|
|
/** Also used as the original DOC0 idempotency key by the future caller. */
|
|
attemptId: string;
|
|
sourceSha256: string;
|
|
sourceSizeBytes: number;
|
|
requestFingerprint: string;
|
|
}
|
|
export type UploadAttemptState = 'prepared' | 'dispatch_started';
|
|
export interface StoredUploadReceipt {
|
|
documentId: string;
|
|
versionId: string;
|
|
checksumSha256: string;
|
|
pipelineStage: string;
|
|
}
|
|
interface Row {
|
|
source_sha256: string;
|
|
source_size_bytes: string;
|
|
request_fingerprint: string;
|
|
state: UploadAttemptState;
|
|
}
|
|
|
|
function validate(input: UploadAttemptIdentity): void {
|
|
if (
|
|
![input.tenantId, input.projectId, input.actorId, input.attemptId].every(
|
|
(value) => typeof value === 'string' && value.trim().length > 0 && value.length <= 256,
|
|
) ||
|
|
!/^[0-9a-f]{64}$/.test(input.sourceSha256) ||
|
|
!/^[0-9a-f]{64}$/.test(input.requestFingerprint) ||
|
|
!Number.isSafeInteger(input.sourceSizeBytes) ||
|
|
input.sourceSizeBytes <= 0
|
|
) {
|
|
throw new Error('Invalid document upload attempt');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Internal, one-way coordination primitive; not an authentication, project
|
|
* authorization or content-integrity check. Callers must persist the exact
|
|
* DOC0-compatible fingerprint and verify actual uploaded bytes themselves.
|
|
* RLS session settings are set only inside each transaction; the database
|
|
* role must not be superuser or BYPASSRLS. A started dispatch is never
|
|
* automatically retried or declared absent. No customer route is wired.
|
|
*/
|
|
export class PostgresUploadAttemptStore {
|
|
constructor(private readonly sql: RepositorySql) {}
|
|
|
|
private async scoped<T>(
|
|
input: UploadAttemptIdentity,
|
|
action: (tx: postgres.TransactionSql) => Promise<T>,
|
|
): Promise<T> {
|
|
validate(input);
|
|
return this.sql.begin(async (tx) => {
|
|
const roles = await tx<{ rolsuper: boolean; rolbypassrls: boolean }[]>`
|
|
SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user`;
|
|
if (!roles[0] || roles[0].rolsuper || roles[0].rolbypassrls)
|
|
throw new Error('Upload attempts require an RLS-enforced database role');
|
|
await tx`SELECT set_config('app.opt_tenant_id', ${input.tenantId}, true), set_config('app.opt_project_id', ${input.projectId}, true), set_config('app.opt_actor_id', ${input.actorId}, true)`;
|
|
return action(tx);
|
|
}) as Promise<T>;
|
|
}
|
|
|
|
async prepare(input: UploadAttemptIdentity): Promise<{ state: UploadAttemptState; replay: boolean }> {
|
|
return this.scoped(input, async (tx) => {
|
|
const inserted = await tx<Row[]>`
|
|
INSERT INTO opt_document_upload_attempts (tenant_id,project_id,actor_id,attempt_id,source_sha256,source_size_bytes,request_fingerprint,state)
|
|
VALUES (${input.tenantId},${input.projectId},${input.actorId},${input.attemptId},${input.sourceSha256},${input.sourceSizeBytes},${input.requestFingerprint},'prepared')
|
|
ON CONFLICT (tenant_id,attempt_id) DO NOTHING RETURNING source_sha256,source_size_bytes,request_fingerprint,state`;
|
|
const rows = inserted.length
|
|
? inserted
|
|
: await tx<Row[]>`
|
|
SELECT source_sha256,source_size_bytes,request_fingerprint,state FROM opt_document_upload_attempts
|
|
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId} AND attempt_id=${input.attemptId}`;
|
|
const row = rows[0];
|
|
if (
|
|
!row ||
|
|
row.source_sha256 !== input.sourceSha256 ||
|
|
row.source_size_bytes !== String(input.sourceSizeBytes) ||
|
|
row.request_fingerprint !== input.requestFingerprint
|
|
) {
|
|
throw new Error('Document upload attempt cannot be reused');
|
|
}
|
|
return { state: row.state, replay: inserted.length === 0 };
|
|
});
|
|
}
|
|
|
|
/** Exactly one claimant may start dispatch. Persist this before any network write. */
|
|
async startDispatch(input: UploadAttemptIdentity): Promise<boolean> {
|
|
return this.scoped(input, async (tx) => {
|
|
const rows = await tx<{ attempt_id: string }[]>`
|
|
UPDATE opt_document_upload_attempts SET state='dispatch_started', updated_at=clock_timestamp()
|
|
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId}
|
|
AND attempt_id=${input.attemptId} AND source_sha256=${input.sourceSha256}
|
|
AND source_size_bytes=${input.sourceSizeBytes} AND request_fingerprint=${input.requestFingerprint}
|
|
AND state='prepared' RETURNING attempt_id`;
|
|
return rows.length === 1;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Persist the verified DOC0 receipt so a retry with the same idempotency key
|
|
* returns the SAME 201 receipt instead of "outcome unknown". Only the fields
|
|
* DOC0 itself returned are stored; storage/extraction are not re-proven here.
|
|
*/
|
|
async recordReceipt(input: UploadAttemptIdentity, receipt: StoredUploadReceipt): Promise<void> {
|
|
if (
|
|
![receipt.documentId, receipt.versionId, receipt.pipelineStage].every(
|
|
(value) => typeof value === 'string' && value.trim().length > 0 && value.length <= 256,
|
|
) ||
|
|
!/^[0-9a-f]{64}$/.test(receipt.checksumSha256)
|
|
) {
|
|
throw new Error('Invalid upload receipt');
|
|
}
|
|
await this.scoped(input, async (tx) => {
|
|
const rows = await tx<{ attempt_id: string }[]>`
|
|
UPDATE opt_document_upload_attempts
|
|
SET document_id=${receipt.documentId}, version_id=${receipt.versionId},
|
|
receipt_checksum=${receipt.checksumSha256}, pipeline_stage=${receipt.pipelineStage},
|
|
verified_at=clock_timestamp(), updated_at=clock_timestamp()
|
|
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId}
|
|
AND attempt_id=${input.attemptId} AND source_sha256=${input.sourceSha256}
|
|
AND source_size_bytes=${input.sourceSizeBytes} AND request_fingerprint=${input.requestFingerprint}
|
|
RETURNING attempt_id`;
|
|
if (rows.length !== 1) throw new Error('Upload attempt receipt could not be recorded');
|
|
});
|
|
}
|
|
|
|
async getReceipt(input: UploadAttemptIdentity): Promise<StoredUploadReceipt | undefined> {
|
|
return this.scoped(input, async (tx) => {
|
|
const rows = await tx<
|
|
{
|
|
document_id: string | null;
|
|
version_id: string | null;
|
|
receipt_checksum: string | null;
|
|
pipeline_stage: string | null;
|
|
}[]
|
|
>`
|
|
SELECT document_id, version_id, receipt_checksum, pipeline_stage
|
|
FROM opt_document_upload_attempts
|
|
WHERE tenant_id=${input.tenantId} AND project_id=${input.projectId} AND actor_id=${input.actorId}
|
|
AND attempt_id=${input.attemptId} AND source_sha256=${input.sourceSha256}
|
|
AND source_size_bytes=${input.sourceSizeBytes} AND request_fingerprint=${input.requestFingerprint}`;
|
|
const row = rows[0];
|
|
if (!row?.document_id || !row.version_id || !row.receipt_checksum || !row.pipeline_stage)
|
|
return undefined;
|
|
return {
|
|
documentId: row.document_id,
|
|
versionId: row.version_id,
|
|
checksumSha256: row.receipt_checksum,
|
|
pipelineStage: row.pipeline_stage,
|
|
};
|
|
});
|
|
}
|
|
}
|