-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
574 lines (509 loc) · 16.5 KB
/
mod.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// deno-lint-ignore-file no-explicit-any
import { createErreurStore, type TErreurStore } from "@dldc/erreur";
export type TUnsubscribe = () => void;
export type TOnUnsubscribed = () => void;
export type TSubscriptionCallback<T> = (value: T) => void;
export type VoidSubscriptionCallback = () => void;
export type UnsubscribeAllMethod = () => void;
export type SubscribeMethod<T> = (
callback: TSubscriptionCallback<T>,
onUnsubscribe?: TOnUnsubscribed,
) => TUnsubscribe;
export type SubscribeByIdMethod<T> = (
subId: string,
callback: TSubscriptionCallback<T>,
onUnsubscribe?: TOnUnsubscribed,
) => TUnsubscribe;
export type VoidSubscribeMethod = (
callback: VoidSubscriptionCallback,
onUnsubscribe?: TOnUnsubscribed,
) => TUnsubscribe;
export type VoidSubscribeByIdMethod = (
subId: string,
callback: VoidSubscriptionCallback,
onUnsubscribe?: TOnUnsubscribed,
) => TUnsubscribe;
export type IsSubscribedMethod<T> = (
callback: TSubscriptionCallback<T>,
) => boolean;
export type IsSubscribedByIdMethod = (subId: string) => boolean;
export type UnsubscribeMethod<T> = (callback: TSubscriptionCallback<T>) => void;
export type UnsubscribeByIdMethod = (subId: string) => void;
export type VoidIsSubscribedMethod = (
callback: VoidSubscriptionCallback,
) => boolean;
export type VoidIsSubscribedByIdMethod = (subId: string) => boolean;
export type VoidUnsubscribeMethod = (
callback: VoidSubscriptionCallback,
) => void;
export type VoidUnsubscribeByIdMethod = (subId: string) => void;
export type BatchMethod = <Result>(callback: () => Result) => Result;
export const IS_SUBSCRIPTION = Symbol("IS_SUBSCRIPTION");
export interface TSubscription<Data> {
readonly [IS_SUBSCRIPTION]: true;
readonly scheduler: TScheduler;
readonly subscribe: SubscribeMethod<Data>;
readonly subscribeById: SubscribeByIdMethod<Data>;
readonly unsubscribe: UnsubscribeMethod<Data>;
readonly unsubscribeById: UnsubscribeByIdMethod;
readonly isSubscribed: IsSubscribedMethod<Data>;
readonly isSubscribedById: IsSubscribedByIdMethod;
readonly unsubscribeAll: UnsubscribeAllMethod;
readonly batch: BatchMethod;
readonly size: () => number;
readonly emit: (newValue: Data) => void;
readonly destroy: () => void;
readonly isDestroyed: () => boolean;
}
export interface TVoidSubscription {
readonly scheduler: TScheduler;
readonly subscribe: VoidSubscribeMethod;
readonly subscribeById: VoidSubscribeByIdMethod;
readonly unsubscribe: VoidUnsubscribeMethod;
readonly unsubscribeById: VoidUnsubscribeByIdMethod;
readonly isSubscribed: VoidIsSubscribedMethod;
readonly isSubscribedById: VoidIsSubscribedByIdMethod;
readonly unsubscribeAll: UnsubscribeAllMethod;
readonly batch: BatchMethod;
readonly size: () => number;
readonly emit: () => void;
readonly destroy: () => void;
readonly isDestroyed: () => boolean;
}
export interface TSubscriptionOptions {
readonly onFirstSubscription?: () => void;
readonly onLastUnsubscribe?: () => void;
}
export interface TSchedulerOptions {
readonly onFirstSubscription?: () => void;
readonly onLastUnsubscribe?: () => void;
readonly onDestroy?: () => void;
readonly maxSubscriptionCount?: number;
readonly maxRecursiveEmit?: number;
readonly maxUnsubscribeAllLoop?: number;
}
export type TSchedulerEmit = <Data>(
subscription: TSubscription<Data>,
subscriptionOptions: TSubscriptionOptions,
callback: TSubscriptionCallback<Data>,
subId: string | null,
onUnsubscribe: TOnUnsubscribed | undefined,
) => TUnsubscribe;
export type TSchedulerIsSubscribed = <Data>(
subscription: TSubscription<Data>,
subId: string | null,
callback?: TSubscriptionCallback<Data>,
) => boolean;
export type TSchedulerUnsubscribe = <Data>(
subscription: TSubscription<Data>,
subId: string | null,
callback?: TSubscriptionCallback<Data>,
) => void;
export const IS_SCHEDULER = Symbol("IS_SCHEDULER");
export interface TScheduler {
readonly [IS_SCHEDULER]: true;
readonly size: (subscription: TSubscription<any> | null) => number;
readonly isDestroyed: () => boolean;
readonly destroy: () => void;
readonly emit: <Data>(
subscription: TSubscription<Data>,
newValue: Data,
) => void;
readonly batch: BatchMethod;
readonly unsubscribeAll: (subscription: TSubscription<any> | null) => void;
readonly subscribe: TSchedulerEmit;
readonly isSubscribed: TSchedulerIsSubscribed;
readonly unsubscribe: TSchedulerUnsubscribe;
}
export function createScheduler(options: TSchedulerOptions = {}): TScheduler {
const {
onFirstSubscription,
onLastUnsubscribe,
onDestroy,
maxRecursiveEmit = 1000,
maxSubscriptionCount = 10000,
maxUnsubscribeAllLoop = 1000,
} = options;
interface TSubscriptionItem<Data> {
subscription: TSubscription<Data>;
callback: TSubscriptionCallback<Data>;
subId: string | null;
unsubscribe: TUnsubscribe;
onUnsubscribe: TOnUnsubscribed | undefined;
}
interface TEmitQueueItem<Data> {
value: Data;
subscription: TSubscription<Data>;
}
const subscriptions: Array<TSubscriptionItem<any>> = [];
let nextSubscriptions: Array<TSubscriptionItem<any>> = [];
const emitQueue: Array<TEmitQueueItem<any>> = [];
let isEmitting = false;
let destroyed = false;
return {
[IS_SCHEDULER]: true,
size,
isDestroyed,
destroy,
emit,
batch,
unsubscribeAll,
subscribe,
isSubscribed,
unsubscribe,
};
function size(subscription: TSubscription<any> | null): number {
if (!subscription) {
return subscriptions.length;
}
return subscriptions.filter((sub) => sub.subscription === subscription)
.length;
}
function isDestroyed() {
return destroyed;
}
function destroy() {
if (destroyed) {
return;
}
destroyed = true;
unsubscribeAll(null);
if (onDestroy) {
onDestroy();
}
}
function emit<Data>(subscription: TSubscription<Data>, newValue: Data): void {
if (destroyed) {
return throwSubscriptionDestroyed();
}
emitQueue.push({ value: newValue, subscription });
if (isEmitting) {
return;
}
isEmitting = true;
handleEmitQueue();
}
function batch<Result>(callback: () => Result): Result {
if (isEmitting) {
return callback();
}
isEmitting = true;
const result = callback();
handleEmitQueue();
return result;
}
function handleEmitQueue() {
let emitQueueSafe = maxRecursiveEmit + 1; // add one because we don't count the first one
while (emitQueueSafe > 0 && emitQueue.length > 0) {
emitQueueSafe--;
const emitItem = emitQueue.shift()!;
nextSubscriptions = [...subscriptions];
let safe = maxSubscriptionCount;
while (safe > 0 && nextSubscriptions.length > 0) {
safe--;
// cannot be undefined because length > 0
const subItem = nextSubscriptions.shift()!;
if (subItem.subscription === emitItem.subscription) {
subItem.callback(emitItem.value);
}
}
if (safe <= 0) {
isEmitting = false;
return throwMaxSubscriptionCountReached();
}
}
isEmitting = false;
if (emitQueueSafe <= 0) {
return throwMaxRecursiveEmitReached(maxRecursiveEmit);
}
}
function unsubscribeAll(subscription: TSubscription<any> | null): void {
let safe = maxUnsubscribeAllLoop + subscriptions.length;
while (safe > 0) {
if (subscriptions.length === 0) {
break;
}
const nextItem = subscriptions.find((item) =>
subscription === null || item.subscription === subscription
);
if (!nextItem) {
break;
}
safe--;
nextItem.unsubscribe();
}
if (safe <= 0) {
return throwMaxUnsubscribeAllLoopReached(maxUnsubscribeAllLoop);
}
// Note: we don't need to clear the emit queue because the unsubscribe() will take care of it
return;
}
function subscribe<Data>(
subscription: TSubscription<Data>,
subscriptionOptions: TSubscriptionOptions,
callback: TSubscriptionCallback<Data>,
subId: string | null,
onUnsubscribe: TOnUnsubscribed | undefined,
): TUnsubscribe {
if (destroyed) {
return throwSubscriptionDestroyed();
}
if (typeof callback !== "function") {
return throwInvalidCallback();
}
const alreadySubscribed = findSubscriptionItem(
subscription,
subId,
callback,
);
if (alreadySubscribed) {
if (subId !== null) {
// We have a subId
// We need to update callback and onUnsubscribe
alreadySubscribed.callback = callback;
}
alreadySubscribed.onUnsubscribe = onUnsubscribe;
// Now we move move the subscription to the end
const subIndex = subscriptions.indexOf(alreadySubscribed);
subscriptions.splice(subIndex, 1);
subscriptions.push(alreadySubscribed);
// return the unsub
return alreadySubscribed.unsubscribe;
}
// New subscription
const subSizeBefore = subscriptionOptions.onFirstSubscription
? subscriptions.filter((i) => i.subscription === subscription).length
: 0;
let isSubscribed = true;
subscriptions.push({
subscription,
subId,
callback: callback,
unsubscribe: unsubscribeCurrent,
onUnsubscribe,
});
if (subscriptions.length === 1 && onFirstSubscription) {
onFirstSubscription();
}
if (subscriptionOptions.onFirstSubscription && subSizeBefore === 0) {
const subSizeAfter = subscriptions.filter((i) =>
i.subscription === subscription
).length;
if (subSizeAfter === 1) {
subscriptionOptions.onFirstSubscription();
}
}
function unsubscribeCurrent(): void {
if (!isSubscribed) {
return;
}
isSubscribed = false;
const index = subscriptions.findIndex((i) =>
i.subscription === subscription && i.callback === callback
);
// isSubscribed is true but the callback is not in the list
// this should not happend but if it does we ignore the unsub
/* istanbul ignore next */
if (index === -1) {
console.warn(
`Subscribe (isSubscribed === true) callback is not in the subscriptions list. Please report a bug.`,
);
return;
}
const item = subscriptions[index];
const subSizeBefore = subscriptionOptions.onLastUnsubscribe
? subscriptions.filter((i) => i.subscription === subscription).length
: 0;
subscriptions.splice(index, 1);
const queueIndex = nextSubscriptions.findIndex((i) =>
i.callback === callback
);
if (queueIndex >= 0) {
nextSubscriptions.splice(queueIndex, 1);
}
if (item.onUnsubscribe) {
item.onUnsubscribe();
}
if (subscriptionOptions.onLastUnsubscribe && subSizeBefore > 0) {
const subSizeAfter = subscriptions.filter((i) =>
i.subscription === subscription
).length;
if (subSizeAfter === 0) {
subscriptionOptions.onLastUnsubscribe();
}
}
if (subscriptions.length === 0 && onLastUnsubscribe) {
onLastUnsubscribe();
}
}
return unsubscribeCurrent;
}
function findSubscriptionItem<Data>(
subscription: TSubscription<Data>,
subId: string | null,
callback?: TSubscriptionCallback<any>,
): TSubscriptionItem<Data> | undefined {
return subscriptions.find((item) => {
if (item.subscription !== subscription) {
return false;
}
return subId === null ? item.callback === callback : item.subId === subId;
}) as TSubscriptionItem<Data> | undefined;
}
function isSubscribed<Data>(
subscription: TSubscription<Data>,
subId: string | null,
callback?: TSubscriptionCallback<Data>,
): boolean {
const subscriptionItem = findSubscriptionItem(
subscription,
subId,
callback,
);
return subscriptionItem !== undefined;
}
function unsubscribe<Data>(
subscription: TSubscription<Data>,
subId: string | null,
callback?: TSubscriptionCallback<Data>,
): void {
const subscriptionItem = findSubscriptionItem(
subscription,
subId,
callback,
);
if (subscriptionItem) {
subscriptionItem.unsubscribe();
}
}
}
export function createVoidSubscription(
scheduler?: TSchedulerOptions,
): TVoidSubscription;
export function createVoidSubscription(
scheduler: TScheduler,
options?: TSubscriptionOptions,
): TVoidSubscription;
export function createVoidSubscription(
scheduler: TSchedulerOptions | TScheduler = {},
options: TSubscriptionOptions = {},
): TVoidSubscription {
return createSubscriptionInternal<void>(scheduler, options);
}
export function createSubscription<Data>(
scheduler?: TSchedulerOptions,
): TSubscription<Data>;
export function createSubscription<Data>(
scheduler?: TScheduler,
options?: TSubscriptionOptions,
): TSubscription<Data>;
export function createSubscription<Data>(
scheduler: TSchedulerOptions | TScheduler = {},
options: TSubscriptionOptions = {},
): TSubscription<Data> {
return createSubscriptionInternal<Data>(scheduler, options);
}
function createSubscriptionInternal<Data>(
scheduler: TSchedulerOptions | TScheduler = {},
options: TSubscriptionOptions = {},
): TSubscription<Data> {
const sch = isScheduler(scheduler) ? scheduler : createScheduler(scheduler);
const sub: TSubscription<Data> = {
[IS_SUBSCRIPTION]: true,
scheduler: sch,
subscribe,
subscribeById,
unsubscribe,
unsubscribeById,
isSubscribed,
isSubscribedById,
unsubscribeAll,
emit,
size,
batch: sch.batch,
destroy: sch.destroy,
isDestroyed: sch.isDestroyed,
};
return sub as any;
function emit(newValue: Data): void {
return sch.emit(sub, newValue);
}
function subscribe(
callback: TSubscriptionCallback<Data>,
onUnsubscribe?: TOnUnsubscribed,
): TUnsubscribe {
return sch.subscribe(sub, options, callback, null, onUnsubscribe);
}
function subscribeById(
subId: string,
callback: TSubscriptionCallback<Data>,
onUnsubscribe?: TOnUnsubscribed,
): TUnsubscribe {
return sch.subscribe(sub, options, callback, subId, onUnsubscribe);
}
function unsubscribeAll(): void {
return sch.unsubscribeAll(sub);
}
function unsubscribe(callback: TSubscriptionCallback<Data>): void {
sch.unsubscribe(sub, null, callback);
}
function unsubscribeById(subId: string): void {
sch.unsubscribe(sub, subId);
}
function isSubscribed(callback: TSubscriptionCallback<Data>): boolean {
return sch.isSubscribed(sub, null, callback);
}
function isSubscribedById(subId: string): boolean {
return sch.isSubscribed(sub, subId);
}
function size(): number {
return sch.size(sub);
}
}
export function isScheduler(scheduler: any): scheduler is TScheduler {
return scheduler[IS_SCHEDULER] === true;
}
export function isSubscription(
subscription: any,
): subscription is TSubscription<any> {
return subscription[IS_SUBSCRIPTION] === true;
}
export type TPubSubErreurData =
| { kind: "SubscriptionDestroyed" }
| { kind: "MaxSubscriptionCountReached" }
| { kind: "MaxRecursiveEmitReached"; limit: number }
| { kind: "MaxUnsubscribeAllLoopReached"; limit: number }
| { kind: "InvalidCallback" };
const PubSubErreurInternal: TErreurStore<TPubSubErreurData> = createErreurStore<
TPubSubErreurData
>();
export const PubSubErreur = PubSubErreurInternal.asReadonly;
function throwSubscriptionDestroyed() {
return PubSubErreurInternal.setAndThrow(
"The subscription has been destroyed",
{ kind: "SubscriptionDestroyed" },
);
}
function throwMaxSubscriptionCountReached() {
return PubSubErreurInternal.setAndThrow(
`The maxSubscriptionCount has been reached. If this is expected you can use the maxSubscriptionCount option to raise the limit`,
{ kind: "MaxSubscriptionCountReached" },
);
}
function throwMaxRecursiveEmitReached(limit: number) {
return PubSubErreurInternal.setAndThrow(
`The maxRecursiveEmit limit (${limit}) has been reached, did you emit() in a callback ? If this is expected you can use the maxRecursiveEmit option to raise the limit`,
{ kind: "MaxRecursiveEmitReached", limit },
);
}
function throwMaxUnsubscribeAllLoopReached(limit: number) {
return PubSubErreurInternal.setAndThrow(
`The maxUnsubscribeAllLoop limit (${limit}) has been reached, did you call subscribe() in the onUnsubscribe callback then called unsubscribeAll ? If this is expected you can use the maxUnsubscribeAllLoop option to raise the limit`,
{ kind: "MaxUnsubscribeAllLoopReached", limit },
);
}
function throwInvalidCallback() {
return PubSubErreurInternal.setAndThrow("The callback is not a function", {
kind: "InvalidCallback",
});
}