@fungi.computer/darkroom 0.11.10 → 0.11.12
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/README.md +13 -0
- package/examples/standalone/README.md +52 -0
- package/examples/standalone/worker.ts +87 -0
- package/examples/standalone/wrangler.jsonc +26 -0
- package/package.json +8 -2
- package/src/app-media-contracts.ts +142 -0
- package/src/audio-providers/elevenlabs.ts +108 -0
- package/src/audio-reference-types.ts +47 -0
- package/src/audio-references.ts +107 -0
- package/src/browser-failure.ts +73 -0
- package/src/browser.ts +7 -0
- package/src/cloudflare/provider-reason.ts +89 -0
- package/src/cloudflare/provider.ts +405 -0
- package/src/cloudflare/r2-destination.ts +130 -0
- package/src/cloudflare/reference-images.ts +193 -0
- package/src/cloudflare.ts +38 -0
- package/src/cost-estimate.ts +129 -0
- package/src/daily-media-meter.ts +163 -0
- package/src/effect.ts +2 -0
- package/src/execution-error.ts +98 -0
- package/src/failure.ts +13 -0
- package/src/gateway-models.ts +304 -0
- package/src/gateway-wire.ts +36 -0
- package/src/index.ts +1454 -0
- package/src/media-binding.ts +260 -0
- package/src/media-content-type.ts +60 -0
- package/src/media-generation.ts +171 -0
- package/src/media-operation-contract.ts +173 -0
- package/src/media-operation-do.ts +257 -0
- package/src/media-operation-owner.ts +1786 -0
- package/src/media-operation-storage.ts +110 -0
- package/src/media-operation.ts +454 -0
- package/src/media-path.ts +8 -0
- package/src/media-quote.ts +34 -0
- package/src/media-run-lifetime.ts +5 -0
- package/src/media-written.ts +38 -0
- package/src/model-catalog.ts +1574 -0
- package/src/neurons.ts +6 -0
- package/src/node-webpmux.d.ts +12 -0
- package/src/provenance-bytes.ts +22 -0
- package/src/provenance-export.ts +126 -0
- package/src/provenance-jpeg.ts +83 -0
- package/src/provenance-png.ts +26 -0
- package/src/provenance-signed.ts +7 -0
- package/src/provenance-xmp.ts +57 -0
- package/src/provenance.ts +87 -0
- package/src/reference-image-size.ts +67 -0
- package/src/reference-read.ts +50 -0
- package/src/server.ts +711 -0
- package/src/video-providers/index.ts +18 -0
- package/src/video-providers/minimax.ts +96 -0
- package/src/video-providers/reference-encoding.ts +32 -0
- package/src/video-providers/types.ts +47 -0
- package/src/video-providers/unified.ts +68 -0
- package/test/audio-models.test.ts +428 -0
- package/test/audio-references.test.ts +428 -0
- package/test/custom-catalogue.test.ts +257 -0
- package/test/daily-media-meter.test.ts +287 -0
- package/test/failure.test.ts +190 -0
- package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
- package/test/fixtures/media-operation.fixture.ts +134 -0
- package/test/fixtures/media-team-prompts.ts +7 -0
- package/test/fixtures/native-sqlite.fixture.ts +40 -0
- package/test/gateway-models.test.ts +712 -0
- package/test/media-operation-do.test.ts +1565 -0
- package/test/media-quote.test.ts +81 -0
- package/test/media-retention.test.ts +597 -0
- package/test/media-service.test.ts +549 -0
- package/test/media-team-prompts.test.ts +92 -0
- package/test/model-facts.test.ts +126 -0
- package/test/prompt-limit.test.ts +53 -0
- package/test/provenance-export.test.ts +144 -0
- package/test/provenance-images.fixture.mjs +17 -0
- package/test/provenance.test.ts +179 -0
- package/test/provider-gateway.test.ts +114 -0
- package/test/provider-reasons.test.ts +133 -0
- package/test/r2-destination.test.ts +166 -0
- package/test/reference-image-size.test.ts +73 -0
- package/test/reference-images-billing.test.ts +40 -0
- package/test/reference-images.test.ts +399 -0
- package/test/standalone.cloudflare.test.mjs +298 -0
- package/test/standalone.worker.mjs +70 -0
- package/test/transform-models.test.ts +400 -0
- package/test/video-capabilities.test.ts +160 -0
- package/test/video-contract.test.ts +533 -0
- package/test/video-failure-lifecycle.test.ts +177 -0
- package/test/video-provider.test.ts +136 -0
- package/test/video-wire.test.ts +251 -0
- package/vitest.cloudflare.config.ts +22 -0
- package/vitest.node.config.ts +14 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** Facts an erased operation keeps: its destination file, and whether a billing hold may be open. */
|
|
2
|
+
export type MediaErasureMarker = Readonly<{
|
|
3
|
+
/** The destination path the operation wrote or could have written. */
|
|
4
|
+
destinationPath: string | null;
|
|
5
|
+
/** SHA-256 of the bytes it wrote or was about to write there. */
|
|
6
|
+
writtenSha256: string | null;
|
|
7
|
+
/** The operation was erased before it finished. */
|
|
8
|
+
abandonedGeneration: boolean;
|
|
9
|
+
}>;
|
|
10
|
+
|
|
11
|
+
/** SQL rows stay untrusted until the owner decodes their stored representation. */
|
|
12
|
+
export type MediaOperationStorage = {
|
|
13
|
+
/** Native synchronous SQL interface. */
|
|
14
|
+
sql: {
|
|
15
|
+
/** Execute a native SQL statement with positional bindings. */
|
|
16
|
+
exec(
|
|
17
|
+
query: string,
|
|
18
|
+
...bindings: (string | number | null)[]
|
|
19
|
+
): {
|
|
20
|
+
/** Read the native SQL rows as objects for boundary decoding. */
|
|
21
|
+
toArray(): readonly object[];
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
/** Run one atomic synchronous local mutation. */
|
|
25
|
+
transactionSync<T>(body: () => T): T;
|
|
26
|
+
/** Read the durable erasure marker. */
|
|
27
|
+
isErased(): Promise<boolean>;
|
|
28
|
+
/**
|
|
29
|
+
* Persist the durable erasure marker with the facts the host needs after
|
|
30
|
+
* erasure. Never removed: nothing may delete it.
|
|
31
|
+
*/
|
|
32
|
+
markErased(marker: MediaErasureMarker): Promise<void>;
|
|
33
|
+
/** Read the facts kept with the marker, or null for a marker without them. */
|
|
34
|
+
readErasureMarker(): Promise<MediaErasureMarker | null>;
|
|
35
|
+
/** List local key-value storage keys for erasure readback. */
|
|
36
|
+
listKeys(): Promise<readonly string[]>;
|
|
37
|
+
/** Remove any scheduled background alarm. */
|
|
38
|
+
deleteAlarm(): Promise<void>;
|
|
39
|
+
/** Remove the named key-value entries. */
|
|
40
|
+
deleteKeys(keys: readonly string[]): Promise<void>;
|
|
41
|
+
/** Read the current background alarm, or null. */
|
|
42
|
+
getAlarm(): Promise<number | null>;
|
|
43
|
+
/** Schedule background generation at the given timestamp. */
|
|
44
|
+
setAlarm(timestamp: number): Promise<void>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** The identity, serialization and storage owned by one media operation. */
|
|
48
|
+
export type MediaOperationContext = {
|
|
49
|
+
/** Durable operation identity selected by the host. */
|
|
50
|
+
id: {
|
|
51
|
+
/** Stable error name or durable object name. */
|
|
52
|
+
name: string | undefined;
|
|
53
|
+
};
|
|
54
|
+
/** Host-owned SQL, key-value storage and alarms. */
|
|
55
|
+
storage: MediaOperationStorage;
|
|
56
|
+
/** Serialize asynchronous owner initialization with requests. */
|
|
57
|
+
blockConcurrencyWhile<T>(body: () => Promise<T>): Promise<T>;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/** Object metadata consumed by retention and recovery; mirrors the native R2 fields used here. */
|
|
61
|
+
export type MediaOperationObject = Readonly<{
|
|
62
|
+
/** Immutable output key. */
|
|
63
|
+
key: string;
|
|
64
|
+
/** Object version captured when its exact bytes were written. */
|
|
65
|
+
version: string;
|
|
66
|
+
/** Stored byte length. */
|
|
67
|
+
size: number;
|
|
68
|
+
/** Actual retained MIME type. */
|
|
69
|
+
httpMetadata?: Readonly<{
|
|
70
|
+
/** MIME type of the retained output. */ contentType?: string;
|
|
71
|
+
}>;
|
|
72
|
+
}>;
|
|
73
|
+
|
|
74
|
+
/** Exact object operations needed for immutable media outputs and references. */
|
|
75
|
+
export type MediaOperationBucket = {
|
|
76
|
+
/** Conditionally retain immutable provider bytes or background reference bytes. */
|
|
77
|
+
put(
|
|
78
|
+
key: string,
|
|
79
|
+
bytes: Uint8Array,
|
|
80
|
+
options?: Readonly<{
|
|
81
|
+
/** Native R2 conditional write, used once for an immutable output. */
|
|
82
|
+
onlyIf?: Readonly<{
|
|
83
|
+
/** Refuse an existing output key. */ etagDoesNotMatch: string;
|
|
84
|
+
}>;
|
|
85
|
+
/** MIME type for exact-output recovery. */
|
|
86
|
+
httpMetadata?: Readonly<{
|
|
87
|
+
/** MIME type of the retained output. */ contentType: string;
|
|
88
|
+
}>;
|
|
89
|
+
/** Decoded reference format and dimensions for background generation. */
|
|
90
|
+
customMetadata?: Readonly<Record<string, string>>;
|
|
91
|
+
}>,
|
|
92
|
+
): Promise<Readonly<{
|
|
93
|
+
/** Stored immutable object version. */ version: string;
|
|
94
|
+
}> | null>;
|
|
95
|
+
/** Read immutable object metadata without loading bytes. */
|
|
96
|
+
head(key: string): Promise<MediaOperationObject | null>;
|
|
97
|
+
/** Read retained object bytes and metadata. */
|
|
98
|
+
get(key: string): Promise<
|
|
99
|
+
| (Omit<MediaOperationObject, "httpMetadata"> &
|
|
100
|
+
Readonly<{
|
|
101
|
+
/** Stored background reference metadata. */
|
|
102
|
+
customMetadata?: Readonly<Record<string, string>>;
|
|
103
|
+
/** Read the exact retained object bytes. */
|
|
104
|
+
arrayBuffer: () => Promise<ArrayBuffer>;
|
|
105
|
+
}>)
|
|
106
|
+
| null
|
|
107
|
+
>;
|
|
108
|
+
/** Delete the owner-selected object key. */
|
|
109
|
+
delete(key: string): Promise<void>;
|
|
110
|
+
};
|
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MediaExecutionError,
|
|
3
|
+
MediaOutputFormatMismatch,
|
|
4
|
+
MediaSafetyFilterRefusal,
|
|
5
|
+
type MediaFailureStage,
|
|
6
|
+
} from "./execution-error.js";
|
|
7
|
+
import * as Effect from "effect/Effect";
|
|
8
|
+
import { reportCatchFailure } from "./failure.js";
|
|
9
|
+
|
|
10
|
+
import { mediaUnits } from "./gateway-models.js";
|
|
11
|
+
import { getMediaModel } from "./model-catalog.js";
|
|
12
|
+
import { mediaWrittenDigest } from "./media-written.js";
|
|
13
|
+
import { embedProvenance, type ProvenanceEmbedResult } from "./provenance.js";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
import type { MediaImage } from "./media-operation-owner.js";
|
|
16
|
+
import {
|
|
17
|
+
mediaGenerationSettingsSchema,
|
|
18
|
+
validateMediaGenerationSettings,
|
|
19
|
+
} from "./index.js";
|
|
20
|
+
|
|
21
|
+
type GeneratedMedia = Readonly<{
|
|
22
|
+
/** Generated output bytes. */
|
|
23
|
+
bytes: Uint8Array;
|
|
24
|
+
/** Actual output encoding. */
|
|
25
|
+
format: string;
|
|
26
|
+
}>;
|
|
27
|
+
|
|
28
|
+
import type { MediaExecution } from "./media-operation-contract.js";
|
|
29
|
+
|
|
30
|
+
function unchargedFailure(error: MediaExecutionError): MediaExecutionError {
|
|
31
|
+
const options = {
|
|
32
|
+
cause: error.cause,
|
|
33
|
+
provider: error.provider,
|
|
34
|
+
customerCharge: "none" as const,
|
|
35
|
+
};
|
|
36
|
+
return error instanceof MediaSafetyFilterRefusal
|
|
37
|
+
? new MediaSafetyFilterRefusal(options)
|
|
38
|
+
: new MediaExecutionError(error.stage, options);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function call<A>(body: () => A | Promise<A>, stage: MediaFailureStage) {
|
|
42
|
+
return Effect.tryPromise({
|
|
43
|
+
try: () => Promise.resolve(body()),
|
|
44
|
+
catch: (cause) =>
|
|
45
|
+
cause instanceof MediaExecutionError
|
|
46
|
+
? cause
|
|
47
|
+
: new MediaExecutionError(stage, {
|
|
48
|
+
cause: cause instanceof Error ? cause : new Error(String(cause)),
|
|
49
|
+
}),
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function untilAborted<A>(
|
|
54
|
+
signal: AbortSignal | undefined,
|
|
55
|
+
body: () => Promise<A>,
|
|
56
|
+
) {
|
|
57
|
+
if (signal === undefined) return body();
|
|
58
|
+
if (signal.aborted)
|
|
59
|
+
return Promise.reject(
|
|
60
|
+
new Error("Media generation was cancelled", { cause: signal.reason }),
|
|
61
|
+
);
|
|
62
|
+
return new Promise<A>((resolve, reject) => {
|
|
63
|
+
const abort = () => {
|
|
64
|
+
reject(
|
|
65
|
+
new Error("Media generation was cancelled", { cause: signal.reason }),
|
|
66
|
+
);
|
|
67
|
+
};
|
|
68
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
69
|
+
Promise.resolve()
|
|
70
|
+
.then(body)
|
|
71
|
+
.then(resolve, reject)
|
|
72
|
+
.finally(() => {
|
|
73
|
+
signal.removeEventListener("abort", abort);
|
|
74
|
+
});
|
|
75
|
+
if (signal.aborted) abort();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Own one replay-safe Media execution. Network effects stay outside storage
|
|
81
|
+
* transactions; the durable operation hides its transition sequence.
|
|
82
|
+
*/
|
|
83
|
+
export function executeMediaOperation(input: MediaExecution) {
|
|
84
|
+
return Effect.gen(function* () {
|
|
85
|
+
const admission = yield* call(
|
|
86
|
+
() =>
|
|
87
|
+
input.operation.admit(
|
|
88
|
+
input.actorUserId,
|
|
89
|
+
input.coordinates,
|
|
90
|
+
input.requestId,
|
|
91
|
+
input.request,
|
|
92
|
+
),
|
|
93
|
+
"operation",
|
|
94
|
+
);
|
|
95
|
+
if (admission.kind === "conflict") return { kind: "conflict" as const };
|
|
96
|
+
yield* call(input.destination.authorize, "destination-authorization");
|
|
97
|
+
const metering = input.metering === "unmetered" ? null : input.metering;
|
|
98
|
+
const operationId = admission.operation.operationId;
|
|
99
|
+
const billed = mediaUnits(
|
|
100
|
+
validateMediaGenerationSettings(
|
|
101
|
+
mediaGenerationSettingsSchema.strip().parse(input.request),
|
|
102
|
+
input.catalogue,
|
|
103
|
+
),
|
|
104
|
+
input.catalogue,
|
|
105
|
+
);
|
|
106
|
+
// Video and audio run through the durable alarm; only an image is inline.
|
|
107
|
+
const background =
|
|
108
|
+
getMediaModel(input.request.model, input.catalogue)?.kind !== "image";
|
|
109
|
+
/** Best-effort release; true proves customer settlement, not supplier billing. */
|
|
110
|
+
const settleNothing = () =>
|
|
111
|
+
metering === null
|
|
112
|
+
? Effect.succeed(false)
|
|
113
|
+
: call(
|
|
114
|
+
() => metering.settle({ operationId, units: 0 }),
|
|
115
|
+
"billing",
|
|
116
|
+
).pipe(
|
|
117
|
+
Effect.match({ onFailure: () => false, onSuccess: () => true }),
|
|
118
|
+
);
|
|
119
|
+
const claim = yield* call(() => input.operation.claim(), "operation");
|
|
120
|
+
if (
|
|
121
|
+
claim.kind === "succeeded" &&
|
|
122
|
+
claim.operation.image !== null &&
|
|
123
|
+
claim.operation.estimatedCostMilliunits !== null
|
|
124
|
+
)
|
|
125
|
+
return {
|
|
126
|
+
kind: "succeeded" as const,
|
|
127
|
+
bytes: claim.operation.image.bytes,
|
|
128
|
+
format: claim.operation.image.format,
|
|
129
|
+
costMilliunits: claim.operation.estimatedCostMilliunits,
|
|
130
|
+
};
|
|
131
|
+
if (claim.kind === "interrupted" && claim.operation.spentFailure !== null) {
|
|
132
|
+
if (metering !== null)
|
|
133
|
+
yield* call(
|
|
134
|
+
() => metering.settle({ operationId, units: billed.units }),
|
|
135
|
+
"billing",
|
|
136
|
+
);
|
|
137
|
+
return yield* Effect.fail(
|
|
138
|
+
new MediaExecutionError("artifact", {
|
|
139
|
+
cause: new MediaOutputFormatMismatch(),
|
|
140
|
+
}),
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
if (claim.kind === "interrupted") {
|
|
144
|
+
const uncharged = yield* settleNothing();
|
|
145
|
+
const failure = claim.operation.providerFailure;
|
|
146
|
+
if (failure !== null) {
|
|
147
|
+
const error = failure.safetyRefused
|
|
148
|
+
? new MediaSafetyFilterRefusal({ provider: failure.provider })
|
|
149
|
+
: new MediaExecutionError(failure.stage, {
|
|
150
|
+
provider: failure.provider,
|
|
151
|
+
});
|
|
152
|
+
return yield* Effect.fail(uncharged ? unchargedFailure(error) : error);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (claim.kind !== "claimed" || claim.leaseId === undefined)
|
|
156
|
+
return {
|
|
157
|
+
kind: claim.kind === "pending" ? "pending" : "unavailable",
|
|
158
|
+
} as const;
|
|
159
|
+
|
|
160
|
+
const leaseId = claim.leaseId;
|
|
161
|
+
let costMilliunits: number;
|
|
162
|
+
let image: MediaImage;
|
|
163
|
+
if (
|
|
164
|
+
claim.operation.state === "charging" &&
|
|
165
|
+
claim.operation.image !== null &&
|
|
166
|
+
claim.operation.estimatedCostMilliunits !== null
|
|
167
|
+
) {
|
|
168
|
+
// The save committed; only the idempotent settlement remains.
|
|
169
|
+
image = claim.operation.image;
|
|
170
|
+
costMilliunits = claim.operation.estimatedCostMilliunits;
|
|
171
|
+
} else {
|
|
172
|
+
let output: GeneratedMedia;
|
|
173
|
+
if (
|
|
174
|
+
claim.operation.state === "writing" &&
|
|
175
|
+
claim.operation.image !== null &&
|
|
176
|
+
claim.operation.estimatedCostMilliunits !== null
|
|
177
|
+
) {
|
|
178
|
+
output = {
|
|
179
|
+
bytes: yield* call(
|
|
180
|
+
() => input.operation.readGenerated(leaseId),
|
|
181
|
+
"artifact",
|
|
182
|
+
),
|
|
183
|
+
format: claim.operation.image.format,
|
|
184
|
+
};
|
|
185
|
+
costMilliunits = claim.operation.estimatedCostMilliunits;
|
|
186
|
+
} else {
|
|
187
|
+
// A retained save never rereads reference files or recomputes its quote.
|
|
188
|
+
const releaseEstimate = () =>
|
|
189
|
+
call(
|
|
190
|
+
() => input.operation.releaseEstimate(leaseId),
|
|
191
|
+
"operation",
|
|
192
|
+
).pipe(Effect.ignore);
|
|
193
|
+
const prepared = yield* call(input.generation.prepare, "estimate").pipe(
|
|
194
|
+
Effect.tapError(releaseEstimate),
|
|
195
|
+
);
|
|
196
|
+
// Billing admission is the last gate before durable dispatch. A refusal
|
|
197
|
+
// returns the request to admitted, so the same request id can retry.
|
|
198
|
+
costMilliunits =
|
|
199
|
+
metering === null
|
|
200
|
+
? prepared.costMilliunits
|
|
201
|
+
: (yield* call(
|
|
202
|
+
() =>
|
|
203
|
+
metering.admit({
|
|
204
|
+
operationId,
|
|
205
|
+
model: input.request.model,
|
|
206
|
+
unit: billed.unit,
|
|
207
|
+
units: billed.units,
|
|
208
|
+
providerCostMilliunits: prepared.costMilliunits,
|
|
209
|
+
}),
|
|
210
|
+
"billing",
|
|
211
|
+
).pipe(Effect.tapError(releaseEstimate))).priceMilliunits;
|
|
212
|
+
yield* call(
|
|
213
|
+
() => input.operation.recordEstimate(leaseId, costMilliunits),
|
|
214
|
+
"estimate",
|
|
215
|
+
).pipe(
|
|
216
|
+
// Erasure settled its hold before this admit ran, so the hold just
|
|
217
|
+
// opened belongs to nobody: release it rather than leave it to expire.
|
|
218
|
+
Effect.tapError(() =>
|
|
219
|
+
call(async () => {
|
|
220
|
+
const kept = await input.operation.retained(
|
|
221
|
+
input.coordinates.namespace,
|
|
222
|
+
input.requestId,
|
|
223
|
+
);
|
|
224
|
+
if (kept === null && metering !== null)
|
|
225
|
+
await metering.settle({ operationId, units: 0 });
|
|
226
|
+
}, "billing").pipe(
|
|
227
|
+
Effect.catch((cause) => {
|
|
228
|
+
reportCatchFailure("media-operation-erased-hold", cause);
|
|
229
|
+
return Effect.void;
|
|
230
|
+
}),
|
|
231
|
+
),
|
|
232
|
+
),
|
|
233
|
+
);
|
|
234
|
+
if (background) {
|
|
235
|
+
// Video outlives one request: the owner's alarm generates, and a
|
|
236
|
+
// retry of this request id saves and charges the retained output.
|
|
237
|
+
yield* call(
|
|
238
|
+
() =>
|
|
239
|
+
input.operation.dispatchInBackground(
|
|
240
|
+
leaseId,
|
|
241
|
+
prepared.references,
|
|
242
|
+
prepared.audioReferences,
|
|
243
|
+
),
|
|
244
|
+
"operation",
|
|
245
|
+
).pipe(
|
|
246
|
+
Effect.tapError(() =>
|
|
247
|
+
call(
|
|
248
|
+
() => input.operation.interruptGeneration(leaseId),
|
|
249
|
+
"operation",
|
|
250
|
+
).pipe(Effect.andThen(settleNothing()), Effect.ignore),
|
|
251
|
+
),
|
|
252
|
+
);
|
|
253
|
+
return { kind: "accepted" as const };
|
|
254
|
+
}
|
|
255
|
+
const generation = yield* call(async () => {
|
|
256
|
+
let output: GeneratedMedia;
|
|
257
|
+
try {
|
|
258
|
+
output = await untilAborted(input.signal, () =>
|
|
259
|
+
prepared.run(input.signal),
|
|
260
|
+
);
|
|
261
|
+
} catch (cause) {
|
|
262
|
+
if (!input.signal?.aborted) throw cause;
|
|
263
|
+
await input.operation.interruptGeneration(leaseId);
|
|
264
|
+
return {
|
|
265
|
+
kind: "interrupted" as const,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
if (input.signal?.aborted) {
|
|
269
|
+
await input.operation.interruptGeneration(leaseId);
|
|
270
|
+
return {
|
|
271
|
+
kind: "interrupted" as const,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
kind: "generated" as const,
|
|
276
|
+
output,
|
|
277
|
+
};
|
|
278
|
+
}, "provider").pipe(
|
|
279
|
+
// A provider failure delivered nothing and wrote no output: end the
|
|
280
|
+
// request now and release its hold rather than leave it unresolved.
|
|
281
|
+
Effect.catch((error) =>
|
|
282
|
+
Effect.gen(function* () {
|
|
283
|
+
const stage = error.stage;
|
|
284
|
+
if (stage === "provider" || stage === "normalization") {
|
|
285
|
+
const uncharged = yield* call(
|
|
286
|
+
() =>
|
|
287
|
+
input.operation.interruptGeneration(leaseId, {
|
|
288
|
+
stage,
|
|
289
|
+
safetyRefused: error instanceof MediaSafetyFilterRefusal,
|
|
290
|
+
provider: error.provider,
|
|
291
|
+
}),
|
|
292
|
+
"operation",
|
|
293
|
+
).pipe(
|
|
294
|
+
Effect.andThen(settleNothing()),
|
|
295
|
+
Effect.catch((cause) => {
|
|
296
|
+
reportCatchFailure("media-operation-interrupt", cause);
|
|
297
|
+
return Effect.succeed(false);
|
|
298
|
+
}),
|
|
299
|
+
);
|
|
300
|
+
if (uncharged)
|
|
301
|
+
return yield* Effect.fail(unchargedFailure(error));
|
|
302
|
+
}
|
|
303
|
+
return yield* Effect.fail(error);
|
|
304
|
+
}),
|
|
305
|
+
),
|
|
306
|
+
);
|
|
307
|
+
if (generation.kind === "interrupted") {
|
|
308
|
+
yield* settleNothing();
|
|
309
|
+
return { kind: "interrupted" as const };
|
|
310
|
+
}
|
|
311
|
+
output = generation.output;
|
|
312
|
+
const recorded = yield* call(
|
|
313
|
+
() =>
|
|
314
|
+
input.operation.recordGenerated(
|
|
315
|
+
leaseId,
|
|
316
|
+
output.bytes,
|
|
317
|
+
output.format,
|
|
318
|
+
),
|
|
319
|
+
"artifact",
|
|
320
|
+
);
|
|
321
|
+
if ("kind" in recorded) {
|
|
322
|
+
// The provider ran. The owner recorded a durable spent failure before
|
|
323
|
+
// this idempotent charge, so replay cannot refund or redispatch it.
|
|
324
|
+
if (metering !== null)
|
|
325
|
+
yield* call(
|
|
326
|
+
() => metering.settle({ operationId, units: billed.units }),
|
|
327
|
+
"billing",
|
|
328
|
+
);
|
|
329
|
+
return yield* Effect.fail(
|
|
330
|
+
new MediaExecutionError("artifact", {
|
|
331
|
+
cause: new MediaOutputFormatMismatch(),
|
|
332
|
+
}),
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Embedded fresh from the recorded (unembedded) bytes on every attempt,
|
|
338
|
+
// including a retry of a "writing" lease: deterministic facts in, so a
|
|
339
|
+
// retry writes byte-identical output. A charged generation is never
|
|
340
|
+
// failed over metadata, so a malformed or truncated provider image is
|
|
341
|
+
// written as-is; embedProvenance never throws.
|
|
342
|
+
// MP3 is not listed: audio carries no embedded provenance, like MP4.
|
|
343
|
+
const format = z
|
|
344
|
+
.enum(["png", "jpeg", "gif", "webp", "mp4"])
|
|
345
|
+
.safeParse(output.format);
|
|
346
|
+
const provenance: ProvenanceEmbedResult = format.success
|
|
347
|
+
? yield* call(
|
|
348
|
+
() =>
|
|
349
|
+
embedProvenance(output.bytes, format.data, {
|
|
350
|
+
printId: operationId,
|
|
351
|
+
model: input.request.model,
|
|
352
|
+
prompt:
|
|
353
|
+
input.embedPrompt === true ? input.request.prompt : null,
|
|
354
|
+
createdAt: admission.operation.createdAt,
|
|
355
|
+
}),
|
|
356
|
+
"operation",
|
|
357
|
+
)
|
|
358
|
+
: {
|
|
359
|
+
bytes: output.bytes,
|
|
360
|
+
embedded: false,
|
|
361
|
+
reason: "unsupported-format",
|
|
362
|
+
};
|
|
363
|
+
// Formats with no embed path (MP4, GIF) are expected; only a real failure warns.
|
|
364
|
+
if (!provenance.embedded && provenance.reason !== "unsupported-format")
|
|
365
|
+
console.warn("Media provenance not embedded", {
|
|
366
|
+
format: output.format,
|
|
367
|
+
reason: provenance.reason,
|
|
368
|
+
});
|
|
369
|
+
// The digest of what is about to land is durable before it lands, so an
|
|
370
|
+
// erasure knows which file is this operation's and refuses the write.
|
|
371
|
+
const digest = yield* call(
|
|
372
|
+
() => mediaWrittenDigest(provenance.bytes),
|
|
373
|
+
"operation",
|
|
374
|
+
);
|
|
375
|
+
const receipt = `sha256:${digest}`;
|
|
376
|
+
yield* call(
|
|
377
|
+
() => input.operation.recordWriteIntent(leaseId, digest),
|
|
378
|
+
"operation",
|
|
379
|
+
);
|
|
380
|
+
yield* call(
|
|
381
|
+
() => input.destination.write(provenance.bytes),
|
|
382
|
+
"destination-write",
|
|
383
|
+
).pipe(
|
|
384
|
+
Effect.tapError(() =>
|
|
385
|
+
call(() => input.operation.releaseWrite(leaseId), "operation").pipe(
|
|
386
|
+
Effect.ignore,
|
|
387
|
+
),
|
|
388
|
+
),
|
|
389
|
+
);
|
|
390
|
+
image = {
|
|
391
|
+
bytes: provenance.bytes.byteLength,
|
|
392
|
+
format: output.format,
|
|
393
|
+
};
|
|
394
|
+
// The write landed. If erasure won the race the operation can no longer
|
|
395
|
+
// record it, and nothing else points at the file: delete what landed.
|
|
396
|
+
const deleteIfErased = <E>(error: E) =>
|
|
397
|
+
call(async () => {
|
|
398
|
+
const kept = await input.operation.retained(
|
|
399
|
+
input.coordinates.namespace,
|
|
400
|
+
input.requestId,
|
|
401
|
+
);
|
|
402
|
+
if (kept === null) await input.destination.remove(digest);
|
|
403
|
+
}, "destination-write").pipe(
|
|
404
|
+
Effect.catch((cause) => {
|
|
405
|
+
reportCatchFailure("media-operation-erased-write", cause);
|
|
406
|
+
return Effect.void;
|
|
407
|
+
}),
|
|
408
|
+
Effect.andThen(Effect.fail(error)),
|
|
409
|
+
);
|
|
410
|
+
if (metering === null) {
|
|
411
|
+
yield* call(
|
|
412
|
+
() =>
|
|
413
|
+
input.operation.recordWrittenWithoutSettlement(
|
|
414
|
+
leaseId,
|
|
415
|
+
receipt,
|
|
416
|
+
image,
|
|
417
|
+
),
|
|
418
|
+
"operation",
|
|
419
|
+
).pipe(Effect.catch(deleteIfErased));
|
|
420
|
+
return {
|
|
421
|
+
kind: "succeeded" as const,
|
|
422
|
+
bytes: image.bytes,
|
|
423
|
+
format: image.format,
|
|
424
|
+
costMilliunits,
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
yield* call(
|
|
428
|
+
() => input.operation.recordWritten(leaseId, receipt, image),
|
|
429
|
+
"operation",
|
|
430
|
+
).pipe(Effect.catch(deleteIfErased));
|
|
431
|
+
}
|
|
432
|
+
if (metering === null) return { kind: "unavailable" as const };
|
|
433
|
+
yield* call(
|
|
434
|
+
() => metering.settle({ operationId, units: billed.units }),
|
|
435
|
+
"billing",
|
|
436
|
+
);
|
|
437
|
+
yield* call(
|
|
438
|
+
() =>
|
|
439
|
+
input.operation.recordSucceeded(leaseId, {
|
|
440
|
+
generationId: operationId,
|
|
441
|
+
bytes: image.bytes,
|
|
442
|
+
format: image.format,
|
|
443
|
+
costMilliunits,
|
|
444
|
+
}),
|
|
445
|
+
"operation",
|
|
446
|
+
);
|
|
447
|
+
return {
|
|
448
|
+
kind: "succeeded" as const,
|
|
449
|
+
bytes: image.bytes,
|
|
450
|
+
format: image.format,
|
|
451
|
+
costMilliunits,
|
|
452
|
+
};
|
|
453
|
+
});
|
|
454
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { estimate } from "./cloudflare/provider.js";
|
|
2
|
+
import { mediaUnits, type MediaUnits } from "./gateway-models.js";
|
|
3
|
+
import {
|
|
4
|
+
resolveMediaReferences,
|
|
5
|
+
validateMediaGenerationSettings,
|
|
6
|
+
type MediaGenerationSettingsInput,
|
|
7
|
+
type MediaReferenceReader,
|
|
8
|
+
} from "./index.js";
|
|
9
|
+
|
|
10
|
+
/** The provider cost of one exact generation request, before any billing policy. */
|
|
11
|
+
export type MediaQuote = Readonly<
|
|
12
|
+
MediaUnits & {
|
|
13
|
+
/** Provider milliunits of a cent, as admission would estimate them. */
|
|
14
|
+
providerCostMilliunits: number;
|
|
15
|
+
}
|
|
16
|
+
>;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Quote one exact request: the same settings validation, reference reads,
|
|
20
|
+
* estimator and billing units a generation uses at admission, run without
|
|
21
|
+
* dispatching anything. A host applies its billing policy to this per unit,
|
|
22
|
+
* the way its metering does, so the number matches the charge.
|
|
23
|
+
*/
|
|
24
|
+
export async function quoteMediaGeneration(
|
|
25
|
+
raw: MediaGenerationSettingsInput,
|
|
26
|
+
references: MediaReferenceReader,
|
|
27
|
+
): Promise<MediaQuote> {
|
|
28
|
+
const settings = validateMediaGenerationSettings(raw);
|
|
29
|
+
const resolved = await resolveMediaReferences(settings, references);
|
|
30
|
+
return {
|
|
31
|
+
...mediaUnits(settings),
|
|
32
|
+
providerCostMilliunits: estimate(settings, resolved),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** What a destination did when asked to delete a file this operation wrote. */
|
|
2
|
+
export type MediaRemoval =
|
|
3
|
+
/** The file matched what the operation wrote and was deleted. */
|
|
4
|
+
| "removed"
|
|
5
|
+
/** Nothing was at the path. */
|
|
6
|
+
| "absent"
|
|
7
|
+
/** The path holds different bytes now; it is not this operation's file and was left alone. */
|
|
8
|
+
| "not-ours"
|
|
9
|
+
/** The destination cannot delete files; the host must remove the matching file itself. */
|
|
10
|
+
| "kept";
|
|
11
|
+
|
|
12
|
+
/** Lowercase hex SHA-256 of the exact bytes written to a destination. */
|
|
13
|
+
export async function mediaWrittenDigest(bytes: Uint8Array): Promise<string> {
|
|
14
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes.slice());
|
|
15
|
+
return [...new Uint8Array(digest)]
|
|
16
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
17
|
+
.join("");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Delete the file at a destination path only while it still holds the exact
|
|
22
|
+
* bytes the operation wrote, so a path reused for something else is never lost.
|
|
23
|
+
*/
|
|
24
|
+
export async function removeMediaIfWritten(
|
|
25
|
+
file: Readonly<{
|
|
26
|
+
/** Read the current bytes at the path, or null when absent. */
|
|
27
|
+
read: () => Promise<Uint8Array | null>;
|
|
28
|
+
/** Delete the file at the path. */
|
|
29
|
+
delete: () => Promise<void>;
|
|
30
|
+
}>,
|
|
31
|
+
sha256: string,
|
|
32
|
+
): Promise<MediaRemoval> {
|
|
33
|
+
const current = await file.read();
|
|
34
|
+
if (current === null) return "absent";
|
|
35
|
+
if ((await mediaWrittenDigest(current)) !== sha256) return "not-ours";
|
|
36
|
+
await file.delete();
|
|
37
|
+
return "removed";
|
|
38
|
+
}
|