-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbatchGeneration.ts
More file actions
1538 lines (1368 loc) · 50.7 KB
/
Copy pathbatchGeneration.ts
File metadata and controls
1538 lines (1368 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Convex Batch Generation Functions
*
* Handles async batch image generation with Cloudflare-backed worker dispatch.
* Items are seeded in fixed-size chunks so the UX stays fast without burning
* Convex action compute on provider waits.
*
* BYOP (Bring Your Own Pollen) Architecture:
* - Client obtains API key from PollenAuth context (fetched from encrypted Convex storage)
* - startBatchJob: Receives API key, creates batch record + batchItems, schedules the first chunk
* - Cloudflare worker: Claims each batch item, calls Pollinations, uploads media, finalizes in Convex
* - storeGeneratedImage: Stores image metadata in Convex
*
* This is a true "fire and forget" implementation - users can close their browser
* and the batch will continue processing on the server using the stored API key.
*/
import { ConvexError, v } from "convex/values"
import { internal } from "./_generated/api"
import type { Doc } from "./_generated/dataModel"
import {
internalMutation,
internalQuery,
mutation,
query,
type MutationCtx,
} from "./_generated/server"
import {
buildRecordBatchItemResultTransition,
getBatchStatusAfterItemSettlement,
} from "./lib/batchGenerationState"
import { analyzePromptForNSFW } from "./lib/nsfwDetection"
import { canUserGenerate } from "./lib/subscription"
/** Maximum batch size */
const MAX_BATCH_SIZE = 1000
/** Minimum batch size */
const MIN_BATCH_SIZE = 1
/** Seed work in chunks of 10 with 1.5s spacing between chunks. */
const BATCH_DISPATCH_CHUNK_SIZE = 10
const BATCH_DISPATCH_CHUNK_DELAY_MS = 1_500
const BATCH_ITEM_INSERT_CHUNK_SIZE = 100
/** Legacy adaptive delay state retained for backward compatibility with existing docs/UI. */
const BASE_RATE_LIMIT_DELAY_MS = 100
const MAX_ADAPTIVE_DELAY_MS = 2_000
const MIN_JITTER_MS = 0
const MAX_JITTER_MS = 250
const THROTTLE_BACKOFF_MULTIPLIER = 1.5
const TRANSIENT_BACKOFF_MULTIPLIER = 1.25
const SUCCESS_RECOVERY_MULTIPLIER = 0.9
/**
* Lightweight batch job data for list views.
* Excludes heavy fields (generationParams, apiKey, imageIds) to reduce bandwidth.
*/
type BatchJobSummary = {
_id: Doc<"batchJobs">["_id"]
_creationTime: number
status: Doc<"batchJobs">["status"]
totalCount: number
completedCount: number
failedCount: number
currentIndex: number
inFlightCount?: number
adaptiveDelayMs?: number
createdAt: number
updatedAt: number
lastErrorCode?: number
}
/**
* Find an existing active batch for a user. This makes startBatchJob idempotent
* across double-clicks, hotkey repeats, stale tabs, and direct mutation calls.
*/
async function getExistingActiveBatchJob(
ctx: MutationCtx,
ownerId: string
): Promise<Doc<"batchJobs"> | null> {
const [pending, processing, paused] = await Promise.all([
ctx.db
.query("batchJobs")
.withIndex("by_owner_status", (q) =>
q.eq("ownerId", ownerId).eq("status", "pending")
)
.order("desc")
.take(1),
ctx.db
.query("batchJobs")
.withIndex("by_owner_status", (q) =>
q.eq("ownerId", ownerId).eq("status", "processing")
)
.order("desc")
.take(1),
ctx.db
.query("batchJobs")
.withIndex("by_owner_status", (q) =>
q.eq("ownerId", ownerId).eq("status", "paused")
)
.order("desc")
.take(1),
])
return [...pending, ...processing, ...paused].sort((a, b) => b.createdAt - a.createdAt)[0] ?? null
}
/**
* Convert a full batch job document to a lightweight summary.
* Strips generationParams (can be 10-50KB for complex workflows),
* apiKey (sensitive), and imageIds (only needed for detail views).
*/
function toBatchJobSummary(job: Doc<"batchJobs">): BatchJobSummary {
return {
_id: job._id,
_creationTime: job._creationTime,
status: job.status,
totalCount: job.totalCount,
completedCount: job.completedCount,
failedCount: job.failedCount,
currentIndex: job.currentIndex,
inFlightCount: job.inFlightCount,
adaptiveDelayMs: job.adaptiveDelayMs,
createdAt: job.createdAt,
updatedAt: job.updatedAt,
lastErrorCode: job.lastErrorCode,
}
}
/**
* Generation params validator (shared between functions)
*/
const generationParamsValidator = v.object({
prompt: v.string(),
negativePrompt: v.optional(v.string()),
model: v.optional(v.string()),
width: v.optional(v.number()),
height: v.optional(v.number()),
seed: v.optional(v.number()),
enhance: v.optional(v.boolean()),
private: v.optional(v.boolean()),
safe: v.optional(v.boolean()),
image: v.optional(v.string()),
// Video-specific parameters
duration: v.optional(v.number()),
audio: v.optional(v.boolean()),
aspectRatio: v.optional(v.string()),
lastFrameImage: v.optional(v.string()),
})
/**
* Start a new batch generation job.
* Creates the batch job record and schedules the first item for processing.
*/
export const startBatchJob = mutation({
args: {
count: v.number(),
generationParams: generationParamsValidator,
/** The Pollinations API key from the client (BYOP flow) */
apiKey: v.string(),
},
handler: async (ctx, args) => {
const identity = await ctx.auth.getUserIdentity()
if (!identity) {
throw new Error("Not authenticated")
}
// Validate API key is provided
if (!args.apiKey || args.apiKey.trim().length === 0) {
throw new ConvexError({
code: "MISSING_API_KEY",
message: "Pollinations API key is required. Please connect to Pollinations first.",
})
}
// Check if user can generate (has active subscription or is in trial)
const accessCheck = await canUserGenerate(ctx, identity.subject)
if (!accessCheck.allowed) {
throw new ConvexError({
code: "TRIAL_EXPIRED",
message: accessCheck.reason,
})
}
// Validate batch size
if (args.count < MIN_BATCH_SIZE || args.count > MAX_BATCH_SIZE) {
throw new Error(`Batch size must be between ${MIN_BATCH_SIZE} and ${MAX_BATCH_SIZE}`)
}
const existingActiveBatch = await getExistingActiveBatchJob(ctx, identity.subject)
if (existingActiveBatch) {
return existingActiveBatch._id
}
const now = Date.now()
// Create the aggregate batch job document. Per-item execution lives in
// batchItems so the parent doc no longer acts as the queue itself.
const batchJobId = await ctx.db.insert("batchJobs", {
ownerId: identity.subject,
status: "pending",
totalCount: args.count,
completedCount: 0,
failedCount: 0,
currentIndex: 0,
inFlightCount: 0,
adaptiveDelayMs: BASE_RATE_LIMIT_DELAY_MS,
generationParams: args.generationParams,
apiKey: args.apiKey, // Store the API key for use by processor actions
imageIds: [],
createdAt: now,
updatedAt: now,
})
const firstChunkEnd = Math.min(args.count, BATCH_ITEM_INSERT_CHUNK_SIZE)
for (let itemIndex = 0; itemIndex < firstChunkEnd; itemIndex += 1) {
await ctx.db.insert("batchItems", {
batchJobId,
ownerId: identity.subject,
itemIndex,
status: "pending",
dispatchStatus: "pending",
dispatchAttempts: 0,
createdAt: now,
updatedAt: now,
})
}
if (firstChunkEnd < args.count) {
await ctx.scheduler.runAfter(0, internal.batchGeneration.seedBatchItemChunk, {
batchJobId,
startIndex: firstChunkEnd,
})
} else {
// Seed the first dispatch chunk immediately. Additional chunks self-schedule.
await ctx.scheduler.runAfter(0, internal.batchGeneration.seedBatchDispatchChunk, {
batchJobId,
startIndex: 0,
})
}
return batchJobId
},
})
/**
* Internal mutation to store a generated image in the database.
* Called by the worker-backed batch completion path after successful generation.
*/
export const storeGeneratedImage = internalMutation({
args: {
ownerId: v.string(),
r2Key: v.string(),
url: v.string(),
thumbnailR2Key: v.optional(v.string()),
thumbnailUrl: v.optional(v.string()),
previewR2Key: v.optional(v.string()),
previewUrl: v.optional(v.string()),
prompt: v.string(),
width: v.number(),
height: v.number(),
model: v.string(),
seed: v.optional(v.number()),
contentType: v.string(),
sizeBytes: v.number(),
generationParams: v.any(),
visibility: v.union(v.literal("public"), v.literal("unlisted")),
},
handler: async (ctx, args) => {
const now = Date.now()
const needsSecondaryAssets = args.contentType.startsWith("video/")
// Private images (unlisted) bypass NSFW detection entirely.
// They are never shown in public feeds, so content analysis is unnecessary.
const isPrivate = args.visibility === "unlisted"
const needsModeration = !isPrivate
let isSensitive: boolean | null = false
let sensitiveSource: "prompt_analysis" | undefined = undefined
let sensitiveConfidence = 0
if (!isPrivate) {
// Analyze prompt for NSFW content (public images only)
const promptAnalysis = analyzePromptForNSFW(args.prompt)
console.log(`[Batch Prompt Analysis] Score: ${promptAnalysis.confidence}, Sensitive: ${promptAnalysis.isSensitive}, Terms: ${promptAnalysis.matchedTerms.join(", ")}`)
isSensitive = promptAnalysis.confidence >= 0.9 ? true : null
sensitiveSource = promptAnalysis.confidence >= 0.9 ? "prompt_analysis" : undefined
sensitiveConfidence = promptAnalysis.confidence
} else {
console.log(`[Batch Prompt Analysis] Skipped — private image`)
}
const imageId = await ctx.db.insert("generatedImages", {
ownerId: args.ownerId,
r2Key: args.r2Key,
url: args.url,
thumbnailR2Key: args.thumbnailR2Key,
thumbnailUrl: args.thumbnailUrl,
previewR2Key: args.previewR2Key,
previewUrl: args.previewUrl,
filename: `img_${now}_${Math.random().toString(36).substring(2, 9)}`,
contentType: args.contentType,
sizeBytes: args.sizeBytes,
width: args.width,
height: args.height,
aspectRatio: Math.max(args.width, args.height) / Math.min(args.width, args.height),
prompt: args.prompt,
negativePrompt: undefined,
model: args.model,
seed: args.seed,
visibility: args.visibility,
createdAt: now,
isSensitive,
sensitiveSource,
sensitiveConfidence,
moderationStage: needsModeration && sensitiveConfidence < 0.9 ? "prompt_inference" : undefined,
moderationDispatchStatus: needsModeration && sensitiveConfidence < 0.9 ? "pending" : undefined,
moderationDispatchAttempts: needsModeration && sensitiveConfidence < 0.9 ? 0 : undefined,
moderationUpdatedAt: needsModeration && sensitiveConfidence < 0.9 ? now : undefined,
secondaryAssetsDispatchStatus: needsSecondaryAssets ? "pending" : undefined,
secondaryAssetsDispatchAttempts: needsSecondaryAssets ? 0 : undefined,
secondaryAssetsUpdatedAt: needsSecondaryAssets ? now : undefined,
})
// Store heavy details in side table (P0 Optimization)
await ctx.db.insert("generatedImageDetails", {
imageId,
generationParams: args.generationParams,
})
// Schedule async Prompt Inference (Phase 3) only for public images
// that were not explicitly flagged by Gate 1.
if (!isPrivate && sensitiveConfidence < 0.9) {
await ctx.scheduler.runAfter(0, internal.promptInference.analyzePromptImage, {
imageId,
prompt: args.prompt,
})
}
return imageId
},
})
/**
* Insert batch item rows in bounded chunks so very large batches stay under
* Convex mutation limits.
*/
export const seedBatchItemChunk = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
startIndex: v.number(),
},
returns: v.object({
insertedCount: v.number(),
nextStartIndex: v.union(v.number(), v.null()),
}),
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
if (!batchJob || batchJob.status === "cancelled" || batchJob.status === "completed" || batchJob.status === "failed") {
return { insertedCount: 0, nextStartIndex: null }
}
const endExclusive = Math.min(args.startIndex + BATCH_ITEM_INSERT_CHUNK_SIZE, batchJob.totalCount)
const now = Date.now()
let insertedCount = 0
for (let itemIndex = args.startIndex; itemIndex < endExclusive; itemIndex += 1) {
const existingItems = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", itemIndex)
)
.take(1)
if (existingItems[0]) {
continue
}
await ctx.db.insert("batchItems", {
batchJobId: args.batchJobId,
ownerId: batchJob.ownerId,
itemIndex,
status: "pending",
dispatchStatus: "pending",
dispatchAttempts: 0,
createdAt: now,
updatedAt: now,
})
insertedCount += 1
}
const nextStartIndex = endExclusive < batchJob.totalCount ? endExclusive : null
if (nextStartIndex !== null) {
await ctx.scheduler.runAfter(0, internal.batchGeneration.seedBatchItemChunk, {
batchJobId: args.batchJobId,
startIndex: nextStartIndex,
})
} else {
await ctx.scheduler.runAfter(0, internal.batchGeneration.seedBatchDispatchChunk, {
batchJobId: args.batchJobId,
startIndex: 0,
})
}
return { insertedCount, nextStartIndex }
},
})
/**
* Seed a batch dispatch chunk into the Cloudflare worker plane.
*
* This is the pacing primitive for batch throughput:
* - schedule up to 10 items immediately
* - schedule the next chunk 1.5s later
* - stop seeding while paused/cancelled/completed
*/
export const seedBatchDispatchChunk = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
startIndex: v.number(),
},
returns: v.object({
scheduledCount: v.number(),
nextStartIndex: v.union(v.number(), v.null()),
}),
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
if (!batchJob || (batchJob.status !== "pending" && batchJob.status !== "processing")) {
return { scheduledCount: 0, nextStartIndex: null }
}
const endExclusive = Math.min(args.startIndex + BATCH_DISPATCH_CHUNK_SIZE, batchJob.totalCount)
let scheduledCount = 0
for (let itemIndex = args.startIndex; itemIndex < endExclusive; itemIndex += 1) {
const batchItems = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", itemIndex)
)
.take(1)
const batchItem = batchItems[0]
if (!batchItem) {
continue
}
if (batchItem.status !== "pending" || batchItem.dispatchStatus !== "pending") {
continue
}
await ctx.scheduler.runAfter(0, internal.cloudflareDispatch.dispatchBatchItem, {
batchJobId: args.batchJobId,
itemIndex,
})
scheduledCount += 1
}
const nextStartIndex = endExclusive < batchJob.totalCount ? endExclusive : null
if (nextStartIndex !== null) {
await ctx.scheduler.runAfter(BATCH_DISPATCH_CHUNK_DELAY_MS, internal.batchGeneration.seedBatchDispatchChunk, {
batchJobId: args.batchJobId,
startIndex: nextStartIndex,
})
}
return { scheduledCount, nextStartIndex }
},
})
/**
* Internal query to fetch a batch item by parent/id coordinates.
*/
export const getBatchItemInternal = internalQuery({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
},
handler: async (ctx, args) => {
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
return items[0] ?? null
},
})
/**
* Mark a batch item as dispatched to the Cloudflare worker plane.
*/
export const markBatchItemDispatched = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
},
returns: v.object({
dispatched: v.boolean(),
dispatchAttempts: v.number(),
}),
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
if (!batchJob || (batchJob.status !== "pending" && batchJob.status !== "processing")) {
return { dispatched: false, dispatchAttempts: 0 }
}
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (!batchItem) {
return { dispatched: false, dispatchAttempts: 0 }
}
if (batchItem.status === "completed" || batchItem.status === "failed" || batchItem.status === "cancelled") {
return {
dispatched: false,
dispatchAttempts: batchItem.dispatchAttempts ?? 0,
}
}
if (batchItem.dispatchStatus === "dispatched" || batchItem.dispatchStatus === "processing") {
return {
dispatched: false,
dispatchAttempts: batchItem.dispatchAttempts ?? 0,
}
}
const nextAttempts = (batchItem.dispatchAttempts ?? 0) + 1
const now = Date.now()
await ctx.db.patch(batchItem._id, {
dispatchStatus: "dispatched",
dispatchAttempts: nextAttempts,
dispatchedAt: now,
lastDispatchError: undefined,
updatedAt: now,
})
await ctx.db.patch(args.batchJobId, {
status: batchJob.status === "pending" ? "processing" : batchJob.status,
currentIndex: Math.max(batchJob.currentIndex, args.itemIndex + 1),
inFlightCount: (batchJob.inFlightCount ?? 0) + 1,
updatedAt: now,
})
return {
dispatched: true,
dispatchAttempts: nextAttempts,
}
},
})
/**
* Record a failed dispatch attempt for a batch item and release the in-flight slot.
*/
export const recordBatchItemDispatchFailure = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
errorMessage: v.string(),
},
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (!batchItem) {
return
}
const now = Date.now()
await ctx.db.patch(batchItem._id, {
dispatchStatus: "pending",
lastDispatchError: args.errorMessage,
updatedAt: now,
})
if (batchJob) {
await ctx.db.patch(args.batchJobId, {
inFlightCount: Math.max(0, (batchJob.inFlightCount ?? 0) - 1),
updatedAt: now,
})
}
},
})
/**
* Record a terminal dispatch failure for a batch item when all retries
* have been exhausted. Unlike recordBatchItemDispatchFailure (which resets
* the item to "pending" for another attempt), this permanently marks the
* item as failed and settles the parent batch job counters.
*/
export const recordBatchItemDispatchTerminalFailure = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
errorMessage: v.string(),
},
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (!batchItem) {
return
}
// If the item is already in a terminal state, skip
if (batchItem.status === "completed" || batchItem.status === "failed" || batchItem.status === "cancelled") {
return
}
const now = Date.now()
await ctx.db.patch(batchItem._id, {
status: "failed",
dispatchStatus: "failed",
lastDispatchError: args.errorMessage,
errorMessage: `Dispatch failed after exhausting all retry attempts: ${args.errorMessage}`,
updatedAt: now,
})
if (batchJob) {
const nextCompletedCount = batchJob.completedCount
const nextFailedCount = batchJob.failedCount + 1
const nextInFlightCount = Math.max(0, (batchJob.inFlightCount ?? 0) - 1)
const totalProcessed = nextCompletedCount + nextFailedCount
const nextStatus = getBatchStatusAfterItemSettlement({
completedCount: nextCompletedCount,
failedCount: nextFailedCount,
totalCount: batchJob.totalCount,
status: batchJob.status,
})
await ctx.db.patch(args.batchJobId, {
status: nextStatus,
completedCount: nextCompletedCount,
failedCount: nextFailedCount,
inFlightCount: nextInFlightCount,
currentIndex: Math.max(batchJob.currentIndex, args.itemIndex + 1),
apiKey: totalProcessed >= batchJob.totalCount ? undefined : batchJob.apiKey,
updatedAt: now,
})
}
},
})
/**
* Claim a batch item for Cloudflare worker execution.
*/
export const claimBatchItemForWorker = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
claimToken: v.string(),
workerAttempt: v.number(),
providerRequestId: v.optional(v.string()),
},
returns: v.object({
claimed: v.boolean(),
}),
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
if (
!batchJob ||
(batchJob.status !== "pending" &&
batchJob.status !== "processing" &&
batchJob.status !== "paused")
) {
return { claimed: false }
}
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (!batchItem) {
return { claimed: false }
}
if (batchItem.status === "completed" || batchItem.status === "failed" || batchItem.status === "cancelled") {
return { claimed: false }
}
const currentAttempt = batchItem.workerAttempt ?? 0
const canClaimPending =
batchItem.status === "pending" &&
batchItem.dispatchStatus === "dispatched" &&
(batchJob.status === "pending" || batchJob.status === "processing")
const canReclaimProcessing =
batchItem.status === "processing" &&
args.workerAttempt > currentAttempt
if (!canClaimPending && !canReclaimProcessing) {
// When the job is paused and the item was pre-dispatched but not
// yet claimed, release it back to pending so it can be
// re-dispatched when the job resumes.
if (
batchJob.status === "paused" &&
batchItem.status === "pending" &&
batchItem.dispatchStatus === "dispatched"
) {
await ctx.db.patch(batchItem._id, {
dispatchStatus: "pending",
updatedAt: Date.now(),
})
}
return { claimed: false }
}
await ctx.db.patch(batchItem._id, {
status: "processing",
dispatchStatus: "processing",
claimToken: args.claimToken,
workerAttempt: args.workerAttempt,
providerRequestId: args.providerRequestId,
updatedAt: Date.now(),
})
return { claimed: true }
},
})
/**
* Return the continuation state for a claimed batch item.
*/
export const getBatchItemWorkerContinuationState = internalQuery({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
claimToken: v.string(),
},
returns: v.object({
canContinue: v.boolean(),
ownerId: v.optional(v.string()),
generationParams: v.optional(generationParamsValidator),
apiKey: v.optional(v.string()),
}),
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
if (
!batchJob ||
(batchJob.status !== "pending" &&
batchJob.status !== "processing" &&
batchJob.status !== "paused")
) {
return { canContinue: false }
}
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (
!batchItem ||
batchItem.claimToken !== args.claimToken ||
batchItem.status !== "processing" ||
batchItem.dispatchStatus !== "processing"
) {
return { canContinue: false }
}
return {
canContinue: true,
ownerId: batchJob.ownerId,
generationParams: batchJob.generationParams,
apiKey: batchJob.apiKey,
}
},
})
/**
* Finalize a worker-owned batch item exactly once and schedule the next item.
*/
export const completeBatchItemFromWorkerResult = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
claimToken: v.string(),
r2Key: v.string(),
url: v.string(),
width: v.number(),
height: v.number(),
seed: v.optional(v.number()),
contentType: v.string(),
sizeBytes: v.number(),
retryCount: v.optional(v.number()),
providerRequestId: v.optional(v.string()),
},
returns: v.object({
completed: v.boolean(),
duplicate: v.boolean(),
imageId: v.optional(v.id("generatedImages")),
}),
handler: async (
ctx,
args
): Promise<{ completed: boolean; duplicate: boolean; imageId?: Doc<"generatedImages">["_id"] }> => {
const batchJob = await ctx.db.get(args.batchJobId)
if (!batchJob || batchJob.status === "cancelled") {
return { completed: false, duplicate: false }
}
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (!batchItem) {
return { completed: false, duplicate: false }
}
if (batchItem.status === "completed") {
return {
completed: false,
duplicate: true,
imageId: batchItem.imageId,
}
}
if (batchItem.status === "failed" || batchItem.status === "cancelled") {
return { completed: false, duplicate: false }
}
if (batchItem.claimToken !== args.claimToken) {
return { completed: false, duplicate: false }
}
const imageId: Doc<"generatedImages">["_id"] = await ctx.runMutation(internal.batchGeneration.storeGeneratedImage, {
ownerId: batchJob.ownerId,
r2Key: args.r2Key,
url: args.url,
thumbnailR2Key: undefined,
thumbnailUrl: undefined,
previewR2Key: undefined,
previewUrl: undefined,
prompt: batchJob.generationParams.prompt,
width: args.width,
height: args.height,
model: batchJob.generationParams.model ?? "flux",
seed: args.seed,
contentType: args.contentType,
sizeBytes: args.sizeBytes,
generationParams: {
...batchJob.generationParams,
seed: args.seed ?? batchJob.generationParams.seed,
width: args.width,
height: args.height,
},
visibility: batchJob.generationParams.private ? "unlisted" : "public",
})
const now = Date.now()
await ctx.db.patch(batchItem._id, {
status: "completed",
dispatchStatus: "completed",
imageId,
retryCount: args.retryCount,
providerRequestId: args.providerRequestId ?? batchItem.providerRequestId,
errorMessage: undefined,
errorCode: undefined,
updatedAt: now,
})
const nextCompletedCount = batchJob.completedCount + 1
const nextFailedCount = batchJob.failedCount
const nextInFlightCount = Math.max(0, (batchJob.inFlightCount ?? 0) - 1)
const totalProcessed = nextCompletedCount + nextFailedCount
const nextStatus = getBatchStatusAfterItemSettlement({
completedCount: nextCompletedCount,
failedCount: nextFailedCount,
totalCount: batchJob.totalCount,
status: batchJob.status,
})
await ctx.db.patch(args.batchJobId, {
status: nextStatus,
completedCount: nextCompletedCount,
failedCount: nextFailedCount,
inFlightCount: nextInFlightCount,
currentIndex: Math.max(batchJob.currentIndex, args.itemIndex + 1),
apiKey: totalProcessed >= batchJob.totalCount ? undefined : batchJob.apiKey,
updatedAt: now,
})
if (args.contentType.startsWith("video/")) {
await ctx.scheduler.runAfter(0, internal.cloudflareDispatch.dispatchSecondaryAssets, {
imageId,
})
}
return { completed: true, duplicate: false, imageId }
},
})
/**
* Fail a worker-owned batch item exactly once and schedule the next item when appropriate.
*/
export const failBatchItemFromWorker = internalMutation({
args: {
batchJobId: v.id("batchJobs"),
itemIndex: v.number(),
claimToken: v.string(),
errorMessage: v.string(),
errorCode: v.optional(v.number()),
retryCount: v.optional(v.number()),
providerRequestId: v.optional(v.string()),
/** Skip claim token check — used by the queue error handler on final attempt */
skipClaimTokenCheck: v.optional(v.boolean()),
},
returns: v.object({
failed: v.boolean(),
duplicate: v.boolean(),
}),
handler: async (ctx, args) => {
const batchJob = await ctx.db.get(args.batchJobId)
if (!batchJob || batchJob.status === "cancelled") {
return { failed: false, duplicate: false }
}
const items = await ctx.db
.query("batchItems")
.withIndex("by_batch_item", (q) =>
q.eq("batchJobId", args.batchJobId).eq("itemIndex", args.itemIndex)
)
.take(1)
const batchItem = items[0]
if (!batchItem) {
return { failed: false, duplicate: false }
}
if (batchItem.status === "failed") {
return { failed: false, duplicate: true }
}
if (batchItem.status === "completed" || batchItem.status === "cancelled") {
return { failed: false, duplicate: false }
}
if (!args.skipClaimTokenCheck && batchItem.claimToken !== args.claimToken) {
return { failed: false, duplicate: false }
}
const now = Date.now()
await ctx.db.patch(batchItem._id, {
status: "failed",
dispatchStatus: "failed",
errorMessage: args.errorMessage,
errorCode: args.errorCode,
retryCount: args.retryCount,
providerRequestId: args.providerRequestId ?? batchItem.providerRequestId,
updatedAt: now,
})
const nextCompletedCount = batchJob.completedCount
const nextFailedCount = batchJob.failedCount + 1
const nextInFlightCount = Math.max(0, (batchJob.inFlightCount ?? 0) - 1)
const totalProcessed = nextCompletedCount + nextFailedCount
const nextStatus = getBatchStatusAfterItemSettlement({
completedCount: nextCompletedCount,
failedCount: nextFailedCount,
totalCount: batchJob.totalCount,
status: batchJob.status,
})
await ctx.db.patch(args.batchJobId, {
status: nextStatus,