@convex-dev/persistent-text-streaming 0.0.1

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.
Files changed (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/dist/commonjs/client/index.d.ts +89 -0
  4. package/dist/commonjs/client/index.d.ts.map +1 -0
  5. package/dist/commonjs/client/index.js +133 -0
  6. package/dist/commonjs/client/index.js.map +1 -0
  7. package/dist/commonjs/component/_generated/api.d.ts +14 -0
  8. package/dist/commonjs/component/_generated/api.d.ts.map +1 -0
  9. package/dist/commonjs/component/_generated/api.js +22 -0
  10. package/dist/commonjs/component/_generated/api.js.map +1 -0
  11. package/dist/commonjs/component/_generated/server.d.ts +64 -0
  12. package/dist/commonjs/component/_generated/server.d.ts.map +1 -0
  13. package/dist/commonjs/component/_generated/server.js +74 -0
  14. package/dist/commonjs/component/_generated/server.js.map +1 -0
  15. package/dist/commonjs/component/convex.config.d.ts +3 -0
  16. package/dist/commonjs/component/convex.config.d.ts.map +1 -0
  17. package/dist/commonjs/component/convex.config.js +3 -0
  18. package/dist/commonjs/component/convex.config.js.map +1 -0
  19. package/dist/commonjs/component/crons.d.ts +3 -0
  20. package/dist/commonjs/component/crons.d.ts.map +1 -0
  21. package/dist/commonjs/component/crons.js +7 -0
  22. package/dist/commonjs/component/crons.js.map +1 -0
  23. package/dist/commonjs/component/lib.d.ts +21 -0
  24. package/dist/commonjs/component/lib.d.ts.map +1 -0
  25. package/dist/commonjs/component/lib.js +134 -0
  26. package/dist/commonjs/component/lib.js.map +1 -0
  27. package/dist/commonjs/component/schema.d.ts +23 -0
  28. package/dist/commonjs/component/schema.d.ts.map +1 -0
  29. package/dist/commonjs/component/schema.js +13 -0
  30. package/dist/commonjs/component/schema.js.map +1 -0
  31. package/dist/commonjs/package.json +3 -0
  32. package/dist/commonjs/react/index.d.ts +23 -0
  33. package/dist/commonjs/react/index.d.ts.map +1 -0
  34. package/dist/commonjs/react/index.js +131 -0
  35. package/dist/commonjs/react/index.js.map +1 -0
  36. package/dist/esm/client/index.d.ts +89 -0
  37. package/dist/esm/client/index.d.ts.map +1 -0
  38. package/dist/esm/client/index.js +133 -0
  39. package/dist/esm/client/index.js.map +1 -0
  40. package/dist/esm/component/_generated/api.d.ts +14 -0
  41. package/dist/esm/component/_generated/api.d.ts.map +1 -0
  42. package/dist/esm/component/_generated/api.js +22 -0
  43. package/dist/esm/component/_generated/api.js.map +1 -0
  44. package/dist/esm/component/_generated/server.d.ts +64 -0
  45. package/dist/esm/component/_generated/server.d.ts.map +1 -0
  46. package/dist/esm/component/_generated/server.js +74 -0
  47. package/dist/esm/component/_generated/server.js.map +1 -0
  48. package/dist/esm/component/convex.config.d.ts +3 -0
  49. package/dist/esm/component/convex.config.d.ts.map +1 -0
  50. package/dist/esm/component/convex.config.js +3 -0
  51. package/dist/esm/component/convex.config.js.map +1 -0
  52. package/dist/esm/component/crons.d.ts +3 -0
  53. package/dist/esm/component/crons.d.ts.map +1 -0
  54. package/dist/esm/component/crons.js +7 -0
  55. package/dist/esm/component/crons.js.map +1 -0
  56. package/dist/esm/component/lib.d.ts +21 -0
  57. package/dist/esm/component/lib.d.ts.map +1 -0
  58. package/dist/esm/component/lib.js +134 -0
  59. package/dist/esm/component/lib.js.map +1 -0
  60. package/dist/esm/component/schema.d.ts +23 -0
  61. package/dist/esm/component/schema.d.ts.map +1 -0
  62. package/dist/esm/component/schema.js +13 -0
  63. package/dist/esm/component/schema.js.map +1 -0
  64. package/dist/esm/package.json +3 -0
  65. package/dist/esm/react/index.d.ts +23 -0
  66. package/dist/esm/react/index.d.ts.map +1 -0
  67. package/dist/esm/react/index.js +131 -0
  68. package/dist/esm/react/index.js.map +1 -0
  69. package/package.json +89 -0
  70. package/react/package.json +5 -0
  71. package/src/client/index.ts +223 -0
  72. package/src/component/_generated/api.d.ts +80 -0
  73. package/src/component/_generated/api.js +23 -0
  74. package/src/component/_generated/dataModel.d.ts +60 -0
  75. package/src/component/_generated/server.d.ts +149 -0
  76. package/src/component/_generated/server.js +90 -0
  77. package/src/component/convex.config.ts +3 -0
  78. package/src/component/crons.ts +13 -0
  79. package/src/component/lib.test.ts +9 -0
  80. package/src/component/lib.ts +149 -0
  81. package/src/component/schema.ts +21 -0
  82. package/src/react/index.ts +158 -0
@@ -0,0 +1,60 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ DataModelFromSchemaDefinition,
13
+ DocumentByName,
14
+ TableNamesInDataModel,
15
+ SystemTableNames,
16
+ } from "convex/server";
17
+ import type { GenericId } from "convex/values";
18
+ import schema from "../schema.js";
19
+
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
23
+ export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
30
+ export type Doc<TableName extends TableNames> = DocumentByName<
31
+ DataModel,
32
+ TableName
33
+ >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
48
+ export type Id<TableName extends TableNames | SystemTableNames> =
49
+ GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
60
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,149 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import {
12
+ ActionBuilder,
13
+ AnyComponents,
14
+ HttpActionBuilder,
15
+ MutationBuilder,
16
+ QueryBuilder,
17
+ GenericActionCtx,
18
+ GenericMutationCtx,
19
+ GenericQueryCtx,
20
+ GenericDatabaseReader,
21
+ GenericDatabaseWriter,
22
+ FunctionReference,
23
+ } from "convex/server";
24
+ import type { DataModel } from "./dataModel.js";
25
+
26
+ type GenericCtx =
27
+ | GenericActionCtx<DataModel>
28
+ | GenericMutationCtx<DataModel>
29
+ | GenericQueryCtx<DataModel>;
30
+
31
+ /**
32
+ * Define a query in this Convex app's public API.
33
+ *
34
+ * This function will be allowed to read your Convex database and will be accessible from the client.
35
+ *
36
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
37
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
38
+ */
39
+ export declare const query: QueryBuilder<DataModel, "public">;
40
+
41
+ /**
42
+ * Define a query that is only accessible from other Convex functions (but not from the client).
43
+ *
44
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
45
+ *
46
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
47
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
48
+ */
49
+ export declare const internalQuery: QueryBuilder<DataModel, "internal">;
50
+
51
+ /**
52
+ * Define a mutation in this Convex app's public API.
53
+ *
54
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
55
+ *
56
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
57
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
58
+ */
59
+ export declare const mutation: MutationBuilder<DataModel, "public">;
60
+
61
+ /**
62
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
63
+ *
64
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
65
+ *
66
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
67
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
68
+ */
69
+ export declare const internalMutation: MutationBuilder<DataModel, "internal">;
70
+
71
+ /**
72
+ * Define an action in this Convex app's public API.
73
+ *
74
+ * An action is a function which can execute any JavaScript code, including non-deterministic
75
+ * code and code with side-effects, like calling third-party services.
76
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
77
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
78
+ *
79
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
80
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
81
+ */
82
+ export declare const action: ActionBuilder<DataModel, "public">;
83
+
84
+ /**
85
+ * Define an action that is only accessible from other Convex functions (but not from the client).
86
+ *
87
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
88
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
89
+ */
90
+ export declare const internalAction: ActionBuilder<DataModel, "internal">;
91
+
92
+ /**
93
+ * Define an HTTP action.
94
+ *
95
+ * This function will be used to respond to HTTP requests received by a Convex
96
+ * deployment if the requests matches the path and method where this action
97
+ * is routed. Be sure to route your action in `convex/http.js`.
98
+ *
99
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
100
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
101
+ */
102
+ export declare const httpAction: HttpActionBuilder;
103
+
104
+ /**
105
+ * A set of services for use within Convex query functions.
106
+ *
107
+ * The query context is passed as the first argument to any Convex query
108
+ * function run on the server.
109
+ *
110
+ * This differs from the {@link MutationCtx} because all of the services are
111
+ * read-only.
112
+ */
113
+ export type QueryCtx = GenericQueryCtx<DataModel>;
114
+
115
+ /**
116
+ * A set of services for use within Convex mutation functions.
117
+ *
118
+ * The mutation context is passed as the first argument to any Convex mutation
119
+ * function run on the server.
120
+ */
121
+ export type MutationCtx = GenericMutationCtx<DataModel>;
122
+
123
+ /**
124
+ * A set of services for use within Convex action functions.
125
+ *
126
+ * The action context is passed as the first argument to any Convex action
127
+ * function run on the server.
128
+ */
129
+ export type ActionCtx = GenericActionCtx<DataModel>;
130
+
131
+ /**
132
+ * An interface to read from the database within Convex query functions.
133
+ *
134
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
135
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
136
+ * building a query.
137
+ */
138
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
139
+
140
+ /**
141
+ * An interface to read from and write to the database within Convex mutation
142
+ * functions.
143
+ *
144
+ * Convex guarantees that all writes within a single mutation are
145
+ * executed atomically, so you never have to worry about partial writes leaving
146
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
147
+ * for the guarantees Convex provides your functions.
148
+ */
149
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,90 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import {
12
+ actionGeneric,
13
+ httpActionGeneric,
14
+ queryGeneric,
15
+ mutationGeneric,
16
+ internalActionGeneric,
17
+ internalMutationGeneric,
18
+ internalQueryGeneric,
19
+ componentsGeneric,
20
+ } from "convex/server";
21
+
22
+ /**
23
+ * Define a query in this Convex app's public API.
24
+ *
25
+ * This function will be allowed to read your Convex database and will be accessible from the client.
26
+ *
27
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
28
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
29
+ */
30
+ export const query = queryGeneric;
31
+
32
+ /**
33
+ * Define a query that is only accessible from other Convex functions (but not from the client).
34
+ *
35
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
36
+ *
37
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
38
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
39
+ */
40
+ export const internalQuery = internalQueryGeneric;
41
+
42
+ /**
43
+ * Define a mutation in this Convex app's public API.
44
+ *
45
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
46
+ *
47
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
48
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
49
+ */
50
+ export const mutation = mutationGeneric;
51
+
52
+ /**
53
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
54
+ *
55
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
56
+ *
57
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
58
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
59
+ */
60
+ export const internalMutation = internalMutationGeneric;
61
+
62
+ /**
63
+ * Define an action in this Convex app's public API.
64
+ *
65
+ * An action is a function which can execute any JavaScript code, including non-deterministic
66
+ * code and code with side-effects, like calling third-party services.
67
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
68
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
69
+ *
70
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
71
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
72
+ */
73
+ export const action = actionGeneric;
74
+
75
+ /**
76
+ * Define an action that is only accessible from other Convex functions (but not from the client).
77
+ *
78
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
79
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
80
+ */
81
+ export const internalAction = internalActionGeneric;
82
+
83
+ /**
84
+ * Define a Convex HTTP action.
85
+ *
86
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
87
+ * as its second.
88
+ * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
89
+ */
90
+ export const httpAction = httpActionGeneric;
@@ -0,0 +1,3 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ export default defineComponent("persistentTextStreaming");
@@ -0,0 +1,13 @@
1
+ import { cronJobs } from "convex/server";
2
+ import { internal } from "./_generated/api";
3
+
4
+ const crons = cronJobs();
5
+
6
+ // Run every minute
7
+ crons.interval(
8
+ "cleanup expired streams",
9
+ { minutes: 1 },
10
+ internal.lib.cleanupExpiredStreams
11
+ );
12
+
13
+ export default crons;
@@ -0,0 +1,9 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ import { describe, it } from "vitest";
4
+
5
+ describe("persistent-text-streaming", () => {
6
+ it("should be implemented", () => {
7
+ // TODO: Add tests for persistent text streaming functionality
8
+ });
9
+ });
@@ -0,0 +1,149 @@
1
+ import { v } from "convex/values";
2
+ import { internalMutation, mutation, query } from "./_generated/server";
3
+ import { streamStatusValidator } from "./schema";
4
+
5
+ // Create a new stream with zero chunks.
6
+ export const createStream = mutation({
7
+ args: {},
8
+ handler: async (ctx) => {
9
+ const streamId = await ctx.db.insert("streams", {
10
+ status: "pending",
11
+ });
12
+ return streamId;
13
+ },
14
+ });
15
+
16
+ // Add a chunk to a stream.
17
+ // If final is true, set the stream to done.
18
+ // Can only be done on streams which are pending or streaming.
19
+ export const addChunk = mutation({
20
+ args: {
21
+ streamId: v.id("streams"),
22
+ text: v.string(),
23
+ final: v.boolean(),
24
+ },
25
+ handler: async (ctx, args) => {
26
+ const stream = await ctx.db.get(args.streamId);
27
+ if (!stream) {
28
+ throw new Error("Stream not found");
29
+ }
30
+ if (stream.status === "pending") {
31
+ await ctx.db.patch(args.streamId, {
32
+ status: "streaming",
33
+ });
34
+ } else if (stream.status !== "streaming") {
35
+ throw new Error("Stream is not streaming; did it timeout?");
36
+ }
37
+ await ctx.db.insert("chunks", {
38
+ streamId: args.streamId,
39
+ text: args.text,
40
+ });
41
+ if (args.final) {
42
+ await ctx.db.patch(args.streamId, {
43
+ status: "done",
44
+ });
45
+ }
46
+ },
47
+ });
48
+
49
+ // Set the status of a stream.
50
+ // Can only be done on streams which are pending or streaming.
51
+ export const setStreamStatus = mutation({
52
+ args: {
53
+ streamId: v.id("streams"),
54
+ status: v.union(
55
+ v.literal("pending"),
56
+ v.literal("streaming"),
57
+ v.literal("done"),
58
+ v.literal("error"),
59
+ v.literal("timeout")
60
+ ),
61
+ },
62
+ handler: async (ctx, args) => {
63
+ const stream = await ctx.db.get(args.streamId);
64
+ if (!stream) {
65
+ throw new Error("Stream not found");
66
+ }
67
+ if (stream.status !== "pending" && stream.status !== "streaming") {
68
+ console.log(
69
+ "Stream is already finalized; ignoring status change",
70
+ stream
71
+ );
72
+ return;
73
+ }
74
+ await ctx.db.patch(args.streamId, {
75
+ status: args.status,
76
+ });
77
+ },
78
+ });
79
+
80
+ // Get the status of a stream.
81
+ export const getStreamStatus = query({
82
+ args: {
83
+ streamId: v.id("streams"),
84
+ },
85
+ returns: streamStatusValidator,
86
+ handler: async (ctx, args) => {
87
+ const stream = await ctx.db.get(args.streamId);
88
+ return stream?.status ?? "error";
89
+ },
90
+ });
91
+
92
+ // Get the full text of a stream.
93
+ // Involves concatenating all the chunks.
94
+ export const getStreamText = query({
95
+ args: {
96
+ streamId: v.id("streams"),
97
+ },
98
+ returns: v.object({
99
+ text: v.string(),
100
+ status: streamStatusValidator,
101
+ }),
102
+ handler: async (ctx, args) => {
103
+ const stream = await ctx.db.get(args.streamId);
104
+ if (!stream) {
105
+ throw new Error("Stream not found");
106
+ }
107
+ let text = "";
108
+ if (stream.status !== "pending") {
109
+ const chunks = await ctx.db
110
+ .query("chunks")
111
+ .withIndex("byStream", (q) => q.eq("streamId", args.streamId))
112
+ .collect();
113
+ text = chunks.map((chunk) => chunk.text).join("");
114
+ }
115
+ return {
116
+ text,
117
+ status: stream.status,
118
+ };
119
+ },
120
+ });
121
+
122
+ const EXPIRATION_TIME = 20 * 60 * 1000; // 20 minutes in milliseconds
123
+ const BATCH_SIZE = 100;
124
+
125
+ // If the last chunk of a stream was added more than 20 minutes ago,
126
+ // set the stream to timeout. The action feeding it has to be dead.
127
+ export const cleanupExpiredStreams = internalMutation({
128
+ args: {},
129
+ handler: async (ctx) => {
130
+ const now = Date.now();
131
+ const pendingStreams = await ctx.db
132
+ .query("streams")
133
+ .withIndex("byStatus", (q) => q.eq("status", "pending"))
134
+ .take(BATCH_SIZE);
135
+ const streamingStreams = await ctx.db
136
+ .query("streams")
137
+ .withIndex("byStatus", (q) => q.eq("status", "streaming"))
138
+ .take(BATCH_SIZE);
139
+
140
+ for (const stream of [...pendingStreams, ...streamingStreams]) {
141
+ if (now - stream._creationTime > EXPIRATION_TIME) {
142
+ console.log("Cleaning up expired stream", stream._id);
143
+ await ctx.db.patch(stream._id, {
144
+ status: "timeout",
145
+ });
146
+ }
147
+ }
148
+ },
149
+ });
@@ -0,0 +1,21 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { Infer, v } from "convex/values";
3
+
4
+ export const streamStatusValidator = v.union(
5
+ v.literal("pending"),
6
+ v.literal("streaming"),
7
+ v.literal("done"),
8
+ v.literal("error"),
9
+ v.literal("timeout")
10
+ );
11
+ export type StreamStatus = Infer<typeof streamStatusValidator>;
12
+
13
+ export default defineSchema({
14
+ streams: defineTable({
15
+ status: streamStatusValidator,
16
+ }).index("byStatus", ["status"]),
17
+ chunks: defineTable({
18
+ streamId: v.id("streams"),
19
+ text: v.string(),
20
+ }).index("byStream", ["streamId"]),
21
+ });
@@ -0,0 +1,158 @@
1
+ "use client";
2
+
3
+ /// React helpers for persistent text streaming.
4
+ import { StreamStatus } from "../component/schema";
5
+ import { useQuery } from "convex/react";
6
+ import { StreamBody, StreamId } from "../client";
7
+ import { useEffect, useMemo, useRef, useState } from "react";
8
+ import { FunctionReference } from "convex/server";
9
+
10
+ if (typeof window === "undefined") {
11
+ throw new Error("this is frontend code, but it's running somewhere else!");
12
+ }
13
+
14
+ /**
15
+ * React hook for persistent text streaming.
16
+ *
17
+ * @param getPersistentBody - A query function reference that returns the body
18
+ * of a stream using the component's `getStreamBody` method.
19
+ * @param streamUrl - The URL of the http action that will kick off the stream
20
+ * generation and stream the result back to the client using the component's
21
+ * `stream` method.
22
+ * @param driven - Whether this particular session is driving the stream. Set this
23
+ * to true if this is the client session that first created the stream using the
24
+ * component's `createStream` method. If you're simply reloading an existing
25
+ * stream, set this to false.
26
+ * @param streamId - The ID of the stream. If this is not provided, the return
27
+ * value will be an empty string for the stream body and the status will be
28
+ * `pending`.
29
+ * @returns The body and status of the stream.
30
+ */
31
+ export function useStream(
32
+ getPersistentBody: FunctionReference<
33
+ "query",
34
+ "public",
35
+ { streamId: string },
36
+ StreamBody
37
+ >,
38
+ streamUrl: URL,
39
+ driven: boolean,
40
+ streamId?: StreamId
41
+ ) {
42
+ const [streamEnded, setStreamEnded] = useState(null as boolean | null);
43
+
44
+ // Used to prevent strict mode from causing multiple streams to be started.
45
+ const streamStarted = useRef(false);
46
+
47
+ const usePersistence = useMemo(() => {
48
+ // Something is wrong with the stream, so we need to use the database value.
49
+ if (streamEnded === false) {
50
+ return true;
51
+ }
52
+ // If we're not driving the stream, we must use the database value.
53
+ if (!driven) {
54
+ return true;
55
+ }
56
+ // Otherwise, we'll try to drive the stream and use the HTTP response.
57
+ return false;
58
+ }, [driven, streamId, streamEnded]);
59
+ // console.log("usePersistence", usePersistence);
60
+ const persistentBody = useQuery(
61
+ getPersistentBody,
62
+ usePersistence && streamId ? { streamId: streamId! } : "skip"
63
+ );
64
+ const [streamBody, setStreamBody] = useState<string>("");
65
+
66
+ useEffect(() => {
67
+ if (driven && streamId && !streamStarted.current) {
68
+ // Kick off HTTP action.
69
+ void (async () => {
70
+ const success = await startStreaming(streamUrl, streamId, (text) => {
71
+ setStreamBody((prev) => prev + text);
72
+ });
73
+ setStreamEnded(success);
74
+ })();
75
+ // If we get remounted, we don't want to start a new stream.
76
+ return () => {
77
+ streamStarted.current = true;
78
+ };
79
+ }
80
+ }, [driven, streamId, setStreamEnded, streamStarted]);
81
+
82
+ const body = useMemo<StreamBody>(() => {
83
+ // console.log(
84
+ // "body info p vs. s",
85
+ // persistentBody?.text?.length ?? 0,
86
+ // streamBody.length
87
+ //);
88
+ if (persistentBody) {
89
+ return persistentBody;
90
+ }
91
+ let status: StreamStatus;
92
+ if (streamEnded === null) {
93
+ status = streamBody.length > 0 ? "streaming" : "pending";
94
+ } else {
95
+ status = streamEnded ? "done" : "error";
96
+ }
97
+ return {
98
+ text: streamBody,
99
+ status: status as StreamStatus,
100
+ };
101
+ }, [persistentBody, streamBody, streamEnded]);
102
+
103
+ return body;
104
+ }
105
+
106
+ /**
107
+ * Internal helper for starting a stream.
108
+ *
109
+ * @param url - The URL of the http action that will kick off the stream
110
+ * generation and stream the result back to the client using the component's
111
+ * `stream` method.
112
+ * @param streamId - The ID of the stream.
113
+ * @param onUpdate - A function that updates the stream body.
114
+ * @returns A promise that resolves to a boolean indicating whether the stream
115
+ * was started successfully. It can fail if the http action is not found, or
116
+ * CORS fails, or an exception is raised, or the stream is already running
117
+ * or finished, etc.
118
+ */
119
+ async function startStreaming(
120
+ url: URL,
121
+ streamId: StreamId,
122
+ onUpdate: (text: string) => void
123
+ ) {
124
+ const response = await fetch(url, {
125
+ method: "POST",
126
+ body: JSON.stringify({
127
+ streamId: streamId,
128
+ }),
129
+ headers: { "Content-Type": "application/json" },
130
+ });
131
+ // Adapted from https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
132
+ if (response.status === 205) {
133
+ console.error("Stream already finished", response);
134
+ return false;
135
+ }
136
+ if (!response.ok) {
137
+ console.error("Failed to reach streaming endpoint", response);
138
+ return false;
139
+ }
140
+ if (!response.body) {
141
+ console.error("No body in response", response);
142
+ return false;
143
+ }
144
+ const reader = response.body.getReader();
145
+ while (true) {
146
+ try {
147
+ const { done, value } = await reader.read();
148
+ if (done) {
149
+ onUpdate(new TextDecoder().decode(value));
150
+ return true;
151
+ }
152
+ onUpdate(new TextDecoder().decode(value));
153
+ } catch (e) {
154
+ console.error("Error reading stream", e);
155
+ return false;
156
+ }
157
+ }
158
+ }