@dxos/async 0.8.4-main.fffef41 → 0.8.4-staging.ac66bdf99f
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/browser/index.mjs +95 -15
- package/dist/lib/browser/index.mjs.map +3 -3
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node-esm/index.mjs +95 -15
- package/dist/lib/node-esm/index.mjs.map +3 -3
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/cleanup.d.ts +2 -2
- package/dist/types/src/cleanup.d.ts.map +1 -1
- package/dist/types/src/debounce.d.ts +15 -10
- package/dist/types/src/debounce.d.ts.map +1 -1
- package/dist/types/src/observable-value.d.ts.map +1 -1
- package/dist/types/src/persistent-lifecycle.d.ts +2 -2
- package/dist/types/src/persistent-lifecycle.d.ts.map +1 -1
- package/dist/types/src/task-scheduling.d.ts +29 -1
- package/dist/types/src/task-scheduling.d.ts.map +1 -1
- package/dist/types/src/timeout.d.ts +1 -1
- package/dist/types/src/timeout.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +11 -7
- package/src/cleanup.ts +7 -4
- package/src/debounce.ts +19 -14
- package/src/event-emitter.test.ts +0 -1
- package/src/observable-value.ts +4 -2
- package/src/persistent-lifecycle.ts +2 -2
- package/src/task-scheduling.ts +95 -1
- package/src/timeout.ts +6 -9
package/package.json
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxos/async",
|
|
3
|
-
"version": "0.8.4-
|
|
3
|
+
"version": "0.8.4-staging.ac66bdf99f",
|
|
4
4
|
"description": "Async utilities.",
|
|
5
5
|
"homepage": "https://dxos.org",
|
|
6
6
|
"bugs": "https://github.com/dxos/dxos/issues",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/dxos/dxos"
|
|
10
|
+
},
|
|
7
11
|
"license": "MIT",
|
|
8
12
|
"author": "DXOS.org",
|
|
9
13
|
"sideEffects": true,
|
|
@@ -29,12 +33,12 @@
|
|
|
29
33
|
"dependencies": {
|
|
30
34
|
"zen-observable": "^0.10.0",
|
|
31
35
|
"zen-push": "^0.3.1",
|
|
32
|
-
"@dxos/context": "0.8.4-
|
|
33
|
-
"@dxos/
|
|
34
|
-
"@dxos/debug": "0.8.4-
|
|
35
|
-
"@dxos/
|
|
36
|
-
"@dxos/
|
|
37
|
-
"@dxos/
|
|
36
|
+
"@dxos/context": "0.8.4-staging.ac66bdf99f",
|
|
37
|
+
"@dxos/invariant": "0.8.4-staging.ac66bdf99f",
|
|
38
|
+
"@dxos/debug": "0.8.4-staging.ac66bdf99f",
|
|
39
|
+
"@dxos/log": "0.8.4-staging.ac66bdf99f",
|
|
40
|
+
"@dxos/node-std": "0.8.4-staging.ac66bdf99f",
|
|
41
|
+
"@dxos/util": "0.8.4-staging.ac66bdf99f"
|
|
38
42
|
},
|
|
39
43
|
"devDependencies": {
|
|
40
44
|
"@types/zen-observable": "^0.8.3"
|
package/src/cleanup.ts
CHANGED
|
@@ -10,9 +10,12 @@ export type CleanupFn = () => void;
|
|
|
10
10
|
* Combine multiple cleanup functions into a single cleanup function.
|
|
11
11
|
* Can be used in effect hooks in conjunction with `addEventListener`.
|
|
12
12
|
*/
|
|
13
|
-
export const combine = (...cleanupFns: (CleanupFn | CleanupFn[])[]): CleanupFn => {
|
|
13
|
+
export const combine = (...cleanupFns: (boolean | undefined | CleanupFn | CleanupFn[])[]): CleanupFn => {
|
|
14
14
|
return () => {
|
|
15
|
-
cleanupFns
|
|
15
|
+
cleanupFns
|
|
16
|
+
.flat()
|
|
17
|
+
.filter((f): f is CleanupFn => typeof f === 'function')
|
|
18
|
+
.forEach((cleanupFn) => cleanupFn());
|
|
16
19
|
};
|
|
17
20
|
};
|
|
18
21
|
|
|
@@ -51,8 +54,8 @@ export const addEventListener = <T extends EventTarget, K extends keyof EventMap
|
|
|
51
54
|
export class SubscriptionList {
|
|
52
55
|
private readonly _cleanups: CleanupFn[] = [];
|
|
53
56
|
|
|
54
|
-
add(cb: CleanupFn): this {
|
|
55
|
-
this._cleanups.push(cb);
|
|
57
|
+
add(...cb: CleanupFn[]): this {
|
|
58
|
+
this._cleanups.push(...cb);
|
|
56
59
|
return this;
|
|
57
60
|
}
|
|
58
61
|
|
package/src/debounce.ts
CHANGED
|
@@ -12,7 +12,7 @@ type Callback = (...args: any[]) => void;
|
|
|
12
12
|
* @param delay Time to wait before invoking the callback.
|
|
13
13
|
* @returns A new function that schedules the callback once and ignores subsequent calls until executed.
|
|
14
14
|
*/
|
|
15
|
-
export const delay = <
|
|
15
|
+
export const delay = <F extends Callback>(cb: F, delay = 100): F => {
|
|
16
16
|
let pending = false;
|
|
17
17
|
return ((...args: any[]) => {
|
|
18
18
|
if (pending) {
|
|
@@ -27,32 +27,37 @@ export const delay = <CB extends Callback>(cb: CB, delay = 100): CB => {
|
|
|
27
27
|
pending = false;
|
|
28
28
|
}
|
|
29
29
|
}, delay);
|
|
30
|
-
}) as
|
|
30
|
+
}) as F;
|
|
31
31
|
};
|
|
32
32
|
|
|
33
33
|
/**
|
|
34
|
-
* Debounce callback.
|
|
34
|
+
* Debounce callback: delays execution until calls stop.
|
|
35
|
+
* Each new call resets the timer, so the callback fires only after the delay elapses with no further calls (trailing-edge).
|
|
36
|
+
* Use when you want to react to the end of a burst of events (e.g. user stops typing).
|
|
35
37
|
*
|
|
36
38
|
* @param cb Callback to invoke.
|
|
37
|
-
* @param delay
|
|
38
|
-
* @returns
|
|
39
|
+
* @param delay Idle time (ms) to wait after the last call before invoking.
|
|
40
|
+
* @returns Wrapped function that postpones invocation until activity ceases.
|
|
39
41
|
*/
|
|
40
|
-
export const debounce = <
|
|
42
|
+
export const debounce = <F extends Callback>(cb: F, delay = 100): F => {
|
|
41
43
|
let t: ReturnType<typeof setTimeout>;
|
|
42
44
|
return ((...args: any[]) => {
|
|
43
45
|
clearTimeout(t);
|
|
44
46
|
t = setTimeout(() => cb(...args), delay);
|
|
45
|
-
}) as
|
|
47
|
+
}) as F;
|
|
46
48
|
};
|
|
47
49
|
|
|
48
50
|
/**
|
|
49
|
-
* Throttle callback.
|
|
51
|
+
* Throttle callback: limits execution to at most once per interval.
|
|
52
|
+
* The callback fires immediately on the first call;
|
|
53
|
+
* subsequent calls within the same interval are dropped (leading-edge).
|
|
54
|
+
* Use when you need regular updates at a bounded rate (e.g. scroll or resize handlers).
|
|
50
55
|
*
|
|
51
56
|
* @param cb Callback to invoke.
|
|
52
|
-
* @param delay
|
|
53
|
-
* @returns
|
|
57
|
+
* @param delay Minimum interval (ms) between successive invocations.
|
|
58
|
+
* @returns Wrapped function that rate-limits invocations.
|
|
54
59
|
*/
|
|
55
|
-
export const throttle = <
|
|
60
|
+
export const throttle = <F extends Callback>(cb: F, delay = 100): F => {
|
|
56
61
|
let lastCall = 0;
|
|
57
62
|
return ((...args: any[]) => {
|
|
58
63
|
const now = Date.now();
|
|
@@ -60,7 +65,7 @@ export const throttle = <CB extends Callback>(cb: CB, delay = 100): CB => {
|
|
|
60
65
|
cb(...args);
|
|
61
66
|
lastCall = now;
|
|
62
67
|
}
|
|
63
|
-
}) as
|
|
68
|
+
}) as F;
|
|
64
69
|
};
|
|
65
70
|
|
|
66
71
|
/**
|
|
@@ -72,7 +77,7 @@ export const throttle = <CB extends Callback>(cb: CB, delay = 100): CB => {
|
|
|
72
77
|
* @param delay Time window for both throttle and debounce.
|
|
73
78
|
* @returns A new function that combines throttle and debounce behavior.
|
|
74
79
|
*/
|
|
75
|
-
export const debounceAndThrottle = <
|
|
80
|
+
export const debounceAndThrottle = <F extends Callback>(cb: F, delay = 100): F => {
|
|
76
81
|
let timeout: ReturnType<typeof setTimeout>;
|
|
77
82
|
let lastCall = 0;
|
|
78
83
|
|
|
@@ -94,5 +99,5 @@ export const debounceAndThrottle = <CB extends Callback>(cb: CB, delay = 100): C
|
|
|
94
99
|
lastCall = Date.now();
|
|
95
100
|
}, delay - delta);
|
|
96
101
|
}
|
|
97
|
-
}) as
|
|
102
|
+
}) as F;
|
|
98
103
|
};
|
package/src/observable-value.ts
CHANGED
|
@@ -66,8 +66,10 @@ export interface CancellableObservableEvents {
|
|
|
66
66
|
/**
|
|
67
67
|
* @deprecated
|
|
68
68
|
*/
|
|
69
|
-
export interface CancellableObservable<
|
|
70
|
-
extends
|
|
69
|
+
export interface CancellableObservable<
|
|
70
|
+
Events extends CancellableObservableEvents,
|
|
71
|
+
Value = unknown,
|
|
72
|
+
> extends ObservableValue<Events, Value> {
|
|
71
73
|
cancel(): Promise<void>;
|
|
72
74
|
}
|
|
73
75
|
|
|
@@ -13,7 +13,7 @@ import { sleep } from './timeout';
|
|
|
13
13
|
const INIT_RESTART_DELAY = 100;
|
|
14
14
|
const DEFAULT_MAX_RESTART_DELAY = 5000;
|
|
15
15
|
|
|
16
|
-
export type
|
|
16
|
+
export type PersistentLifecycleProps<T> = {
|
|
17
17
|
/**
|
|
18
18
|
* Create connection.
|
|
19
19
|
* If promise resolves successfully, connection is considered established.
|
|
@@ -51,7 +51,7 @@ export class PersistentLifecycle<T> extends Resource {
|
|
|
51
51
|
private _restartTask?: DeferredTask = undefined;
|
|
52
52
|
private _restartAfter = 0;
|
|
53
53
|
|
|
54
|
-
constructor({ start, stop, onRestart, maxRestartDelay = DEFAULT_MAX_RESTART_DELAY }:
|
|
54
|
+
constructor({ start, stop, onRestart, maxRestartDelay = DEFAULT_MAX_RESTART_DELAY }: PersistentLifecycleProps<T>) {
|
|
55
55
|
super();
|
|
56
56
|
this._start = start;
|
|
57
57
|
this._stop = stop;
|
package/src/task-scheduling.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Copyright 2022 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { Context, ContextDisposedError } from '@dxos/context';
|
|
6
6
|
import { StackTrace } from '@dxos/debug';
|
|
7
7
|
import { type MaybePromise } from '@dxos/util';
|
|
8
8
|
|
|
@@ -77,6 +77,100 @@ export class DeferredTask {
|
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
// TODO(dmaretskyi): Protyping this an alternative API to DeferredTask.
|
|
81
|
+
export class AsyncTask {
|
|
82
|
+
#callback: () => Promise<void>;
|
|
83
|
+
#ctx?: Context = undefined;
|
|
84
|
+
|
|
85
|
+
#scheduled = false;
|
|
86
|
+
#currentTask: Promise<void> | null = null; // Can't be rejected.
|
|
87
|
+
#nextTask = new Trigger();
|
|
88
|
+
|
|
89
|
+
constructor(callback: () => Promise<void>) {
|
|
90
|
+
this.#callback = callback;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get scheduled() {
|
|
94
|
+
return this.#scheduled;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Context of the resource that owns the task.
|
|
99
|
+
* When the context is disposed, the task is cancelled and cannot be scheduled again.
|
|
100
|
+
*/
|
|
101
|
+
open(): void {
|
|
102
|
+
this.#ctx = new Context();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Closes the task and waits for it to finish if it is running.
|
|
107
|
+
*/
|
|
108
|
+
async close(): Promise<void> {
|
|
109
|
+
await this.#ctx?.dispose();
|
|
110
|
+
await this.join();
|
|
111
|
+
this.#ctx = undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
[Symbol.asyncDispose](): Promise<void> {
|
|
115
|
+
return this.close();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Schedule the task to run asynchronously.
|
|
120
|
+
*/
|
|
121
|
+
// TODO(dmaretskyi): Add scheduleAt. Where the earlier time will override the later one.
|
|
122
|
+
schedule(): void {
|
|
123
|
+
if (!this.#ctx || this.#ctx.disposed) {
|
|
124
|
+
throw new Error('AsyncTask not open');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (this.#scheduled) {
|
|
128
|
+
return; // Already scheduled.
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
scheduleTask(this.#ctx, async () => {
|
|
132
|
+
// The previous task might still be running, so we need to wait for it to finish.
|
|
133
|
+
await this.#currentTask; // Can't be rejected.
|
|
134
|
+
|
|
135
|
+
if (!this.#ctx || this.#ctx.disposed) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Reset the flag. New tasks can now be scheduled. They would wait for the callback to finish.
|
|
140
|
+
this.#scheduled = false;
|
|
141
|
+
const completionTrigger = this.#nextTask;
|
|
142
|
+
this.#nextTask = new Trigger(); // Re-create the trigger as opposed to resetting it since there might be listeners waiting for it.
|
|
143
|
+
|
|
144
|
+
// Store the promise so that new tasks could wait for this one to finish.
|
|
145
|
+
this.#currentTask = runInContextAsync(this.#ctx, () => this.#callback()).then(() => {
|
|
146
|
+
completionTrigger.wake();
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
this.#scheduled = true;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Schedule the task to run and wait for it to finish.
|
|
155
|
+
*/
|
|
156
|
+
async runBlocking(): Promise<void> {
|
|
157
|
+
if (this.#ctx?.disposed) {
|
|
158
|
+
throw new ContextDisposedError();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
this.schedule();
|
|
162
|
+
await this.#nextTask.wait();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Waits for the current task to finish if it is running.
|
|
167
|
+
* Does not schedule a new task.
|
|
168
|
+
*/
|
|
169
|
+
async join(): Promise<void> {
|
|
170
|
+
await this.#currentTask;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
80
174
|
export const runInContext = (ctx: Context, fn: () => void) => {
|
|
81
175
|
try {
|
|
82
176
|
fn();
|
package/src/timeout.ts
CHANGED
|
@@ -4,7 +4,6 @@
|
|
|
4
4
|
|
|
5
5
|
import { type Context, ContextDisposedError } from '@dxos/context';
|
|
6
6
|
|
|
7
|
-
import { promiseFromCallback } from './callback';
|
|
8
7
|
import { TimeoutError } from './errors';
|
|
9
8
|
|
|
10
9
|
/**
|
|
@@ -57,12 +56,11 @@ export const asyncReturn = () => sleep(0);
|
|
|
57
56
|
/**
|
|
58
57
|
* Wait for promise or throw error.
|
|
59
58
|
*/
|
|
60
|
-
export const asyncTimeout = async <T>(
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
): Promise<T> => {
|
|
59
|
+
export const asyncTimeout = async <T>(promise: Promise<T>, timeout: number, err?: Error | string): Promise<T> => {
|
|
60
|
+
if (typeof promise === 'function') {
|
|
61
|
+
throw new Error('First argument must be a promise.');
|
|
62
|
+
}
|
|
63
|
+
|
|
66
64
|
let timeoutId: NodeJS.Timeout;
|
|
67
65
|
const throwable = err === undefined || typeof err === 'string' ? new TimeoutError(timeout, err) : err;
|
|
68
66
|
const timeoutPromise = new Promise<T>((resolve, reject) => {
|
|
@@ -73,8 +71,7 @@ export const asyncTimeout = async <T>(
|
|
|
73
71
|
unrefTimeout(timeoutId);
|
|
74
72
|
});
|
|
75
73
|
|
|
76
|
-
|
|
77
|
-
return await Promise.race([conditionTimeout, timeoutPromise]).finally(() => {
|
|
74
|
+
return await Promise.race([promise, timeoutPromise]).finally(() => {
|
|
78
75
|
clearTimeout(timeoutId);
|
|
79
76
|
});
|
|
80
77
|
};
|