forked from denodrivers/redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.ts
388 lines (335 loc) Β· 9.36 KB
/
stream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import type { ConditionalArray, Raw, RedisValue } from "./protocol/mod.ts";
export interface XId {
unixMs: number;
seqNo: number;
}
export interface XMessage {
xid: XId;
fieldValues: Record<string, string>;
}
export interface XKeyId {
key: string;
xid: XIdInput;
}
export type XKeyIdLike = [string, XIdInput];
export interface XKeyIdGroup {
key: string;
xid: XIdGroupRead;
}
export type XKeyIdGroupLike = [string, XIdGroupRead];
export type XReadStream = { key: string; messages: XMessage[] };
export type XReadReply = XReadStream[];
// basic data returned by redis
export type XReadIdData = [string, string[]];
export type XReadStreamRaw = [string, XReadIdData[]];
export type XReadReplyRaw = XReadStreamRaw[];
/** Flexible input type for commands which require message
* ID to be passed (represented in lower-level Redis API as
* "1000-0" etc).
*
* We also include an array format for ease of use, where
* the first element is the epochMillis, second is seqNo.
*
* We also allow passing a single number,
* which will represent the the epoch Millis with
* seqNo of zero. (Especially useful is to pass 0.)
*/
export type XIdInput = XId | [number, number] | number;
/**
* ID input type for XADD, which is allowed to include the
* "*" operator. */
export type XIdAdd = XIdInput | "*";
/**
* ID input type for XGROUPREAD, which is allowed to include
* the ">" operator. We include an array format for ease of
* use, where the first element is the epochMillis, second
* is seqNo. */
export type XIdGroupRead = XIdInput | ">";
/** Allows special maximum ID for XRANGE and XREVRANGE */
export type XIdPos = XIdInput | " ";
/** Allows special minimum ID for XRANGE and XREVRANGE */
export type XIdNeg = XIdInput | "-";
/** Allow special $ ID for XGROUP CREATE */
export type XIdCreateGroup = XIdInput | "$";
export type XAddFieldValues =
| Record<string | number, RedisValue>
| Map<string | number, RedisValue>;
export interface XReadOpts {
count?: number;
block?: number;
}
export interface XReadGroupOpts {
group: string;
consumer: string;
count?: number;
block?: number;
}
export interface XMaxlen {
approx?: boolean;
elements: number;
}
export type XClaimReply = XClaimMessages | XClaimJustXId;
export interface XClaimMessages {
kind: "messages";
messages: XMessage[];
}
export interface XClaimJustXId {
kind: "justxid";
xids: XId[];
}
/**
* @param count Limit on the number of messages to return per call.
* @param startId ID for the first pending record.
* @param endId ID for the final pending record.
* @param consumers Every consumer in the consumer group
* with at least one pending message, and the number of
* pending messages it has.
*/
export interface XPendingReply {
count: number;
startId: XId;
endId: XId;
consumers: XPendingConsumer[];
}
export interface XPendingConsumer {
name: string;
pending: number;
}
/**
* Represents a pending message parsed from xpending.
*
* @param id The ID of the message
* @param consumer The name of the consumer that fetched the message
* and has still to acknowledge it. We call it the
* current owner of the message.
* @param lastDeliveredMs The number of milliseconds that elapsed since the
* last time this message was delivered to this consumer.
* @param timesDelivered The number of times this message was delivered.
*/
export interface XPendingCount {
xid: XId;
owner: string;
lastDeliveredMs: number;
timesDelivered: number;
}
/** Used in the XPENDING command, all three of these
* args must be specified if _any_ are specified.
*/
export interface StartEndCount {
start: number | "-";
end: number | " ";
count: number;
}
export interface XInfoStreamReply {
length: number;
radixTreeKeys: number;
radixTreeNodes: number;
groups: number;
lastGeneratedId: XId;
firstEntry: XMessage;
lastEntry: XMessage;
}
export interface XInfoStreamFullReply {
length: number;
radixTreeKeys: number;
radixTreeNodes: number;
lastGeneratedId: XId;
entries: XMessage[];
groups: XGroupDetail[];
}
/**
* Child of the return type for xinfo_stream_full
*/
export interface XGroupDetail {
name: string;
lastDeliveredId: XId;
pelCount: number;
pending: XPendingCount[];
consumers: XConsumerDetail[];
}
/** Child of XINFO STREAMS FULL response */
export interface XConsumerDetail {
name: string;
seenTime: number;
pelCount: number;
pending: { xid: XId; lastDeliveredMs: number; timesDelivered: number }[];
}
export type XInfoConsumersReply = XInfoConsumer[];
/**
* A consumer parsed from xinfo command.
*
* @param name Name of the consumer group.
* @param pending Number of pending messages for this specific consumer.
* @param idle This consumer's idle time in milliseconds.
*/
export interface XInfoConsumer {
name: string;
pending: number;
idle: number;
}
/** Response to XINFO GROUPS <key> */
export type XInfoGroupsReply = XInfoGroup[];
export interface XInfoGroup {
name: string;
consumers: number;
pending: number;
lastDeliveredId: XId;
}
export interface XClaimOpts {
group: string;
consumer: string;
minIdleTime: number;
idle?: number;
time?: number;
retryCount?: number;
force?: boolean;
justXId?: boolean;
}
export function parseXMessage(raw: XReadIdData): XMessage {
const fieldValues: Record<string, string> = {};
let f: string | undefined = undefined;
let m = 0;
for (const data of raw[1]) {
if (m % 2 === 0) {
f = data;
} else if (f) {
fieldValues[f] = data;
}
m ;
}
return { xid: parseXId(raw[0]), fieldValues: fieldValues };
}
export function convertMap(raw: ConditionalArray): Map<string, Raw> {
const fieldValues: Map<string, Raw> = new Map();
let f: string | undefined = undefined;
let m = 0;
for (const data of raw) {
if (m % 2 === 0 && typeof data === "string") {
f = data;
} else if (m % 2 === 1 && f) {
fieldValues.set(f, data);
}
m ;
}
return fieldValues;
}
export function parseXReadReply(raw: XReadReplyRaw): XReadReply {
const out: XReadStream[] = [];
for (const [key, idData] of raw ?? []) {
const messages = [];
for (const rawMsg of idData) {
messages.push(parseXMessage(rawMsg));
}
out.push({ key, messages });
}
return out;
}
export function parseXId(raw: string): XId {
const [ms, sn] = raw.split("-");
return { unixMs: parseInt(ms), seqNo: parseInt(sn) };
}
export function parseXPendingConsumers(
raws: ConditionalArray,
): XPendingConsumer[] {
const out: XPendingConsumer[] = [];
for (const raw of raws) {
if (isCondArray(raw) && isString(raw[0]) && isString(raw[1])) {
out.push({ name: raw[0], pending: parseInt(raw[1]) });
}
}
return out;
}
export function parseXPendingCounts(raw: ConditionalArray): XPendingCount[] {
const infos: XPendingCount[] = [];
for (const r of raw) {
if (
isCondArray(r) &&
isString(r[0]) &&
isString(r[1]) &&
isNumber(r[2]) &&
isNumber(r[3])
) {
infos.push({
xid: parseXId(r[0]),
owner: r[1],
lastDeliveredMs: r[2],
timesDelivered: r[3],
});
}
}
return infos;
}
export function parseXGroupDetail(rawGroups: ConditionalArray): XGroupDetail[] {
const out = [];
for (const rawGroup of rawGroups) {
if (isCondArray(rawGroup)) {
const data = convertMap(rawGroup);
// array of arrays
const consDeets = data.get("consumers") as ConditionalArray[];
out.push({
name: rawstr(data.get("name") ?? null),
lastDeliveredId: parseXId(
rawstr(data.get("last-delivered-id") ?? null),
),
pelCount: rawnum(data.get("pel-count") ?? null),
pending: parseXPendingCounts(data.get("pending") as ConditionalArray),
consumers: parseXConsumerDetail(consDeets),
});
}
}
return out;
}
export function parseXConsumerDetail(nestedRaws: Raw[][]): XConsumerDetail[] {
const out: XConsumerDetail[] = [];
for (const raws of nestedRaws) {
const data = convertMap(raws);
const pending = (data.get("pending") as [string, number, number][]).map(
(p) => {
return {
xid: parseXId(rawstr(p[0])),
lastDeliveredMs: rawnum(p[1]),
timesDelivered: rawnum(p[2]),
};
},
);
const r = {
name: rawstr(data.get("name") ?? null),
seenTime: rawnum(data.get("seen-time") ?? null),
pelCount: rawnum(data.get("pel-count") ?? null),
pending,
};
out.push(r);
}
return out;
}
export function xidstr(
xid: XIdAdd | XIdNeg | XIdPos | XIdCreateGroup | XIdGroupRead,
) {
if (typeof xid === "string") return xid;
if (typeof xid === "number") return `${xid}-0`;
if (xid instanceof Array && xid.length > 1) return `${xid[0]}-${xid[1]}`;
if (isXId(xid)) return `${xid.unixMs}-${xid.seqNo}`;
throw "fail";
}
export function rawnum(raw: Raw): number {
return raw ? raw.toString() : 0;
}
export function rawstr(raw: Raw): string {
return raw ? raw.toString() : "";
}
// deno-lint-ignore no-explicit-any
export function isString(x: any): x is string {
return typeof x === "string";
}
// deno-lint-ignore no-explicit-any
export function isNumber(x: any): x is number {
return typeof x === "number";
}
export function isCondArray(x: Raw): x is ConditionalArray {
const l = (x as ConditionalArray).length;
if (l > 0 || l < 1) return true;
else return false;
}
function isXId(xid: XIdAdd): xid is XId {
return (xid as XId).unixMs !== undefined;
}