@motiadev/adapter-redis-streams 0.8.2-beta.140-709523
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/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +168 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/redis-stream-adapter.d.ts +28 -0
- package/dist/redis-stream-adapter.d.ts.map +1 -0
- package/dist/redis-stream-adapter.js +209 -0
- package/dist/types.d.ts +13 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/package.json +23 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.1.0] - 2025-10-22
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- Initial release of Redis streams adapter for Motia
|
|
7
|
+
- Support for distributed stream management across multiple instances
|
|
8
|
+
- Real-time pub/sub for stream updates
|
|
9
|
+
- Support for querying with filtering, sorting, and pagination
|
|
10
|
+
- Separate Redis clients for pub/sub operations
|
|
11
|
+
- Efficient SCAN operations for data retrieval
|
|
12
|
+
- Type-safe generic implementation
|
|
13
|
+
- Configurable key prefixes
|
|
14
|
+
- Automatic reconnection handling
|
|
15
|
+
- Full TypeScript support with type definitions
|
|
16
|
+
- Comprehensive documentation and examples
|
|
17
|
+
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
# @motiadev/adapter-redis-streams
|
|
2
|
+
|
|
3
|
+
Redis streams adapter for Motia framework, enabling distributed stream management with real-time updates across multiple instances.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @motiadev/adapter-redis-streams
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Configure the Redis streams adapter in your `motia.config.ts`:
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { config } from '@motiadev/core'
|
|
17
|
+
import { RedisStreamAdapter } from '@motiadev/adapter-redis-streams'
|
|
18
|
+
|
|
19
|
+
export default config({
|
|
20
|
+
adapters: {
|
|
21
|
+
streams: new RedisStreamAdapter({
|
|
22
|
+
host: process.env.REDIS_HOST || 'localhost',
|
|
23
|
+
port: parseInt(process.env.REDIS_PORT || '6379'),
|
|
24
|
+
password: process.env.REDIS_PASSWORD,
|
|
25
|
+
keyPrefix: 'motia:stream:',
|
|
26
|
+
}),
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Configuration Options
|
|
32
|
+
|
|
33
|
+
### RedisStreamAdapterConfig
|
|
34
|
+
|
|
35
|
+
| Option | Type | Default | Description |
|
|
36
|
+
|--------|------|---------|-------------|
|
|
37
|
+
| `host` | `string` | `'localhost'` | Redis server host |
|
|
38
|
+
| `port` | `number` | `6379` | Redis server port |
|
|
39
|
+
| `password` | `string` | `undefined` | Redis authentication password |
|
|
40
|
+
| `username` | `string` | `undefined` | Redis authentication username |
|
|
41
|
+
| `database` | `number` | `0` | Redis database number |
|
|
42
|
+
| `keyPrefix` | `string` | `'motia:stream:'` | Prefix for all stream keys |
|
|
43
|
+
| `socket.reconnectStrategy` | `function` | Auto-retry | Custom reconnection strategy |
|
|
44
|
+
| `socket.connectTimeout` | `number` | `10000` | Connection timeout in milliseconds |
|
|
45
|
+
|
|
46
|
+
## Features
|
|
47
|
+
|
|
48
|
+
- **Distributed Streams**: Share stream data across multiple Motia instances
|
|
49
|
+
- **Real-time Updates**: Pub/sub for instant data synchronization
|
|
50
|
+
- **Efficient Querying**: Support for filtering, sorting, and pagination
|
|
51
|
+
- **Automatic Reconnection**: Handles connection failures gracefully
|
|
52
|
+
- **Connection Pooling**: Separate clients for pub/sub operations
|
|
53
|
+
- **Type Safety**: Full TypeScript support with generics
|
|
54
|
+
|
|
55
|
+
## Key Namespacing
|
|
56
|
+
|
|
57
|
+
The adapter uses the following patterns:
|
|
58
|
+
- **Stream data**: `{keyPrefix}{groupId}:{id}`
|
|
59
|
+
- **Events**: `motia:stream:events:{groupId}` or `motia:stream:events:{groupId}:{id}`
|
|
60
|
+
|
|
61
|
+
For example:
|
|
62
|
+
```
|
|
63
|
+
motia:stream:users:user-123
|
|
64
|
+
motia:stream:orders:order-456
|
|
65
|
+
motia:stream:events:users
|
|
66
|
+
motia:stream:events:users:user-123
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Example
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { RedisStreamAdapter } from '@motiadev/adapter-redis-streams'
|
|
73
|
+
|
|
74
|
+
const adapter = new RedisStreamAdapter({
|
|
75
|
+
host: 'redis.example.com',
|
|
76
|
+
port: 6379,
|
|
77
|
+
password: 'your-secure-password',
|
|
78
|
+
keyPrefix: 'myapp:stream:',
|
|
79
|
+
socket: {
|
|
80
|
+
connectTimeout: 5000,
|
|
81
|
+
reconnectStrategy: (retries) => {
|
|
82
|
+
if (retries > 20) {
|
|
83
|
+
return new Error('Too many retries')
|
|
84
|
+
}
|
|
85
|
+
return Math.min(retries * 50, 2000)
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
})
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Real-time Updates
|
|
92
|
+
|
|
93
|
+
The adapter uses Redis pub/sub to notify all instances about stream changes:
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
await adapter.subscribe(
|
|
97
|
+
{ groupId: 'users' },
|
|
98
|
+
async (event) => {
|
|
99
|
+
console.log('Stream event:', event.type, event.data)
|
|
100
|
+
}
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
await adapter.set('users', 'user-123', { name: 'John', email: 'john@example.com' })
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Querying
|
|
107
|
+
|
|
108
|
+
The adapter supports flexible querying:
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
const results = await adapter.query('users', {
|
|
112
|
+
where: { status: 'active' },
|
|
113
|
+
orderBy: 'createdAt',
|
|
114
|
+
orderDirection: 'desc',
|
|
115
|
+
limit: 10,
|
|
116
|
+
offset: 0,
|
|
117
|
+
})
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Environment Variables
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
REDIS_HOST=localhost
|
|
124
|
+
REDIS_PORT=6379
|
|
125
|
+
REDIS_PASSWORD=your-password
|
|
126
|
+
REDIS_DATABASE=0
|
|
127
|
+
STREAM_KEY_PREFIX=motia:stream:
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Performance Considerations
|
|
131
|
+
|
|
132
|
+
- **Pub/Sub Overhead**: Real-time updates add slight latency (~10-50ms)
|
|
133
|
+
- **Key Scanning**: Uses SCAN to avoid blocking on large datasets
|
|
134
|
+
- **Connection Pooling**: Maintains separate connections for pub/sub
|
|
135
|
+
- **Batch Operations**: Uses multi-get for group operations
|
|
136
|
+
- **Memory Usage**: Monitor Redis memory with large stream datasets
|
|
137
|
+
|
|
138
|
+
## Troubleshooting
|
|
139
|
+
|
|
140
|
+
### Connection Issues
|
|
141
|
+
|
|
142
|
+
If you experience connection problems:
|
|
143
|
+
1. Verify Redis is running and accessible
|
|
144
|
+
2. Check your host, port, and credentials
|
|
145
|
+
3. Ensure firewall rules allow connections
|
|
146
|
+
4. Review Redis logs for errors
|
|
147
|
+
|
|
148
|
+
### Subscription Issues
|
|
149
|
+
|
|
150
|
+
If real-time updates aren't working:
|
|
151
|
+
1. Verify pub/sub client is connected
|
|
152
|
+
2. Check subscription handlers are registered
|
|
153
|
+
3. Monitor Redis pub/sub channels with `PUBSUB CHANNELS`
|
|
154
|
+
4. Review network latency between instances
|
|
155
|
+
|
|
156
|
+
### Performance Issues
|
|
157
|
+
|
|
158
|
+
If you experience slow operations:
|
|
159
|
+
1. Monitor Redis server performance
|
|
160
|
+
2. Check network latency
|
|
161
|
+
3. Review query patterns and add appropriate filtering
|
|
162
|
+
4. Consider Redis clustering for large datasets
|
|
163
|
+
5. Monitor pub/sub message rates
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT
|
|
168
|
+
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAC3D,YAAY,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
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; } });
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { BaseStreamItem, StateStreamEvent, StateStreamEventChannel } from '@motiadev/core';
|
|
2
|
+
import { StreamAdapter, type StreamQueryFilter } from '@motiadev/core';
|
|
3
|
+
import type { RedisStreamAdapterConfig } from './types';
|
|
4
|
+
export declare class RedisStreamAdapter<TData> extends StreamAdapter<TData> {
|
|
5
|
+
private client;
|
|
6
|
+
private pubClient;
|
|
7
|
+
private subClient?;
|
|
8
|
+
private keyPrefix;
|
|
9
|
+
private connected;
|
|
10
|
+
private subscriptions;
|
|
11
|
+
constructor(config: RedisStreamAdapterConfig);
|
|
12
|
+
private connect;
|
|
13
|
+
private ensureConnected;
|
|
14
|
+
private makeKey;
|
|
15
|
+
private makeChannelKey;
|
|
16
|
+
get(groupId: string, id: string): Promise<BaseStreamItem<TData> | null>;
|
|
17
|
+
set(groupId: string, id: string, data: TData): Promise<BaseStreamItem<TData>>;
|
|
18
|
+
delete(groupId: string, id: string): Promise<BaseStreamItem<TData> | null>;
|
|
19
|
+
getGroup(groupId: string): Promise<BaseStreamItem<TData>[]>;
|
|
20
|
+
send<T>(channel: StateStreamEventChannel, event: StateStreamEvent<T>): Promise<void>;
|
|
21
|
+
subscribe<T>(channel: StateStreamEventChannel, handler: (event: StateStreamEvent<T>) => void | Promise<void>): Promise<void>;
|
|
22
|
+
unsubscribe(channel: StateStreamEventChannel): Promise<void>;
|
|
23
|
+
clear(groupId: string): Promise<void>;
|
|
24
|
+
query(groupId: string, filter: StreamQueryFilter<TData>): Promise<BaseStreamItem<TData>[]>;
|
|
25
|
+
private scanKeys;
|
|
26
|
+
cleanup(): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=redis-stream-adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
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;AAEtE,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,SAAS,CAAiB;IAClC,OAAO,CAAC,SAAS,CAAC,CAAiB;IACnC,OAAO,CAAC,SAAS,CAAQ;IACzB,OAAO,CAAC,SAAS,CAAQ;IACzB,OAAO,CAAC,aAAa,CAAiF;gBAE1F,MAAM,EAAE,wBAAwB;YA8C9B,OAAO;YAWP,eAAe;IAM7B,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,cAAc;IAMhB,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;IAOvE,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAW7E,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;IAW1E,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;IAW3D,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,uBAAuB,EAAE,KAAK,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAMpF,SAAS,CAAC,CAAC,EACf,OAAO,EAAE,uBAAuB,EAChC,OAAO,EAAE,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAC5D,OAAO,CAAC,IAAI,CAAC;IAmCV,WAAW,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC;IAa5D,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAUrC,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,EAAE,CAAC;YA+BlF,QAAQ;IAgBhB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAY/B"}
|
|
@@ -0,0 +1,209 @@
|
|
|
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(config) {
|
|
8
|
+
super();
|
|
9
|
+
this.connected = false;
|
|
10
|
+
this.subscriptions = new Map();
|
|
11
|
+
this.keyPrefix = config.keyPrefix || 'motia:stream:';
|
|
12
|
+
const clientConfig = {
|
|
13
|
+
socket: {
|
|
14
|
+
host: config.host || 'localhost',
|
|
15
|
+
port: config.port || 6379,
|
|
16
|
+
reconnectStrategy: config.socket?.reconnectStrategy ||
|
|
17
|
+
((retries) => {
|
|
18
|
+
if (retries > 10) {
|
|
19
|
+
return new Error('Redis connection retry limit exceeded');
|
|
20
|
+
}
|
|
21
|
+
return Math.min(retries * 100, 3000);
|
|
22
|
+
}),
|
|
23
|
+
connectTimeout: config.socket?.connectTimeout || 10000,
|
|
24
|
+
},
|
|
25
|
+
password: config.password,
|
|
26
|
+
username: config.username,
|
|
27
|
+
database: config.database || 0,
|
|
28
|
+
};
|
|
29
|
+
this.client = (0, redis_1.createClient)(clientConfig);
|
|
30
|
+
this.pubClient = (0, redis_1.createClient)(clientConfig);
|
|
31
|
+
this.client.on('error', (err) => {
|
|
32
|
+
console.error('[Redis Stream] Client error:', err);
|
|
33
|
+
});
|
|
34
|
+
this.client.on('connect', () => {
|
|
35
|
+
this.connected = true;
|
|
36
|
+
});
|
|
37
|
+
this.client.on('disconnect', () => {
|
|
38
|
+
console.warn('[Redis Stream] Disconnected');
|
|
39
|
+
this.connected = false;
|
|
40
|
+
});
|
|
41
|
+
this.pubClient.on('error', (err) => {
|
|
42
|
+
console.error('[Redis Stream] Pub client error:', err);
|
|
43
|
+
});
|
|
44
|
+
this.connect();
|
|
45
|
+
}
|
|
46
|
+
async connect() {
|
|
47
|
+
if (!this.connected) {
|
|
48
|
+
try {
|
|
49
|
+
await Promise.all([this.client.connect(), this.pubClient.connect()]);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
console.error('[Redis Stream] Failed to connect:', error);
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async ensureConnected() {
|
|
58
|
+
if (!this.client.isOpen || !this.pubClient.isOpen) {
|
|
59
|
+
await this.connect();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
makeKey(groupId, id) {
|
|
63
|
+
return id ? `${this.keyPrefix}${groupId}:${id}` : `${this.keyPrefix}${groupId}`;
|
|
64
|
+
}
|
|
65
|
+
makeChannelKey(channel) {
|
|
66
|
+
return channel.id
|
|
67
|
+
? `motia:stream:events:${channel.groupId}:${channel.id}`
|
|
68
|
+
: `motia:stream:events:${channel.groupId}`;
|
|
69
|
+
}
|
|
70
|
+
async get(groupId, id) {
|
|
71
|
+
await this.ensureConnected();
|
|
72
|
+
const key = this.makeKey(groupId, id);
|
|
73
|
+
const value = await this.client.get(key);
|
|
74
|
+
return value ? JSON.parse(value) : null;
|
|
75
|
+
}
|
|
76
|
+
async set(groupId, id, data) {
|
|
77
|
+
await this.ensureConnected();
|
|
78
|
+
const key = this.makeKey(groupId, id);
|
|
79
|
+
const item = { ...data, id };
|
|
80
|
+
await this.client.set(key, JSON.stringify(item));
|
|
81
|
+
await this.send({ groupId, id }, { type: 'update', data: item });
|
|
82
|
+
return item;
|
|
83
|
+
}
|
|
84
|
+
async delete(groupId, id) {
|
|
85
|
+
await this.ensureConnected();
|
|
86
|
+
const item = await this.get(groupId, id);
|
|
87
|
+
if (item) {
|
|
88
|
+
const key = this.makeKey(groupId, id);
|
|
89
|
+
await this.client.del(key);
|
|
90
|
+
await this.send({ groupId, id }, { type: 'delete', data: item });
|
|
91
|
+
}
|
|
92
|
+
return item;
|
|
93
|
+
}
|
|
94
|
+
async getGroup(groupId) {
|
|
95
|
+
await this.ensureConnected();
|
|
96
|
+
const pattern = `${this.makeKey(groupId)}:*`;
|
|
97
|
+
const keys = await this.scanKeys(pattern);
|
|
98
|
+
if (keys.length === 0)
|
|
99
|
+
return [];
|
|
100
|
+
const values = await this.client.mGet(keys);
|
|
101
|
+
return values.filter((v) => v !== null).map((v) => JSON.parse(v));
|
|
102
|
+
}
|
|
103
|
+
async send(channel, event) {
|
|
104
|
+
await this.ensureConnected();
|
|
105
|
+
const channelKey = this.makeChannelKey(channel);
|
|
106
|
+
await this.pubClient.publish(channelKey, JSON.stringify(event));
|
|
107
|
+
}
|
|
108
|
+
async subscribe(channel, handler) {
|
|
109
|
+
const channelKey = this.makeChannelKey(channel);
|
|
110
|
+
if (!this.subClient) {
|
|
111
|
+
const socketConfig = this.client.options?.socket;
|
|
112
|
+
const clientConfig = {
|
|
113
|
+
socket: {
|
|
114
|
+
host: socketConfig?.host || 'localhost',
|
|
115
|
+
port: socketConfig?.port || 6379,
|
|
116
|
+
},
|
|
117
|
+
password: this.client.options?.password,
|
|
118
|
+
username: this.client.options?.username,
|
|
119
|
+
database: this.client.options?.database || 0,
|
|
120
|
+
};
|
|
121
|
+
this.subClient = (0, redis_1.createClient)(clientConfig);
|
|
122
|
+
this.subClient.on('error', (err) => {
|
|
123
|
+
console.error('[Redis Stream] Sub client error:', err);
|
|
124
|
+
});
|
|
125
|
+
await this.subClient.connect();
|
|
126
|
+
}
|
|
127
|
+
this.subscriptions.set(channelKey, handler);
|
|
128
|
+
await this.subClient.subscribe(channelKey, async (message) => {
|
|
129
|
+
try {
|
|
130
|
+
const event = JSON.parse(message);
|
|
131
|
+
await handler(event);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
console.error('[Redis Stream] Error processing subscription message:', error);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
async unsubscribe(channel) {
|
|
139
|
+
if (!this.subClient)
|
|
140
|
+
return;
|
|
141
|
+
const channelKey = this.makeChannelKey(channel);
|
|
142
|
+
this.subscriptions.delete(channelKey);
|
|
143
|
+
try {
|
|
144
|
+
await this.subClient.unsubscribe(channelKey);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
console.error('[Redis Stream] Error unsubscribing:', error);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
async clear(groupId) {
|
|
151
|
+
await this.ensureConnected();
|
|
152
|
+
const pattern = `${this.makeKey(groupId)}:*`;
|
|
153
|
+
const keys = await this.scanKeys(pattern);
|
|
154
|
+
if (keys.length > 0) {
|
|
155
|
+
await this.client.del(keys);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async query(groupId, filter) {
|
|
159
|
+
let items = await this.getGroup(groupId);
|
|
160
|
+
if (filter.where) {
|
|
161
|
+
items = items.filter((item) => {
|
|
162
|
+
return Object.entries(filter.where).every(([key, value]) => {
|
|
163
|
+
return item[key] === value;
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
if (filter.orderBy) {
|
|
168
|
+
items.sort((a, b) => {
|
|
169
|
+
const aVal = a[filter.orderBy];
|
|
170
|
+
const bVal = b[filter.orderBy];
|
|
171
|
+
const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
|
|
172
|
+
return filter.orderDirection === 'desc' ? -comparison : comparison;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (filter.offset) {
|
|
176
|
+
items = items.slice(filter.offset);
|
|
177
|
+
}
|
|
178
|
+
if (filter.limit) {
|
|
179
|
+
items = items.slice(0, filter.limit);
|
|
180
|
+
}
|
|
181
|
+
return items;
|
|
182
|
+
}
|
|
183
|
+
async scanKeys(pattern) {
|
|
184
|
+
const keys = [];
|
|
185
|
+
let cursor = 0;
|
|
186
|
+
do {
|
|
187
|
+
const result = await this.client.scan(cursor, {
|
|
188
|
+
MATCH: pattern,
|
|
189
|
+
COUNT: 100,
|
|
190
|
+
});
|
|
191
|
+
cursor = result.cursor;
|
|
192
|
+
keys.push(...result.keys);
|
|
193
|
+
} while (cursor !== 0);
|
|
194
|
+
return keys;
|
|
195
|
+
}
|
|
196
|
+
async cleanup() {
|
|
197
|
+
if (this.subClient?.isOpen) {
|
|
198
|
+
await this.subClient.quit();
|
|
199
|
+
}
|
|
200
|
+
if (this.pubClient.isOpen) {
|
|
201
|
+
await this.pubClient.quit();
|
|
202
|
+
}
|
|
203
|
+
if (this.client.isOpen) {
|
|
204
|
+
await this.client.quit();
|
|
205
|
+
}
|
|
206
|
+
this.subscriptions.clear();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
exports.RedisStreamAdapter = RedisStreamAdapter;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface RedisStreamAdapterConfig {
|
|
2
|
+
host?: string;
|
|
3
|
+
port?: number;
|
|
4
|
+
password?: string;
|
|
5
|
+
username?: string;
|
|
6
|
+
database?: number;
|
|
7
|
+
keyPrefix?: string;
|
|
8
|
+
socket?: {
|
|
9
|
+
reconnectStrategy?: (retries: number) => number | Error;
|
|
10
|
+
connectTimeout?: number;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,wBAAwB;IACvC,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,CAAC,EAAE;QACP,iBAAiB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,MAAM,GAAG,KAAK,CAAA;QACvD,cAAc,CAAC,EAAE,MAAM,CAAA;KACxB,CAAA;CACF"}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@motiadev/adapter-redis-streams",
|
|
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.8.2-beta.140-709523",
|
|
7
|
+
"dependencies": {
|
|
8
|
+
"redis": "^4.7.0",
|
|
9
|
+
"@motiadev/core": "0.8.2-beta.140-709523"
|
|
10
|
+
},
|
|
11
|
+
"devDependencies": {
|
|
12
|
+
"@types/node": "^22.10.2",
|
|
13
|
+
"typescript": "^5.7.2"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"@motiadev/core": "^0.8.0"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "rm -rf dist && tsc",
|
|
20
|
+
"lint": "biome check .",
|
|
21
|
+
"watch": "tsc --watch"
|
|
22
|
+
}
|
|
23
|
+
}
|