@flink-app/streaming-plugin 0.12.1-alpha.45

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) Frost Experience AB https://www.frost.se
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,476 @@
1
+ # @flink-app/streaming-plugin
2
+
3
+ Streaming response support for Flink Framework, enabling Server-Sent Events (SSE) and NDJSON streaming for real-time data transmission.
4
+
5
+ ## Features
6
+
7
+ - **Server-Sent Events (SSE)**: Perfect for live updates, notifications, and dashboards
8
+ - **NDJSON Streaming**: Ideal for LLM chat streaming (OpenAI/Anthropic style)
9
+ - **Type-Safe**: Full TypeScript support with generic event types
10
+ - **Simple API**: Clean `StreamWriter` interface for writing data
11
+ - **Connection Management**: Automatic handling of client disconnections
12
+ - **Flexible**: Works alongside regular Flink handlers
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @flink-app/streaming-plugin
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ### 1. Add Plugin to Your App
23
+
24
+ ```typescript
25
+ import { FlinkApp } from "@flink-app/flink";
26
+ import { streamingPlugin } from "@flink-app/streaming-plugin";
27
+
28
+ const streaming = streamingPlugin({ debug: true });
29
+
30
+ const app = await new FlinkApp({
31
+ name: "My App",
32
+ plugins: [streaming],
33
+ }).start();
34
+ ```
35
+
36
+ ### 2. Create a Streaming Handler
37
+
38
+ **LLM-Style Chat Streaming (NDJSON):**
39
+
40
+ ```typescript
41
+ // src/streaming/GetChatStream.ts
42
+ import { StreamHandler, StreamingRouteProps } from "@flink-app/streaming-plugin";
43
+
44
+ export const Route: StreamingRouteProps = {
45
+ path: "/chat/stream",
46
+ format: "ndjson", // Use NDJSON for LLM streaming
47
+ skipAutoRegister: true, // Required for streaming handlers
48
+ };
49
+
50
+ interface ChatEvent {
51
+ delta: string;
52
+ done?: boolean;
53
+ }
54
+
55
+ const GetChatStream: StreamHandler<AppContext, ChatEvent> = async ({ req, stream }) => {
56
+ const prompt = req.query.prompt as string;
57
+
58
+ // Call your LLM API
59
+ for await (const chunk of callLLMAPI(prompt)) {
60
+ stream.write({
61
+ delta: chunk.text,
62
+ });
63
+ }
64
+
65
+ stream.write({ delta: "", done: true });
66
+ stream.end();
67
+ };
68
+
69
+ export default GetChatStream;
70
+ ```
71
+
72
+ **Live Updates (SSE):**
73
+
74
+ ```typescript
75
+ // src/streaming/GetLiveUpdates.ts
76
+ import { StreamHandler, StreamingRouteProps } from "@flink-app/streaming-plugin";
77
+
78
+ export const Route: StreamingRouteProps = {
79
+ path: "/live-updates",
80
+ format: "sse", // Use SSE for live updates
81
+ skipAutoRegister: true,
82
+ };
83
+
84
+ interface UpdateEvent {
85
+ type: "update" | "notification";
86
+ message: string;
87
+ timestamp: number;
88
+ }
89
+
90
+ const GetLiveUpdates: StreamHandler<AppContext, UpdateEvent> = async ({ stream }) => {
91
+ // Send updates periodically
92
+ const interval = setInterval(() => {
93
+ if (!stream.isOpen()) {
94
+ clearInterval(interval);
95
+ return;
96
+ }
97
+
98
+ stream.write({
99
+ type: "update",
100
+ message: "New data available",
101
+ timestamp: Date.now(),
102
+ });
103
+ }, 1000);
104
+ };
105
+
106
+ export default GetLiveUpdates;
107
+ ```
108
+
109
+ ### 3. Register Streaming Handlers
110
+
111
+ **Preferred: Module-based registration**
112
+
113
+ ```typescript
114
+ // src/index.ts
115
+ import * as GetChatStream from "./streaming/GetChatStream";
116
+ import * as GetLiveUpdates from "./streaming/GetLiveUpdates";
117
+
118
+ // After app.start()
119
+ streaming.registerStreamHandler(GetChatStream);
120
+ streaming.registerStreamHandler(GetLiveUpdates);
121
+ ```
122
+
123
+ **Alternative: Explicit registration**
124
+
125
+ ```typescript
126
+ // If you prefer explicit control
127
+ streaming.registerStreamHandler(
128
+ async ({ stream }) => {
129
+ stream.write({ message: "Hello" });
130
+ stream.end();
131
+ },
132
+ { path: "/custom", format: "sse", skipAutoRegister: true }
133
+ );
134
+ ```
135
+
136
+ ## Client-Side Usage
137
+
138
+ ### Consuming NDJSON Streams (Fetch API)
139
+
140
+ ```typescript
141
+ async function streamChat(prompt: string) {
142
+ const response = await fetch(`/chat/stream?prompt=${encodeURIComponent(prompt)}`);
143
+ const reader = response.body!.getReader();
144
+ const decoder = new TextDecoder();
145
+
146
+ let buffer = "";
147
+
148
+ while (true) {
149
+ const { done, value } = await reader.read();
150
+
151
+ if (done) break;
152
+
153
+ buffer += decoder.decode(value, { stream: true });
154
+ const lines = buffer.split("\n");
155
+ buffer = lines.pop() || ""; // Keep incomplete line
156
+
157
+ for (const line of lines) {
158
+ if (line.trim()) {
159
+ const event = JSON.parse(line);
160
+ console.log("Delta:", event.delta);
161
+
162
+ if (event.done) {
163
+ console.log("Stream complete");
164
+ return;
165
+ }
166
+ }
167
+ }
168
+ }
169
+ }
170
+ ```
171
+
172
+ ### Consuming SSE Streams (EventSource)
173
+
174
+ ```typescript
175
+ const eventSource = new EventSource("/live-updates");
176
+
177
+ eventSource.onmessage = (event) => {
178
+ const data = JSON.parse(event.data);
179
+ console.log("Update:", data);
180
+ };
181
+
182
+ eventSource.addEventListener("error", (event) => {
183
+ const error = JSON.parse(event.data);
184
+ console.error("Error:", error.message);
185
+ });
186
+
187
+ // Close connection when done
188
+ eventSource.close();
189
+ ```
190
+
191
+ ## API Reference
192
+
193
+ ### `streamingPlugin(options?)`
194
+
195
+ Creates a streaming plugin instance.
196
+
197
+ **Options:**
198
+
199
+ - `defaultFormat?: 'sse' | 'ndjson'` - Default format if not specified (default: `'sse'`)
200
+ - `debug?: boolean` - Enable debug logging (default: `false`)
201
+
202
+ ### `StreamHandler<Ctx, T>`
203
+
204
+ Handler function type for streaming endpoints.
205
+
206
+ **Type Parameters:**
207
+
208
+ - `Ctx` - Your application context type
209
+ - `T` - Event data type
210
+
211
+ **Props:**
212
+
213
+ - `req: FlinkRequest` - Flink request object
214
+ - `ctx: Ctx` - Application context
215
+ - `stream: StreamWriter<T>` - Stream writer for sending data
216
+ - `origin?: string` - Route origin
217
+
218
+ ### `StreamWriter<T>`
219
+
220
+ Interface for writing data to streams.
221
+
222
+ **Methods:**
223
+
224
+ - `write(data: T): void` - Write data to the stream
225
+ - `error(error: Error | string): void` - Send error event
226
+ - `end(): void` - Close the stream
227
+ - `isOpen(): boolean` - Check if connection is still open
228
+
229
+ ### `StreamingRouteProps`
230
+
231
+ Route configuration for streaming endpoints.
232
+
233
+ **Properties:**
234
+
235
+ - `path: string` - HTTP path (required)
236
+ - `method?: HttpMethod` - HTTP method (default: `GET`)
237
+ - `format?: 'sse' | 'ndjson'` - Streaming format (default: plugin default)
238
+ - `skipAutoRegister: true` - Must be `true` (required)
239
+ - `permissions?: string | string[]` - Route permissions (uses Flink auth plugin)
240
+ - `origin?: string` - Route origin (optional)
241
+
242
+ ## Streaming Formats
243
+
244
+ ### SSE (Server-Sent Events)
245
+
246
+ **When to use:**
247
+
248
+ - Live dashboards and real-time updates
249
+ - Notifications and alerts
250
+ - Progress indicators
251
+ - Traditional one-way server → client streaming
252
+
253
+ **Format:**
254
+
255
+ ```
256
+ data: {"message":"Hello"}\n\n
257
+ data: {"message":"World"}\n\n
258
+ ```
259
+
260
+ **Headers:**
261
+
262
+ - `Content-Type: text/event-stream`
263
+ - `Cache-Control: no-cache`
264
+ - `Connection: keep-alive`
265
+
266
+ ### NDJSON (Newline-Delimited JSON)
267
+
268
+ **When to use:**
269
+
270
+ - LLM chat streaming (OpenAI/Anthropic style)
271
+ - Bulk data export
272
+ - Log streaming
273
+ - Any streaming JSON data
274
+
275
+ **Format:**
276
+
277
+ ```
278
+ {"delta":"Hello"}\n
279
+ {"delta":" world","done":true}\n
280
+ ```
281
+
282
+ **Headers:**
283
+
284
+ - `Content-Type: application/x-ndjson`
285
+ - `Cache-Control: no-cache`
286
+
287
+ ## Authentication
288
+
289
+ Streaming handlers support Flink's authentication system just like regular handlers. Simply add `permissions` to your route configuration:
290
+
291
+ ```typescript
292
+ export const Route: StreamingRouteProps = {
293
+ path: "/admin/stream",
294
+ format: "sse",
295
+ skipAutoRegister: true,
296
+ permissions: ["admin"], // Requires admin role
297
+ };
298
+
299
+ const AdminStream: StreamHandler<AppContext> = async ({ req, stream }) => {
300
+ // ✅ req.user is populated by auth plugin after successful authentication
301
+ const user = req.user; // Type depends on your auth plugin
302
+
303
+ stream.write({
304
+ message: `Hello ${user?.name}`,
305
+ userId: user?.userId,
306
+ permissions: user?.permissions,
307
+ });
308
+ stream.end();
309
+ };
310
+ ```
311
+
312
+ **How it works:**
313
+
314
+ 1. Plugin checks `routeProps.permissions` before starting the stream
315
+ 2. Calls your configured auth plugin (JWT, BankID, OAuth, etc.)
316
+ 3. Returns 401 if authentication fails
317
+ 4. **✅ Authenticated user info is available in `req.user`** (populated by your auth plugin)
318
+
319
+ **Example with JWT:**
320
+
321
+ ```typescript
322
+ import { jwtAuthPlugin } from "@flink-app/jwt-auth-plugin";
323
+
324
+ const app = new FlinkApp({
325
+ auth: jwtAuthPlugin({ secret: "your-secret" }),
326
+ plugins: [streaming],
327
+ });
328
+
329
+ // Client must send Authorization header
330
+ fetch("/admin/stream", {
331
+ headers: {
332
+ Authorization: "Bearer your-jwt-token",
333
+ },
334
+ });
335
+ ```
336
+
337
+ ## Best Practices
338
+
339
+ ### 1. Check Connection Status
340
+
341
+ Always check if the stream is still open before writing:
342
+
343
+ ```typescript
344
+ if (stream.isOpen()) {
345
+ stream.write(data);
346
+ }
347
+ ```
348
+
349
+ ### 2. Clean Up Resources
350
+
351
+ Clean up intervals, timers, and resources when the connection closes:
352
+
353
+ ```typescript
354
+ const interval = setInterval(() => {
355
+ if (!stream.isOpen()) {
356
+ clearInterval(interval);
357
+ return;
358
+ }
359
+ stream.write(data);
360
+ }, 1000);
361
+ ```
362
+
363
+ ### 3. Handle Errors Gracefully
364
+
365
+ Always wrap streaming logic in try-catch:
366
+
367
+ ```typescript
368
+ const handler: StreamHandler<Ctx> = async ({ stream }) => {
369
+ try {
370
+ // Your streaming logic
371
+ } catch (err) {
372
+ stream.error(err);
373
+ stream.end();
374
+ }
375
+ };
376
+ ```
377
+
378
+ ### 4. Use Type Parameters
379
+
380
+ Leverage TypeScript for type-safe events:
381
+
382
+ ```typescript
383
+ interface ChatEvent {
384
+ delta: string;
385
+ done?: boolean;
386
+ metadata?: {
387
+ model: string;
388
+ tokens: number;
389
+ };
390
+ }
391
+
392
+ const handler: StreamHandler<Ctx, ChatEvent> = async ({ stream }) => {
393
+ stream.write({
394
+ delta: "Hello",
395
+ metadata: { model: "gpt-4", tokens: 5 },
396
+ }); // ✅ Type-safe
397
+
398
+ // stream.write({ invalid: "data" }); // ❌ Type error
399
+ };
400
+ ```
401
+
402
+ ## Limitations
403
+
404
+ ### Manual Registration Required
405
+
406
+ Unlike regular Flink handlers, streaming handlers must be registered manually after `app.start()`:
407
+
408
+ ```typescript
409
+ // ❌ Won't auto-register
410
+ export const Route: StreamingRouteProps = {
411
+ path: "/stream",
412
+ skipAutoRegister: true, // Required
413
+ };
414
+
415
+ // ✅ Must register manually
416
+ streaming.registerStreamHandler(handler, Route);
417
+ ```
418
+
419
+ This is a trade-off for zero core framework changes and allows the plugin to work independently.
420
+
421
+ ### ⚠️ File Location Requirement
422
+
423
+ **IMPORTANT:** Streaming handlers MUST be placed outside the `src/handlers/` directory.
424
+
425
+ ```typescript
426
+ // ❌ WRONG - Will cause TypeScript compilation error
427
+ src/handlers/streaming/GetChatStream.ts
428
+
429
+ // ✅ CORRECT - Place outside handlers directory
430
+ src/streaming/GetChatStream.ts
431
+ ```
432
+
433
+ **Why?** Flink's TypeScript compiler automatically scans `src/handlers/` for auto-registration and attempts to analyze all handler types at compile-time. Since it doesn't recognize the `StreamHandler` type from this plugin, it will throw an error:
434
+
435
+ ```
436
+ Error: Unknown handler type StreamHandler in GetChatStream.ts - should be Handler or GetHandler
437
+ ```
438
+
439
+ **Recommended locations:**
440
+ - `src/streaming/` - Dedicated directory for streaming handlers (recommended)
441
+ - `src/streams/` - Alternative naming
442
+ - Any directory outside `src/handlers/`
443
+
444
+ ### No Schema Validation
445
+
446
+ Streaming responses bypass Flink's JSON schema validation since data is sent incrementally. Ensure your event types are well-defined and validated manually if needed.
447
+
448
+ ### Connection Limits
449
+
450
+ Be mindful of:
451
+
452
+ - Server connection limits (max concurrent streams)
453
+ - Client browser limits (typically 6 connections per domain)
454
+ - Load balancer timeout settings
455
+
456
+ ## Examples
457
+
458
+ See the [demo-app](../../demo-app) for complete working examples:
459
+
460
+ - `/chat/stream` - NDJSON streaming chat
461
+ - `/live-updates` - SSE live updates
462
+
463
+ ## Roadmap
464
+
465
+ Potential future enhancements:
466
+
467
+ - [ ] Auto-registration support (requires core framework changes)
468
+ - [ ] Binary streaming support
469
+ - [ ] WebSocket integration
470
+ - [ ] Compression support (gzip)
471
+ - [ ] Rate limiting/backpressure
472
+ - [ ] Metrics and monitoring hooks
473
+
474
+ ## License
475
+
476
+ MIT
@@ -0,0 +1,45 @@
1
+ import { FlinkApp, FlinkContext, FlinkPlugin } from "@flink-app/flink";
2
+ import { StreamHandler, StreamHandlerModule, StreamingPluginOptions, StreamingRouteProps } from "./types";
3
+ /**
4
+ * Streaming plugin for Flink Framework
5
+ * Provides SSE and NDJSON streaming support
6
+ */
7
+ export declare class StreamingPlugin implements FlinkPlugin {
8
+ id: string;
9
+ private app?;
10
+ private options;
11
+ constructor(options?: StreamingPluginOptions);
12
+ init(app: FlinkApp<any>): Promise<void>;
13
+ /**
14
+ * Register a streaming handler from a module (preferred DX)
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import * as GetChatStream from "./handlers/streaming/GetChatStream";
19
+ *
20
+ * // After app.start()
21
+ * streaming.registerStreamHandler(GetChatStream);
22
+ * ```
23
+ */
24
+ registerStreamHandler<Ctx extends FlinkContext, T = any>(handlerModule: StreamHandlerModule<Ctx, T>): void;
25
+ /**
26
+ * Register a streaming handler with explicit handler and route props
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * streaming.registerStreamHandler(
31
+ * async ({ stream }) => {
32
+ * stream.write({ message: "Hello" });
33
+ * stream.end();
34
+ * },
35
+ * { path: "/stream", skipAutoRegister: true }
36
+ * );
37
+ * ```
38
+ */
39
+ registerStreamHandler<Ctx extends FlinkContext, T = any>(handler: StreamHandler<Ctx, T>, routeProps: StreamingRouteProps): void;
40
+ }
41
+ /**
42
+ * Factory function to create streaming plugin
43
+ */
44
+ export declare function streamingPlugin(options?: StreamingPluginOptions): StreamingPlugin;
45
+ //# sourceMappingURL=StreamingPlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StreamingPlugin.d.ts","sourceRoot":"","sources":["../src/StreamingPlugin.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAmB,MAAM,kBAAkB,CAAC;AACxF,OAAO,EAEH,aAAa,EACb,mBAAmB,EACnB,sBAAsB,EACtB,mBAAmB,EAEtB,MAAM,SAAS,CAAC;AAyEjB;;;GAGG;AACH,qBAAa,eAAgB,YAAW,WAAW;IACxC,EAAE,SAAe;IACxB,OAAO,CAAC,GAAG,CAAC,CAAgB;IAC5B,OAAO,CAAC,OAAO,CAAmC;gBAEtC,OAAO,GAAE,sBAA2B;IAO1C,IAAI,CAAC,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAQ7C;;;;;;;;;;OAUG;IACI,qBAAqB,CAAC,GAAG,SAAS,YAAY,EAAE,CAAC,GAAG,GAAG,EAC1D,aAAa,EAAE,mBAAmB,CAAC,GAAG,EAAE,CAAC,CAAC,GAC3C,IAAI;IAEP;;;;;;;;;;;;;OAaG;IACI,qBAAqB,CAAC,GAAG,SAAS,YAAY,EAAE,CAAC,GAAG,GAAG,EAC1D,OAAO,EAAE,aAAa,CAAC,GAAG,EAAE,CAAC,CAAC,EAC9B,UAAU,EAAE,mBAAmB,GAChC,IAAI;CAuIV;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,CAAC,EAAE,sBAAsB,GAAG,eAAe,CAEjF"}