-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathuseRealtime.ts
More file actions
1100 lines (953 loc) · 31.3 KB
/
useRealtime.ts
File metadata and controls
1100 lines (953 loc) · 31.3 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
"use client";
import {
AnyTask,
ApiClient,
InferRunTypes,
InferStreamType,
RealtimeDefinedStream,
RealtimeRun,
RealtimeRunSkipColumns,
} from "@trigger.dev/core/v3";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { KeyedMutator, useSWR } from "../utils/trigger-swr.js";
import { useApiClient, UseApiClientOptions } from "./useApiClient.js";
import { createThrottledQueue } from "../utils/throttle.js";
export type UseRealtimeRunOptions = UseApiClientOptions & {
id?: string;
enabled?: boolean;
/**
* The number of milliseconds to throttle the stream updates.
*
* @default 16
*/
throttleInMs?: number;
};
export type UseRealtimeSingleRunOptions<TTask extends AnyTask = AnyTask> = UseRealtimeRunOptions & {
/**
* Callback this is called when the run completes, an error occurs, or the subscription is stopped.
*
* @param {RealtimeRun<TTask>} run - The run object
* @param {Error} [err] - The error that occurred
*/
onComplete?: (run: RealtimeRun<TTask>, err?: Error) => void;
/**
* Whether to stop the subscription when the run completes
*
* @default true
*
* Set this to false if you are making updates to the run metadata after completion through child runs
*/
stopOnCompletion?: boolean;
/**
* Skip columns from the subscription.
*
* @default []
*/
skipColumns?: RealtimeRunSkipColumns;
};
export type UseRealtimeRunInstance<TTask extends AnyTask = AnyTask> = {
run: RealtimeRun<TTask> | undefined;
error: Error | undefined;
/**
* Abort the current request immediately.
*/
stop: () => void;
};
/**
* Hook to subscribe to realtime updates of a task run.
*
* @template TTask - The type of the task
* @param {string} [runId] - The unique identifier of the run to subscribe to
* @param {UseRealtimeSingleRunOptions} [options] - Configuration options for the subscription
* @returns {UseRealtimeRunInstance<TTask>} An object containing the current state of the run, error handling, and control methods
*
* @example
* ```ts
* import type { myTask } from './path/to/task';
* const { run, error } = useRealtimeRun<typeof myTask>('run-id-123');
* ```
*/
export function useRealtimeRun<TTask extends AnyTask>(
runId?: string,
options?: UseRealtimeSingleRunOptions<TTask>
): UseRealtimeRunInstance<TTask> {
const hookId = useId();
const idKey = options?.id ?? hookId;
// Store the streams state in SWR, using the idKey as the key to share states.
const { data: run, mutate: mutateRun } = useSWR<RealtimeRun<TTask>>([idKey, "run"], null);
const { data: error = undefined, mutate: setError } = useSWR<undefined | Error>(
[idKey, "error"],
null
);
// Add state to track when the subscription is complete
const { data: isComplete = false, mutate: setIsComplete } = useSWR<boolean>(
[idKey, "complete"],
null
);
// Abort controller to cancel the current API call.
const abortControllerRef = useRef<AbortController | null>(null);
const stop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
const apiClient = useApiClient(options);
const triggerRequest = useCallback(async () => {
try {
if (!runId || !apiClient) {
return;
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
await processRealtimeRun(
runId,
{ skipColumns: options?.skipColumns },
apiClient,
mutateRun,
setError,
abortControllerRef,
typeof options?.stopOnCompletion === "boolean" ? options.stopOnCompletion : true
);
} catch (err) {
// Ignore abort errors as they are expected.
if ((err as any).name === "AbortError") {
abortControllerRef.current = null;
return;
}
setError(err as Error);
} finally {
if (abortControllerRef.current) {
abortControllerRef.current = null;
}
// Mark the subscription as complete
setIsComplete(true);
}
}, [runId, mutateRun, abortControllerRef, apiClient, setError]);
const hasCalledOnCompleteRef = useRef(false);
// Effect to handle onComplete callback
// Only call onComplete when the run has actually finished (has finishedAt),
// not just when the subscription stream ends (which can happen due to network issues)
useEffect(() => {
if (isComplete && run?.finishedAt && options?.onComplete && !hasCalledOnCompleteRef.current) {
options.onComplete(run, error);
hasCalledOnCompleteRef.current = true;
}
}, [isComplete, run, error, options?.onComplete]);
useEffect(() => {
if (typeof options?.enabled === "boolean" && !options.enabled) {
return;
}
if (!runId) {
return;
}
triggerRequest().finally(() => {});
return () => {
stop();
};
}, [runId, stop, options?.enabled]);
useEffect(() => {
if (run?.finishedAt) {
setIsComplete(true);
}
}, [run]);
return { run, error, stop };
}
export type StreamResults<TStreams extends Record<string, any>> = {
[K in keyof TStreams]: Array<TStreams[K]>;
};
export type UseRealtimeRunWithStreamsInstance<
TTask extends AnyTask = AnyTask,
TStreams extends Record<string, any> = Record<string, any>,
> = {
run: RealtimeRun<TTask> | undefined;
streams: StreamResults<TStreams>;
error: Error | undefined;
/**
* Abort the current request immediately, keep the generated tokens if any.
*/
stop: () => void;
};
/**
* Hook to subscribe to realtime updates of a task run with associated data streams.
*
* @template TTask - The type of the task
* @template TStreams - The type of the streams data
* @param {string} [runId] - The unique identifier of the run to subscribe to
* @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
* @returns {UseRealtimeRunWithStreamsInstance<TTask, TStreams>} An object containing the current state of the run, streams data, and error handling
*
* @example
* ```ts
* import type { myTask } from './path/to/task';
* const { run, streams, error } = useRealtimeRunWithStreams<typeof myTask, {
* output: string;
* }>('run-id-123');
* ```
*/
export function useRealtimeRunWithStreams<
TTask extends AnyTask = AnyTask,
TStreams extends Record<string, any> = Record<string, any>,
>(
runId?: string,
options?: UseRealtimeSingleRunOptions<TTask>
): UseRealtimeRunWithStreamsInstance<TTask, TStreams> {
const hookId = useId();
const idKey = options?.id ?? hookId;
const [initialStreamsFallback] = useState({} as StreamResults<TStreams>);
// Store the streams state in SWR, using the idKey as the key to share states.
const { data: streams, mutate: mutateStreams } = useSWR<StreamResults<TStreams>>(
[idKey, "streams"],
null,
{
fallbackData: initialStreamsFallback,
}
);
// Keep the latest streams in a ref.
const streamsRef = useRef<StreamResults<TStreams>>(streams ?? ({} as StreamResults<TStreams>));
useEffect(() => {
streamsRef.current = streams || ({} as StreamResults<TStreams>);
}, [streams]);
// Store the streams state in SWR, using the idKey as the key to share states.
const { data: run, mutate: mutateRun } = useSWR<RealtimeRun<TTask>>([idKey, "run"], null);
// Add state to track when the subscription is complete
const { data: isComplete = false, mutate: setIsComplete } = useSWR<boolean>(
[idKey, "complete"],
null
);
const { data: error = undefined, mutate: setError } = useSWR<undefined | Error>(
[idKey, "error"],
null
);
// Abort controller to cancel the current API call.
const abortControllerRef = useRef<AbortController | null>(null);
const stop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
const apiClient = useApiClient(options);
const triggerRequest = useCallback(async () => {
try {
if (!runId || !apiClient) {
return;
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
await processRealtimeRunWithStreams(
runId,
{ skipColumns: options?.skipColumns },
apiClient,
mutateRun,
mutateStreams,
streamsRef,
setError,
abortControllerRef,
typeof options?.stopOnCompletion === "boolean" ? options.stopOnCompletion : true,
options?.throttleInMs ?? 16
);
} catch (err) {
// Ignore abort errors as they are expected.
if ((err as any).name === "AbortError") {
abortControllerRef.current = null;
return;
}
setError(err as Error);
} finally {
if (abortControllerRef.current) {
abortControllerRef.current = null;
}
// Mark the subscription as complete
setIsComplete(true);
}
}, [runId, mutateRun, mutateStreams, streamsRef, abortControllerRef, apiClient, setError]);
const hasCalledOnCompleteRef = useRef(false);
// Effect to handle onComplete callback
// Only call onComplete when the run has actually finished (has finishedAt),
// not just when the subscription stream ends (which can happen due to network issues)
useEffect(() => {
if (isComplete && run?.finishedAt && options?.onComplete && !hasCalledOnCompleteRef.current) {
options.onComplete(run, error);
hasCalledOnCompleteRef.current = true;
}
}, [isComplete, run, error, options?.onComplete]);
useEffect(() => {
if (typeof options?.enabled === "boolean" && !options.enabled) {
return;
}
if (!runId) {
return;
}
triggerRequest().finally(() => {});
return () => {
stop();
};
}, [runId, stop, options?.enabled]);
useEffect(() => {
if (run?.finishedAt) {
setIsComplete(true);
}
}, [run]);
return { run, streams: streams ?? initialStreamsFallback, error, stop };
}
export type UseRealtimeRunsInstance<TTask extends AnyTask = AnyTask> = {
runs: RealtimeRun<TTask>[];
error: Error | undefined;
/**
* Abort the current request immediately.
*/
stop: () => void;
};
export type UseRealtimeRunsWithTagOptions = UseRealtimeRunOptions & {
/**
* Filter runs by the time they were created. You must specify the duration string like "1h", "10s", "30m", etc.
*
* @example
* "1h" - 1 hour ago
* "10s" - 10 seconds ago
* "30m" - 30 minutes ago
* "1d" - 1 day ago
* "1w" - 1 week ago
*
* The maximum duration is 1 week
*
* @note The timestamp will be calculated on the server side when you first subscribe to the runs.
*
*/
createdAt?: string;
/**
* Skip columns from the subscription.
*
* @default []
*/
skipColumns?: RealtimeRunSkipColumns;
};
/**
* Hook to subscribe to realtime updates of task runs filtered by tag(s).
*
* @template TTask - The type of the task
* @param {string | string[]} tag - The tag or array of tags to filter runs by
* @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
* @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs and any error encountered
*
* @example
* ```ts
* import type { myTask } from './path/to/task';
* const { runs, error } = useRealtimeRunsWithTag<typeof myTask>('my-tag');
* // Or with multiple tags
* const { runs, error } = useRealtimeRunsWithTag<typeof myTask>(['tag1', 'tag2']);
* // Or with a createdAt filter
* const { runs, error } = useRealtimeRunsWithTag<typeof myTask>('my-tag', { createdAt: '1h' });
* ```
*/
export function useRealtimeRunsWithTag<TTask extends AnyTask>(
tag: string | string[],
options?: UseRealtimeRunsWithTagOptions
): UseRealtimeRunsInstance<TTask> {
const normalizedTag = (Array.isArray(tag) ? tag : [tag]).join("-");
const hookId = useId();
const idKey = options?.id ?? hookId;
// Store the streams state in SWR, using the idKey as the key to share states.
const { data: runs, mutate: mutateRuns } = useSWR<RealtimeRun<TTask>[]>([idKey, "run"], null, {
fallbackData: [],
});
// Keep the latest streams in a ref.
const runsRef = useRef<RealtimeRun<TTask>[]>([]);
useEffect(() => {
runsRef.current = runs ?? [];
}, [runs]);
const { data: error = undefined, mutate: setError } = useSWR<undefined | Error>(
[idKey, "error"],
null
);
// Abort controller to cancel the current API call.
const abortControllerRef = useRef<AbortController | null>(null);
const stop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
const apiClient = useApiClient(options);
const triggerRequest = useCallback(async () => {
try {
if (!apiClient) {
return;
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
await processRealtimeRunsWithTag(
tag,
{ createdAt: options?.createdAt, skipColumns: options?.skipColumns },
apiClient,
mutateRuns,
runsRef,
setError,
abortControllerRef
);
} catch (err) {
// Ignore abort errors as they are expected.
if ((err as any).name === "AbortError") {
abortControllerRef.current = null;
return;
}
setError(err as Error);
} finally {
if (abortControllerRef.current) {
abortControllerRef.current = null;
}
}
}, [normalizedTag, mutateRuns, runsRef, abortControllerRef, apiClient, setError]);
useEffect(() => {
if (typeof options?.enabled === "boolean" && !options.enabled) {
return;
}
triggerRequest().finally(() => {});
return () => {
stop();
};
}, [normalizedTag, stop, options?.enabled]);
return { runs: runs ?? [], error, stop };
}
/**
* Hook to subscribe to realtime updates of a batch of task runs.
*
* @template TTask - The type of the task
* @param {string} batchId - The unique identifier of the batch to subscribe to
* @param {UseRealtimeRunOptions} [options] - Configuration options for the subscription
* @returns {UseRealtimeRunsInstance<TTask>} An object containing the current state of the runs, error handling, and control methods
*
* @example
* ```ts
* import type { myTask } from './path/to/task';
* const { runs, error } = useRealtimeBatch<typeof myTask>('batch-id-123');
* ```
*/
export function useRealtimeBatch<TTask extends AnyTask>(
batchId: string,
options?: UseRealtimeRunOptions
): UseRealtimeRunsInstance<TTask> {
const hookId = useId();
const idKey = options?.id ?? hookId;
// Store the streams state in SWR, using the idKey as the key to share states.
const { data: runs, mutate: mutateRuns } = useSWR<RealtimeRun<TTask>[]>([idKey, "run"], null, {
fallbackData: [],
});
// Keep the latest streams in a ref.
const runsRef = useRef<RealtimeRun<TTask>[]>([]);
useEffect(() => {
runsRef.current = runs ?? [];
}, [runs]);
const { data: error = undefined, mutate: setError } = useSWR<undefined | Error>(
[idKey, "error"],
null
);
// Abort controller to cancel the current API call.
const abortControllerRef = useRef<AbortController | null>(null);
const stop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
const apiClient = useApiClient(options);
const triggerRequest = useCallback(async () => {
try {
if (!apiClient) {
return;
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
await processRealtimeBatch(
batchId,
apiClient,
mutateRuns,
runsRef,
setError,
abortControllerRef
);
} catch (err) {
// Ignore abort errors as they are expected.
if ((err as any).name === "AbortError") {
abortControllerRef.current = null;
return;
}
setError(err as Error);
} finally {
if (abortControllerRef.current) {
abortControllerRef.current = null;
}
}
}, [batchId, mutateRuns, runsRef, abortControllerRef, apiClient, setError]);
useEffect(() => {
if (typeof options?.enabled === "boolean" && !options.enabled) {
return;
}
triggerRequest().finally(() => {});
return () => {
stop();
};
}, [batchId, stop, options?.enabled]);
return { runs: runs ?? [], error, stop };
}
export type UseRealtimeStreamInstance<TPart> = {
parts: Array<TPart>;
error: Error | undefined;
/**
* Abort the current request immediately, keep the generated tokens if any.
*/
stop: () => void;
};
export type UseRealtimeStreamOptions<TPart> = UseApiClientOptions & {
id?: string;
enabled?: boolean;
/**
* The number of milliseconds to throttle the stream updates.
*
* @default 16
*/
throttleInMs?: number;
/**
* The number of seconds to wait for new data to be available,
* If no data arrives within the timeout, the stream will be closed.
*
* @default 60 seconds
*/
timeoutInSeconds?: number;
/**
* The index to start reading from.
* If not provided, the stream will start from the beginning.
* @default 0
*/
startIndex?: number;
/**
* Callback this is called when new data is received.
*/
onData?: (data: TPart) => void;
};
export function useRealtimeStream<TDefinedStream extends RealtimeDefinedStream<any>>(
stream: TDefinedStream,
runId: string,
options?: UseRealtimeStreamOptions<InferStreamType<TDefinedStream>>
): UseRealtimeStreamInstance<InferStreamType<TDefinedStream>>;
/**
* Hook to subscribe to realtime updates of a stream with a specific stream key.
*
* This hook automatically subscribes to a stream and updates the `parts` array as new data arrives.
* The stream subscription is automatically managed: it starts when the component mounts (or when
* `enabled` becomes `true`) and stops when the component unmounts or when `stop()` is called.
*
* @template TPart - The type of each chunk/part in the stream
* @param runId - The unique identifier of the run to subscribe to
* @param streamKey - The unique identifier of the stream to subscribe to. Use this overload
* when you want to read from a specific stream key.
* @param options - Optional configuration for the stream subscription
* @returns An object containing:
* - `parts`: An array of all stream chunks received so far (accumulates over time)
* - `error`: Any error that occurred during subscription
* - `stop`: A function to manually stop the subscription
*
* @example
* ```tsx
* "use client";
* import { useRealtimeStream } from "@trigger.dev/react-hooks";
*
* function StreamViewer({ runId }: { runId: string }) {
* const { parts, error } = useRealtimeStream<string>(
* runId,
* "my-stream",
* {
* accessToken: process.env.NEXT_PUBLIC_TRIGGER_PUBLIC_KEY,
* }
* );
*
* if (error) return <div>Error: {error.message}</div>;
*
* // Parts array accumulates all chunks
* const fullText = parts.join("");
*
* return <div>{fullText}</div>;
* }
* ```
*
* @example
* ```tsx
* // With custom options
* const { parts, error, stop } = useRealtimeStream<ChatChunk>(
* runId,
* "chat-stream",
* {
* accessToken: publicKey,
* timeoutInSeconds: 120,
* startIndex: 10, // Start from the 10th chunk
* throttleInMs: 50, // Throttle updates to every 50ms
* onData: (chunk) => {
* console.log("New chunk received:", chunk);
* },
* }
* );
*
* // Manually stop the subscription
* <button onClick={stop}>Stop Stream</button>
* ```
*/
export function useRealtimeStream<TPart>(
runId: string,
streamKey: string,
options?: UseRealtimeStreamOptions<TPart>
): UseRealtimeStreamInstance<TPart>;
/**
* Hook to subscribe to realtime updates of a stream using the default stream key (`"default"`).
*
* This is a convenience overload that allows you to subscribe to the default stream without
* specifying a stream key. The stream will be accessed with the key `"default"`.
*
* @template TPart - The type of each chunk/part in the stream
* @param runId - The unique identifier of the run to subscribe to
* @param options - Optional configuration for the stream subscription
* @returns An object containing:
* - `parts`: An array of all stream chunks received so far (accumulates over time)
* - `error`: Any error that occurred during subscription
* - `stop`: A function to manually stop the subscription
*
* @example
* ```tsx
* "use client";
* import { useRealtimeStream } from "@trigger.dev/react-hooks";
*
* function DefaultStreamViewer({ runId }: { runId: string }) {
* // Subscribe to the default stream
* const { parts, error } = useRealtimeStream<string>(runId, {
* accessToken: process.env.NEXT_PUBLIC_TRIGGER_PUBLIC_KEY,
* });
*
* if (error) return <div>Error: {error.message}</div>;
*
* const fullText = parts.join("");
* return <div>{fullText}</div>;
* }
* ```
*
* @example
* ```tsx
* // Conditionally enable the stream
* const { parts } = useRealtimeStream<string>(runId, {
* accessToken: publicKey,
* enabled: !!runId && isStreaming, // Only subscribe when runId exists and isStreaming is true
* });
* ```
*/
export function useRealtimeStream<TPart>(
runId: string,
options?: UseRealtimeStreamOptions<TPart>
): UseRealtimeStreamInstance<TPart>;
export function useRealtimeStream<TPart>(
runIdOrDefinedStream: string | RealtimeDefinedStream<TPart>,
streamKeyOrOptionsOrRunId?: string | UseRealtimeStreamOptions<TPart>,
options?: UseRealtimeStreamOptions<TPart>
): UseRealtimeStreamInstance<TPart> {
if (typeof runIdOrDefinedStream === "string") {
if (typeof streamKeyOrOptionsOrRunId === "string") {
return useRealtimeStreamImplementation(
runIdOrDefinedStream,
streamKeyOrOptionsOrRunId,
options
);
} else {
return useRealtimeStreamImplementation(
runIdOrDefinedStream,
"default",
streamKeyOrOptionsOrRunId
);
}
} else {
if (typeof streamKeyOrOptionsOrRunId === "string") {
return useRealtimeStreamImplementation(
streamKeyOrOptionsOrRunId,
runIdOrDefinedStream.id,
options
);
} else {
throw new Error(
"Invalid second argument to useRealtimeStream. When using a defined stream instance, the second argument to useRealtimeStream must be a run ID."
);
}
}
}
function useRealtimeStreamImplementation<TPart>(
runId: string,
streamKey: string,
options?: UseRealtimeStreamOptions<TPart>
): UseRealtimeStreamInstance<TPart> {
const hookId = useId();
const idKey = options?.id ?? hookId;
const [initialPartsFallback] = useState([] as Array<TPart>);
// Store the streams state in SWR, using the idKey as the key to share states.
const { data: parts, mutate: mutateParts } = useSWR<Array<TPart>>(
[idKey, runId, streamKey, "parts"],
null,
{
fallbackData: initialPartsFallback,
}
);
// Keep the latest streams in a ref.
const partsRef = useRef<Array<TPart>>(parts ?? ([] as Array<TPart>));
useEffect(() => {
partsRef.current = parts || ([] as Array<TPart>);
}, [parts]);
// Add state to track when the subscription is complete
const { data: isComplete = false, mutate: setIsComplete } = useSWR<boolean>(
[idKey, runId, streamKey, "complete"],
null
);
const { data: error = undefined, mutate: setError } = useSWR<undefined | Error>(
[idKey, runId, streamKey, "error"],
null
);
// Abort controller to cancel the current API call.
const abortControllerRef = useRef<AbortController | null>(null);
const stop = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
}, []);
const onData = useCallback(
(data: TPart) => {
if (options?.onData) {
options.onData(data);
}
},
[options?.onData]
);
const apiClient = useApiClient(options);
const triggerRequest = useCallback(async () => {
try {
if (!runId || !apiClient) {
return;
}
const abortController = new AbortController();
abortControllerRef.current = abortController;
await processRealtimeStream<TPart>(
runId,
streamKey,
apiClient,
mutateParts,
partsRef,
setError,
onData,
abortControllerRef,
options?.timeoutInSeconds,
options?.startIndex,
options?.throttleInMs ?? 16
);
} catch (err) {
// Ignore abort errors as they are expected.
if ((err as any).name === "AbortError") {
abortControllerRef.current = null;
return;
}
setError(err as Error);
} finally {
if (abortControllerRef.current) {
abortControllerRef.current = null;
}
// Mark the subscription as complete
setIsComplete(true);
}
}, [runId, streamKey, mutateParts, partsRef, abortControllerRef, apiClient, setError]);
useEffect(() => {
if (typeof options?.enabled === "boolean" && !options.enabled) {
return;
}
if (!runId) {
return;
}
triggerRequest().finally(() => {});
return () => {
stop();
};
}, [runId, stop, options?.enabled]);
return { parts: parts ?? initialPartsFallback, error, stop };
}
async function processRealtimeBatch<TTask extends AnyTask = AnyTask>(
batchId: string,
apiClient: ApiClient,
mutateRunsData: KeyedMutator<RealtimeRun<TTask>[]>,
existingRunsRef: React.MutableRefObject<RealtimeRun<TTask>[]>,
onError: (e: Error) => void,
abortControllerRef: React.MutableRefObject<AbortController | null>
) {
const subscription = apiClient.subscribeToBatch<InferRunTypes<TTask>>(batchId, {
signal: abortControllerRef.current?.signal,
onFetchError: onError,
});
for await (const part of subscription) {
mutateRunsData(insertRunShapeInOrder(existingRunsRef.current, part));
}
}
// Inserts and then orders by the run createdAt timestamp, and ensures that the run is not duplicated
function insertRunShapeInOrder<TTask extends AnyTask>(
previousRuns: RealtimeRun<TTask>[],
run: RealtimeRun<TTask>
) {
const existingRun = previousRuns.find((r) => r.id === run.id);
if (existingRun) {
return previousRuns.map((r) => (r.id === run.id ? run : r));
}
const runCreatedAt = run.createdAt;
const index = previousRuns.findIndex((r) => r.createdAt > runCreatedAt);
if (index === -1) {
return [...previousRuns, run];
}
return [...previousRuns.slice(0, index), run, ...previousRuns.slice(index)];
}
async function processRealtimeRunsWithTag<TTask extends AnyTask = AnyTask>(
tag: string | string[],
filters: { createdAt?: string; skipColumns?: RealtimeRunSkipColumns },
apiClient: ApiClient,
mutateRunsData: KeyedMutator<RealtimeRun<TTask>[]>,
existingRunsRef: React.MutableRefObject<RealtimeRun<TTask>[]>,
onError: (e: Error) => void,
abortControllerRef: React.MutableRefObject<AbortController | null>
) {
const subscription = apiClient.subscribeToRunsWithTag<InferRunTypes<TTask>>(tag, filters, {
signal: abortControllerRef.current?.signal,
onFetchError: onError,
});
for await (const part of subscription) {
mutateRunsData(insertRunShape(existingRunsRef.current, part));
}
}
// Replaces or inserts a run shape, ordered by the createdAt timestamp
function insertRunShape<TTask extends AnyTask>(
previousRuns: RealtimeRun<TTask>[],
run: RealtimeRun<TTask>
) {
const existingRun = previousRuns.find((r) => r.id === run.id);
if (existingRun) {
return previousRuns.map((r) => (r.id === run.id ? run : r));
}
const createdAt = run.createdAt;
const index = previousRuns.findIndex((r) => r.createdAt > createdAt);
if (index === -1) {
return [...previousRuns, run];
}
return [...previousRuns.slice(0, index), run, ...previousRuns.slice(index)];
}
async function processRealtimeRunWithStreams<
TTask extends AnyTask = AnyTask,
TStreams extends Record<string, any> = Record<string, any>,
>(
runId: string,
filters: { skipColumns?: RealtimeRunSkipColumns },
apiClient: ApiClient,
mutateRunData: KeyedMutator<RealtimeRun<TTask>>,
mutateStreamData: KeyedMutator<StreamResults<TStreams>>,
existingDataRef: React.MutableRefObject<StreamResults<TStreams>>,
onError: (e: Error) => void,
abortControllerRef: React.MutableRefObject<AbortController | null>,
stopOnCompletion: boolean = true,
throttleInMs?: number
) {
const subscription = apiClient.subscribeToRun<InferRunTypes<TTask>>(runId, {
signal: abortControllerRef.current?.signal,
closeOnComplete: stopOnCompletion,
onFetchError: onError,
skipColumns: filters.skipColumns,
});
type StreamUpdate = {
type: keyof TStreams;
chunk: any;
};
const streamQueue = createThrottledQueue<StreamUpdate>(async (updates) => {