@motiadev/adapter-redis-streams 0.13.0 → 0.13.1-beta.163-660633

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 CHANGED
@@ -1,21 +1,93 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Motia
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 all
13
- 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 THE
21
- SOFTWARE.
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject
14
+ to the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor's trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that organization.
84
+ **control** means ownership of substantially all the assets of an entity, or the
85
+ power to direct its management and policies by vote, contract, or otherwise.
86
+ Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md CHANGED
@@ -173,5 +173,5 @@ If you experience slow operations:
173
173
 
174
174
  ## License
175
175
 
176
- MIT
176
+ [Elastic License 2.0 (ELv2)](https://github.com/MotiaDev/motia/blob/main/LICENSE)
177
177
 
@@ -0,0 +1,4 @@
1
+ import { RedisStreamAdapterConfig, RedisStreamAdapterOptions } from "./types.mjs";
2
+ import { RedisStreamAdapter } from "./redis-stream-adapter.mjs";
3
+ import { RedisStreamAdapterManager } from "./redis-stream-adapter-manager.mjs";
4
+ export { RedisStreamAdapter, type RedisStreamAdapterConfig, RedisStreamAdapterManager, type RedisStreamAdapterOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import { RedisStreamAdapter } from "./redis-stream-adapter.mjs";
2
+ import { RedisStreamAdapterManager } from "./redis-stream-adapter-manager.mjs";
3
+
4
+ export { RedisStreamAdapter, RedisStreamAdapterManager };
@@ -0,0 +1,19 @@
1
+ import { RedisStreamAdapterOptions } from "./types.mjs";
2
+ import { StreamAdapter, StreamAdapterManager } from "@motiadev/core";
3
+ import { RedisClientOptions, RedisClientType } from "redis";
4
+
5
+ //#region src/redis-stream-adapter-manager.d.ts
6
+ declare class RedisStreamAdapterManager implements StreamAdapterManager {
7
+ private client;
8
+ private connected;
9
+ private isExternalClient;
10
+ private config;
11
+ constructor(redisConnection: RedisClientType | RedisClientOptions, options?: RedisStreamAdapterOptions);
12
+ private connect;
13
+ createStream<TData>(streamName: string): StreamAdapter<TData>;
14
+ getClient(): RedisClientType;
15
+ shutdown(): Promise<void>;
16
+ }
17
+ //#endregion
18
+ export { RedisStreamAdapterManager };
19
+ //# sourceMappingURL=redis-stream-adapter-manager.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-stream-adapter-manager.d.mts","names":[],"sources":["../src/redis-stream-adapter-manager.ts"],"sourcesContent":[],"mappings":";;;;;cASa,yBAAA,YAAqC;;EAArC,QAAA,SAAA;EAMkB,QAAA,gBAAA;EAAkB,QAAA,MAAA;EAA8B,WAAA,CAAA,eAAA,EAAhD,eAAgD,GAA9B,kBAA8B,EAAA,OAAA,CAAA,EAAA,yBAAA;EAmDtB,QAAA,OAAA;EAAd,YAAA,CAAA,KAAA,CAAA,CAAA,UAAA,EAAA,MAAA,CAAA,EAAA,aAAA,CAAc,KAAd,CAAA;EAI5B,SAAA,CAAA,CAAA,EAAA,eAAA;EAIK,QAAA,CAAA,CAAA,EAAA,OAAA,CAAA,IAAA,CAAA"}
@@ -0,0 +1,64 @@
1
+ import { RedisStreamAdapter } from "./redis-stream-adapter.mjs";
2
+ import { createClient } from "redis";
3
+
4
+ //#region src/redis-stream-adapter-manager.ts
5
+ function isRedisClient(input) {
6
+ return typeof input === "object" && "isOpen" in input && "connect" in input;
7
+ }
8
+ var RedisStreamAdapterManager = class {
9
+ constructor(redisConnection, options) {
10
+ this.connected = false;
11
+ this.config = {
12
+ keyPrefix: options?.keyPrefix || "motia:stream:",
13
+ socketKeepAlive: options?.socketKeepAlive ?? true
14
+ };
15
+ if (isRedisClient(redisConnection)) {
16
+ this.client = redisConnection;
17
+ this.isExternalClient = true;
18
+ this.connected = this.client.isOpen;
19
+ } else {
20
+ const config = {
21
+ ...redisConnection,
22
+ socket: {
23
+ ...redisConnection.socket || {},
24
+ keepAlive: this.config.socketKeepAlive,
25
+ noDelay: true
26
+ }
27
+ };
28
+ this.isExternalClient = false;
29
+ this.client = createClient(config);
30
+ this.client.on("error", (err) => {
31
+ console.error("[Redis Stream Manager] Client error:", err);
32
+ });
33
+ this.client.on("connect", () => {
34
+ this.connected = true;
35
+ });
36
+ this.client.on("disconnect", () => {
37
+ console.warn("[Redis Stream Manager] Disconnected");
38
+ this.connected = false;
39
+ });
40
+ this.connect();
41
+ }
42
+ }
43
+ async connect() {
44
+ if (!this.connected && !this.isExternalClient) try {
45
+ await this.client.connect();
46
+ } catch (error) {
47
+ console.error("[Redis Stream Manager] Failed to connect:", error);
48
+ throw error;
49
+ }
50
+ }
51
+ createStream(streamName) {
52
+ return new RedisStreamAdapter(streamName, this.config, this.client);
53
+ }
54
+ getClient() {
55
+ return this.client;
56
+ }
57
+ async shutdown() {
58
+ if (!this.isExternalClient && this.client.isOpen) await this.client.quit();
59
+ }
60
+ };
61
+
62
+ //#endregion
63
+ export { RedisStreamAdapterManager };
64
+ //# sourceMappingURL=redis-stream-adapter-manager.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-stream-adapter-manager.mjs","names":["config: RedisClientOptions"],"sources":["../src/redis-stream-adapter-manager.ts"],"sourcesContent":["import type { StreamAdapter, StreamAdapterManager } from '@motiadev/core'\nimport { createClient, type RedisClientOptions, type RedisClientType } from 'redis'\nimport { RedisStreamAdapter } from './redis-stream-adapter'\nimport type { RedisStreamAdapterConfig, RedisStreamAdapterOptions } from './types'\n\nfunction isRedisClient(input: RedisClientType | RedisClientOptions): input is RedisClientType {\n return typeof input === 'object' && 'isOpen' in input && 'connect' in input\n}\n\nexport class RedisStreamAdapterManager implements StreamAdapterManager {\n private client: RedisClientType\n private connected = false\n private isExternalClient: boolean\n private config: RedisStreamAdapterConfig\n\n constructor(redisConnection: RedisClientType | RedisClientOptions, options?: RedisStreamAdapterOptions) {\n this.config = {\n keyPrefix: options?.keyPrefix || 'motia:stream:',\n socketKeepAlive: options?.socketKeepAlive ?? true,\n }\n\n if (isRedisClient(redisConnection)) {\n this.client = redisConnection\n this.isExternalClient = true\n this.connected = this.client.isOpen\n } else {\n const config: RedisClientOptions = {\n ...redisConnection,\n socket: {\n ...(redisConnection.socket || {}),\n keepAlive: this.config.socketKeepAlive,\n noDelay: true,\n },\n } as RedisClientOptions\n this.isExternalClient = false\n\n this.client = createClient(config) as RedisClientType\n\n this.client.on('error', (err) => {\n console.error('[Redis Stream Manager] Client error:', err)\n })\n\n this.client.on('connect', () => {\n this.connected = true\n })\n\n this.client.on('disconnect', () => {\n console.warn('[Redis Stream Manager] Disconnected')\n this.connected = false\n })\n\n this.connect()\n }\n }\n\n private async connect(): Promise<void> {\n if (!this.connected && !this.isExternalClient) {\n try {\n await this.client.connect()\n } catch (error) {\n console.error('[Redis Stream Manager] Failed to connect:', error)\n throw error\n }\n }\n }\n\n createStream<TData>(streamName: string): StreamAdapter<TData> {\n return new RedisStreamAdapter<TData>(streamName, this.config, this.client)\n }\n\n getClient(): RedisClientType {\n return this.client\n }\n\n async shutdown(): Promise<void> {\n if (!this.isExternalClient && this.client.isOpen) {\n await this.client.quit()\n }\n }\n}\n"],"mappings":";;;;AAKA,SAAS,cAAc,OAAuE;AAC5F,QAAO,OAAO,UAAU,YAAY,YAAY,SAAS,aAAa;;AAGxE,IAAa,4BAAb,MAAuE;CAMrE,YAAY,iBAAuD,SAAqC;mBAJpF;AAKlB,OAAK,SAAS;GACZ,WAAW,SAAS,aAAa;GACjC,iBAAiB,SAAS,mBAAmB;GAC9C;AAED,MAAI,cAAc,gBAAgB,EAAE;AAClC,QAAK,SAAS;AACd,QAAK,mBAAmB;AACxB,QAAK,YAAY,KAAK,OAAO;SACxB;GACL,MAAMA,SAA6B;IACjC,GAAG;IACH,QAAQ;KACN,GAAI,gBAAgB,UAAU,EAAE;KAChC,WAAW,KAAK,OAAO;KACvB,SAAS;KACV;IACF;AACD,QAAK,mBAAmB;AAExB,QAAK,SAAS,aAAa,OAAO;AAElC,QAAK,OAAO,GAAG,UAAU,QAAQ;AAC/B,YAAQ,MAAM,wCAAwC,IAAI;KAC1D;AAEF,QAAK,OAAO,GAAG,iBAAiB;AAC9B,SAAK,YAAY;KACjB;AAEF,QAAK,OAAO,GAAG,oBAAoB;AACjC,YAAQ,KAAK,sCAAsC;AACnD,SAAK,YAAY;KACjB;AAEF,QAAK,SAAS;;;CAIlB,MAAc,UAAyB;AACrC,MAAI,CAAC,KAAK,aAAa,CAAC,KAAK,iBAC3B,KAAI;AACF,SAAM,KAAK,OAAO,SAAS;WACpB,OAAO;AACd,WAAQ,MAAM,6CAA6C,MAAM;AACjE,SAAM;;;CAKZ,aAAoB,YAA0C;AAC5D,SAAO,IAAI,mBAA0B,YAAY,KAAK,QAAQ,KAAK,OAAO;;CAG5E,YAA6B;AAC3B,SAAO,KAAK;;CAGd,MAAM,WAA0B;AAC9B,MAAI,CAAC,KAAK,oBAAoB,KAAK,OAAO,OACxC,OAAM,KAAK,OAAO,MAAM"}
@@ -0,0 +1,28 @@
1
+ import { RedisStreamAdapterConfig } from "./types.mjs";
2
+ import { BaseStreamItem, StateStreamEvent, StateStreamEventChannel, StreamAdapter, StreamQueryFilter } from "@motiadev/core";
3
+ import { RedisClientType } from "redis";
4
+
5
+ //#region src/redis-stream-adapter.d.ts
6
+ declare class RedisStreamAdapter<TData> extends StreamAdapter<TData> {
7
+ private client;
8
+ private subClient?;
9
+ private keyPrefix;
10
+ private groupPrefix;
11
+ private subscriptions;
12
+ constructor(streamName: string, config: RedisStreamAdapterConfig, sharedClient: RedisClientType);
13
+ private makeGroupKey;
14
+ private makeChannelKey;
15
+ get(groupId: string, id: string): Promise<BaseStreamItem<TData> | null>;
16
+ set(groupId: string, id: string, data: TData): Promise<BaseStreamItem<TData>>;
17
+ delete(groupId: string, id: string): Promise<BaseStreamItem<TData> | null>;
18
+ getGroup(groupId: string): Promise<BaseStreamItem<TData>[]>;
19
+ send<T>(channel: StateStreamEventChannel, event: StateStreamEvent<T>): Promise<void>;
20
+ subscribe<T>(channel: StateStreamEventChannel, handler: (event: StateStreamEvent<T>) => void | Promise<void>): Promise<void>;
21
+ unsubscribe(channel: StateStreamEventChannel): Promise<void>;
22
+ clear(groupId: string): Promise<void>;
23
+ query(groupId: string, filter: StreamQueryFilter<TData>): Promise<BaseStreamItem<TData>[]>;
24
+ cleanup(): Promise<void>;
25
+ }
26
+ //#endregion
27
+ export { RedisStreamAdapter };
28
+ //# sourceMappingURL=redis-stream-adapter.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-stream-adapter.d.mts","names":[],"sources":["../src/redis-stream-adapter.ts"],"sourcesContent":[],"mappings":";;;;;cAkBa,kCAAkC,cAAc;EAAhD,QAAA,MAAA;EAAgD,QAAA,SAAA;EAOnB,QAAA,SAAA;EAAwC,QAAA,WAAA;EAkBjB,QAAA,aAAA;EAAf,WAAA,CAAA,UAAA,EAAA,MAAA,EAAA,MAAA,EAlBR,wBAkBQ,EAAA,YAAA,EAlBgC,eAkBhC;EAAR,QAAA,YAAA;EAMK,QAAA,cAAA;EAA+B,GAAA,CAAA,OAAA,EAAA,MAAA,EAAA,EAAA,EAAA,MAAA,CAAA,EANpC,OAMoC,CAN5B,cAM4B,CANb,KAMa,CAAA,GAAA,IAAA,CAAA;EAAf,GAAA,CAAA,OAAA,EAAA,MAAA,EAAA,EAAA,EAAA,MAAA,EAAA,IAAA,EAAhB,KAAgB,CAAA,EAAR,OAAQ,CAAA,cAAA,CAAe,KAAf,CAAA,CAAA;EAAR,MAAA,CAAA,OAAA,EAAA,MAAA,EAAA,EAAA,EAAA,MAAA,CAAA,EAqBV,OArBU,CAqBF,cArBE,CAqBa,KArBb,CAAA,GAAA,IAAA,CAAA;EAqBa,QAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EAajC,OAbiC,CAazB,cAbyB,CAaV,KAbU,CAAA,EAAA,CAAA;EAAf,IAAA,CAAA,CAAA,CAAA,CAAA,OAAA,EA0B5B,uBA1B4B,EAAA,KAAA,EA0BI,gBA1BJ,CA0BqB,CA1BrB,CAAA,CAAA,EA0B0B,OA1B1B,CAAA,IAAA,CAAA;EAAR,SAAA,CAAA,CAAA,CAAA,CAAA,OAAA,EAgChC,uBAhCgC,EAAA,OAAA,EAAA,CAAA,KAAA,EAiCxB,gBAjCwB,CAiCP,CAjCO,CAAA,EAAA,GAAA,IAAA,GAiCO,OAjCP,CAAA,IAAA,CAAA,CAAA,EAkCxC,OAlCwC,CAAA,IAAA,CAAA;EAaa,WAAA,CAAA,OAAA,EA8D7B,uBA9D6B,CAAA,EA8DH,OA9DG,CAAA,IAAA,CAAA;EAAf,KAAA,CAAA,OAAA,EAAA,MAAA,CAAA,EA2EX,OA3EW,CAAA,IAAA,CAAA;EAAR,KAAA,CAAA,OAAA,EAAA,MAAA,EAAA,MAAA,EAgFI,iBAhFJ,CAgFsB,KAhFtB,CAAA,CAAA,EAgF+B,OAhF/B,CAgFuC,cAhFvC,CAgFsD,KAhFtD,CAAA,EAAA,CAAA;EAaV,OAAA,CAAA,CAAA,EAqGN,OArGM,CAAA,IAAA,CAAA"}
@@ -0,0 +1,142 @@
1
+ import { StreamAdapter } from "@motiadev/core";
2
+ import { createClient } from "redis";
3
+
4
+ //#region src/redis-stream-adapter.ts
5
+ var RedisStreamAdapter = class extends StreamAdapter {
6
+ constructor(streamName, config, sharedClient) {
7
+ super(streamName);
8
+ this.subscriptions = /* @__PURE__ */ new Map();
9
+ this.keyPrefix = config.keyPrefix || "motia:stream:";
10
+ this.groupPrefix = `${this.keyPrefix}${streamName}:group:`;
11
+ this.client = sharedClient;
12
+ }
13
+ makeGroupKey(groupId) {
14
+ return `${this.groupPrefix}${groupId}`;
15
+ }
16
+ makeChannelKey(channel) {
17
+ return channel.id ? `motia:stream:events:${this.streamName}:${channel.groupId}:${channel.id}` : `motia:stream:events:${this.streamName}:${channel.groupId}`;
18
+ }
19
+ async get(groupId, id) {
20
+ const hashKey = this.makeGroupKey(groupId);
21
+ const value = await this.client.hGet(hashKey, id);
22
+ return value ? JSON.parse(value) : null;
23
+ }
24
+ async set(groupId, id, data) {
25
+ const hashKey = this.makeGroupKey(groupId);
26
+ const dataWithTimestamp = data;
27
+ const item = {
28
+ ...data,
29
+ id,
30
+ _createdAt: dataWithTimestamp._createdAt || Date.now()
31
+ };
32
+ const itemJson = JSON.stringify(item);
33
+ const eventType = await this.client.hExists(hashKey, id) ? "update" : "create";
34
+ await Promise.all([this.client.hSet(hashKey, id, itemJson), this.send({
35
+ groupId,
36
+ id
37
+ }, {
38
+ type: eventType,
39
+ data: item
40
+ })]);
41
+ return item;
42
+ }
43
+ async delete(groupId, id) {
44
+ const hashKey = this.makeGroupKey(groupId);
45
+ const value = await this.client.hGet(hashKey, id);
46
+ if (!value) return null;
47
+ const item = JSON.parse(value);
48
+ await Promise.all([this.client.hDel(hashKey, id), this.send({
49
+ groupId,
50
+ id
51
+ }, {
52
+ type: "delete",
53
+ data: item
54
+ })]);
55
+ return item;
56
+ }
57
+ async getGroup(groupId) {
58
+ const hashKey = this.makeGroupKey(groupId);
59
+ const values = await this.client.hGetAll(hashKey);
60
+ return Object.values(values).map((v) => JSON.parse(v)).sort((a, b) => {
61
+ return (a._createdAt || 0) - (b._createdAt || 0);
62
+ });
63
+ }
64
+ async send(channel, event) {
65
+ const channelKey = this.makeChannelKey(channel);
66
+ await this.client.publish(channelKey, JSON.stringify(event));
67
+ }
68
+ async subscribe(channel, handler) {
69
+ const channelKey = this.makeChannelKey(channel);
70
+ if (!this.subClient) {
71
+ const socketConfig = this.client.options?.socket;
72
+ const keepAliveValue = socketConfig?.keepAlive;
73
+ this.subClient = createClient({
74
+ socket: {
75
+ host: socketConfig?.host || "localhost",
76
+ port: socketConfig?.port || 6379,
77
+ keepAlive: keepAliveValue,
78
+ noDelay: true
79
+ },
80
+ password: this.client.options?.password,
81
+ username: this.client.options?.username,
82
+ database: this.client.options?.database || 0
83
+ });
84
+ this.subClient.on("error", (err) => {
85
+ console.error("[Redis Stream] Sub client error:", err);
86
+ });
87
+ await this.subClient.connect();
88
+ }
89
+ this.subscriptions.set(channelKey, handler);
90
+ const subClient = this.subClient;
91
+ if (!subClient) return;
92
+ await subClient.subscribe(channelKey, async (message) => {
93
+ try {
94
+ await handler(JSON.parse(message));
95
+ } catch (error) {
96
+ console.error("[Redis Stream] Error processing subscription message:", error);
97
+ }
98
+ });
99
+ }
100
+ async unsubscribe(channel) {
101
+ if (!this.subClient) return;
102
+ const channelKey = this.makeChannelKey(channel);
103
+ this.subscriptions.delete(channelKey);
104
+ try {
105
+ await this.subClient.unsubscribe(channelKey);
106
+ } catch (error) {
107
+ console.error("[Redis Stream] Error unsubscribing:", error);
108
+ }
109
+ }
110
+ async clear(groupId) {
111
+ const hashKey = this.makeGroupKey(groupId);
112
+ await this.client.del(hashKey);
113
+ }
114
+ async query(groupId, filter) {
115
+ let items = await this.getGroup(groupId);
116
+ if (filter.where) {
117
+ const where = filter.where;
118
+ items = items.filter((item) => {
119
+ return Object.entries(where).every(([key, value]) => {
120
+ return item[key] === value;
121
+ });
122
+ });
123
+ }
124
+ if (filter.orderBy) items.sort((a, b) => {
125
+ const orderKey = filter.orderBy;
126
+ const aVal = a[orderKey];
127
+ const bVal = b[orderKey];
128
+ const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
129
+ return filter.orderDirection === "desc" ? -comparison : comparison;
130
+ });
131
+ if (filter.offset) items = items.slice(filter.offset);
132
+ if (filter.limit) items = items.slice(0, filter.limit);
133
+ return items;
134
+ }
135
+ async cleanup() {
136
+ this.subscriptions.clear();
137
+ }
138
+ };
139
+
140
+ //#endregion
141
+ export { RedisStreamAdapter };
142
+ //# sourceMappingURL=redis-stream-adapter.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis-stream-adapter.mjs","names":["item: StreamItemWithTimestamp<TData>"],"sources":["../src/redis-stream-adapter.ts"],"sourcesContent":["import type { BaseStreamItem, StateStreamEvent, StateStreamEventChannel } from '@motiadev/core'\nimport { StreamAdapter, type StreamQueryFilter } from '@motiadev/core'\nimport { createClient, type RedisClientOptions, type RedisClientType } from 'redis'\nimport type { RedisStreamAdapterConfig } from './types'\n\ntype StreamItemWithTimestamp<TData> = BaseStreamItem<TData> & {\n _createdAt?: number\n}\n\ntype RedisSocketConfig = {\n host?: string\n port?: number\n keepAlive?: boolean\n noDelay?: boolean\n}\n\ntype EventHandler<T> = (event: StateStreamEvent<T>) => void | Promise<void>\n\nexport class RedisStreamAdapter<TData> extends StreamAdapter<TData> {\n private client: RedisClientType\n private subClient?: RedisClientType\n private keyPrefix: string\n private groupPrefix: string\n private subscriptions: Map<string, EventHandler<unknown>> = new Map()\n\n constructor(streamName: string, config: RedisStreamAdapterConfig, sharedClient: RedisClientType) {\n super(streamName)\n this.keyPrefix = config.keyPrefix || 'motia:stream:'\n this.groupPrefix = `${this.keyPrefix}${streamName}:group:`\n\n this.client = sharedClient\n }\n\n private makeGroupKey(groupId: string): string {\n return `${this.groupPrefix}${groupId}`\n }\n\n private makeChannelKey(channel: StateStreamEventChannel): string {\n return channel.id\n ? `motia:stream:events:${this.streamName}:${channel.groupId}:${channel.id}`\n : `motia:stream:events:${this.streamName}:${channel.groupId}`\n }\n\n async get(groupId: string, id: string): Promise<BaseStreamItem<TData> | null> {\n const hashKey = this.makeGroupKey(groupId)\n const value = await this.client.hGet(hashKey, id)\n return value ? JSON.parse(value) : null\n }\n\n async set(groupId: string, id: string, data: TData): Promise<BaseStreamItem<TData>> {\n const hashKey = this.makeGroupKey(groupId)\n const dataWithTimestamp = data as StreamItemWithTimestamp<TData>\n const item: StreamItemWithTimestamp<TData> = {\n ...data,\n id,\n _createdAt: dataWithTimestamp._createdAt || Date.now(),\n }\n const itemJson = JSON.stringify(item)\n\n const existed = await this.client.hExists(hashKey, id)\n const eventType = existed ? 'update' : 'create'\n\n await Promise.all([\n this.client.hSet(hashKey, id, itemJson),\n this.send({ groupId, id }, { type: eventType, data: item }),\n ])\n\n return item\n }\n\n async delete(groupId: string, id: string): Promise<BaseStreamItem<TData> | null> {\n const hashKey = this.makeGroupKey(groupId)\n const value = await this.client.hGet(hashKey, id)\n\n if (!value) return null\n\n const item = JSON.parse(value) as BaseStreamItem<TData>\n\n await Promise.all([this.client.hDel(hashKey, id), this.send({ groupId, id }, { type: 'delete', data: item })])\n\n return item\n }\n\n async getGroup(groupId: string): Promise<BaseStreamItem<TData>[]> {\n const hashKey = this.makeGroupKey(groupId)\n const values = await this.client.hGetAll(hashKey)\n\n const items = Object.values(values).map((v) => JSON.parse(v) as StreamItemWithTimestamp<TData>)\n\n return items.sort((a, b) => {\n const aTime = a._createdAt || 0\n const bTime = b._createdAt || 0\n return aTime - bTime\n })\n }\n\n async send<T>(channel: StateStreamEventChannel, event: StateStreamEvent<T>): Promise<void> {\n const channelKey = this.makeChannelKey(channel)\n await this.client.publish(channelKey, JSON.stringify(event))\n }\n\n async subscribe<T>(\n channel: StateStreamEventChannel,\n handler: (event: StateStreamEvent<T>) => void | Promise<void>,\n ): Promise<void> {\n const channelKey = this.makeChannelKey(channel)\n\n if (!this.subClient) {\n const socketConfig = this.client.options?.socket as RedisSocketConfig | undefined\n const keepAliveValue = socketConfig?.keepAlive\n const clientConfig: RedisClientOptions = {\n socket: {\n host: socketConfig?.host || 'localhost',\n port: socketConfig?.port || 6379,\n keepAlive: keepAliveValue,\n noDelay: true,\n },\n password: this.client.options?.password,\n username: this.client.options?.username,\n database: this.client.options?.database || 0,\n }\n this.subClient = createClient(clientConfig) as RedisClientType\n\n this.subClient.on('error', (err) => {\n console.error('[Redis Stream] Sub client error:', err)\n })\n\n await this.subClient.connect()\n }\n\n this.subscriptions.set(channelKey, handler as EventHandler<unknown>)\n\n const subClient = this.subClient\n if (!subClient) return\n\n await subClient.subscribe(channelKey, async (message) => {\n try {\n const event = JSON.parse(message) as StateStreamEvent<T>\n await handler(event)\n } catch (error) {\n console.error('[Redis Stream] Error processing subscription message:', error)\n }\n })\n }\n\n async unsubscribe(channel: StateStreamEventChannel): Promise<void> {\n if (!this.subClient) return\n\n const channelKey = this.makeChannelKey(channel)\n this.subscriptions.delete(channelKey)\n\n try {\n await this.subClient.unsubscribe(channelKey)\n } catch (error) {\n console.error('[Redis Stream] Error unsubscribing:', error)\n }\n }\n\n async clear(groupId: string): Promise<void> {\n const hashKey = this.makeGroupKey(groupId)\n await this.client.del(hashKey)\n }\n\n async query(groupId: string, filter: StreamQueryFilter<TData>): Promise<BaseStreamItem<TData>[]> {\n let items = await this.getGroup(groupId)\n\n if (filter.where) {\n const where = filter.where\n items = items.filter((item) => {\n return Object.entries(where).every(([key, value]) => {\n const itemKey = key as keyof BaseStreamItem<TData>\n return item[itemKey] === value\n })\n })\n }\n\n if (filter.orderBy) {\n items.sort((a, b) => {\n const orderKey = filter.orderBy as keyof BaseStreamItem<TData>\n const aVal = a[orderKey]\n const bVal = b[orderKey]\n const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0\n return filter.orderDirection === 'desc' ? -comparison : comparison\n })\n }\n\n if (filter.offset) {\n items = items.slice(filter.offset)\n }\n\n if (filter.limit) {\n items = items.slice(0, filter.limit)\n }\n\n return items\n }\n\n async cleanup(): Promise<void> {\n this.subscriptions.clear()\n }\n}\n"],"mappings":";;;;AAkBA,IAAa,qBAAb,cAA+C,cAAqB;CAOlE,YAAY,YAAoB,QAAkC,cAA+B;AAC/F,QAAM,WAAW;uCAHyC,IAAI,KAAK;AAInE,OAAK,YAAY,OAAO,aAAa;AACrC,OAAK,cAAc,GAAG,KAAK,YAAY,WAAW;AAElD,OAAK,SAAS;;CAGhB,AAAQ,aAAa,SAAyB;AAC5C,SAAO,GAAG,KAAK,cAAc;;CAG/B,AAAQ,eAAe,SAA0C;AAC/D,SAAO,QAAQ,KACX,uBAAuB,KAAK,WAAW,GAAG,QAAQ,QAAQ,GAAG,QAAQ,OACrE,uBAAuB,KAAK,WAAW,GAAG,QAAQ;;CAGxD,MAAM,IAAI,SAAiB,IAAmD;EAC5E,MAAM,UAAU,KAAK,aAAa,QAAQ;EAC1C,MAAM,QAAQ,MAAM,KAAK,OAAO,KAAK,SAAS,GAAG;AACjD,SAAO,QAAQ,KAAK,MAAM,MAAM,GAAG;;CAGrC,MAAM,IAAI,SAAiB,IAAY,MAA6C;EAClF,MAAM,UAAU,KAAK,aAAa,QAAQ;EAC1C,MAAM,oBAAoB;EAC1B,MAAMA,OAAuC;GAC3C,GAAG;GACH;GACA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AW,OAAO;GACxB,MAAM,OAAO,EAAE;GACf,MAAM,OAAO,EAAE;GACf,MAAM,aAAa,OAAO,OAAO,KAAK,OAAO,OAAO,IAAI;AACxD,UAAO,OAAO,mBAAmB,SAAS,CAAC,aAAa;IACxD;AAGJ,MAAI,OAAO,OACT,SAAQ,MAAM,MAAM,OAAO,OAAO;AAGpC,MAAI,OAAO,MACT,SAAQ,MAAM,MAAM,GAAG,OAAO,MAAM;AAGtC,SAAO;;CAGT,MAAM,UAAyB;AAC7B,OAAK,cAAc,OAAO"}
@@ -0,0 +1,12 @@
1
+ //#region src/types.d.ts
2
+ interface RedisStreamAdapterConfig {
3
+ keyPrefix?: string;
4
+ socketKeepAlive?: boolean;
5
+ }
6
+ interface RedisStreamAdapterOptions {
7
+ keyPrefix?: string;
8
+ socketKeepAlive?: boolean;
9
+ }
10
+ //#endregion
11
+ export { RedisStreamAdapterConfig, RedisStreamAdapterOptions };
12
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";UAAiB,wBAAA;EAAA,SAAA,CAAA,EAAA,MAAA;EAKA,eAAA,CAAA,EAAA,OAAA;;UAAA,yBAAA"}
package/package.json CHANGED
@@ -1,23 +1,27 @@
1
1
  {
2
2
  "name": "@motiadev/adapter-redis-streams",
3
3
  "description": "Redis streams adapter for Motia framework, enabling distributed stream management with real-time updates.",
4
- "main": "dist/index.js",
5
- "types": "dist/index.d.ts",
6
- "version": "0.13.0",
4
+ "type": "module",
5
+ "main": "dist/index.mjs",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.mts",
8
+ "version": "0.13.1-beta.163-660633",
7
9
  "dependencies": {
8
10
  "redis": "^5.9.0",
9
- "@motiadev/core": "0.13.0"
11
+ "@motiadev/core": "0.13.1-beta.163-660633"
10
12
  },
11
13
  "devDependencies": {
12
14
  "@types/node": "^22.10.2",
15
+ "tsdown": "^0.16.6",
13
16
  "typescript": "^5.7.2"
14
17
  },
15
18
  "peerDependencies": {
16
19
  "@motiadev/core": "^0.8.0"
17
20
  },
18
21
  "scripts": {
19
- "build": "rm -rf dist && tsc",
22
+ "build": "tsdown",
23
+ "dev": "tsdown --watch",
20
24
  "lint": "biome check .",
21
- "watch": "tsc --watch"
25
+ "clean": "rm -rf dist"
22
26
  }
23
27
  }
@@ -0,0 +1,17 @@
1
+ import { defineConfig } from 'tsdown'
2
+
3
+ export default defineConfig({
4
+ entry: {
5
+ index: './src/index.ts',
6
+ },
7
+ format: 'esm',
8
+ platform: 'node',
9
+ external: ['@motiadev/core', 'redis'],
10
+ dts: {
11
+ build: true,
12
+ },
13
+ clean: true,
14
+ outDir: 'dist',
15
+ sourcemap: true,
16
+ unbundle: true,
17
+ })
package/dist/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export { RedisStreamAdapter } from './redis-stream-adapter';
2
- export { RedisStreamAdapterManager } from './redis-stream-adapter-manager';
3
- export type { RedisStreamAdapterConfig, RedisStreamAdapterOptions } from './types';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC1E,YAAY,EAAE,wBAAwB,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAA"}
package/dist/index.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RedisStreamAdapterManager = exports.RedisStreamAdapter = void 0;
4
- var redis_stream_adapter_1 = require("./redis-stream-adapter");
5
- Object.defineProperty(exports, "RedisStreamAdapter", { enumerable: true, get: function () { return redis_stream_adapter_1.RedisStreamAdapter; } });
6
- var redis_stream_adapter_manager_1 = require("./redis-stream-adapter-manager");
7
- Object.defineProperty(exports, "RedisStreamAdapterManager", { enumerable: true, get: function () { return redis_stream_adapter_manager_1.RedisStreamAdapterManager; } });
@@ -1,15 +0,0 @@
1
- import type { StreamAdapter, StreamAdapterManager } from '@motiadev/core';
2
- import { type RedisClientOptions, type RedisClientType } from 'redis';
3
- import type { RedisStreamAdapterOptions } from './types';
4
- export declare class RedisStreamAdapterManager implements StreamAdapterManager {
5
- private client;
6
- private connected;
7
- private isExternalClient;
8
- private config;
9
- constructor(redisConnection: RedisClientType | RedisClientOptions, options?: RedisStreamAdapterOptions);
10
- private connect;
11
- createStream<TData>(streamName: string): StreamAdapter<TData>;
12
- getClient(): RedisClientType;
13
- shutdown(): Promise<void>;
14
- }
15
- //# sourceMappingURL=redis-stream-adapter-manager.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"redis-stream-adapter-manager.d.ts","sourceRoot":"","sources":["../src/redis-stream-adapter-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAA;AACzE,OAAO,EAAgB,KAAK,kBAAkB,EAAE,KAAK,eAAe,EAAE,MAAM,OAAO,CAAA;AAEnF,OAAO,KAAK,EAA4B,yBAAyB,EAAE,MAAM,SAAS,CAAA;AAMlF,qBAAa,yBAA0B,YAAW,oBAAoB;IACpE,OAAO,CAAC,MAAM,CAAiB;IAC/B,OAAO,CAAC,SAAS,CAAQ;IACzB,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,MAAM,CAA0B;gBAE5B,eAAe,EAAE,eAAe,GAAG,kBAAkB,EAAE,OAAO,CAAC,EAAE,yBAAyB;YAwCxF,OAAO;IAWrB,YAAY,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC;IAI7D,SAAS,IAAI,eAAe;IAItB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAKhC"}
@@ -1,68 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RedisStreamAdapterManager = void 0;
4
- const redis_1 = require("redis");
5
- const redis_stream_adapter_1 = require("./redis-stream-adapter");
6
- function isRedisClient(input) {
7
- return typeof input === 'object' && 'isOpen' in input && 'connect' in input;
8
- }
9
- class RedisStreamAdapterManager {
10
- constructor(redisConnection, options) {
11
- this.connected = false;
12
- this.config = {
13
- keyPrefix: options?.keyPrefix || 'motia:stream:',
14
- socketKeepAlive: options?.socketKeepAlive ?? true,
15
- };
16
- if (isRedisClient(redisConnection)) {
17
- this.client = redisConnection;
18
- this.isExternalClient = true;
19
- this.connected = this.client.isOpen;
20
- }
21
- else {
22
- const config = {
23
- ...redisConnection,
24
- socket: {
25
- ...(redisConnection.socket || {}),
26
- keepAlive: this.config.socketKeepAlive,
27
- noDelay: true,
28
- },
29
- };
30
- this.isExternalClient = false;
31
- this.client = (0, redis_1.createClient)(config);
32
- this.client.on('error', (err) => {
33
- console.error('[Redis Stream Manager] Client error:', err);
34
- });
35
- this.client.on('connect', () => {
36
- this.connected = true;
37
- });
38
- this.client.on('disconnect', () => {
39
- console.warn('[Redis Stream Manager] Disconnected');
40
- this.connected = false;
41
- });
42
- this.connect();
43
- }
44
- }
45
- async connect() {
46
- if (!this.connected && !this.isExternalClient) {
47
- try {
48
- await this.client.connect();
49
- }
50
- catch (error) {
51
- console.error('[Redis Stream Manager] Failed to connect:', error);
52
- throw error;
53
- }
54
- }
55
- }
56
- createStream(streamName) {
57
- return new redis_stream_adapter_1.RedisStreamAdapter(streamName, this.config, this.client);
58
- }
59
- getClient() {
60
- return this.client;
61
- }
62
- async shutdown() {
63
- if (!this.isExternalClient && this.client.isOpen) {
64
- await this.client.quit();
65
- }
66
- }
67
- }
68
- exports.RedisStreamAdapterManager = RedisStreamAdapterManager;
@@ -1,25 +0,0 @@
1
- import type { BaseStreamItem, StateStreamEvent, StateStreamEventChannel } from '@motiadev/core';
2
- import { StreamAdapter, type StreamQueryFilter } from '@motiadev/core';
3
- import { type RedisClientType } from 'redis';
4
- import type { RedisStreamAdapterConfig } from './types';
5
- export declare class RedisStreamAdapter<TData> extends StreamAdapter<TData> {
6
- private client;
7
- private subClient?;
8
- private keyPrefix;
9
- private groupPrefix;
10
- private subscriptions;
11
- constructor(streamName: string, config: RedisStreamAdapterConfig, sharedClient: RedisClientType);
12
- private makeGroupKey;
13
- private makeChannelKey;
14
- get(groupId: string, id: string): Promise<BaseStreamItem<TData> | null>;
15
- set(groupId: string, id: string, data: TData): Promise<BaseStreamItem<TData>>;
16
- delete(groupId: string, id: string): Promise<BaseStreamItem<TData> | null>;
17
- getGroup(groupId: string): Promise<BaseStreamItem<TData>[]>;
18
- send<T>(channel: StateStreamEventChannel, event: StateStreamEvent<T>): Promise<void>;
19
- subscribe<T>(channel: StateStreamEventChannel, handler: (event: StateStreamEvent<T>) => void | Promise<void>): Promise<void>;
20
- unsubscribe(channel: StateStreamEventChannel): Promise<void>;
21
- clear(groupId: string): Promise<void>;
22
- query(groupId: string, filter: StreamQueryFilter<TData>): Promise<BaseStreamItem<TData>[]>;
23
- cleanup(): Promise<void>;
24
- }
25
- //# sourceMappingURL=redis-stream-adapter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"redis-stream-adapter.d.ts","sourceRoot":"","sources":["../src/redis-stream-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAA;AAC/F,OAAO,EAAE,aAAa,EAAE,KAAK,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AACtE,OAAO,EAAyC,KAAK,eAAe,EAAE,MAAM,OAAO,CAAA;AACnF,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA;AAevD,qBAAa,kBAAkB,CAAC,KAAK,CAAE,SAAQ,aAAa,CAAC,KAAK,CAAC;IACjE,OAAO,CAAC,MAAM,CAAiB;IAC/B,OAAO,CAAC,S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KAAK,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;IAkC1F,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAG/B"}
@@ -1,151 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RedisStreamAdapter = void 0;
4
- const core_1 = require("@motiadev/core");
5
- const redis_1 = require("redis");
6
- class RedisStreamAdapter extends core_1.StreamAdapter {
7
- constructor(streamName, config, sharedClient) {
8
- super(streamName);
9
- this.subscriptions = new Map();
10
- this.keyPrefix = config.keyPrefix || 'motia:stream:';
11
- this.groupPrefix = `${this.keyPrefix}${streamName}:group:`;
12
- this.client = sharedClient;
13
- }
14
- makeGroupKey(groupId) {
15
- return `${this.groupPrefix}${groupId}`;
16
- }
17
- makeChannelKey(channel) {
18
- return channel.id
19
- ? `motia:stream:events:${this.streamName}:${channel.groupId}:${channel.id}`
20
- : `motia:stream:events:${this.streamName}:${channel.groupId}`;
21
- }
22
- async get(groupId, id) {
23
- const hashKey = this.makeGroupKey(groupId);
24
- const value = await this.client.hGet(hashKey, id);
25
- return value ? JSON.parse(value) : null;
26
- }
27
- async set(groupId, id, data) {
28
- const hashKey = this.makeGroupKey(groupId);
29
- const dataWithTimestamp = data;
30
- const item = {
31
- ...data,
32
- id,
33
- _createdAt: dataWithTimestamp._createdAt || Date.now(),
34
- };
35
- const itemJson = JSON.stringify(item);
36
- const existed = await this.client.hExists(hashKey, id);
37
- const eventType = existed ? 'update' : 'create';
38
- await Promise.all([
39
- this.client.hSet(hashKey, id, itemJson),
40
- this.send({ groupId, id }, { type: eventType, data: item }),
41
- ]);
42
- return item;
43
- }
44
- async delete(groupId, id) {
45
- const hashKey = this.makeGroupKey(groupId);
46
- const value = await this.client.hGet(hashKey, id);
47
- if (!value)
48
- return null;
49
- const item = JSON.parse(value);
50
- await Promise.all([this.client.hDel(hashKey, id), this.send({ groupId, id }, { type: 'delete', data: item })]);
51
- return item;
52
- }
53
- async getGroup(groupId) {
54
- const hashKey = this.makeGroupKey(groupId);
55
- const values = await this.client.hGetAll(hashKey);
56
- const items = Object.values(values).map((v) => JSON.parse(v));
57
- return items.sort((a, b) => {
58
- const aTime = a._createdAt || 0;
59
- const bTime = b._createdAt || 0;
60
- return aTime - bTime;
61
- });
62
- }
63
- async send(channel, event) {
64
- const channelKey = this.makeChannelKey(channel);
65
- await this.client.publish(channelKey, JSON.stringify(event));
66
- }
67
- async subscribe(channel, handler) {
68
- const channelKey = this.makeChannelKey(channel);
69
- if (!this.subClient) {
70
- const socketConfig = this.client.options?.socket;
71
- const keepAliveValue = socketConfig?.keepAlive;
72
- const clientConfig = {
73
- socket: {
74
- host: socketConfig?.host || 'localhost',
75
- port: socketConfig?.port || 6379,
76
- keepAlive: keepAliveValue,
77
- noDelay: true,
78
- },
79
- password: this.client.options?.password,
80
- username: this.client.options?.username,
81
- database: this.client.options?.database || 0,
82
- };
83
- this.subClient = (0, redis_1.createClient)(clientConfig);
84
- this.subClient.on('error', (err) => {
85
- console.error('[Redis Stream] Sub client error:', err);
86
- });
87
- await this.subClient.connect();
88
- }
89
- this.subscriptions.set(channelKey, handler);
90
- const subClient = this.subClient;
91
- if (!subClient)
92
- return;
93
- await subClient.subscribe(channelKey, async (message) => {
94
- try {
95
- const event = JSON.parse(message);
96
- await handler(event);
97
- }
98
- catch (error) {
99
- console.error('[Redis Stream] Error processing subscription message:', error);
100
- }
101
- });
102
- }
103
- async unsubscribe(channel) {
104
- if (!this.subClient)
105
- return;
106
- const channelKey = this.makeChannelKey(channel);
107
- this.subscriptions.delete(channelKey);
108
- try {
109
- await this.subClient.unsubscribe(channelKey);
110
- }
111
- catch (error) {
112
- console.error('[Redis Stream] Error unsubscribing:', error);
113
- }
114
- }
115
- async clear(groupId) {
116
- const hashKey = this.makeGroupKey(groupId);
117
- await this.client.del(hashKey);
118
- }
119
- async query(groupId, filter) {
120
- let items = await this.getGroup(groupId);
121
- if (filter.where) {
122
- const where = filter.where;
123
- items = items.filter((item) => {
124
- return Object.entries(where).every(([key, value]) => {
125
- const itemKey = key;
126
- return item[itemKey] === value;
127
- });
128
- });
129
- }
130
- if (filter.orderBy) {
131
- items.sort((a, b) => {
132
- const orderKey = filter.orderBy;
133
- const aVal = a[orderKey];
134
- const bVal = b[orderKey];
135
- const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
136
- return filter.orderDirection === 'desc' ? -comparison : comparison;
137
- });
138
- }
139
- if (filter.offset) {
140
- items = items.slice(filter.offset);
141
- }
142
- if (filter.limit) {
143
- items = items.slice(0, filter.limit);
144
- }
145
- return items;
146
- }
147
- async cleanup() {
148
- this.subscriptions.clear();
149
- }
150
- }
151
- exports.RedisStreamAdapter = RedisStreamAdapter;
package/dist/types.d.ts DELETED
@@ -1,9 +0,0 @@
1
- export interface RedisStreamAdapterConfig {
2
- keyPrefix?: string;
3
- socketKeepAlive?: boolean;
4
- }
5
- export interface RedisStreamAdapterOptions {
6
- keyPrefix?: string;
7
- socketKeepAlive?: boolean;
8
- }
9
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,wBAAwB;IACvC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,MAAM,WAAW,yBAAyB;IACxC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B"}
package/dist/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });