@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,130 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
MediaReference,
|
|
3
|
+
MediaReferenceBytes,
|
|
4
|
+
ReferenceImageFitter,
|
|
5
|
+
} from "../index.js";
|
|
6
|
+
import { MediaSettingsError } from "../model-catalog.js";
|
|
7
|
+
import { mediaContentType } from "../media-content-type.js";
|
|
8
|
+
import {
|
|
9
|
+
readHostReference,
|
|
10
|
+
referenceFilename,
|
|
11
|
+
type HostReferenceSource,
|
|
12
|
+
} from "../reference-read.js";
|
|
13
|
+
import { mediaPathSchema } from "../media-path.js";
|
|
14
|
+
import { removeMediaIfWritten } from "../media-written.js";
|
|
15
|
+
import type { MediaServiceHost } from "../server.js";
|
|
16
|
+
|
|
17
|
+
/** The R2 bucket operations a Media destination needs; a native `R2Bucket` satisfies it. */
|
|
18
|
+
export type MediaR2Bucket = {
|
|
19
|
+
/** Read one object, or null when the key is absent. */
|
|
20
|
+
get(key: string): Promise<
|
|
21
|
+
| (Readonly<{
|
|
22
|
+
/** Stored byte length. */ size: number;
|
|
23
|
+
}> & {
|
|
24
|
+
/** Load the stored bytes. */ arrayBuffer(): Promise<ArrayBuffer>;
|
|
25
|
+
})
|
|
26
|
+
| null
|
|
27
|
+
>;
|
|
28
|
+
/** Store exact bytes with their MIME type. */
|
|
29
|
+
put(
|
|
30
|
+
key: string,
|
|
31
|
+
bytes: Uint8Array,
|
|
32
|
+
options: Readonly<{
|
|
33
|
+
/** MIME type recorded on the object. */
|
|
34
|
+
httpMetadata: Readonly<{ /** MIME type. */ contentType: string }>;
|
|
35
|
+
}>,
|
|
36
|
+
): Promise<object | null>;
|
|
37
|
+
/** Delete one object; absent keys are not an error. */
|
|
38
|
+
delete(key: string): Promise<void>;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Host-owned R2 destination configuration. */
|
|
42
|
+
export type R2MediaDestinationOptions = Readonly<{
|
|
43
|
+
/** The bucket holding reference images and generated output. */
|
|
44
|
+
bucket: MediaR2Bucket;
|
|
45
|
+
/**
|
|
46
|
+
* The destination identity the host admitted. A reference must carry this
|
|
47
|
+
* same value (in `MediaReference.computerId`) or it is refused.
|
|
48
|
+
*/
|
|
49
|
+
destinationId: string;
|
|
50
|
+
/** The Images-binding reference fitter, from `createImagesReferenceFitter`. */
|
|
51
|
+
fit: ReferenceImageFitter;
|
|
52
|
+
/**
|
|
53
|
+
* The host's own permission check for one object key. It runs before every
|
|
54
|
+
* dispatch, write and reference read; throw to refuse. Omitted, any valid
|
|
55
|
+
* key in `bucket` is allowed.
|
|
56
|
+
*/
|
|
57
|
+
authorize?: ((key: string) => Promise<void> | void) | undefined;
|
|
58
|
+
}>;
|
|
59
|
+
|
|
60
|
+
/** The host destination over an R2 bucket, with both reference readers present. */
|
|
61
|
+
export type R2MediaDestination = MediaServiceHost["destination"] &
|
|
62
|
+
Readonly<{
|
|
63
|
+
/** Authorize, read and fit one reference image for the catalog model. */
|
|
64
|
+
readReference: (
|
|
65
|
+
reference: MediaReference,
|
|
66
|
+
model: string,
|
|
67
|
+
) => Promise<MediaReferenceBytes>;
|
|
68
|
+
/** Authorize and read the raw bytes of one reference audio clip. */
|
|
69
|
+
readAudioReference: (reference: MediaReference) => Promise<Uint8Array>;
|
|
70
|
+
}>;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* A Media destination over one R2 bucket: object keys are the paths, validated
|
|
74
|
+
* with Darkroom's path schema. Never accepts URLs.
|
|
75
|
+
*/
|
|
76
|
+
export function createR2MediaDestination(
|
|
77
|
+
options: R2MediaDestinationOptions,
|
|
78
|
+
): R2MediaDestination {
|
|
79
|
+
const { bucket, destinationId, fit } = options;
|
|
80
|
+
const authorize = async (key: string): Promise<void> => {
|
|
81
|
+
const parsed = mediaPathSchema.safeParse(key);
|
|
82
|
+
if (!parsed.success)
|
|
83
|
+
throw new MediaSettingsError("R2 object key is not a valid path");
|
|
84
|
+
await options.authorize?.(parsed.data);
|
|
85
|
+
};
|
|
86
|
+
const read = (kind: "image" | "audio", reference: MediaReference) =>
|
|
87
|
+
readHostReference({
|
|
88
|
+
reference,
|
|
89
|
+
destinationId,
|
|
90
|
+
kind,
|
|
91
|
+
open: async (key): Promise<HostReferenceSource | null> => {
|
|
92
|
+
await authorize(key);
|
|
93
|
+
const object = await bucket.get(key);
|
|
94
|
+
if (object === null) return null;
|
|
95
|
+
return {
|
|
96
|
+
size: object.size,
|
|
97
|
+
bytes: async () => new Uint8Array(await object.arrayBuffer()),
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
return {
|
|
102
|
+
authorize,
|
|
103
|
+
write: async (key, bytes) => {
|
|
104
|
+
await authorize(key);
|
|
105
|
+
await bucket.put(key, bytes, {
|
|
106
|
+
httpMetadata: { contentType: mediaContentType(bytes) },
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
remove: async (key, written) => {
|
|
110
|
+
await authorize(key);
|
|
111
|
+
return removeMediaIfWritten(
|
|
112
|
+
{
|
|
113
|
+
read: async () => {
|
|
114
|
+
const object = await bucket.get(key);
|
|
115
|
+
return object === null
|
|
116
|
+
? null
|
|
117
|
+
: new Uint8Array(await object.arrayBuffer());
|
|
118
|
+
},
|
|
119
|
+
delete: () => bucket.delete(key),
|
|
120
|
+
},
|
|
121
|
+
written.sha256,
|
|
122
|
+
);
|
|
123
|
+
},
|
|
124
|
+
readReference: async (reference, model) => ({
|
|
125
|
+
...(await fit(await read("image", reference), model)),
|
|
126
|
+
filename: referenceFilename(reference),
|
|
127
|
+
}),
|
|
128
|
+
readAudioReference: (reference) => read("audio", reference),
|
|
129
|
+
};
|
|
130
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import {
|
|
3
|
+
MAX_REFERENCE_BYTES,
|
|
4
|
+
MediaSettingsError,
|
|
5
|
+
viewDimensionSchema,
|
|
6
|
+
type ImageViewFitter,
|
|
7
|
+
type ReferenceImageFitter,
|
|
8
|
+
} from "../index.js";
|
|
9
|
+
import {
|
|
10
|
+
referenceImageFormat,
|
|
11
|
+
referenceImageTransform,
|
|
12
|
+
} from "../reference-image-size.js";
|
|
13
|
+
|
|
14
|
+
/** WebP quality for lossy references; visually near-lossless at a fraction of PNG's bytes. */
|
|
15
|
+
const REFERENCE_WEBP_QUALITY = 85;
|
|
16
|
+
|
|
17
|
+
/** The retained `read_image` encoding: JPEG at quality 80. */
|
|
18
|
+
const VIEW_JPEG_QUALITY = 80;
|
|
19
|
+
|
|
20
|
+
const metadata = z.lazy(() =>
|
|
21
|
+
z.object({
|
|
22
|
+
format: z.enum(["image/png", "image/jpeg", "image/gif", "image/webp"]),
|
|
23
|
+
width: z.number().int().positive(),
|
|
24
|
+
height: z.number().int().positive(),
|
|
25
|
+
}),
|
|
26
|
+
);
|
|
27
|
+
const formats = {
|
|
28
|
+
"image/png": "png",
|
|
29
|
+
"image/jpeg": "jpeg",
|
|
30
|
+
"image/gif": "gif",
|
|
31
|
+
"image/webp": "webp",
|
|
32
|
+
} as const;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Cloudflare answers the Images binding with error 9432 ("not available using
|
|
36
|
+
* legacy billing") when the account has not moved to the current billing
|
|
37
|
+
* model. Say what to do, not the raw binding failure.
|
|
38
|
+
*/
|
|
39
|
+
export const imagesLegacyBillingMessage =
|
|
40
|
+
"Cloudflare Images is not available on this Cloudflare account because it is on legacy billing (Cloudflare error 9432). Reference images need the Images binding. Update the account's billing in the Cloudflare dashboard, or generate without reference images.";
|
|
41
|
+
|
|
42
|
+
/** The Images binding's `ImagesError` carries Cloudflare's numeric error code. */
|
|
43
|
+
const legacyBillingFailure = z.object({ code: z.literal(9432) });
|
|
44
|
+
|
|
45
|
+
function legacyBillingRefusal(cause: unknown): MediaSettingsError | undefined {
|
|
46
|
+
return legacyBillingFailure.safeParse(cause).success
|
|
47
|
+
? new MediaSettingsError(imagesLegacyBillingMessage)
|
|
48
|
+
: undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const stream = (bytes: Uint8Array) =>
|
|
52
|
+
new ReadableStream<Uint8Array>({
|
|
53
|
+
start(controller) {
|
|
54
|
+
controller.enqueue(bytes.slice());
|
|
55
|
+
controller.close();
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
/** Only image metadata and the bounded resize chain are consumed by Media. */
|
|
60
|
+
export type MediaImagePort = {
|
|
61
|
+
/** Read decoded image metadata through the Images binding. */
|
|
62
|
+
info(input: ReadableStream<Uint8Array>): ReturnType<ImagesBinding["info"]>;
|
|
63
|
+
/** Start the native resize and encode chain. */
|
|
64
|
+
input(input: ReadableStream<Uint8Array>): {
|
|
65
|
+
/** Apply the native aspect-preserving resize. */
|
|
66
|
+
transform(options: {
|
|
67
|
+
/** Image width in pixels. */
|
|
68
|
+
width: number;
|
|
69
|
+
/** Image height in pixels. */
|
|
70
|
+
height: number;
|
|
71
|
+
fit: "scale-down" | "contain";
|
|
72
|
+
}): {
|
|
73
|
+
/** Encode the transformed image through the native Images binding. */
|
|
74
|
+
output(
|
|
75
|
+
options:
|
|
76
|
+
| {
|
|
77
|
+
/** Actual output encoding. */
|
|
78
|
+
format: "image/png";
|
|
79
|
+
}
|
|
80
|
+
| {
|
|
81
|
+
/** Actual output encoding. */
|
|
82
|
+
format: "image/jpeg";
|
|
83
|
+
quality: number;
|
|
84
|
+
}
|
|
85
|
+
| {
|
|
86
|
+
/** Actual output encoding. */
|
|
87
|
+
format: "image/webp";
|
|
88
|
+
quality: number;
|
|
89
|
+
},
|
|
90
|
+
): Promise<{
|
|
91
|
+
/** Provider response or encoded image response. */
|
|
92
|
+
response(): Response;
|
|
93
|
+
}>;
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Media's reference preparation on the Images binding: decode the real bytes,
|
|
100
|
+
* fit the selected model's reference size in its catalog encoding, then decode
|
|
101
|
+
* the output so its metadata describes the bytes actually sent.
|
|
102
|
+
*/
|
|
103
|
+
export function createImagesReferenceFitter(
|
|
104
|
+
images: MediaImagePort,
|
|
105
|
+
): ReferenceImageFitter {
|
|
106
|
+
return async (input, model) => {
|
|
107
|
+
let bytes = input;
|
|
108
|
+
let info: z.output<typeof metadata>;
|
|
109
|
+
try {
|
|
110
|
+
info = metadata.parse(await images.info(stream(bytes)));
|
|
111
|
+
} catch (cause) {
|
|
112
|
+
// Other Images failure detail is never surfaced; the caller's bytes are.
|
|
113
|
+
throw (
|
|
114
|
+
legacyBillingRefusal(cause) ??
|
|
115
|
+
new MediaSettingsError("reference image is not a supported image")
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
const transform = referenceImageTransform(model, info.width, info.height);
|
|
119
|
+
const target = referenceImageFormat(model);
|
|
120
|
+
if (
|
|
121
|
+
info.width !== transform.width ||
|
|
122
|
+
info.height !== transform.height ||
|
|
123
|
+
(target === "image/webp" && info.format !== target)
|
|
124
|
+
) {
|
|
125
|
+
const output = await images
|
|
126
|
+
.input(stream(bytes))
|
|
127
|
+
.transform(transform)
|
|
128
|
+
.output(
|
|
129
|
+
target === "image/webp"
|
|
130
|
+
? { format: target, quality: REFERENCE_WEBP_QUALITY }
|
|
131
|
+
: { format: target },
|
|
132
|
+
)
|
|
133
|
+
.catch((cause: unknown) => {
|
|
134
|
+
throw legacyBillingRefusal(cause) ?? cause;
|
|
135
|
+
});
|
|
136
|
+
bytes = new Uint8Array(await output.response().arrayBuffer());
|
|
137
|
+
if (bytes.byteLength === 0 || bytes.byteLength > MAX_REFERENCE_BYTES)
|
|
138
|
+
throw new MediaSettingsError("reference image exceeds the byte limit");
|
|
139
|
+
info = metadata.parse(await images.info(stream(bytes)));
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
bytes,
|
|
143
|
+
format: formats[info.format],
|
|
144
|
+
width: info.width,
|
|
145
|
+
height: info.height,
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Fit one image for a model to look at on the Images binding: always
|
|
152
|
+
* re-encode it as JPEG (quality 80), scaled down within `maxDimension`, and
|
|
153
|
+
* decode the output so its metadata describes the bytes actually returned.
|
|
154
|
+
*/
|
|
155
|
+
export function createImagesViewFitter(
|
|
156
|
+
images: MediaImagePort,
|
|
157
|
+
): ImageViewFitter {
|
|
158
|
+
return async (input, maxDimension) => {
|
|
159
|
+
const bound = viewDimensionSchema.safeParse(maxDimension);
|
|
160
|
+
if (!bound.success)
|
|
161
|
+
throw new MediaSettingsError("view dimension is out of bounds");
|
|
162
|
+
try {
|
|
163
|
+
metadata.parse(await images.info(stream(input)));
|
|
164
|
+
} catch (cause) {
|
|
165
|
+
// Other Images failure detail is never surfaced.
|
|
166
|
+
throw (
|
|
167
|
+
legacyBillingRefusal(cause) ??
|
|
168
|
+
new MediaSettingsError("image is not a supported image")
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
const output = await images
|
|
172
|
+
.input(stream(input))
|
|
173
|
+
.transform({
|
|
174
|
+
width: bound.data,
|
|
175
|
+
height: bound.data,
|
|
176
|
+
fit: "scale-down",
|
|
177
|
+
})
|
|
178
|
+
.output({
|
|
179
|
+
format: "image/jpeg",
|
|
180
|
+
quality: VIEW_JPEG_QUALITY,
|
|
181
|
+
});
|
|
182
|
+
const bytes = new Uint8Array(await output.response().arrayBuffer());
|
|
183
|
+
if (bytes.byteLength === 0 || bytes.byteLength > MAX_REFERENCE_BYTES)
|
|
184
|
+
throw new MediaSettingsError("image exceeds the byte limit");
|
|
185
|
+
const info = metadata.parse(await images.info(stream(bytes)));
|
|
186
|
+
return {
|
|
187
|
+
bytes,
|
|
188
|
+
format: formats[info.format],
|
|
189
|
+
width: info.width,
|
|
190
|
+
height: info.height,
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export {
|
|
2
|
+
MediaOperationDO,
|
|
3
|
+
type MediaOperationCloudflareEnvironment,
|
|
4
|
+
type MediaOperationCoordinates,
|
|
5
|
+
type MediaOperationRequest,
|
|
6
|
+
} from "./media-operation-do.js";
|
|
7
|
+
export {
|
|
8
|
+
createWorkersAiMediaProvider,
|
|
9
|
+
type MediaAiPort,
|
|
10
|
+
} from "./cloudflare/provider.js";
|
|
11
|
+
export type { MediaAiResult } from "./index.js";
|
|
12
|
+
export {
|
|
13
|
+
createImagesReferenceFitter,
|
|
14
|
+
createImagesViewFitter,
|
|
15
|
+
type MediaImagePort,
|
|
16
|
+
} from "./cloudflare/reference-images.js";
|
|
17
|
+
export {
|
|
18
|
+
createR2MediaDestination,
|
|
19
|
+
type MediaR2Bucket,
|
|
20
|
+
type R2MediaDestination,
|
|
21
|
+
type R2MediaDestinationOptions,
|
|
22
|
+
} from "./cloudflare/r2-destination.js";
|
|
23
|
+
|
|
24
|
+
export { MediaOperationOwner } from "./media-operation-owner.js";
|
|
25
|
+
export type {
|
|
26
|
+
MediaErasure,
|
|
27
|
+
MediaRetained,
|
|
28
|
+
MediaRetainedBytes,
|
|
29
|
+
MediaErasePolicy,
|
|
30
|
+
MediaShareSource,
|
|
31
|
+
} from "./media-operation-owner.js";
|
|
32
|
+
export type {
|
|
33
|
+
MediaOperationContext,
|
|
34
|
+
MediaOperationStorage,
|
|
35
|
+
MediaErasureMarker,
|
|
36
|
+
MediaOperationBucket,
|
|
37
|
+
MediaOperationObject,
|
|
38
|
+
} from "./media-operation-storage.js";
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import {
|
|
2
|
+
getGatewayModel,
|
|
3
|
+
MAX_REFERENCE_COUNT,
|
|
4
|
+
MediaSettingsError,
|
|
5
|
+
} from "./model-catalog.js";
|
|
6
|
+
import { neuronsToMilliunits } from "./neurons.js";
|
|
7
|
+
import * as z from "zod";
|
|
8
|
+
|
|
9
|
+
/** Dimensions and optional settings used by the deterministic image quote. */
|
|
10
|
+
export type ImageParams = {
|
|
11
|
+
/** Output height in pixels. */
|
|
12
|
+
readonly height: number;
|
|
13
|
+
/** Reference dimensions counted in the quote. */
|
|
14
|
+
readonly references?: readonly ImageReference[];
|
|
15
|
+
/** Inference steps, using catalog defaults when omitted. */
|
|
16
|
+
readonly steps?: number;
|
|
17
|
+
/** Output width in pixels. */
|
|
18
|
+
readonly width: number;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** Reference-image dimensions used to estimate provider work. */
|
|
22
|
+
export type ImageReference = {
|
|
23
|
+
/** Reference height in pixels. */
|
|
24
|
+
readonly height: number;
|
|
25
|
+
/** Reference width in pixels. */
|
|
26
|
+
readonly width: number;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const TILE = 512;
|
|
30
|
+
const MAX_DIMENSION = 4_096;
|
|
31
|
+
|
|
32
|
+
const imageParamsSchema = z.lazy(() =>
|
|
33
|
+
z
|
|
34
|
+
.object({
|
|
35
|
+
width: z.number().int().min(1).max(MAX_DIMENSION),
|
|
36
|
+
height: z.number().int().min(1).max(MAX_DIMENSION),
|
|
37
|
+
steps: z.number().int().min(1).optional(),
|
|
38
|
+
references: z
|
|
39
|
+
.array(
|
|
40
|
+
z
|
|
41
|
+
.object({
|
|
42
|
+
width: z.number().int().min(1).max(MAX_DIMENSION),
|
|
43
|
+
height: z.number().int().min(1).max(MAX_DIMENSION),
|
|
44
|
+
})
|
|
45
|
+
.strict(),
|
|
46
|
+
)
|
|
47
|
+
.max(MAX_REFERENCE_COUNT)
|
|
48
|
+
.optional(),
|
|
49
|
+
})
|
|
50
|
+
.strict(),
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const invalid = (message: string): never => {
|
|
54
|
+
throw new MediaSettingsError(`image cost parameters are invalid: ${message}`);
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const tiles = (width: number, height: number): number =>
|
|
58
|
+
Math.ceil(width / TILE) * Math.ceil(height / TILE);
|
|
59
|
+
|
|
60
|
+
const checked = (modelId: string, params: ImageParams): ImageParams => {
|
|
61
|
+
const parsed = imageParamsSchema.safeParse(params);
|
|
62
|
+
if (!parsed.success)
|
|
63
|
+
return invalid("dimensions, steps, or references are invalid");
|
|
64
|
+
const candidate = parsed.data;
|
|
65
|
+
const references = candidate.references ?? [];
|
|
66
|
+
const model = getGatewayModel(modelId);
|
|
67
|
+
if (model === undefined)
|
|
68
|
+
throw new MediaSettingsError(`Image cost unknown for model "${modelId}"`);
|
|
69
|
+
if (references.length > model.input.maxReferences)
|
|
70
|
+
return invalid(
|
|
71
|
+
`${modelId} accepts at most ${String(model.input.maxReferences)} references`,
|
|
72
|
+
);
|
|
73
|
+
const normalized = {
|
|
74
|
+
width: candidate.width,
|
|
75
|
+
height: candidate.height,
|
|
76
|
+
references,
|
|
77
|
+
};
|
|
78
|
+
if (candidate.steps !== undefined)
|
|
79
|
+
return { ...normalized, steps: candidate.steps };
|
|
80
|
+
return normalized;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** Estimate Workers AI neurons from a validated image request. */
|
|
84
|
+
export const estimateImageNeurons = (
|
|
85
|
+
modelId: string,
|
|
86
|
+
params: ImageParams,
|
|
87
|
+
): number => {
|
|
88
|
+
const p = checked(modelId, params);
|
|
89
|
+
const outputTiles = tiles(p.width, p.height);
|
|
90
|
+
const inputTiles = (p.references ?? []).reduce(
|
|
91
|
+
(sum, reference) => sum + tiles(reference.width, reference.height),
|
|
92
|
+
0,
|
|
93
|
+
);
|
|
94
|
+
switch (modelId) {
|
|
95
|
+
case "@cf/black-forest-labs/flux-1-schnell":
|
|
96
|
+
return outputTiles * 4.8 + (p.steps ?? 4) * 9.6;
|
|
97
|
+
case "@cf/black-forest-labs/flux-2-klein-4b":
|
|
98
|
+
return inputTiles * 5.37 + outputTiles * 26.05;
|
|
99
|
+
case "@cf/black-forest-labs/flux-2-dev":
|
|
100
|
+
return (
|
|
101
|
+
inputTiles * (p.steps ?? 20) * 19.09 +
|
|
102
|
+
outputTiles * (p.steps ?? 20) * 37.27
|
|
103
|
+
);
|
|
104
|
+
case "@cf/black-forest-labs/flux-2-klein-9b": {
|
|
105
|
+
const outputMp = (p.width / 1024) * (p.height / 1024);
|
|
106
|
+
const outputCost =
|
|
107
|
+
Math.min(outputMp, 1) * 1363.64 + Math.max(0, outputMp - 1) * 181.82;
|
|
108
|
+
const inputMp = (p.references ?? []).reduce(
|
|
109
|
+
(sum, reference) =>
|
|
110
|
+
sum + (reference.width / 1024) * (reference.height / 1024),
|
|
111
|
+
0,
|
|
112
|
+
);
|
|
113
|
+
return (outputMp < 1 ? 1363.64 : outputCost) + inputMp * 181.82;
|
|
114
|
+
}
|
|
115
|
+
case "@cf/leonardo/lucid-origin":
|
|
116
|
+
return outputTiles * 636 + (p.steps ?? 20) * 12;
|
|
117
|
+
case "@cf/leonardo/phoenix-1.0":
|
|
118
|
+
return outputTiles * 530 + (p.steps ?? 25) * 10;
|
|
119
|
+
default:
|
|
120
|
+
// checked() owns this rejection; keep the switch exhaustive at runtime.
|
|
121
|
+
throw new MediaSettingsError(`Image cost unknown for model "${modelId}"`);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** Quote the same estimate in milliunits (1 cent = 1,000 milliunits). */
|
|
126
|
+
export const estimateImageMilliunits = (
|
|
127
|
+
modelId: string,
|
|
128
|
+
params: ImageParams,
|
|
129
|
+
): number => neuronsToMilliunits(estimateImageNeurons(modelId, params));
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import type { MediaMetering } from "./media-operation-contract.js";
|
|
3
|
+
import { MediaBillingRefusal } from "./execution-error.js";
|
|
4
|
+
|
|
5
|
+
/** The Durable Object storage slice the meter owns tables in. */
|
|
6
|
+
export type DailyMediaMeterStorage = Readonly<{
|
|
7
|
+
/** SQLite access owned by the Durable Object. */
|
|
8
|
+
sql: Readonly<{
|
|
9
|
+
/** Run one statement with positional bindings. */
|
|
10
|
+
exec: (
|
|
11
|
+
query: string,
|
|
12
|
+
...bindings: readonly (string | number)[]
|
|
13
|
+
) => Readonly<{
|
|
14
|
+
/** Read every returned row. */
|
|
15
|
+
toArray: () => readonly unknown[];
|
|
16
|
+
}>;
|
|
17
|
+
}>;
|
|
18
|
+
/** Run the body in one synchronous transaction. */
|
|
19
|
+
transactionSync: <T>(body: () => T) => T;
|
|
20
|
+
}>;
|
|
21
|
+
|
|
22
|
+
/** RPC surface of the Durable Object that owns one Oyster's daily media total. */
|
|
23
|
+
export type DailyMediaMeterPort = Readonly<{
|
|
24
|
+
/** Hold one generation's provider cost against today's limit; false when it would exceed it. */
|
|
25
|
+
dailyAdmit: (
|
|
26
|
+
input: Readonly<{
|
|
27
|
+
operationId: string;
|
|
28
|
+
costMilliunits: number;
|
|
29
|
+
limitMilliunits: number;
|
|
30
|
+
}>,
|
|
31
|
+
) => Promise<boolean> | boolean;
|
|
32
|
+
/** Release the hold when nothing was delivered, or keep it once delivered. */
|
|
33
|
+
dailySettle: (
|
|
34
|
+
input: Readonly<{ operationId: string; delivered: boolean }>,
|
|
35
|
+
) => Promise<void> | void;
|
|
36
|
+
}>;
|
|
37
|
+
|
|
38
|
+
const totalRowSchema = z.strictObject({ total: z.number() });
|
|
39
|
+
|
|
40
|
+
const MS_PER_DAY = 86_400_000;
|
|
41
|
+
|
|
42
|
+
/** The UTC day number a timestamp falls in; the total resets when it changes. */
|
|
43
|
+
function utcDay(timestamp: number): number {
|
|
44
|
+
return Math.floor(timestamp / MS_PER_DAY);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A UTC-day total of admitted media cost, kept in one Durable Object's SQLite.
|
|
49
|
+
* Every statement runs inside one synchronous transaction, so two concurrent
|
|
50
|
+
* admits near the limit are serialized by the object and cannot both pass.
|
|
51
|
+
* Holds are keyed by the durable operation id, so a retried admit never counts
|
|
52
|
+
* twice. A hold that is never settled stays counted until its day ends.
|
|
53
|
+
*/
|
|
54
|
+
export class DailyMediaMeter {
|
|
55
|
+
private ready = false;
|
|
56
|
+
constructor(
|
|
57
|
+
private readonly storage: DailyMediaMeterStorage,
|
|
58
|
+
private readonly now: () => number = Date.now,
|
|
59
|
+
) {}
|
|
60
|
+
|
|
61
|
+
private ensureSchema(): void {
|
|
62
|
+
if (this.ready) return;
|
|
63
|
+
this.storage.sql.exec(
|
|
64
|
+
"CREATE TABLE IF NOT EXISTS daily_media_hold (operation_id TEXT PRIMARY KEY, day INTEGER NOT NULL, milliunits INTEGER NOT NULL CHECK(milliunits>=0)) STRICT",
|
|
65
|
+
);
|
|
66
|
+
this.ready = true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Hold `costMilliunits` for this operation unless the day's total would exceed the limit. */
|
|
70
|
+
admit(
|
|
71
|
+
input: Readonly<{
|
|
72
|
+
operationId: string;
|
|
73
|
+
costMilliunits: number;
|
|
74
|
+
limitMilliunits: number;
|
|
75
|
+
}>,
|
|
76
|
+
): boolean {
|
|
77
|
+
return this.storage.transactionSync(() => {
|
|
78
|
+
this.ensureSchema();
|
|
79
|
+
const day = utcDay(this.now());
|
|
80
|
+
const { sql } = this.storage;
|
|
81
|
+
sql.exec("DELETE FROM daily_media_hold WHERE day < ?", day);
|
|
82
|
+
const held = sql
|
|
83
|
+
.exec(
|
|
84
|
+
"SELECT day FROM daily_media_hold WHERE operation_id = ?",
|
|
85
|
+
input.operationId,
|
|
86
|
+
)
|
|
87
|
+
.toArray()[0];
|
|
88
|
+
if (held !== undefined) return true;
|
|
89
|
+
const { total } = totalRowSchema.parse(
|
|
90
|
+
sql
|
|
91
|
+
.exec(
|
|
92
|
+
"SELECT COALESCE(SUM(milliunits),0) AS total FROM daily_media_hold WHERE day = ?",
|
|
93
|
+
day,
|
|
94
|
+
)
|
|
95
|
+
.toArray()[0],
|
|
96
|
+
);
|
|
97
|
+
if (total + input.costMilliunits > input.limitMilliunits) return false;
|
|
98
|
+
sql.exec(
|
|
99
|
+
"INSERT INTO daily_media_hold (operation_id, day, milliunits) VALUES (?, ?, ?)",
|
|
100
|
+
input.operationId,
|
|
101
|
+
day,
|
|
102
|
+
input.costMilliunits,
|
|
103
|
+
);
|
|
104
|
+
return true;
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Keep the hold when media was delivered; release it when nothing was. */
|
|
109
|
+
settle(input: Readonly<{ operationId: string; delivered: boolean }>): void {
|
|
110
|
+
if (input.delivered) return;
|
|
111
|
+
this.storage.transactionSync(() => {
|
|
112
|
+
this.ensureSchema();
|
|
113
|
+
this.storage.sql.exec(
|
|
114
|
+
"DELETE FROM daily_media_hold WHERE operation_id = ?",
|
|
115
|
+
input.operationId,
|
|
116
|
+
);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Which daily-meter RPC failed; its original cause stays private. */
|
|
122
|
+
export class DailyMediaMeterError extends Error {
|
|
123
|
+
constructor(
|
|
124
|
+
readonly operation: "admit" | "settle",
|
|
125
|
+
options: ErrorOptions,
|
|
126
|
+
) {
|
|
127
|
+
super(`Daily media meter ${operation} failed`, options);
|
|
128
|
+
this.name = "DailyMediaMeterError";
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** `MediaMetering` that enforces one exact daily limit through the owning object. */
|
|
133
|
+
export function createDailyMediaMetering(
|
|
134
|
+
meter: DailyMediaMeterPort,
|
|
135
|
+
limitMilliunits: number,
|
|
136
|
+
): MediaMetering {
|
|
137
|
+
return {
|
|
138
|
+
admit: async (input) => {
|
|
139
|
+
let admitted: boolean;
|
|
140
|
+
try {
|
|
141
|
+
admitted = await meter.dailyAdmit({
|
|
142
|
+
operationId: input.operationId,
|
|
143
|
+
costMilliunits: input.providerCostMilliunits,
|
|
144
|
+
limitMilliunits,
|
|
145
|
+
});
|
|
146
|
+
} catch (cause) {
|
|
147
|
+
throw new DailyMediaMeterError("admit", { cause });
|
|
148
|
+
}
|
|
149
|
+
if (!admitted) throw new MediaBillingRefusal("daily_limit_reached");
|
|
150
|
+
return { priceMilliunits: input.providerCostMilliunits };
|
|
151
|
+
},
|
|
152
|
+
settle: async (input) => {
|
|
153
|
+
try {
|
|
154
|
+
await meter.dailySettle({
|
|
155
|
+
operationId: input.operationId,
|
|
156
|
+
delivered: input.units > 0,
|
|
157
|
+
});
|
|
158
|
+
} catch (cause) {
|
|
159
|
+
throw new DailyMediaMeterError("settle", { cause });
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
package/src/effect.ts
ADDED