Persist staged image uploads alongside document operations
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import type { Id, Json } from '../canvas-core/types.ts';
|
||||
import { fault, freeze, validJson } from '../canvas-core/values.ts';
|
||||
import type { AssetPort, ResourceRecord, StoredAsset } from '../canvas-runtime/resources.ts';
|
||||
import type { FrozenRequest } from '../canvas-runtime/ledger.ts';
|
||||
import type { OperationStatus } from '../canvas-runtime/scheduler.ts';
|
||||
import type { ServiceResponse, ServiceTransport } from './foundry.ts';
|
||||
|
||||
const uuid = /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i;
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
if (!value || Array.isArray(value) || typeof value !== 'object') throw fault('invalid_asset_response');
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
function payload(request: FrozenRequest) {
|
||||
const raw = object(JSON.parse(request.body));
|
||||
if (request.kind !== 'asset.upload' || request.protocolVersion !== 2 || raw.protocol_version !== 2 || raw.request_id !== request.id || !uuid.test(request.id) || typeof raw.resource_id !== 'string' || !uuid.test(raw.resource_id) || request.operationIds.length !== 1 || raw.operation_id !== request.operationIds[0] || request.canvasIds.length || Object.keys(request.expectedVersions).length || typeof raw.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(raw.sha256) || typeof raw.byte_length !== 'number' || !Number.isSafeInteger(raw.byte_length) || raw.byte_length < 1 || raw.byte_length > 20 * 1024 * 1024 || typeof raw.name !== 'string' || !raw.name || typeof raw.mime_type !== 'string') throw fault('invalid_asset_request');
|
||||
return raw;
|
||||
}
|
||||
function status(request: FrozenRequest, response: ServiceResponse, query: boolean): OperationStatus {
|
||||
const body = object(response.body), matching = body.protocol_version === 2 && body.request_id === request.id;
|
||||
if (matching && body.status === 'applied' && response.status >= 200 && response.status < 300) {
|
||||
if (!validJson(body)) throw fault('invalid_asset_response');
|
||||
return freeze({ outcome: 'applied', canonical: JSON.parse(JSON.stringify(body)) as Json });
|
||||
}
|
||||
if (query && matching && body.status === 'unknown' && response.status === 404) return { outcome: 'unresolved', error: 'asset_receipt_unknown', retryAfterMs: response.retryAfterMs };
|
||||
const error = typeof body.error === 'string' ? body.error : 'asset_transport_unknown';
|
||||
// A bare rejection does not prove whether an earlier upload committed.
|
||||
return { outcome: 'unresolved', error, retryAfterMs: response.retryAfterMs, ...(response.status >= 400 && response.status < 500 ? { blocked: true } : {}) };
|
||||
}
|
||||
|
||||
/** Immutable bytes and a preallocated resource ID survive response loss and view changes. */
|
||||
export function createFoundryAssets(options: { workspaceId: Id; transport: ServiceTransport; project?: string; origin?: string }): AssetPort {
|
||||
if (!uuid.test(options.workspaceId)) throw fault('invalid_service_scope');
|
||||
const origin = new URL(options.origin ?? 'https://api.foundry.entroia.com');
|
||||
if (origin.protocol !== 'https:' || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== '/') throw fault('invalid_asset_origin');
|
||||
const path = `workspaces/${encodeURIComponent(options.workspaceId)}/assets`;
|
||||
const sourceURL = (id: Id) => `${origin.origin}/projects/${encodeURIComponent(options.project ?? 'endoleap')}/${path}/${encodeURIComponent(id)}`;
|
||||
const accept = (request: FrozenRequest, result: OperationStatus, resource: ResourceRecord): StoredAsset => {
|
||||
const raw = payload(request), receipt = object(result.canonical), asset = object(receipt.asset);
|
||||
if (result.outcome !== 'applied' || receipt.protocol_version !== 2 || receipt.request_id !== request.id || receipt.status !== 'applied' || resource.id !== raw.resource_id || resource.operationId !== raw.operation_id || resource.digest !== raw.sha256 || resource.byteLength !== raw.byte_length || asset.id !== resource.id || asset.url !== sourceURL(resource.id) || asset.bytes !== resource.byteLength || typeof asset.width !== 'number' || typeof asset.height !== 'number' || !Number.isSafeInteger(asset.width) || !Number.isSafeInteger(asset.height) || asset.width <= 0 || asset.height <= 0 || asset.width * asset.height > 40_000_000 || !['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(asset.mime_type as string)) throw fault('asset_receipt_mismatch');
|
||||
return freeze(JSON.parse(JSON.stringify(asset)) as StoredAsset);
|
||||
};
|
||||
async function execute(request: FrozenRequest, bytes: Blob | undefined, signal: AbortSignal) {
|
||||
try {
|
||||
const raw = payload(request);
|
||||
let body: FormData | undefined;
|
||||
if (bytes) {
|
||||
const digest = [...new Uint8Array(await crypto.subtle.digest('SHA-256', await bytes.arrayBuffer()))].map(value => value.toString(16).padStart(2, '0')).join('');
|
||||
if (bytes.size !== raw.byte_length || digest !== raw.sha256) throw fault('resource_bytes_mismatch');
|
||||
body = new FormData(); body.append('image', bytes, raw.name as string);
|
||||
}
|
||||
const response = await options.transport({ method: bytes ? 'POST' : 'GET', path: bytes ? path : `${path}/operations/${encodeURIComponent(request.id)}`, requestId: bytes ? request.id : undefined, resourceId: bytes ? raw.resource_id as string : undefined, body, signal });
|
||||
return status(request, response, !bytes);
|
||||
} catch (error) {
|
||||
const code = (error as { code?: string }).code;
|
||||
return { outcome: 'unresolved' as const, error: code ?? 'asset_transport_unknown', ...(code && code !== 'invalid_asset_response' ? { blocked: true } : {}) };
|
||||
}
|
||||
}
|
||||
return Object.freeze({ sourceURL, displayURL: (id: Id) => `/api/foundry/${path}/${encodeURIComponent(id)}?variant=preview`, accept,
|
||||
upload: (request: FrozenRequest, bytes: Blob, signal: AbortSignal) => execute(request, bytes, signal),
|
||||
query: (request: FrozenRequest, signal: AbortSignal) => execute(request, undefined, signal),
|
||||
});
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import type { EngineSnapshot, PersistencePort } from '../canvas-runtime/contract
|
||||
import type { FrozenRequest } from '../canvas-runtime/ledger.ts';
|
||||
import type { OperationStatus } from '../canvas-runtime/scheduler.ts';
|
||||
|
||||
export type ServiceRequest = { readonly path: string; readonly method: 'GET' | 'POST'; readonly requestId?: Id; readonly body?: string; readonly signal?: AbortSignal };
|
||||
export type ServiceRequest = { readonly path: string; readonly method: 'GET' | 'POST'; readonly requestId?: Id; readonly body?: string | FormData; readonly resourceId?: Id; readonly signal?: AbortSignal };
|
||||
export type ServiceResponse = { readonly status: number; readonly body: unknown; readonly retryAfterMs?: number };
|
||||
export type ServiceTransport = (request: ServiceRequest) => Promise<ServiceResponse>;
|
||||
const uuid = /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i;
|
||||
@@ -26,7 +26,7 @@ export function createFoundryTransport(options: { accountId: Id; isCurrentIdenti
|
||||
return async input => {
|
||||
if (!options.isCurrentIdentity()) throw fault('identity_changed');
|
||||
const response = await requestFetch(`${options.basePath ?? '/api/foundry/'}${input.path}`, { method: input.method, body: input.body, signal: input.signal, credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: {
|
||||
Accept: 'application/json', 'Content-Type': 'application/json', 'X-Expected-Account': options.accountId, ...(input.requestId ? { 'Idempotency-Key': input.requestId } : {}),
|
||||
Accept: 'application/json', ...(input.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }), ...(input.resourceId ? { 'X-Resource-Id': input.resourceId } : {}), 'X-Expected-Account': options.accountId, ...(input.requestId ? { 'Idempotency-Key': input.requestId } : {}),
|
||||
} });
|
||||
if (!options.isCurrentIdentity()) { await response.body?.cancel(); throw fault('identity_changed'); }
|
||||
let body: unknown;
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export * from './foundry.ts';
|
||||
export * from './assets.ts';
|
||||
|
||||
Reference in New Issue
Block a user