@langgraph-js/pure-graph 1.2.0 → 1.4.0

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 (79) hide show
  1. package/README.md +22 -14
  2. package/dist/adapter/hono/runs.js +18 -1
  3. package/dist/adapter/nextjs/router.js +18 -7
  4. package/dist/adapter/zod.d.ts +15 -8
  5. package/dist/adapter/zod.js +8 -0
  6. package/dist/global.d.ts +3 -2
  7. package/dist/storage/index.d.ts +4 -3
  8. package/dist/storage/index.js +13 -1
  9. package/dist/storage/memory/threads.d.ts +3 -2
  10. package/dist/storage/memory/threads.js +29 -2
  11. package/dist/storage/pg/checkpoint.d.ts +2 -0
  12. package/dist/storage/pg/checkpoint.js +9 -0
  13. package/dist/storage/pg/threads.d.ts +43 -0
  14. package/dist/storage/pg/threads.js +304 -0
  15. package/dist/storage/sqlite/threads.d.ts +3 -2
  16. package/dist/storage/sqlite/threads.js +37 -3
  17. package/dist/threads/index.d.ts +3 -2
  18. package/dist/threads/index.js +1 -26
  19. package/dist/tsconfig.tsbuildinfo +1 -0
  20. package/dist/types.d.ts +2 -1
  21. package/package.json +38 -5
  22. package/.prettierrc +0 -11
  23. package/bun.lock +0 -209
  24. package/dist/adapter/nextjs/zod.d.ts +0 -203
  25. package/dist/adapter/nextjs/zod.js +0 -60
  26. package/examples/nextjs/README.md +0 -36
  27. package/examples/nextjs/app/api/langgraph/[...path]/route.ts +0 -10
  28. package/examples/nextjs/app/favicon.ico +0 -0
  29. package/examples/nextjs/app/globals.css +0 -26
  30. package/examples/nextjs/app/layout.tsx +0 -34
  31. package/examples/nextjs/app/page.tsx +0 -211
  32. package/examples/nextjs/next.config.ts +0 -26
  33. package/examples/nextjs/package.json +0 -24
  34. package/examples/nextjs/postcss.config.mjs +0 -5
  35. package/examples/nextjs/tsconfig.json +0 -27
  36. package/packages/agent-graph/demo.json +0 -35
  37. package/packages/agent-graph/package.json +0 -18
  38. package/packages/agent-graph/src/index.ts +0 -47
  39. package/packages/agent-graph/src/tools/tavily.ts +0 -9
  40. package/packages/agent-graph/src/tools.ts +0 -38
  41. package/packages/agent-graph/src/types.ts +0 -42
  42. package/pnpm-workspace.yaml +0 -4
  43. package/src/adapter/hono/assistants.ts +0 -24
  44. package/src/adapter/hono/endpoint.ts +0 -3
  45. package/src/adapter/hono/index.ts +0 -14
  46. package/src/adapter/hono/runs.ts +0 -65
  47. package/src/adapter/hono/threads.ts +0 -37
  48. package/src/adapter/nextjs/endpoint.ts +0 -2
  49. package/src/adapter/nextjs/index.ts +0 -2
  50. package/src/adapter/nextjs/router.ts +0 -193
  51. package/src/adapter/nextjs/zod.ts +0 -66
  52. package/src/adapter/zod.ts +0 -135
  53. package/src/createEndpoint.ts +0 -116
  54. package/src/e.d.ts +0 -3
  55. package/src/global.ts +0 -11
  56. package/src/graph/stream.ts +0 -263
  57. package/src/graph/stringify.ts +0 -219
  58. package/src/index.ts +0 -6
  59. package/src/queue/JsonPlusSerializer.ts +0 -143
  60. package/src/queue/event_message.ts +0 -30
  61. package/src/queue/stream_queue.ts +0 -237
  62. package/src/storage/index.ts +0 -52
  63. package/src/storage/memory/checkpoint.ts +0 -2
  64. package/src/storage/memory/queue.ts +0 -91
  65. package/src/storage/memory/threads.ts +0 -154
  66. package/src/storage/redis/queue.ts +0 -148
  67. package/src/storage/sqlite/DB.ts +0 -16
  68. package/src/storage/sqlite/checkpoint.ts +0 -503
  69. package/src/storage/sqlite/threads.ts +0 -366
  70. package/src/storage/sqlite/type.ts +0 -12
  71. package/src/threads/index.ts +0 -51
  72. package/src/types.ts +0 -116
  73. package/src/utils/createEntrypointGraph.ts +0 -20
  74. package/src/utils/getGraph.ts +0 -44
  75. package/src/utils/getLangGraphCommand.ts +0 -21
  76. package/test/graph/entrypoint.ts +0 -21
  77. package/test/graph/index.ts +0 -60
  78. package/test/hono.ts +0 -15
  79. package/tsconfig.json +0 -20
@@ -1,237 +0,0 @@
1
- import { EventEmitter } from 'eventemitter3';
2
- import { JsonPlusSerializer } from './JsonPlusSerializer.js';
3
- import { EventMessage } from './event_message.js';
4
-
5
- /**
6
- * 流队列事件接口
7
- * Stream queue events interface
8
- */
9
- interface StreamQueueEvents<T extends EventMessage> {
10
- /** 数据事件:当有新数据时触发 / Data event: triggered when new data arrives */
11
- data: (data: T) => void;
12
- /** 其他事件 / Other events */
13
- [key: string]: ((...args: any[]) => void) | undefined;
14
- }
15
-
16
- /**
17
- * 基础流队列类
18
- * Base stream queue class
19
- */
20
- export class BaseStreamQueue extends EventEmitter<StreamQueueEvents<EventMessage>> {
21
- /** 序列化器实例 / Serializer instance */
22
- serializer = new JsonPlusSerializer();
23
-
24
- /**
25
- * 构造函数
26
- * Constructor
27
- * @param compressMessages 是否压缩消息 / Whether to compress messages
28
- */
29
- constructor(readonly id: string, readonly compressMessages: boolean = true) {
30
- super();
31
- }
32
-
33
- /**
34
- * 编码数据为 Uint8Array
35
- * Encode data to Uint8Array
36
- * @param message 要编码的消息 / Message to encode
37
- * @returns 编码后的 Uint8Array / Encoded Uint8Array
38
- */
39
- async encodeData(message: EventMessage): Promise<Uint8Array> {
40
- const [_, serializedMessage] = await this.serializer.dumpsTyped(message);
41
- return serializedMessage;
42
- }
43
-
44
- /**
45
- * 解码数据为 EventMessage
46
- * Decode data to EventMessage
47
- * @param serializedMessage 要解码的消息 / Message to decode
48
- * @returns 解码后的 EventMessage / Decoded EventMessage
49
- */
50
- async decodeData(serializedMessage: string | Uint8Array): Promise<EventMessage> {
51
- const message = (await this.serializer.loadsTyped('json', serializedMessage)) as EventMessage;
52
- return message;
53
- }
54
- }
55
-
56
- /**
57
- * 基础流队列接口
58
- * Base stream queue interface
59
- */
60
- export interface BaseStreamQueueInterface {
61
- id: string;
62
- /** 是否压缩消息 / Whether to compress messages */
63
- compressMessages: boolean;
64
- /**
65
- * 推送数据项到队列
66
- * Push item to queue
67
- * @param item 要推送的数据项 / Item to push
68
- */
69
- push(item: EventMessage): Promise<void>;
70
- /** 获取所有数据 / Get all data */
71
- getAll(): Promise<EventMessage[]>;
72
- /** 清空队列 / Clear queue */
73
- clear(): void;
74
- /**
75
- * 监听数据变化
76
- * Listen for data changes
77
- * @param listener 数据变化监听器 / Data change listener
78
- * @returns 取消监听函数 / Unsubscribe function
79
- */
80
- onDataReceive(): AsyncGenerator<EventMessage, void, unknown>;
81
- /** 取消信号控制器 / Cancel signal controller */
82
- cancelSignal: AbortController;
83
- /** 取消操作 / Cancel operation */
84
- cancel(): void;
85
- }
86
-
87
- /**
88
- * StreamQueue 管理器,通过 id 管理多个队列实例
89
- * StreamQueue manager, manages multiple queue instances by id
90
- */
91
- export class StreamQueueManager<Q extends BaseStreamQueueInterface> {
92
- /** 存储队列实例的 Map / Map storing queue instances */
93
- private queues: Map<string, Q> = new Map();
94
- /** 默认是否压缩消息 / Default compress messages setting */
95
- private defaultCompressMessages: boolean;
96
- /** 队列构造函数 / Queue constructor */
97
- private queueConstructor: new (queueId: string) => Q;
98
-
99
- /**
100
- * 构造函数
101
- * Constructor
102
- * @param queueConstructor 队列构造函数 / Queue constructor
103
- * @param options 配置选项 / Configuration options
104
- */
105
- constructor(
106
- queueConstructor: new (id: string) => Q,
107
- options: {
108
- /** 默认是否压缩消息 / Default compress messages setting */
109
- defaultCompressMessages?: boolean;
110
- } = {},
111
- ) {
112
- this.defaultCompressMessages = options.defaultCompressMessages ?? true;
113
- this.queueConstructor = queueConstructor;
114
- }
115
-
116
- /**
117
- * 创建指定 id 的队列
118
- * Create queue with specified id
119
- * @param id 队列 ID / Queue ID
120
- * @param compressMessages 是否压缩消息 / Whether to compress messages
121
- * @returns 创建的队列实例 / Created queue instance
122
- */
123
- createQueue(id: string, compressMessages?: boolean): Q {
124
- const compress = compressMessages ?? this.defaultCompressMessages;
125
- this.queues.set(id, new this.queueConstructor(id));
126
- return this.queues.get(id)!;
127
- }
128
-
129
- /**
130
- * 获取或创建指定 id 的队列
131
- * Get or create queue with specified id
132
- * @param id 队列 ID / Queue ID
133
- * @param compressMessages 是否压缩消息,默认为构造函数中的默认值 / Whether to compress messages, defaults to constructor default
134
- * @returns StreamQueue 实例 / StreamQueue instance
135
- */
136
- getQueue(id: string): Q {
137
- const queue = this.queues.get(id);
138
- if (!queue) {
139
- throw new Error(`Queue with id '${id}' does not exist`);
140
- }
141
- return queue;
142
- }
143
-
144
- /**
145
- * 取消指定 id 的队列
146
- * Cancel queue with specified id
147
- * @param id 队列 ID / Queue ID
148
- */
149
- cancelQueue(id: string): void {
150
- const queue = this.queues.get(id);
151
- if (queue) {
152
- queue.cancel();
153
- this.removeQueue(id);
154
- }
155
- }
156
- /**
157
- * 向指定 id 的队列推送数据
158
- * Push data to queue with specified id
159
- * @param id 队列 ID / Queue ID
160
- * @param item 要推送的数据项 / Item to push
161
- * @param compressMessages 是否压缩消息,默认为构造函数中的默认值 / Whether to compress messages, defaults to constructor default
162
- */
163
- async pushToQueue(id: string, item: EventMessage, compressMessages?: boolean): Promise<void> {
164
- const queue = this.getQueue(id);
165
- await queue.push(item);
166
- }
167
-
168
- /**
169
- * 获取指定 id 队列中的所有数据
170
- * Get all data from queue with specified id
171
- * @param id 队列 ID / Queue ID
172
- * @returns 队列中的所有数据 / All data in the queue
173
- */
174
- async getQueueData(id: string): Promise<EventMessage[]> {
175
- const queue = this.queues.get(id);
176
- if (!queue) {
177
- throw new Error(`Queue with id '${id}' does not exist`);
178
- }
179
- return await queue.getAll();
180
- }
181
-
182
- /**
183
- * 清空指定 id 的队列
184
- * Clear queue with specified id
185
- * @param id 队列 ID / Queue ID
186
- */
187
- clearQueue(id: string): void {
188
- const queue = this.queues.get(id);
189
- if (queue) {
190
- queue.clear();
191
- }
192
- }
193
-
194
- /**
195
- * 删除指定 id 的队列
196
- * Remove queue with specified id
197
- * @param id 队列 ID / Queue ID
198
- * @returns 是否成功删除 / Whether successfully deleted
199
- */
200
- removeQueue(id: string) {
201
- setTimeout(() => {
202
- return this.queues.delete(id);
203
- }, 500);
204
- }
205
-
206
- /**
207
- * 获取所有队列的 ID
208
- * Get all queue IDs
209
- * @returns 所有队列 ID 的数组 / Array of all queue IDs
210
- */
211
- getAllQueueIds(): string[] {
212
- return Array.from(this.queues.keys());
213
- }
214
-
215
- /**
216
- * 获取所有队列及其数据的快照
217
- * Get snapshot of all queues and their data
218
- * @returns 包含所有队列数据的结果对象 / Result object containing all queue data
219
- */
220
- async getAllQueuesData(): Promise<Record<string, EventMessage[]>> {
221
- const result: Record<string, EventMessage[]> = {};
222
- for (const [id, queue] of this.queues) {
223
- result[id] = await queue.getAll();
224
- }
225
- return result;
226
- }
227
-
228
- /**
229
- * 清空所有队列
230
- * Clear all queues
231
- */
232
- clearAllQueues(): void {
233
- for (const queue of this.queues.values()) {
234
- queue.clear();
235
- }
236
- }
237
- }
@@ -1,52 +0,0 @@
1
- import { BaseStreamQueueInterface, StreamQueueManager } from '../queue/stream_queue';
2
- import { MemorySaver } from './memory/checkpoint';
3
- import { MemoryStreamQueue } from './memory/queue';
4
- import { MemoryThreadsManager } from './memory/threads';
5
- import type { SqliteSaver as SqliteSaverType } from './sqlite/checkpoint';
6
- import { SQLiteThreadsManager } from './sqlite/threads';
7
-
8
- // 所有的适配实现,都请写到这里,通过环境变量进行判断使用哪种方式进行适配
9
-
10
- export const createCheckPointer = async () => {
11
- if (
12
- (process.env.REDIS_URL && process.env.CHECKPOINT_TYPE === 'redis') ||
13
- process.env.CHECKPOINT_TYPE === 'shallow/redis'
14
- ) {
15
- if (process.env.CHECKPOINT_TYPE === 'redis') {
16
- const { RedisSaver } = await import('@langchain/langgraph-checkpoint-redis');
17
- return await RedisSaver.fromUrl(process.env.REDIS_URL!, {
18
- defaultTTL: 60, // TTL in minutes
19
- refreshOnRead: true,
20
- });
21
- }
22
- if (process.env.CHECKPOINT_TYPE === 'shallow/redis') {
23
- const { ShallowRedisSaver } = await import('@langchain/langgraph-checkpoint-redis/shallow');
24
- return await ShallowRedisSaver.fromUrl(process.env.REDIS_URL!);
25
- }
26
- }
27
- if (process.env.SQLITE_DATABASE_URI) {
28
- const { SqliteSaver } = await import('./sqlite/checkpoint');
29
- const db = SqliteSaver.fromConnString(process.env.SQLITE_DATABASE_URI);
30
- return db;
31
- }
32
- return new MemorySaver();
33
- };
34
-
35
- export const createMessageQueue = async () => {
36
- let q: new (id: string) => BaseStreamQueueInterface;
37
- if (process.env.REDIS_URL) {
38
- console.log('Using redis as stream queue');
39
- const { RedisStreamQueue } = await import('./redis/queue');
40
- q = RedisStreamQueue;
41
- } else {
42
- q = MemoryStreamQueue;
43
- }
44
- return new StreamQueueManager(q);
45
- };
46
-
47
- export const createThreadManager = (config: { checkpointer?: SqliteSaverType }) => {
48
- if (process.env.SQLITE_DATABASE_URI && config.checkpointer) {
49
- return new SQLiteThreadsManager(config.checkpointer);
50
- }
51
- return new MemoryThreadsManager();
52
- };
@@ -1,2 +0,0 @@
1
- import { MemorySaver } from '@langchain/langgraph-checkpoint';
2
- export { MemorySaver };
@@ -1,91 +0,0 @@
1
- import { CancelEventMessage, EventMessage } from '../../queue/event_message.js';
2
- import { BaseStreamQueue } from '../../queue/stream_queue.js';
3
- import { BaseStreamQueueInterface } from '../../queue/stream_queue.js';
4
- /** 内存实现的消息队列,用于存储消息 */
5
- export class MemoryStreamQueue extends BaseStreamQueue implements BaseStreamQueueInterface {
6
- private data: EventMessage[] = [];
7
- async push(item: EventMessage): Promise<void> {
8
- const data = this.compressMessages ? ((await this.encodeData(item)) as unknown as EventMessage) : item;
9
- this.data.push(data);
10
- this.emit('dataChange', data);
11
- }
12
-
13
- onDataChange(listener: (data: EventMessage) => void): () => void {
14
- this.on('dataChange', async (item) => {
15
- listener(this.compressMessages ? ((await this.decodeData(item)) as EventMessage) : item);
16
- });
17
- return () => this.off('dataChange', listener);
18
- }
19
-
20
- /**
21
- * 异步生成器:支持 for await...of 方式消费队列数据
22
- */
23
- async *onDataReceive(): AsyncGenerator<EventMessage, void, unknown> {
24
- let queue: EventMessage[] = [];
25
- let pendingResolve: (() => void) | null = null;
26
- let isStreamEnded = false;
27
- const handleData = async (item: EventMessage) => {
28
- const data = this.compressMessages ? ((await this.decodeData(item as any)) as EventMessage) : item;
29
- queue.push(data);
30
- // 检查是否为流结束或错误信号
31
- if (
32
- data.event === '__stream_end__' ||
33
- data.event === '__stream_error__' ||
34
- data.event === '__stream_cancel__'
35
- ) {
36
- setTimeout(() => {
37
- isStreamEnded = true;
38
- if (pendingResolve) {
39
- pendingResolve();
40
- pendingResolve = null;
41
- }
42
- }, 300);
43
-
44
- if (data.event === '__stream_cancel__') {
45
- this.cancel();
46
- }
47
- }
48
-
49
- if (pendingResolve) {
50
- pendingResolve();
51
- pendingResolve = null;
52
- }
53
- };
54
- // todo 这个框架的事件监听的数据返回顺序有误
55
- this.on('dataChange', handleData as any);
56
-
57
- try {
58
- while (!isStreamEnded) {
59
- if (queue.length > 0) {
60
- for (const item of queue) {
61
- yield item;
62
- }
63
- queue = [];
64
- } else {
65
- await new Promise((resolve) => {
66
- pendingResolve = resolve as () => void;
67
- });
68
- }
69
- }
70
- } finally {
71
- this.off('dataChange', handleData as any);
72
- }
73
- }
74
-
75
- async getAll(): Promise<EventMessage[]> {
76
- return this.compressMessages
77
- ? ((await Promise.all(
78
- this.data.map((i) => this.decodeData(i as unknown as string | Uint8Array)),
79
- )) as unknown as EventMessage[])
80
- : this.data;
81
- }
82
-
83
- clear(): void {
84
- this.data = [];
85
- }
86
- public cancelSignal = new AbortController();
87
- cancel(): void {
88
- this.push(new CancelEventMessage());
89
- this.cancelSignal.abort('user cancel this run');
90
- }
91
- }
@@ -1,154 +0,0 @@
1
- import { BaseThreadsManager } from '../../threads/index.js';
2
- import {
3
- Command,
4
- Metadata,
5
- OnConflictBehavior,
6
- Run,
7
- RunStatus,
8
- SortOrder,
9
- Thread,
10
- ThreadSortBy,
11
- ThreadStatus,
12
- } from '@langgraph-js/sdk';
13
-
14
- export class MemoryThreadsManager<ValuesType = unknown> extends BaseThreadsManager {
15
- private threads: Thread<ValuesType>[] = [];
16
-
17
- async create(payload?: {
18
- metadata?: Metadata;
19
- threadId?: string;
20
- ifExists?: OnConflictBehavior;
21
- graphId?: string;
22
- supersteps?: Array<{ updates: Array<{ values: unknown; command?: Command; asNode: string }> }>;
23
- }): Promise<Thread<ValuesType>> {
24
- const threadId = payload?.threadId || crypto.randomUUID();
25
- if (payload?.ifExists === 'raise' && this.threads.some((t) => t.thread_id === threadId)) {
26
- throw new Error(`Thread with ID ${threadId} already exists.`);
27
- }
28
-
29
- const thread: Thread<ValuesType> = {
30
- thread_id: threadId,
31
- created_at: new Date().toISOString(),
32
- updated_at: new Date().toISOString(),
33
- metadata: payload?.metadata || {},
34
- status: 'idle',
35
- values: null as unknown as ValuesType,
36
- interrupts: {},
37
- };
38
- this.threads.push(thread);
39
- return thread;
40
- }
41
-
42
- async search(query?: {
43
- metadata?: Metadata;
44
- limit?: number;
45
- offset?: number;
46
- status?: ThreadStatus;
47
- sortBy?: ThreadSortBy;
48
- sortOrder?: SortOrder;
49
- }): Promise<Thread<ValuesType>[]> {
50
- let filteredThreads = [...this.threads];
51
- if (query?.status) {
52
- filteredThreads = filteredThreads.filter((t) => t.status === query.status);
53
- }
54
-
55
- if (query?.metadata) {
56
- for (const key in query.metadata) {
57
- if (Object.prototype.hasOwnProperty.call(query.metadata, key)) {
58
- filteredThreads = filteredThreads.filter(
59
- (t) => t.metadata && t.metadata[key] === query.metadata?.[key],
60
- );
61
- }
62
- }
63
- }
64
-
65
- if (query?.sortBy) {
66
- filteredThreads.sort((a, b) => {
67
- let aValue: any;
68
- let bValue: any;
69
-
70
- switch (query.sortBy) {
71
- case 'created_at':
72
- aValue = new Date(a.created_at).getTime();
73
- bValue = new Date(b.created_at).getTime();
74
- break;
75
- case 'updated_at':
76
- aValue = new Date(a.updated_at).getTime();
77
- bValue = new Date(b.updated_at).getTime();
78
- break;
79
- default:
80
- return 0;
81
- }
82
-
83
- if (query.sortOrder === 'desc') {
84
- return bValue - aValue;
85
- } else {
86
- return aValue - bValue;
87
- }
88
- });
89
- }
90
-
91
- const offset = query?.offset || 0;
92
- const limit = query?.limit || filteredThreads.length;
93
-
94
- return filteredThreads.slice(offset, offset + limit);
95
- }
96
-
97
- async get(threadId: string): Promise<Thread<ValuesType>> {
98
- const thread = this.threads.find((t) => t.thread_id === threadId);
99
- if (!thread) {
100
- throw new Error(`Thread with ID ${threadId} not found.`);
101
- }
102
- return thread;
103
- }
104
- async set(threadId: string, thread: Partial<Thread<ValuesType>>): Promise<void> {
105
- const index = this.threads.findIndex((t) => t.thread_id === threadId);
106
- if (index === -1) {
107
- throw new Error(`Thread with ID ${threadId} not found.`);
108
- }
109
- this.threads[index] = { ...this.threads[index], ...thread };
110
- }
111
- async delete(threadId: string): Promise<void> {
112
- const initialLength = this.threads.length;
113
- this.threads = this.threads.filter((t) => t.thread_id !== threadId);
114
- if (this.threads.length === initialLength) {
115
- throw new Error(`Thread with ID ${threadId} not found.`);
116
- }
117
- }
118
- runs: Run[] = [];
119
- async createRun(threadId: string, assistantId: string, payload?: { metadata?: Metadata }): Promise<Run> {
120
- const runId = crypto.randomUUID();
121
- const run: Run = {
122
- run_id: runId,
123
- thread_id: threadId,
124
- assistant_id: assistantId,
125
- created_at: new Date().toISOString(),
126
- updated_at: new Date().toISOString(),
127
- status: 'pending',
128
- metadata: payload?.metadata ?? {},
129
- multitask_strategy: 'reject',
130
- };
131
- this.runs.push(run);
132
- return run;
133
- }
134
- async listRuns(
135
- threadId: string,
136
- options?: { limit?: number; offset?: number; status?: RunStatus },
137
- ): Promise<Run[]> {
138
- let filteredRuns = [...this.runs];
139
- if (options?.status) {
140
- filteredRuns = filteredRuns.filter((r) => r.status === options.status);
141
- }
142
- if (options?.limit) {
143
- filteredRuns = filteredRuns.slice(options.offset || 0, (options.offset || 0) + options.limit);
144
- }
145
- return filteredRuns;
146
- }
147
- async updateRun(runId: string, run: Partial<Run>): Promise<void> {
148
- const index = this.runs.findIndex((r) => r.run_id === runId);
149
- if (index === -1) {
150
- throw new Error(`Run with ID ${runId} not found.`);
151
- }
152
- this.runs[index] = { ...this.runs[index], ...run };
153
- }
154
- }
@@ -1,148 +0,0 @@
1
- import { CancelEventMessage, EventMessage } from '../../queue/event_message.js';
2
- import { BaseStreamQueue } from '../../queue/stream_queue.js';
3
- import { BaseStreamQueueInterface } from '../../queue/stream_queue.js';
4
- import { createClient, RedisClientType } from 'redis';
5
-
6
- /**
7
- * Redis 实现的消息队列,用于存储消息
8
- */
9
- export class RedisStreamQueue extends BaseStreamQueue implements BaseStreamQueueInterface {
10
- static redis: RedisClientType = createClient({ url: process.env.REDIS_URL! });
11
- static subscriberRedis: RedisClientType = createClient({ url: process.env.REDIS_URL! });
12
- private redis: RedisClientType;
13
- private subscriberRedis: RedisClientType;
14
- private queueKey: string;
15
- private channelKey: string;
16
- private isConnected = false;
17
- public cancelSignal: AbortController;
18
-
19
- constructor(readonly id: string = 'default') {
20
- super(id, true);
21
- this.queueKey = `queue:${this.id}`;
22
- this.channelKey = `channel:${this.id}`;
23
- this.redis = RedisStreamQueue.redis;
24
- this.subscriberRedis = RedisStreamQueue.subscriberRedis;
25
- this.cancelSignal = new AbortController();
26
-
27
- // 连接 Redis 客户端
28
- this.redis.connect();
29
- this.subscriberRedis.connect();
30
- this.isConnected = true;
31
- }
32
-
33
- /**
34
- * 推送消息到 Redis 队列
35
- */
36
- async push(item: EventMessage): Promise<void> {
37
- const data = await this.encodeData(item);
38
- const serializedData = Buffer.from(data);
39
-
40
- // 推送到队列
41
- await this.redis.lPush(this.queueKey, serializedData);
42
-
43
- // 设置队列 TTL 为 300 秒
44
- await this.redis.expire(this.queueKey, 300);
45
-
46
- // 发布到频道通知有新数据
47
- await this.redis.publish(this.channelKey, serializedData);
48
-
49
- this.emit('dataChange', data);
50
- }
51
-
52
- /**
53
- * 异步生成器:支持 for await...of 方式消费队列数据
54
- */
55
- async *onDataReceive(): AsyncGenerator<EventMessage, void, unknown> {
56
- let queue: EventMessage[] = [];
57
- let pendingResolve: (() => void) | null = null;
58
- let isStreamEnded = false;
59
- const handleMessage = async (message: string) => {
60
- const data = (await this.decodeData(message)) as EventMessage;
61
- queue.push(data);
62
- // 检查是否为流结束或错误信号
63
- if (
64
- data.event === '__stream_end__' ||
65
- data.event === '__stream_error__' ||
66
- data.event === '__stream_cancel__'
67
- ) {
68
- setTimeout(() => {
69
- isStreamEnded = true;
70
- if (pendingResolve) {
71
- pendingResolve();
72
- pendingResolve = null;
73
- }
74
- }, 300);
75
-
76
- if (data.event === '__stream_cancel__') {
77
- this.cancel();
78
- }
79
- }
80
-
81
- if (pendingResolve) {
82
- pendingResolve();
83
- pendingResolve = null;
84
- }
85
- };
86
-
87
- // 订阅 Redis 频道
88
- await this.subscriberRedis.subscribe(this.channelKey, (message) => {
89
- handleMessage(message);
90
- });
91
-
92
- try {
93
- while (!isStreamEnded) {
94
- if (queue.length > 0) {
95
- for (const item of queue) {
96
- yield item;
97
- }
98
- queue = [];
99
- } else {
100
- await new Promise((resolve) => {
101
- pendingResolve = resolve as () => void;
102
- });
103
- }
104
- }
105
- } finally {
106
- await this.subscriberRedis.unsubscribe(this.channelKey);
107
- }
108
- }
109
-
110
- /**
111
- * 获取队列中的所有数据
112
- */
113
- async getAll(): Promise<EventMessage[]> {
114
- const data = await this.redis.lRange(this.queueKey, 0, -1);
115
-
116
- if (!data || data.length === 0) {
117
- return [];
118
- }
119
-
120
- if (this.compressMessages) {
121
- return (await Promise.all(
122
- data.map(async (item: string) => {
123
- const parsed = JSON.parse(item) as EventMessage;
124
- return (await this.decodeData(parsed as any)) as EventMessage;
125
- }),
126
- )) as EventMessage[];
127
- } else {
128
- return data.map((item: string) => JSON.parse(item) as EventMessage);
129
- }
130
- }
131
-
132
- /**
133
- * 清空队列
134
- */
135
- clear(): void {
136
- if (this.isConnected) {
137
- this.redis.del(this.queueKey);
138
- }
139
- }
140
-
141
- /**
142
- * 取消操作
143
- */
144
- cancel(): void {
145
- this.push(new CancelEventMessage());
146
- this.cancelSignal.abort('user cancel this run');
147
- }
148
- }