-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathstream.ts
416 lines (358 loc) · 11.4 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { ProviderEvent, ProviderEventData } from './api';
import { Address, getUniqueId } from './utils';
import { TransactionId, TransactionsBatchInfo } from './models';
import { ProviderRpcClient, Subscription } from './index';
type SubscriptionWithAddress = Extract<ProviderEvent, 'transactionsFound' | 'contractStateChanged'>
type SubscriptionsWithAddress = {
[K in SubscriptionWithAddress]?: {
subscription: Promise<Subscription<K>>
handlers: {
[id: number]: {
onData: (event: ProviderEventData<K>) => void,
onEnd: () => void
}
}
}
};
type UnorderedTransactionsScannerParams = {
address: Address;
onData: (data: ProviderEventData<'transactionsFound'>) => void;
onEnd: () => void;
fromLt?: string;
fromUtime?: number;
};
class UnorderedTransactionsScanner {
private readonly address: Address;
private readonly onData: (data: ProviderEventData<'transactionsFound'>) => void;
private readonly onEnd: () => void;
private readonly fromLt?: string;
private readonly fromUtime?: number;
private continuation?: TransactionId;
private promise?: Promise<void>;
private isRunning: boolean = false;
constructor(private readonly ton: ProviderRpcClient, {
address,
onData,
onEnd,
fromLt,
fromUtime
}: UnorderedTransactionsScannerParams) {
this.address = address;
this.onData = onData;
this.onEnd = onEnd;
this.fromLt = fromLt;
this.fromUtime = fromUtime;
}
public async start() {
if (this.isRunning || this.promise != null) {
return;
}
this.isRunning = true;
this.promise = (async () => {
while (this.isRunning) {
try {
const { transactions, continuation } = await this.ton.getTransactions({
address: this.address,
continuation: this.continuation
});
if (!this.isRunning || transactions.length == null) {
break;
}
const filteredTransactions = transactions.filter((item) => (
(this.fromLt == null || item.id.lt > this.fromLt) && (
(this.fromUtime == null || item.createdAt > this.fromUtime)
)
));
if (filteredTransactions == null) {
break;
}
const info = {
maxLt: filteredTransactions[0].id.lt,
minLt: filteredTransactions[filteredTransactions.length - 1].id.lt,
batchType: 'old'
} as TransactionsBatchInfo;
this.onData({
address: this.address,
transactions: filteredTransactions,
info
});
if (continuation != null) {
this.continuation = continuation;
} else {
break;
}
} catch (e) {
console.error(e);
}
}
this.onEnd();
this.isRunning = false;
this.continuation = undefined;
})();
}
public async stop() {
this.isRunning = false;
if (this.promise != null) {
await this.promise;
} else {
this.onEnd();
}
}
}
/**
* @category Stream
*/
export class Subscriber {
private readonly subscriptions: { [address: string]: SubscriptionsWithAddress } = {};
private readonly scanners: { [id: number]: UnorderedTransactionsScanner } = {};
constructor(private readonly ton: ProviderRpcClient) {
}
/**
* Returns stream of new transactions
*/
public transactions(address: Address): Stream<ProviderEventData<'transactionsFound'>> {
return this._addSubscription('transactionsFound', address);
}
/**
* Returns stream of old transactions
*/
public oldTransactions(address: Address, filter?: { fromLt?: string, fromUtime?: number }): Stream<ProviderEventData<'transactionsFound'>> {
const id = getUniqueId();
return new StreamImpl(async (onData, onEnd) => {
const scanner = new UnorderedTransactionsScanner(this.ton, {
address,
onData,
onEnd,
...filter
});
this.scanners[id] = scanner;
await scanner.start();
}, async () => {
const scanner = this.scanners[id];
delete this.scanners[id];
if (scanner != null) {
await scanner.stop();
}
}, identity);
}
public states(address: Address): Stream<ProviderEventData<'contractStateChanged'>> {
return this._addSubscription('contractStateChanged', address);
}
public async unsubscribe(): Promise<void> {
const subscriptions = Object.assign({}, this.subscriptions);
for (const address of Object.keys(this.subscriptions)) {
delete this.subscriptions[address];
}
const scanners = Object.assign({}, this.scanners);
for (const id of Object.keys(this.scanners)) {
delete this.scanners[id as any];
}
await Promise.all(
Object.values(subscriptions)
.map(async (item: SubscriptionsWithAddress) => {
const events = Object.assign({}, item);
for (const event of Object.keys(events)) {
delete item[event as unknown as SubscriptionWithAddress];
}
await Promise.all(
Object.values(events).map((eventData) => {
if (eventData == null) {
return;
}
return eventData.subscription.then((item: Subscription<SubscriptionWithAddress>) => {
return item.unsubscribe();
}).catch(() => {
// ignore
});
})
);
}).concat(Object.values(scanners).map((item) => item.stop()))
);
}
private _addSubscription<T extends keyof SubscriptionsWithAddress>(event: T, address: Address): Stream<ProviderEventData<T>> {
type EventData = Required<SubscriptionsWithAddress>[T];
const id = getUniqueId();
return new StreamImpl((onData, onEnd) => {
let subscriptions = this.subscriptions[address.toString()] as SubscriptionsWithAddress | undefined;
let eventData = subscriptions?.[event] as EventData | undefined;
if (eventData == null) {
const handlers = {
[id]: { onData, onEnd }
} as EventData['handlers'];
eventData = {
subscription: (this.ton.subscribe as any)(event, {
address
}).then((subscription: Subscription<T>) => {
subscription.on('data', (data) => {
Object.values(handlers).forEach(({ onData }) => {
onData(data);
});
});
subscription.on('unsubscribed', () => {
Object.values(handlers).forEach(({ onEnd }) => {
delete handlers[id];
onEnd();
});
});
return subscription;
}).catch((e: Error) => {
console.error(e);
Object.values(handlers).forEach(({ onEnd }) => {
delete handlers[id];
onEnd();
});
throw e;
}),
handlers
} as EventData;
if (subscriptions == null) {
subscriptions = {
[event]: eventData
};
this.subscriptions[address.toString()] = subscriptions;
} else {
subscriptions[event] = eventData;
}
} else {
eventData.handlers[id] = { onData, onEnd } as EventData['handlers'][number];
}
}, () => {
const subscriptions = this.subscriptions[address.toString()] as SubscriptionsWithAddress | undefined;
if (subscriptions == null) {
return;
}
const eventData = subscriptions[event] as EventData | undefined;
if (eventData != null) {
delete eventData.handlers[id];
if (Object.keys(eventData.handlers).length === 0) {
const subscription = eventData.subscription as Promise<Subscription<T>>;
delete subscriptions[event];
subscription
.then((subscription) => subscription.unsubscribe())
.catch(console.debug);
}
}
if (Object.keys(subscriptions).length === 0) {
delete this.subscriptions[address.toString()];
}
}, identity);
}
}
function identity<P>(event: P, handler: (item: P) => void): void {
handler(event);
}
/**
* @category Stream
*/
export interface Stream<P, T = P> {
readonly makeProducer: (onData: (event: P) => void, onEnd: () => void) => void;
readonly stopProducer: () => void;
first(): Promise<T>
on(handler: (item: T) => void): void
merge(other: Stream<P, T>): Stream<P, T>;
map<U>(f: (item: T) => U): Stream<P, U>;
flatMap<U>(f: (item: T) => U[]): Stream<P, U>;
filter(f: (item: T) => boolean): Stream<P, T>;
filterMap<U>(f: (item: T) => (U | undefined)): Stream<P, U>;
skip(n: number): Stream<P, T>;
skipWhile(f: (item: T) => boolean): Stream<P, T>;
}
class StreamImpl<P, T> implements Stream<P, T> {
constructor(
readonly makeProducer: (onData: (event: P) => void, onEnd: () => void) => void,
readonly stopProducer: () => void,
readonly extractor: (event: P, handler: (item: T) => void) => void) {
}
public first(): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.makeProducer((event) => {
this.extractor(event, (item) => {
this.stopProducer();
resolve(item);
});
}, () => reject(new Error('Subscription closed')));
});
}
public on(handler: (item: T) => void): void {
this.makeProducer((event) => {
this.extractor(event, handler);
}, () => {
});
}
public merge(other: Stream<P, T>): Stream<P, T> {
return new StreamImpl<P, T>((onEvent, onEnd) => {
const state = {
counter: 0
};
const checkEnd = () => {
if (++state.counter == 2) {
onEnd();
}
};
this.makeProducer(onEvent, checkEnd);
other.makeProducer(onEvent, checkEnd);
}, () => {
this.stopProducer();
other.stopProducer();
}, this.extractor) as Stream<P, T>;
}
public filter(f: (item: T) => boolean): Stream<P, T> {
return new StreamImpl(this.makeProducer, this.stopProducer, (event, handler) => {
this.extractor(event, (item) => {
if (f(item)) {
handler(item);
}
});
});
}
public filterMap<U>(f: (item: T) => (U | undefined)): Stream<P, U> {
return new StreamImpl(this.makeProducer, this.stopProducer, (event, handler) => {
this.extractor(event, (item) => {
const newItem = f(item);
if (newItem !== undefined) {
handler(newItem);
}
});
});
}
public map<U>(f: (item: T) => U): Stream<P, U> {
return this.filterMap(f);
}
public flatMap<U>(f: (item: T) => U[]): Stream<P, U> {
return new StreamImpl(this.makeProducer, this.stopProducer, (event, handler) => {
this.extractor(event, (item) => {
const items = f(item);
for (const newItem of items) {
handler(newItem);
}
});
});
}
public skip(n: number): Stream<P, T> {
const state = {
index: 0
};
return new StreamImpl(this.makeProducer, this.stopProducer, (event, handler) => {
this.extractor(event, (item) => {
if (state.index >= n) {
handler(item);
} else {
++state.index;
}
});
});
}
public skipWhile(f: (item: T) => boolean): Stream<P, T> {
const state = {
shouldSkip: true
};
return new StreamImpl(this.makeProducer, this.stopProducer, (event, handler) => {
this.extractor(event, (item) => {
if (!state.shouldSkip || !f(item)) {
state.shouldSkip = false;
handler(item);
}
});
});
}
}