-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathstreamsWriterV2.ts
More file actions
229 lines (201 loc) · 6.82 KB
/
streamsWriterV2.ts
File metadata and controls
229 lines (201 loc) · 6.82 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
import { S2, AppendRecord, BatchTransform } from "@s2-dev/streamstore";
import { StreamsWriter } from "./types.js";
import { nanoid } from "nanoid";
export type StreamsWriterV2Options<T = any> = {
basin: string;
stream: string;
accessToken: string;
endpoint?: string; // Custom S2 endpoint (for s2-lite)
source: ReadableStream<T>;
signal?: AbortSignal;
flushIntervalMs?: number; // Used as lingerDuration for BatchTransform (default 200ms)
maxRetries?: number; // Not used with appendSession, kept for compatibility
debug?: boolean; // Enable debug logging (default false)
maxInflightBytes?: number; // Max queued bytes for appendSession (default 10MB)
};
/**
* StreamsWriterV2 writes metadata stream data directly to S2 (https://s2.dev).
*
* Features:
* - Direct streaming: Uses S2's appendSession for efficient streaming
* - Automatic batching: Uses BatchTransform to batch records
* - No manual buffering: S2 handles buffering internally
* - Debug logging: Enable with debug: true to see detailed operation logs
*
* Example usage:
* ```typescript
* const stream = new StreamsWriterV2({
* basin: "my-basin",
* stream: "my-stream",
* accessToken: "s2-token-here",
* source: myAsyncIterable,
* flushIntervalMs: 200, // Optional: batch linger duration in ms
* debug: true, // Optional: enable debug logging
* });
*
* // Wait for streaming to complete
* await stream.wait();
*
* // Or consume the stream
* for await (const value of stream) {
* console.log(value);
* }
* ```
*/
export class StreamsWriterV2<T = any> implements StreamsWriter {
private s2Client: S2;
private serverStream: ReadableStream<T>;
private consumerStream: ReadableStream<T>;
private streamPromise: Promise<void>;
private readonly flushIntervalMs: number;
private readonly debug: boolean;
private readonly maxInflightBytes: number;
private aborted = false;
private sessionWritable: WritableStream<any> | null = null;
constructor(private options: StreamsWriterV2Options<T>) {
this.debug = options.debug ?? false;
this.s2Client = new S2({
accessToken: options.accessToken,
...(options.endpoint
? {
endpoints: {
account: options.endpoint,
basin: options.endpoint,
},
}
: {}),
});
this.flushIntervalMs = options.flushIntervalMs ?? 200;
this.maxInflightBytes = options.maxInflightBytes ?? 1024 * 1024 * 10; // 10MB default
this.log(
`[S2MetadataStream] Initializing: basin=${options.basin}, stream=${options.stream}, flushIntervalMs=${this.flushIntervalMs}, maxInflightBytes=${this.maxInflightBytes}`
);
// Check if already aborted
if (options.signal?.aborted) {
this.aborted = true;
this.log("[S2MetadataStream] Signal already aborted, skipping initialization");
this.serverStream = new ReadableStream<T>();
this.consumerStream = new ReadableStream<T>();
this.streamPromise = Promise.resolve();
return;
}
// Set up abort signal handler
if (options.signal) {
options.signal.addEventListener("abort", () => {
this.log("[S2MetadataStream] Abort signal received");
this.handleAbort();
});
}
const [serverStream, consumerStream] = this.options.source.tee();
this.serverStream = serverStream;
this.consumerStream = consumerStream;
this.streamPromise = this.initializeServerStream();
}
private handleAbort(): void {
if (this.aborted) {
return; // Already aborted
}
this.aborted = true;
this.log("[S2MetadataStream] Handling abort - cleaning up resources");
// Abort the writable stream if it exists
if (this.sessionWritable) {
this.sessionWritable
.abort("Aborted")
.catch((error) => {
this.logError("[S2MetadataStream] Error aborting writable stream:", error);
})
.finally(() => {
this.log("[S2MetadataStream] Writable stream aborted");
});
}
this.log("[S2MetadataStream] Abort cleanup complete");
}
private async initializeServerStream(): Promise<void> {
try {
if (this.aborted) {
this.log("[S2MetadataStream] Stream initialization aborted");
return;
}
this.log("[S2MetadataStream] Getting S2 basin and stream");
const basin = this.s2Client.basin(this.options.basin);
const stream = basin.stream(this.options.stream);
const session = await stream.appendSession({
maxInflightBytes: this.maxInflightBytes,
});
this.sessionWritable = session.writable;
this.log(`[S2MetadataStream] Starting stream pipeline`);
// Convert source stream to AppendRecord format and pipe to S2
await this.serverStream
.pipeThrough(
new TransformStream<T, AppendRecord>({
transform: (chunk, controller) => {
if (this.aborted) {
controller.error(new Error("Stream aborted"));
return;
}
// Convert each chunk to JSON string and wrap in AppendRecord
controller.enqueue(
AppendRecord.string({ body: JSON.stringify({ data: chunk, id: nanoid(7) }) })
);
},
})
)
.pipeThrough(
new BatchTransform({
lingerDurationMillis: this.flushIntervalMs,
})
)
.pipeTo(session.writable);
this.log("[S2MetadataStream] Stream pipeline completed successfully");
// Get final position to verify completion
const lastAcked = session.lastAckedPosition();
if (lastAcked?.end) {
const recordsWritten = lastAcked.end.seqNum;
this.log(
`[S2MetadataStream] Written ${recordsWritten} records, ending at seqNum=${lastAcked.end.seqNum}`
);
}
} catch (error) {
if (this.aborted) {
this.log("[S2MetadataStream] Stream error occurred but stream was aborted");
return;
}
this.logError("[S2MetadataStream] Error in stream pipeline:", error);
throw error;
}
}
public async wait(): Promise<void> {
await this.streamPromise;
}
public [Symbol.asyncIterator]() {
return streamToAsyncIterator(this.consumerStream);
}
// Helper methods
private log(message: string): void {
if (this.debug) {
console.log(message);
}
}
private logError(message: string, error?: any): void {
if (this.debug) {
console.error(message, error);
}
}
}
async function* streamToAsyncIterator<T>(stream: ReadableStream<T>): AsyncIterableIterator<T> {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
} finally {
safeReleaseLock(reader);
}
}
function safeReleaseLock(reader: ReadableStreamDefaultReader<any>) {
try {
reader.releaseLock();
} catch (error) { }
}