-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathstream.ts
284 lines (242 loc) · 7.95 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
import { ProviderEvent, ProviderEventData } from './api';
import { Address, getUniqueId } from './utils';
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
}
}
}
};
/**
* @category Stream
*/
export class Subscriber {
private readonly subscriptions: { [address: string]: SubscriptionsWithAddress } = {};
constructor(private readonly ton: ProviderRpcClient) {
}
public transactions(address: Address): Stream<ProviderEventData<'transactionsFound'>> {
return this._addSubscription('transactionsFound', address);
}
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];
}
await Promise.all(
Object.values(subscriptions)
.map((item: SubscriptionsWithAddress) => {
const events = Object.assign({}, item);
for (const event of Object.keys(events)) {
delete item[event as unknown as SubscriptionWithAddress];
}
return Promise.all(
Object.values(events).map((eventData) => {
if (eventData == null) {
return;
}
return eventData.subscription.then((item: Subscription<SubscriptionWithAddress>) => {
return item.unsubscribe();
}).catch(() => {
// ignore
});
})
);
})
);
}
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: (onEvent: (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);
}
});
});
}
}