/
subscription.ts
383 lines (363 loc) · 11.4 KB
/
subscription.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
import { Fn, IDeref, SEMAPHORE } from "@thi.ng/api";
import { peek } from "@thi.ng/arrays";
import { implementsFunction, isFunction, isPlainObject } from "@thi.ng/checks";
import { illegalArity, illegalState } from "@thi.ng/errors";
import {
comp,
isReduced,
map,
push,
Reduced,
Reducer,
Transducer,
unreduced,
} from "@thi.ng/transducers";
import {
CloseMode,
CommonOpts,
ISubscribable,
ISubscriber,
ITransformable,
LOGGER,
State,
SubscriptionOpts,
} from "./api";
import { nextID } from "./utils/idgen";
/**
* Creates a new {@link Subscription} instance, the fundamental datatype
* and building block provided by this package.
*
* @remarks
* Most other types in rstream, including {@link Stream}s, are
* `Subscription`s and all can be:
*
* - connected into directed graphs (sync or async & not necessarily
* DAGs)
* - transformed using transducers (incl. support for early termination)
* - can have any number of subscribers (optionally each w/ their own
* transducers)
* - recursively unsubscribe themselves from parent after their last
* subscriber unsubscribed (configurable)
* - will go into a non-recoverable error state if none of the
* subscribers has an error handler itself
* - implement the {@link @thi.ng/api#IDeref} interface
*
* If a transducer is provided (via the `xform` option), all received
* values will be first processed by the transducer and only its
* transformed result(s) (if any) will be passed to downstream
* subscribers. Any uncaught errors *inside* the transducer will cause
* this subscription's error handler to be called and will stop this
* subscription from receiving any further values (by default, unless
* overridden).
*
* Subscription behavior can be customized via the additional (optional)
* options arg. See {@link CommonOpts} and {@link SubscriptionOpts} for
* further details.
*
* @example
* ```ts
* // as reactive value mechanism (same as with stream() above)
* s = subscription();
* s.subscribe(trace("s1"));
* s.subscribe(trace("s2"), { xform: tx.filter((x) => x > 25) });
*
* // external trigger
* s.next(23);
* // s1 23
* s.next(42);
* // s1 42
* // s2 42
* ```
*
* @param sub -
* @param opts -
*/
export const subscription = <A, B>(
sub?: ISubscriber<B>,
opts?: Partial<SubscriptionOpts<A, B>>
) => new Subscription(sub, opts);
export class Subscription<A, B>
implements
IDeref<B | undefined>,
ISubscriber<A>,
ISubscribable<B>,
ITransformable<B> {
id: string;
closeIn: CloseMode;
closeOut: CloseMode;
protected parent?: ISubscribable<A>;
protected subs: ISubscriber<B>[];
protected xform?: Reducer<B[], A>;
protected state: State = State.IDLE;
protected cacheLast: boolean;
protected last: any;
constructor(
sub?: ISubscriber<B>,
opts: Partial<SubscriptionOpts<A, B>> = {}
) {
this.parent = opts.parent;
this.closeIn =
opts.closeIn !== undefined ? opts.closeIn : CloseMode.LAST;
this.closeOut =
opts.closeOut !== undefined ? opts.closeOut : CloseMode.LAST;
this.cacheLast = opts.cache !== false;
this.id = opts.id || `sub-${nextID()}`;
this.last = SEMAPHORE;
this.subs = [];
if (sub) {
this.subs.push(sub);
}
if (opts.xform) {
this.xform = opts.xform(push());
}
}
deref(): B | undefined {
return this.last !== SEMAPHORE ? this.last : undefined;
}
getState() {
return this.state;
}
/**
* Creates new child subscription with given subscriber and/or
* transducer and optional subscription ID.
*/
subscribe(
sub: Partial<ISubscriber<B>>,
opts?: Partial<CommonOpts>
): Subscription<B, B>;
subscribe<C>(sub: Subscription<B, C>): Subscription<B, C>;
subscribe<C>(
xform: Transducer<B, C>,
opts?: Partial<CommonOpts>
): Subscription<B, C>;
subscribe<C>(
sub: Partial<ISubscriber<C>>,
xform: Transducer<B, C>,
opts?: Partial<CommonOpts>
): Subscription<B, C>;
subscribe(...args: any[]): any {
this.ensureState();
let sub: Subscription<any, any> | undefined;
!peek(args) && args.pop();
const opts: Partial<SubscriptionOpts<any, any>> =
args.length > 1 && isPlainObject(peek(args))
? { ...args.pop() }
: {};
switch (args.length) {
case 1:
if (isFunction(args[0])) {
opts.xform = args[0];
!opts.id && (opts.id = `xform-${nextID()}`);
} else {
sub = args[0];
}
break;
case 2:
sub = args[0];
opts.xform = args[1];
break;
default:
illegalArity(args.length);
}
if (implementsFunction(sub!, "subscribe") && !opts.xform) {
sub!.parent = this;
} else {
// FIXME inherit options from this sub or defaults?
sub = subscription<B, B>(sub, { parent: this, ...opts });
}
this.last !== SEMAPHORE && sub!.next(this.last);
return this.addWrapped(sub!);
}
/**
* Returns array of new child subscriptions for all given
* subscribers.
*
* @param subs -
*/
subscribeAll(...subs: ISubscriber<B>[]) {
const wrapped: Subscription<B, B>[] = [];
for (let s of subs) {
wrapped.push(this.subscribe(s));
}
return wrapped;
}
/**
* Creates a new child subscription using given transducers and
* optional subscription ID. Supports up to 4 transducers and if
* more than one transducer is given, composes them in left-to-right
* order using {@link @thi.ng/transducers#(comp:1)}.
*
* Shorthand for `subscribe(comp(xf1, xf2,...), id)`
*/
transform<C>(
a: Transducer<B, C>,
opts?: Partial<CommonOpts>
): Subscription<B, C>;
// prettier-ignore
transform<C, D>(a: Transducer<B, C>, b: Transducer<C, D>, opts?: Partial<CommonOpts>): Subscription<B, D>;
// prettier-ignore
transform<C, D, E>(a: Transducer<B, C>, b: Transducer<C, D>, c: Transducer<D, E>, opts?: Partial<CommonOpts>): Subscription<B, E>;
// prettier-ignore
transform<C, D, E, F>(a: Transducer<B, C>, b: Transducer<C, D>, c: Transducer<D, E>, d: Transducer<E, F>, opts?: Partial<CommonOpts>): Subscription<B, F>;
transform(...xf: any[]) {
const n = xf.length - 1;
return isPlainObject(xf[n])
? this.subscribe((<any>comp)(...xf.slice(0, n)), xf[n])
: this.subscribe((<any>comp)(...xf));
}
/**
* Syntax sugar for {@link Subscription.transform} when using a
* single {@link @thi.ng/transducers#map} transducer only. The given
* function `fn` is used as `map`'s transformation fn.
*
* @param fn
*/
map<C>(fn: Fn<B, C>): Subscription<B, C> {
return this.subscribe(map(fn));
}
/**
* If called without arg, removes this subscription from parent (if
* any), cleans up internal state and goes into DONE state. If
* called with arg, removes the sub from internal pool and if no
* other subs are remaining also cleans up itself and goes into DONE
* state.
*
* @param sub -
*/
unsubscribe(sub?: Subscription<B, any>) {
LOGGER.debug(this.id, "unsub start", sub ? sub.id : "self");
if (!sub) {
let res = true;
if (this.parent) {
res = this.parent.unsubscribe(this);
}
this.state = State.DONE;
this.cleanup();
return res;
}
LOGGER.debug(this.id, "unsub child", sub.id);
const idx = this.subs.indexOf(sub);
if (idx >= 0) {
this.subs.splice(idx, 1);
if (
this.closeOut === CloseMode.FIRST ||
(!this.subs.length && this.closeOut !== CloseMode.NEVER)
) {
this.unsubscribe();
}
return true;
}
return false;
}
next(x: A) {
if (this.state < State.DONE) {
if (this.xform) {
let acc: B[] | Reduced<B[]>;
try {
acc = this.xform[2]([], x);
} catch (e) {
this.error(e);
return;
}
const uacc = unreduced(acc);
const n = uacc.length;
for (let i = 0; i < n; i++) {
this.dispatch(uacc[i]);
}
isReduced(acc) && this.done();
} else {
this.dispatch(<any>x);
}
}
}
done() {
LOGGER.debug(this.id, "entering done()");
if (this.state < State.DONE) {
try {
if (this.xform) {
const acc = this.xform[1]([]);
const uacc = unreduced(acc);
const n = uacc.length;
for (let i = 0; i < n; i++) {
this.dispatch(uacc[i]);
}
}
} catch (e) {
this.error(e);
return;
}
this.state = State.DONE;
for (let s of this.subs.slice()) {
try {
s.done && s.done();
} catch (e) {
s.error ? s.error(e) : this.error(e);
}
}
this.unsubscribe();
LOGGER.debug(this.id, "exiting done()");
}
}
error(e: any) {
this.state = State.ERROR;
const subs = this.subs;
let notified = false;
if (subs.length) {
for (let s of subs.slice()) {
if (s.error) {
s.error(e);
notified = true;
}
}
}
if (!notified) {
LOGGER.warn(this.id, "unhandled error:", e);
if (this.parent) {
LOGGER.debug(this.id, "unsubscribing...");
this.unsubscribe();
this.state = State.ERROR;
}
}
}
protected addWrapped(wrapped: Subscription<any, any>) {
this.subs.push(wrapped);
this.state = State.ACTIVE;
return wrapped;
}
protected dispatch(x: B) {
// LOGGER.debug(this.id, "dispatch", x);
this.cacheLast && (this.last = x);
const subs = this.subs;
let n = subs.length;
let s: ISubscriber<B>;
if (n === 1) {
s = subs[0];
try {
s.next && s.next(x);
} catch (e) {
s.error ? s.error(e) : this.error(e);
}
} else {
for (; --n >= 0; ) {
s = subs[n];
try {
s.next && s.next(x);
} catch (e) {
s.error ? s.error(e) : this.error(e);
}
}
}
}
protected ensureState() {
if (this.state >= State.DONE) {
illegalState(`operation not allowed in state ${this.state}`);
}
}
protected cleanup() {
LOGGER.debug(this.id, "cleanup");
this.subs.length = 0;
delete this.parent;
delete this.xform;
delete this.last;
}
}