@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,399 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import sharp from "sharp";
|
|
3
|
+
import {
|
|
4
|
+
resolveMediaReferences,
|
|
5
|
+
validateMediaGenerationSettings,
|
|
6
|
+
type MediaReference,
|
|
7
|
+
type FittedReferenceImage,
|
|
8
|
+
} from "../src/index.js";
|
|
9
|
+
import { createMediaService } from "../src/server.js";
|
|
10
|
+
import { MediaBillingRefusal } from "../src/execution-error.js";
|
|
11
|
+
import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
|
|
12
|
+
import {
|
|
13
|
+
createImagesReferenceFitter,
|
|
14
|
+
createImagesViewFitter,
|
|
15
|
+
type MediaImagePort,
|
|
16
|
+
} from "../src/cloudflare/reference-images.js";
|
|
17
|
+
|
|
18
|
+
const source = new Uint8Array([1, 2, 3]);
|
|
19
|
+
const resized = new Uint8Array([4, 5]);
|
|
20
|
+
const imageModel = "@cf/black-forest-labs/flux-2-klein-4b";
|
|
21
|
+
const videoModel = "bytedance/seedance-2.0-mini";
|
|
22
|
+
|
|
23
|
+
/** Local Images adapter with real pixel decoding/resizing, never inference. */
|
|
24
|
+
const pixelImages: MediaImagePort = {
|
|
25
|
+
info: async (input) => {
|
|
26
|
+
const bytes = await new Response(input).arrayBuffer();
|
|
27
|
+
const info = await sharp(bytes).metadata();
|
|
28
|
+
return {
|
|
29
|
+
format: info.format === "webp" ? "image/webp" : "image/png",
|
|
30
|
+
width: info.width,
|
|
31
|
+
height: info.height,
|
|
32
|
+
fileSize: bytes.byteLength,
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
input: (input) => ({
|
|
36
|
+
transform: (options) => ({
|
|
37
|
+
output: async (encoding) => {
|
|
38
|
+
const resized = sharp(await new Response(input).arrayBuffer()).resize({
|
|
39
|
+
width: options.width,
|
|
40
|
+
height: options.height,
|
|
41
|
+
fit: "inside",
|
|
42
|
+
withoutEnlargement: options.fit === "scale-down",
|
|
43
|
+
});
|
|
44
|
+
const bytes = await (
|
|
45
|
+
encoding.format === "image/webp"
|
|
46
|
+
? resized.webp({ quality: encoding.quality })
|
|
47
|
+
: encoding.format === "image/jpeg"
|
|
48
|
+
? resized.jpeg({ quality: encoding.quality })
|
|
49
|
+
: resized.png()
|
|
50
|
+
).toBuffer();
|
|
51
|
+
return { response: () => new Response(new Uint8Array(bytes)) };
|
|
52
|
+
},
|
|
53
|
+
}),
|
|
54
|
+
}),
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
describe("Images reference fitting", () => {
|
|
58
|
+
it("passes the selected video model through the real generation service before billing", async () => {
|
|
59
|
+
const fixture = mediaOperationFixture();
|
|
60
|
+
try {
|
|
61
|
+
const bytes = await sharp({
|
|
62
|
+
create: { width: 1774, height: 887, channels: 3, background: "white" },
|
|
63
|
+
})
|
|
64
|
+
.png()
|
|
65
|
+
.toBuffer();
|
|
66
|
+
const fit = createImagesReferenceFitter(pixelImages);
|
|
67
|
+
const prepared: FittedReferenceImage[] = [];
|
|
68
|
+
const readReference = vi.fn(
|
|
69
|
+
async (_reference: MediaReference, model: string) => {
|
|
70
|
+
const fitted = await fit(new Uint8Array(bytes), model);
|
|
71
|
+
prepared.push(fitted);
|
|
72
|
+
return fitted;
|
|
73
|
+
},
|
|
74
|
+
);
|
|
75
|
+
const provider = vi.fn(() =>
|
|
76
|
+
Promise.reject(new Error("Unexpected provider call")),
|
|
77
|
+
);
|
|
78
|
+
const admit = vi.fn(() =>
|
|
79
|
+
Promise.reject(new MediaBillingRefusal("insufficient_credits")),
|
|
80
|
+
);
|
|
81
|
+
const service = createMediaService({
|
|
82
|
+
scope: {
|
|
83
|
+
actorId: "artist",
|
|
84
|
+
namespace: "studio",
|
|
85
|
+
owner: "prints",
|
|
86
|
+
destinationId: "c",
|
|
87
|
+
},
|
|
88
|
+
operations: { getByName: () => fixture.owner },
|
|
89
|
+
provider,
|
|
90
|
+
metering: { admit, settle: () => Promise.resolve() },
|
|
91
|
+
refusalMessages: {
|
|
92
|
+
insufficient_credits: "Refill",
|
|
93
|
+
denied: "Denied",
|
|
94
|
+
daily_limit_reached: "Daily limit",
|
|
95
|
+
},
|
|
96
|
+
destination: {
|
|
97
|
+
authorize: () => Promise.resolve(),
|
|
98
|
+
remove: () => Promise.resolve("absent" as const),
|
|
99
|
+
write: () => Promise.resolve(),
|
|
100
|
+
readReference,
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
const response = await service.request("/generate", {
|
|
104
|
+
method: "POST",
|
|
105
|
+
headers: {
|
|
106
|
+
"Content-Type": "application/json",
|
|
107
|
+
"X-Request-Id": "first-frame-sizing",
|
|
108
|
+
},
|
|
109
|
+
body: JSON.stringify({
|
|
110
|
+
path: "/video.mp4",
|
|
111
|
+
settings: {
|
|
112
|
+
model: videoModel,
|
|
113
|
+
prompt: "Animate the first frame",
|
|
114
|
+
width: 1280,
|
|
115
|
+
height: 720,
|
|
116
|
+
references: [
|
|
117
|
+
{ computerId: "c", path: "/first.png", role: "first-frame" },
|
|
118
|
+
],
|
|
119
|
+
},
|
|
120
|
+
}),
|
|
121
|
+
});
|
|
122
|
+
expect(response.status).toBe(402);
|
|
123
|
+
expect(readReference).toHaveBeenCalledExactlyOnceWith(
|
|
124
|
+
{ computerId: "c", path: "/first.png", role: "first-frame" },
|
|
125
|
+
videoModel,
|
|
126
|
+
);
|
|
127
|
+
const fitted = prepared[0];
|
|
128
|
+
if (fitted === undefined) throw new Error("Missing prepared first frame");
|
|
129
|
+
await expect(sharp(fitted.bytes).metadata()).resolves.toMatchObject({
|
|
130
|
+
width: 640,
|
|
131
|
+
height: 320,
|
|
132
|
+
});
|
|
133
|
+
expect(admit).toHaveBeenCalledOnce();
|
|
134
|
+
expect(provider).not.toHaveBeenCalled();
|
|
135
|
+
} finally {
|
|
136
|
+
fixture.close();
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it.each([
|
|
141
|
+
{
|
|
142
|
+
name: "1774x887 video",
|
|
143
|
+
model: videoModel,
|
|
144
|
+
width: 1774,
|
|
145
|
+
height: 887,
|
|
146
|
+
expected: { width: 640, height: 320 },
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
name: "887x1774 video",
|
|
150
|
+
model: videoModel,
|
|
151
|
+
width: 887,
|
|
152
|
+
height: 1774,
|
|
153
|
+
expected: { width: 320, height: 640 },
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
name: "1774x887 image",
|
|
157
|
+
model: imageModel,
|
|
158
|
+
width: 1774,
|
|
159
|
+
height: 887,
|
|
160
|
+
expected: { width: 512, height: 256 },
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
name: "887x1774 image",
|
|
164
|
+
model: imageModel,
|
|
165
|
+
width: 887,
|
|
166
|
+
height: 1774,
|
|
167
|
+
expected: { width: 256, height: 512 },
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
name: "small video",
|
|
171
|
+
model: videoModel,
|
|
172
|
+
width: 200,
|
|
173
|
+
height: 100,
|
|
174
|
+
expected: { width: 640, height: 320 },
|
|
175
|
+
},
|
|
176
|
+
{
|
|
177
|
+
name: "small image",
|
|
178
|
+
model: imageModel,
|
|
179
|
+
width: 200,
|
|
180
|
+
height: 100,
|
|
181
|
+
expected: { width: 200, height: 100 },
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
name: "already fitted video",
|
|
185
|
+
model: videoModel,
|
|
186
|
+
width: 640,
|
|
187
|
+
height: 320,
|
|
188
|
+
expected: { width: 640, height: 320 },
|
|
189
|
+
},
|
|
190
|
+
])(
|
|
191
|
+
"fits $name references using actual decoded pixels",
|
|
192
|
+
async ({ model, width, height, expected }) => {
|
|
193
|
+
const bytes = await sharp({
|
|
194
|
+
create: {
|
|
195
|
+
width,
|
|
196
|
+
height,
|
|
197
|
+
channels: 3,
|
|
198
|
+
background: "white",
|
|
199
|
+
},
|
|
200
|
+
})
|
|
201
|
+
.png()
|
|
202
|
+
.toBuffer();
|
|
203
|
+
const settings = validateMediaGenerationSettings({
|
|
204
|
+
model,
|
|
205
|
+
prompt: "Animate this first frame",
|
|
206
|
+
width: 1280,
|
|
207
|
+
height: 720,
|
|
208
|
+
references: [{ computerId: "c", path: "/first.png" }],
|
|
209
|
+
});
|
|
210
|
+
const fit = createImagesReferenceFitter(pixelImages);
|
|
211
|
+
const [reference] = await resolveMediaReferences(settings, {
|
|
212
|
+
read: async (_reference, model) => fit(new Uint8Array(bytes), model),
|
|
213
|
+
});
|
|
214
|
+
if (reference === undefined) throw new Error("Missing fitted reference");
|
|
215
|
+
const decoded = await sharp(reference.bytes).metadata();
|
|
216
|
+
expect(decoded).toMatchObject(expected);
|
|
217
|
+
expect(reference).toMatchObject(expected);
|
|
218
|
+
},
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
it("fits GPT Image 2 references to 1024 px as WebP and others to 512 px PNG", async () => {
|
|
222
|
+
const bytes = await sharp({
|
|
223
|
+
create: { width: 2048, height: 1536, channels: 3, background: "teal" },
|
|
224
|
+
})
|
|
225
|
+
.png()
|
|
226
|
+
.toBuffer();
|
|
227
|
+
const fit = createImagesReferenceFitter(pixelImages);
|
|
228
|
+
const fitted = await fit(new Uint8Array(bytes), "openai/gpt-image-2");
|
|
229
|
+
expect(fitted).toMatchObject({ width: 1024, height: 768, format: "webp" });
|
|
230
|
+
expect((await sharp(fitted.bytes).metadata()).format).toBe("webp");
|
|
231
|
+
const flux = await fit(new Uint8Array(bytes), imageModel);
|
|
232
|
+
expect(flux).toMatchObject({ width: 512, height: 384, format: "png" });
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("re-encodes a small PNG as WebP for GPT Image 2 without resizing", async () => {
|
|
236
|
+
const bytes = await sharp({
|
|
237
|
+
create: { width: 300, height: 200, channels: 3, background: "white" },
|
|
238
|
+
})
|
|
239
|
+
.png()
|
|
240
|
+
.toBuffer();
|
|
241
|
+
const fitted = await createImagesReferenceFitter(pixelImages)(
|
|
242
|
+
new Uint8Array(bytes),
|
|
243
|
+
"openai/gpt-image-2",
|
|
244
|
+
);
|
|
245
|
+
expect(fitted).toMatchObject({ width: 300, height: 200, format: "webp" });
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("scales an oversized image and uses decoded output metadata", async () => {
|
|
249
|
+
const info = vi
|
|
250
|
+
.fn<ImagesBinding["info"]>()
|
|
251
|
+
.mockResolvedValueOnce({
|
|
252
|
+
format: "image/jpeg",
|
|
253
|
+
width: 2048,
|
|
254
|
+
height: 1024,
|
|
255
|
+
fileSize: source.byteLength,
|
|
256
|
+
})
|
|
257
|
+
.mockResolvedValueOnce({
|
|
258
|
+
format: "image/png",
|
|
259
|
+
width: 512,
|
|
260
|
+
height: 256,
|
|
261
|
+
fileSize: resized.byteLength,
|
|
262
|
+
});
|
|
263
|
+
const transform = vi.fn(() => transformer);
|
|
264
|
+
const output = vi.fn(() =>
|
|
265
|
+
Promise.resolve({
|
|
266
|
+
response: () => new Response(resized),
|
|
267
|
+
image: () => new Blob([resized]).stream(),
|
|
268
|
+
contentType: () => "image/png",
|
|
269
|
+
}),
|
|
270
|
+
);
|
|
271
|
+
const transformer: ImageTransformer = {
|
|
272
|
+
transform,
|
|
273
|
+
output,
|
|
274
|
+
draw: () => {
|
|
275
|
+
throw new Error("Unexpected draw");
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
const fit = createImagesReferenceFitter({
|
|
279
|
+
info,
|
|
280
|
+
input: vi.fn(() => transformer),
|
|
281
|
+
});
|
|
282
|
+
await expect(fit(source, imageModel)).resolves.toEqual({
|
|
283
|
+
bytes: resized,
|
|
284
|
+
format: "png",
|
|
285
|
+
width: 512,
|
|
286
|
+
height: 256,
|
|
287
|
+
});
|
|
288
|
+
expect(transform).toHaveBeenCalledWith({
|
|
289
|
+
width: 512,
|
|
290
|
+
height: 256,
|
|
291
|
+
fit: "scale-down",
|
|
292
|
+
});
|
|
293
|
+
expect(output).toHaveBeenCalledWith({ format: "image/png" });
|
|
294
|
+
expect(info).toHaveBeenCalledTimes(2);
|
|
295
|
+
const first = info.mock.calls[0]?.[0];
|
|
296
|
+
const second = info.mock.calls[1]?.[0];
|
|
297
|
+
expect(new Uint8Array(await new Response(first).arrayBuffer())).toEqual(
|
|
298
|
+
source,
|
|
299
|
+
);
|
|
300
|
+
expect(new Uint8Array(await new Response(second).arrayBuffer())).toEqual(
|
|
301
|
+
resized,
|
|
302
|
+
);
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("keeps an image within the bound unchanged", async () => {
|
|
306
|
+
const fit = createImagesReferenceFitter({
|
|
307
|
+
info: vi.fn(() =>
|
|
308
|
+
Promise.resolve({
|
|
309
|
+
format: "image/webp" as const,
|
|
310
|
+
width: 64,
|
|
311
|
+
height: 32,
|
|
312
|
+
fileSize: source.byteLength,
|
|
313
|
+
}),
|
|
314
|
+
),
|
|
315
|
+
input: () => {
|
|
316
|
+
throw new Error("Unexpected transform");
|
|
317
|
+
},
|
|
318
|
+
});
|
|
319
|
+
await expect(fit(source, imageModel)).resolves.toEqual({
|
|
320
|
+
bytes: source,
|
|
321
|
+
format: "webp",
|
|
322
|
+
width: 64,
|
|
323
|
+
height: 32,
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it("rejects unsupported or missing metadata without inventing dimensions", async () => {
|
|
328
|
+
const fit = createImagesReferenceFitter({
|
|
329
|
+
info: vi.fn(() => Promise.resolve({ format: "image/svg+xml" as const })),
|
|
330
|
+
input: () => {
|
|
331
|
+
throw new Error("Unexpected transform");
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
await expect(fit(source, imageModel)).rejects.toThrow();
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
describe("Images view fitting", () => {
|
|
339
|
+
it("always re-encodes as JPEG within the requested bound", async () => {
|
|
340
|
+
const info = vi
|
|
341
|
+
.fn<ImagesBinding["info"]>()
|
|
342
|
+
.mockResolvedValueOnce({
|
|
343
|
+
format: "image/png",
|
|
344
|
+
width: 64,
|
|
345
|
+
height: 32,
|
|
346
|
+
fileSize: source.byteLength,
|
|
347
|
+
})
|
|
348
|
+
.mockResolvedValueOnce({
|
|
349
|
+
format: "image/jpeg",
|
|
350
|
+
width: 64,
|
|
351
|
+
height: 32,
|
|
352
|
+
fileSize: resized.byteLength,
|
|
353
|
+
});
|
|
354
|
+
const transform = vi.fn(() => transformer);
|
|
355
|
+
const output = vi.fn(() =>
|
|
356
|
+
Promise.resolve({
|
|
357
|
+
response: () => new Response(resized),
|
|
358
|
+
image: () => new Blob([resized]).stream(),
|
|
359
|
+
contentType: () => "image/jpeg",
|
|
360
|
+
}),
|
|
361
|
+
);
|
|
362
|
+
const transformer: ImageTransformer = {
|
|
363
|
+
transform,
|
|
364
|
+
output,
|
|
365
|
+
draw: () => {
|
|
366
|
+
throw new Error("Unexpected draw");
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
const fit = createImagesViewFitter({
|
|
370
|
+
info,
|
|
371
|
+
input: vi.fn(() => transformer),
|
|
372
|
+
});
|
|
373
|
+
await expect(fit(source, 384)).resolves.toEqual({
|
|
374
|
+
bytes: resized,
|
|
375
|
+
format: "jpeg",
|
|
376
|
+
width: 64,
|
|
377
|
+
height: 32,
|
|
378
|
+
});
|
|
379
|
+
expect(transform).toHaveBeenCalledWith({
|
|
380
|
+
width: 384,
|
|
381
|
+
height: 384,
|
|
382
|
+
fit: "scale-down",
|
|
383
|
+
});
|
|
384
|
+
expect(output).toHaveBeenCalledWith({ format: "image/jpeg", quality: 80 });
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
it("refuses a dimension outside Media's view bound", async () => {
|
|
388
|
+
const fit = createImagesViewFitter({
|
|
389
|
+
info: () => {
|
|
390
|
+
throw new Error("Unexpected info");
|
|
391
|
+
},
|
|
392
|
+
input: () => {
|
|
393
|
+
throw new Error("Unexpected transform");
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
await expect(fit(source, 1_024)).rejects.toThrow("out of bounds");
|
|
397
|
+
await expect(fit(source, 128)).rejects.toThrow("out of bounds");
|
|
398
|
+
});
|
|
399
|
+
});
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { env, exports } from "cloudflare:workers";
|
|
2
|
+
import {
|
|
3
|
+
evictDurableObject,
|
|
4
|
+
runInDurableObject,
|
|
5
|
+
abortAllDurableObjects,
|
|
6
|
+
} from "cloudflare:test";
|
|
7
|
+
import { describe, expect, it } from "vitest";
|
|
8
|
+
import { listMediaModels } from "../dist/index.js";
|
|
9
|
+
import { imageBytes } from "./standalone.worker.mjs";
|
|
10
|
+
|
|
11
|
+
const requestId = "standalone-retry";
|
|
12
|
+
const body = {
|
|
13
|
+
path: "greenhouse.gif",
|
|
14
|
+
settings: {
|
|
15
|
+
model: "@cf/black-forest-labs/flux-1-schnell",
|
|
16
|
+
prompt: "greenhouse",
|
|
17
|
+
width: 1024,
|
|
18
|
+
height: 768,
|
|
19
|
+
steps: 4,
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
async function request(path, options = {}) {
|
|
23
|
+
const response = await exports.default.fetch(
|
|
24
|
+
new globalThis.Request(`https://media.invalid${path}`, {
|
|
25
|
+
...options,
|
|
26
|
+
headers: {
|
|
27
|
+
Authorization: "Bearer local-media-proof",
|
|
28
|
+
...options.headers,
|
|
29
|
+
},
|
|
30
|
+
}),
|
|
31
|
+
);
|
|
32
|
+
return new globalThis.Response(await response.arrayBuffer(), {
|
|
33
|
+
status: response.status,
|
|
34
|
+
headers: response.headers,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function generate(value = body, id = requestId) {
|
|
38
|
+
return request("/generate", {
|
|
39
|
+
method: "POST",
|
|
40
|
+
headers: { "Content-Type": "application/json", "X-Request-Id": id },
|
|
41
|
+
body: JSON.stringify(value),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
it("retains native output across DO eviction and retries without another provider call", async () => {
|
|
46
|
+
expect(
|
|
47
|
+
(
|
|
48
|
+
await exports.default.fetch(
|
|
49
|
+
new globalThis.Request("https://media.invalid/models"),
|
|
50
|
+
)
|
|
51
|
+
).status,
|
|
52
|
+
).toBe(401);
|
|
53
|
+
const catalog = await request("/models");
|
|
54
|
+
expect(catalog.status).toBe(200);
|
|
55
|
+
const listed = await catalog.json();
|
|
56
|
+
expect(listed).toHaveLength(listMediaModels().length);
|
|
57
|
+
expect(listed.map((model) => model.billingUnit)).toEqual(
|
|
58
|
+
listMediaModels().map((model) => model.billingUnit),
|
|
59
|
+
);
|
|
60
|
+
expect(
|
|
61
|
+
(await request("/generate", { method: "POST", body: "{" })).status,
|
|
62
|
+
).toBe(400);
|
|
63
|
+
expect(await env.PROOF.get("provider-count")).toBeNull();
|
|
64
|
+
|
|
65
|
+
await env.PROOF.put("fail-next-save", "yes");
|
|
66
|
+
const failed = await generate();
|
|
67
|
+
expect(failed.status).toBe(503);
|
|
68
|
+
expect(await failed.json()).toMatchObject({
|
|
69
|
+
stage: "destination-write",
|
|
70
|
+
retryable: true,
|
|
71
|
+
});
|
|
72
|
+
expect(await env.OUTPUTS.get(body.path)).toBeNull();
|
|
73
|
+
expect(await (await env.PROOF.get("provider-count")).text()).toBe("1");
|
|
74
|
+
const operation = env.MEDIA_OPERATION.getByName(`media:${requestId}`);
|
|
75
|
+
const retained = await env.APP_ARTIFACTS.get(
|
|
76
|
+
`media-output/v1/media:${requestId}`,
|
|
77
|
+
);
|
|
78
|
+
expect(new Uint8Array(await retained.arrayBuffer())).toEqual(imageBytes);
|
|
79
|
+
await evictDurableObject(operation);
|
|
80
|
+
await evictDurableObject(env.MEDIA_HOST.getByName("media"));
|
|
81
|
+
|
|
82
|
+
const retry = await generate();
|
|
83
|
+
expect(retry.status).toBe(200);
|
|
84
|
+
expect(await retry.json()).toMatchObject({
|
|
85
|
+
path: body.path,
|
|
86
|
+
bytes: imageBytes.byteLength,
|
|
87
|
+
format: "gif",
|
|
88
|
+
});
|
|
89
|
+
expect(await (await env.PROOF.get("provider-count")).text()).toBe("1");
|
|
90
|
+
const saved = await request(`/object?key=${encodeURIComponent(body.path)}`);
|
|
91
|
+
expect(saved.status).toBe(200);
|
|
92
|
+
expect(new Uint8Array(await saved.arrayBuffer())).toEqual(imageBytes);
|
|
93
|
+
expect((await generate()).status).toBe(200);
|
|
94
|
+
expect(await (await env.PROOF.get("provider-count")).text()).toBe("1");
|
|
95
|
+
const conflict = await generate({
|
|
96
|
+
...body,
|
|
97
|
+
settings: { ...body.settings, prompt: "a different request" },
|
|
98
|
+
});
|
|
99
|
+
expect(conflict.status).toBe(409);
|
|
100
|
+
expect(await conflict.json()).toMatchObject({
|
|
101
|
+
stage: "operation",
|
|
102
|
+
retryable: false,
|
|
103
|
+
});
|
|
104
|
+
expect(await (await env.PROOF.get("provider-count")).text()).toBe("1");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("adopts native output after acknowledgement loss and owner restart", async () => {
|
|
108
|
+
const id = "standalone-output-gap";
|
|
109
|
+
const input = { ...body, path: "recovered-greenhouse.gif" };
|
|
110
|
+
const before = await env.PROOF.get("provider-count");
|
|
111
|
+
const expectedCalls = (before === null ? 0 : Number(await before.text())) + 1;
|
|
112
|
+
await env.PROOF.put("fail-next-output-ack", "yes");
|
|
113
|
+
expect((await generate(input, id)).status).toBe(503);
|
|
114
|
+
const operation = env.MEDIA_OPERATION.getByName(`media:${id}`);
|
|
115
|
+
expect(await operation.read()).toMatchObject({
|
|
116
|
+
state: "generating",
|
|
117
|
+
image: null,
|
|
118
|
+
});
|
|
119
|
+
const retained = await env.APP_ARTIFACTS.get(`media-output/v1/media:${id}`);
|
|
120
|
+
expect(new Uint8Array(await retained.arrayBuffer())).toEqual(imageBytes);
|
|
121
|
+
expect(await env.OUTPUTS.get(input.path)).toBeNull();
|
|
122
|
+
// Advance the persisted lease to the crash-recovery boundary without a production test API.
|
|
123
|
+
await runInDurableObject(operation, (_instance, state) => {
|
|
124
|
+
state.storage.sql.exec(
|
|
125
|
+
"UPDATE hub_media_operation SET lease_expires_at=0 WHERE singleton=1",
|
|
126
|
+
);
|
|
127
|
+
});
|
|
128
|
+
await abortAllDurableObjects();
|
|
129
|
+
const recovered = await generate(input, id);
|
|
130
|
+
expect(recovered.status).toBe(200);
|
|
131
|
+
expect(await recovered.json()).toMatchObject({
|
|
132
|
+
path: input.path,
|
|
133
|
+
bytes: imageBytes.byteLength,
|
|
134
|
+
format: "gif",
|
|
135
|
+
});
|
|
136
|
+
const saved = await env.OUTPUTS.get(input.path);
|
|
137
|
+
expect(new Uint8Array(await saved.arrayBuffer())).toEqual(imageBytes);
|
|
138
|
+
expect(await (await env.PROOF.get("provider-count")).text()).toBe(
|
|
139
|
+
String(expectedCalls),
|
|
140
|
+
);
|
|
141
|
+
expect((await generate(input, id)).status).toBe(200);
|
|
142
|
+
expect(await (await env.PROOF.get("provider-count")).text()).toBe(
|
|
143
|
+
String(expectedCalls),
|
|
144
|
+
);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it("embeds real PNG, JPEG and transparent WebP inside workerd", async () => {
|
|
148
|
+
const { embedProvenance } = await import("../dist/provenance.js");
|
|
149
|
+
const { images } = await import("./provenance-images.fixture.mjs");
|
|
150
|
+
for (const image of images) {
|
|
151
|
+
const bytes = Uint8Array.from(globalThis.atob(image.base64), (value) =>
|
|
152
|
+
value.charCodeAt(0),
|
|
153
|
+
);
|
|
154
|
+
const result = await embedProvenance(bytes, image.format, {
|
|
155
|
+
printId: "native-provenance-proof",
|
|
156
|
+
model: "flux-native-proof",
|
|
157
|
+
prompt: "mushroom & moon",
|
|
158
|
+
createdAt: 1_770_000_000_000,
|
|
159
|
+
});
|
|
160
|
+
expect(result.embedded).toBe(true);
|
|
161
|
+
expect(new globalThis.TextDecoder().decode(result.bytes)).toContain(
|
|
162
|
+
"native-provenance-proof",
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("writes enriched bytes through the actual generation destination and reports their size", async () => {
|
|
168
|
+
const { images } = await import("./provenance-images.fixture.mjs");
|
|
169
|
+
const image = images.find((image) => image.format === "png");
|
|
170
|
+
expect(image).toBeDefined();
|
|
171
|
+
const original = Uint8Array.from(globalThis.atob(image.base64), (value) =>
|
|
172
|
+
value.charCodeAt(0),
|
|
173
|
+
);
|
|
174
|
+
await env.PROOF.put("provider-image", original);
|
|
175
|
+
try {
|
|
176
|
+
const id = "native-enriched-write";
|
|
177
|
+
const path = "enriched.png";
|
|
178
|
+
const response = await generate({ ...body, path }, id);
|
|
179
|
+
expect(response.status).toBe(200);
|
|
180
|
+
const result = await response.json();
|
|
181
|
+
const saved = await request(`/object?key=${path}`);
|
|
182
|
+
const output = new Uint8Array(await saved.arrayBuffer());
|
|
183
|
+
expect(result.bytes).toBe(output.byteLength);
|
|
184
|
+
expect(output.byteLength).toBeGreaterThan(original.byteLength);
|
|
185
|
+
expect(new globalThis.TextDecoder().decode(output)).toContain(id);
|
|
186
|
+
const retained = await env.APP_ARTIFACTS.get(`media-output/v1/media:${id}`);
|
|
187
|
+
expect(new Uint8Array(await retained.arrayBuffer())).toEqual(original);
|
|
188
|
+
const replay = await generate({ ...body, path }, id);
|
|
189
|
+
expect(replay.status).toBe(200);
|
|
190
|
+
expect(
|
|
191
|
+
new Uint8Array(
|
|
192
|
+
await (await request(`/object?key=${path}`)).arrayBuffer(),
|
|
193
|
+
),
|
|
194
|
+
).toEqual(output);
|
|
195
|
+
} finally {
|
|
196
|
+
await env.PROOF.delete("provider-image");
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
describe("R2 references and destination", () => {
|
|
201
|
+
const referenceModel = "@cf/black-forest-labs/flux-2-klein-4b";
|
|
202
|
+
const referenceKey = "references/greenhouse-ref.gif";
|
|
203
|
+
const marker = "R2-REFERENCE-MARKER";
|
|
204
|
+
const referenceBytes = Uint8Array.from([
|
|
205
|
+
...imageBytes,
|
|
206
|
+
...new globalThis.TextEncoder().encode(marker),
|
|
207
|
+
]);
|
|
208
|
+
const withReference = (path, reference) => ({
|
|
209
|
+
path,
|
|
210
|
+
settings: {
|
|
211
|
+
model: referenceModel,
|
|
212
|
+
prompt: "greenhouse",
|
|
213
|
+
width: 1024,
|
|
214
|
+
height: 768,
|
|
215
|
+
references: [reference],
|
|
216
|
+
},
|
|
217
|
+
});
|
|
218
|
+
const stored = { computerId: "outputs", path: referenceKey };
|
|
219
|
+
const providerCalls = async () => {
|
|
220
|
+
const count = await env.PROOF.get("provider-count");
|
|
221
|
+
return count === null ? 0 : Number(await count.text());
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
it("sends a reference image stored in R2 to the provider", async () => {
|
|
225
|
+
await env.OUTPUTS.put(referenceKey, referenceBytes);
|
|
226
|
+
const before = await providerCalls();
|
|
227
|
+
const response = await generate(
|
|
228
|
+
withReference("with-reference.gif", stored),
|
|
229
|
+
"r2-reference-read",
|
|
230
|
+
);
|
|
231
|
+
expect(response.status).toBe(200);
|
|
232
|
+
expect(await providerCalls()).toBe(before + 1);
|
|
233
|
+
const sent = await (await env.PROOF.get("provider-input")).text();
|
|
234
|
+
expect(sent).toContain(marker);
|
|
235
|
+
expect(sent).toContain("greenhouse-ref.gif");
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it("refuses a reference for another destination before dispatch", async () => {
|
|
239
|
+
await env.OUTPUTS.put(referenceKey, referenceBytes);
|
|
240
|
+
// Control: the same reference under the admitted destination id is accepted.
|
|
241
|
+
expect(
|
|
242
|
+
(await generate(withReference("control-b.gif", stored), "r2-control-b"))
|
|
243
|
+
.status,
|
|
244
|
+
).toBe(200);
|
|
245
|
+
const before = await providerCalls();
|
|
246
|
+
const response = await generate(
|
|
247
|
+
withReference("wrong-destination.gif", {
|
|
248
|
+
...stored,
|
|
249
|
+
computerId: "someone-else",
|
|
250
|
+
}),
|
|
251
|
+
"r2-reference-wrong-destination",
|
|
252
|
+
);
|
|
253
|
+
expect(response.status).toBe(400);
|
|
254
|
+
expect(await response.json()).toMatchObject({ stage: "settings" });
|
|
255
|
+
expect(await providerCalls()).toBe(before);
|
|
256
|
+
expect(await env.OUTPUTS.get("wrong-destination.gif")).toBeNull();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it("refuses a missing or oversized reference before dispatch", async () => {
|
|
260
|
+
await env.OUTPUTS.put(referenceKey, referenceBytes);
|
|
261
|
+
// Control: a stored, in-limit reference is accepted by the same host.
|
|
262
|
+
expect(
|
|
263
|
+
(await generate(withReference("control-c.gif", stored), "r2-control-c"))
|
|
264
|
+
.status,
|
|
265
|
+
).toBe(200);
|
|
266
|
+
await env.OUTPUTS.put(
|
|
267
|
+
"references/too-big.gif",
|
|
268
|
+
new Uint8Array(8 * 1024 * 1024 + 1),
|
|
269
|
+
);
|
|
270
|
+
const before = await providerCalls();
|
|
271
|
+
for (const [id, path] of [
|
|
272
|
+
["r2-reference-missing", "references/absent.gif"],
|
|
273
|
+
["r2-reference-oversized", "references/too-big.gif"],
|
|
274
|
+
]) {
|
|
275
|
+
const response = await generate(
|
|
276
|
+
withReference(`${id}.gif`, { computerId: "outputs", path }),
|
|
277
|
+
id,
|
|
278
|
+
);
|
|
279
|
+
expect(response.status).toBe(400);
|
|
280
|
+
expect(await response.json()).toMatchObject({ stage: "settings" });
|
|
281
|
+
expect(await providerCalls()).toBe(before);
|
|
282
|
+
expect(await env.OUTPUTS.get(`${id}.gif`)).toBeNull();
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
it("saves the output at the requested key and reuses it on retry", async () => {
|
|
287
|
+
await env.OUTPUTS.put(referenceKey, referenceBytes);
|
|
288
|
+
const input = withReference("results/from-reference.gif", stored);
|
|
289
|
+
const before = await providerCalls();
|
|
290
|
+
expect((await generate(input, "r2-output-retry")).status).toBe(200);
|
|
291
|
+
const object = await env.OUTPUTS.get("results/from-reference.gif");
|
|
292
|
+
expect(new Uint8Array(await object.arrayBuffer())).toEqual(imageBytes);
|
|
293
|
+
expect(object.httpMetadata.contentType).toBe("image/gif");
|
|
294
|
+
expect(await providerCalls()).toBe(before + 1);
|
|
295
|
+
expect((await generate(input, "r2-output-retry")).status).toBe(200);
|
|
296
|
+
expect(await providerCalls()).toBe(before + 1);
|
|
297
|
+
});
|
|
298
|
+
});
|