Skip to content

Commit 6c14033

Browse files
committed
Handle writer failure--but keep the generation going!
1 parent ad15797 commit 6c14033

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/client/index.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -122,14 +122,22 @@ export class PersistentTextStreaming {
122122
}
123123
// Create a TransformStream to handle streaming data
124124
const { readable, writable } = new TransformStream();
125-
const writer = writable.getWriter();
125+
let writer = writable.getWriter() as WritableStreamDefaultWriter<Uint8Array> | null;
126126
const textEncoder = new TextEncoder();
127127
let pending = "";
128128

129129
const doStream = async () => {
130130
const chunkAppender: ChunkAppender = async (text) => {
131131
// write to this handler's response stream on every update
132-
await writer.write(textEncoder.encode(text));
132+
if (writer) {
133+
try {
134+
await writer.write(textEncoder.encode(text));
135+
} catch (e) {
136+
console.error("Error writing to stream", e);
137+
console.error("Will skip writing to stream but continue database updates");
138+
writer = null;
139+
}
140+
}
133141
pending += text;
134142
// write to the database periodically, like at the end of sentences
135143
if (hasDelimeter(text)) {
@@ -141,14 +149,18 @@ export class PersistentTextStreaming {
141149
await streamWriter(ctx, request, streamId, chunkAppender);
142150
} catch (e) {
143151
await this.setStreamStatus(ctx, streamId, "error");
144-
await writer.close();
152+
if (writer) {
153+
await writer.close();
154+
}
145155
throw e;
146156
}
147157

148158
// Success? Flush any last updates
149159
await this.addChunk(ctx, streamId, pending, true);
150160

151-
await writer.close();
161+
if (writer) {
162+
await writer.close();
163+
}
152164
};
153165

154166
// Kick off the streaming, but don't await it.

0 commit comments

Comments
 (0)