@pontlabsai/eventdispatch 0.0.0-stage → 0.3.2
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/LICENSE +201 -0
- package/README.md +115 -2
- package/dist/cs.d.ts +32 -0
- package/dist/cs.js +203 -0
- package/dist/cs.js.map +1 -0
- package/dist/dispatcher.d.ts +66 -0
- package/dist/dispatcher.js +170 -0
- package/dist/dispatcher.js.map +1 -0
- package/dist/event.d.ts +77 -0
- package/dist/event.js +138 -0
- package/dist/event.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/recording.d.ts +103 -0
- package/dist/recording.js +239 -0
- package/dist/recording.js.map +1 -0
- package/dist/semaphore.d.ts +45 -0
- package/dist/semaphore.js +125 -0
- package/dist/semaphore.js.map +1 -0
- package/dist/sim.d.ts +68 -0
- package/dist/sim.js +203 -0
- package/dist/sim.js.map +1 -0
- package/package.json +50 -4
- package/src/cs.ts +192 -0
- package/src/dispatcher.ts +203 -0
- package/src/event.ts +172 -0
- package/src/index.ts +19 -0
- package/src/recording.ts +282 -0
- package/src/semaphore.ts +128 -0
- package/src/sim.ts +217 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,116 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @pontlabsai/eventdispatch (TypeScript)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript implementation of [eventdispatch](https://github.com/pontlabsai/eventdispatch-spec):
|
|
4
|
+
work runs as **Events**, each constructed from a serialized queue item,
|
|
5
|
+
dispatched in its own task, and finished — and only an event's
|
|
6
|
+
`finish` decides what is dispatched next.
|
|
7
|
+
|
|
8
|
+
**eventdispatch spec v0.3: base, sim, recording.** Package versions
|
|
9
|
+
0.3.x implement spec 0.3.
|
|
10
|
+
|
|
11
|
+
Runs in browsers, Node.js (20+), Deno and Bun: web-standard APIs only,
|
|
12
|
+
no dependencies. Everything runs on one thread, as async tasks.
|
|
13
|
+
|
|
14
|
+
## Install
|
|
15
|
+
|
|
16
|
+
1. **Package:** [`@pontlabsai/eventdispatch` on npm](https://www.npmjs.com/package/@pontlabsai/eventdispatch) (browsers, Node.js 20+, Deno, Bun).
|
|
17
|
+
2. **Install:** `npm install @pontlabsai/eventdispatch` (Bun: `bun add @pontlabsai/eventdispatch`; Deno: `deno add npm:@pontlabsai/eventdispatch`).
|
|
18
|
+
3. **Use:** `import { Dispatcher, item } from "@pontlabsai/eventdispatch";`.
|
|
19
|
+
4. **Other languages:** [Python](https://github.com/pontlabsai/python-eventdispatch) · [ROS 2](https://github.com/pontlabsai/ros2_eventdispatch) · [Go](https://github.com/pontlabsai/go-eventdispatch) · [Kotlin](https://github.com/pontlabsai/kotlin-eventdispatch); all follow the [spec](https://github.com/pontlabsai/eventdispatch-spec).
|
|
20
|
+
|
|
21
|
+
## Example
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { Dispatcher, item, type Env } from "@pontlabsai/eventdispatch";
|
|
25
|
+
|
|
26
|
+
const d = new Dispatcher("main", { cs: true });
|
|
27
|
+
|
|
28
|
+
// Greet prints, then hands off to the next event.
|
|
29
|
+
d.register("Greet", () => ({
|
|
30
|
+
dispatch(_env: Env, [who]: unknown[]) { console.log("hello,", who); },
|
|
31
|
+
finish(env: Env, [who]: unknown[]) { env.enqueue(item("Bye", who)); },
|
|
32
|
+
}));
|
|
33
|
+
d.register("Bye", () => ({
|
|
34
|
+
dispatch() {},
|
|
35
|
+
finish(_env: Env, [who]: unknown[]) { console.log("bye,", who); d.stop(); },
|
|
36
|
+
}));
|
|
37
|
+
d.start();
|
|
38
|
+
|
|
39
|
+
// waits for a round of "a" and "b", then runs Greet
|
|
40
|
+
d.enqueue(item("CSWait", "a,b", "main", "Greet", "world"));
|
|
41
|
+
d.enqueue(item("CSRelease", "a,b", 0, 0));
|
|
42
|
+
await d.join();
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Concepts
|
|
46
|
+
|
|
47
|
+
1. **Item**: `[name, arg1, ...]`, as decoded from JSON; `item(name, ...args)` builds one.
|
|
48
|
+
2. **Event**: `dispatch(env, args)` does the work in its own task (it may be
|
|
49
|
+
`async`); `finish(env, args)` runs when it returns and enqueues what is next.
|
|
50
|
+
An error thrown in `dispatch` releases the event without `finish`;
|
|
51
|
+
one in `finish` is logged and the dispatcher carries on.
|
|
52
|
+
3. **Dispatcher**: `new Dispatcher(name, options)`, `register`, `enqueue`,
|
|
53
|
+
`start`, `stop`, `join`. Setting `switch = false` drops items until it is
|
|
54
|
+
turned back on.
|
|
55
|
+
4. **CS** (`cs: true`): `CSWait` holds a pending item until every one of its
|
|
56
|
+
lefts has been released by `CSRelease`; `clearCSWaits()` releases waits
|
|
57
|
+
without their pending items.
|
|
58
|
+
5. **Clockless**: nothing in the base profile waits on a timer.
|
|
59
|
+
|
|
60
|
+
An event that awaits never blocks another. One that computes for a long
|
|
61
|
+
time without awaiting blocks the thread, as any JavaScript does: move that
|
|
62
|
+
work to a Worker and await its result.
|
|
63
|
+
|
|
64
|
+
## Sim clock
|
|
65
|
+
|
|
66
|
+
`SimDispatcher` runs events on a simulated clock that moves only when an
|
|
67
|
+
event completes. An event's `dispatch` returns a duration (synchronously);
|
|
68
|
+
its `finish` runs at completion time, in completion-time order, ties in
|
|
69
|
+
quote order, so a run is deterministic.
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { SimDispatcher, item, type Env } from "@pontlabsai/eventdispatch";
|
|
73
|
+
|
|
74
|
+
const sim = new SimDispatcher("sim");
|
|
75
|
+
sim.register("Move", () => ({
|
|
76
|
+
dispatch: (_env: Env, [, duration]: unknown[]) => duration as number,
|
|
77
|
+
finish: (env: Env, [name]: unknown[]) => console.log(name, "arrived at", sim.now),
|
|
78
|
+
}));
|
|
79
|
+
sim.start();
|
|
80
|
+
sim.enqueue(item("Move", "a", 3), item("Move", "b", 1)); // b arrived at 1, a arrived at 3
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`cancel(eventId)` removes a scheduled completion. Pass `stepWorld(from, to)`
|
|
84
|
+
to step an engine's world before each completion.
|
|
85
|
+
|
|
86
|
+
## Recording
|
|
87
|
+
|
|
88
|
+
Subclass `RecordingEvent` (register it with `RecordingEvent.deserialize`):
|
|
89
|
+
`dispatch` returns the quote, `runOutcome` does the work and returns the
|
|
90
|
+
outcome, and `wake` marks records that need attention.
|
|
91
|
+
`SimRecordingDispatcher` and `WallRecordingDispatcher` write a record per
|
|
92
|
+
completion to `recordings`; `await recordings.take()` returns everything
|
|
93
|
+
buffered. On the wall clock, `cancel(eventId)` aborts the event's
|
|
94
|
+
`preemptSignal`, and its PREEMPTED record is written when it returns.
|
|
95
|
+
|
|
96
|
+
## Tests
|
|
97
|
+
|
|
98
|
+
The spec is a git submodule at `spec/`:
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
git submodule update --init
|
|
102
|
+
npm install
|
|
103
|
+
npm test # build, types, unit + conformance on Node
|
|
104
|
+
node test/conformance.mjs --stress 10 --seed 1 # random delays at every hand-off
|
|
105
|
+
deno run -A test/unit.mjs && deno run -A test/conformance.mjs
|
|
106
|
+
bun test/unit.mjs && bun test/conformance.mjs
|
|
107
|
+
node test/browser.mjs # both suites in Chrome (Playwright)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`Handoff.hook` is the seam the stress mode uses: it is awaited wherever
|
|
111
|
+
work moves between tasks, and random delays there must never change an
|
|
112
|
+
outcome.
|
|
113
|
+
|
|
114
|
+
## License
|
|
115
|
+
|
|
116
|
+
Apache-2.0
|
package/dist/cs.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Env, type Event } from "./event.js";
|
|
2
|
+
/** The status a cleared CS wait is released with; its CSWait enqueues nothing (spec cs.md#clear). */
|
|
3
|
+
export declare const CLEARED_STATUS = -1;
|
|
4
|
+
/** Normalizes a lefts string: split on ",", deduplicated, sorted (spec cs.md#lefts). */
|
|
5
|
+
export declare function parseLefts(s: string): {
|
|
6
|
+
lefts: string[];
|
|
7
|
+
identifier: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Holds a pending item until every one of its lefts has been released
|
|
11
|
+
* (spec cs.md#cswait). Item: `["CSWait", lefts, requester, <pending item...>]`.
|
|
12
|
+
*/
|
|
13
|
+
export declare class CSWait implements Event {
|
|
14
|
+
private state;
|
|
15
|
+
private lefts;
|
|
16
|
+
private identifier;
|
|
17
|
+
private sem;
|
|
18
|
+
private status;
|
|
19
|
+
private using;
|
|
20
|
+
private cleaned;
|
|
21
|
+
private signalled;
|
|
22
|
+
dispatch(env: Env, args: unknown[]): Promise<void>;
|
|
23
|
+
private signal;
|
|
24
|
+
/** Gives back this CSWait's share (once); the last user removes the registration. */
|
|
25
|
+
private cleanup;
|
|
26
|
+
finish(env: Env, args: unknown[]): Promise<void>;
|
|
27
|
+
}
|
|
28
|
+
/** Releases lefts (spec cs.md#csrelease). Item: `["CSRelease", lefts, <unused>, status]`. */
|
|
29
|
+
export declare class CSRelease implements Event {
|
|
30
|
+
dispatch(env: Env, args: unknown[]): Promise<void>;
|
|
31
|
+
finish(): void;
|
|
32
|
+
}
|
package/dist/cs.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { Handoff, Signal } from "./event.js";
|
|
2
|
+
import { CompositeSemaphore } from "./semaphore.js";
|
|
3
|
+
/** The status a cleared CS wait is released with; its CSWait enqueues nothing (spec cs.md#clear). */
|
|
4
|
+
export const CLEARED_STATUS = -1;
|
|
5
|
+
/** Normalizes a lefts string: split on ",", deduplicated, sorted (spec cs.md#lefts). */
|
|
6
|
+
export function parseLefts(s) {
|
|
7
|
+
const lefts = [...new Set(s.split(","))].sort();
|
|
8
|
+
return { lefts, identifier: lefts.join(",") };
|
|
9
|
+
}
|
|
10
|
+
/** @internal A dispatcher's CS registry. */
|
|
11
|
+
export class CsState {
|
|
12
|
+
registry = new Map(); // left -> semaphore
|
|
13
|
+
ids = new Set(); // identifiers of live CSWaits
|
|
14
|
+
pending = new Map(); // dispatched CSWaits not yet waiting
|
|
15
|
+
changed = new Signal(); // a CSWait registered
|
|
16
|
+
/** Counts one CSWait on identifier as waiting (or as never going to), and wakes the gate. */
|
|
17
|
+
registered(identifier) {
|
|
18
|
+
const n = this.pending.get(identifier) ?? 0;
|
|
19
|
+
if (n <= 1)
|
|
20
|
+
this.pending.delete(identifier);
|
|
21
|
+
else
|
|
22
|
+
this.pending.set(identifier, n - 1);
|
|
23
|
+
this.changed.notify();
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Takes this batch's CSWaits out, rejects overlapping ones, and
|
|
27
|
+
* dispatches the rest (spec queue.md#cs-gate). Returns the accepted
|
|
28
|
+
* identifiers and the remaining items.
|
|
29
|
+
*/
|
|
30
|
+
dispatchWaits(d, batch) {
|
|
31
|
+
const accepted = [];
|
|
32
|
+
const rest = [];
|
|
33
|
+
const claimed = new Set(); // lefts of CSWaits accepted in this batch
|
|
34
|
+
const batchIds = new Set(); // their identifiers
|
|
35
|
+
for (const it of batch) {
|
|
36
|
+
if (!Array.isArray(it) || it.length === 0 || it[0] !== "CSWait") {
|
|
37
|
+
rest.push(it);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const raw = it[1];
|
|
41
|
+
if (typeof raw !== "string") {
|
|
42
|
+
d.warn(`malformed CSWait ${JSON.stringify(it)}`);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const { lefts, identifier } = parseLefts(raw);
|
|
46
|
+
if (this.ids.has(identifier) || batchIds.has(identifier)) {
|
|
47
|
+
// exactly the same lefts: joins
|
|
48
|
+
}
|
|
49
|
+
else if (lefts.some((l) => this.registry.has(l) || claimed.has(l))) {
|
|
50
|
+
d.warn(`CSWait ${identifier} overlaps a live CSWait, rejected`);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
for (const l of lefts)
|
|
55
|
+
claimed.add(l);
|
|
56
|
+
batchIds.add(identifier);
|
|
57
|
+
}
|
|
58
|
+
accepted.push([it, identifier]);
|
|
59
|
+
}
|
|
60
|
+
for (const [it, identifier] of accepted) {
|
|
61
|
+
this.pending.set(identifier, (this.pending.get(identifier) ?? 0) + 1);
|
|
62
|
+
if (!d.dispatchItem(it))
|
|
63
|
+
this.registered(identifier); // never started: never waits
|
|
64
|
+
}
|
|
65
|
+
return { expected: accepted.map(([, id]) => id), rest };
|
|
66
|
+
}
|
|
67
|
+
/** Whether any of these identifiers has a CSWait not yet waiting. */
|
|
68
|
+
outstanding(expected) {
|
|
69
|
+
for (const id of expected)
|
|
70
|
+
if ((this.pending.get(id) ?? 0) > 0)
|
|
71
|
+
return true;
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
/** The gate: dispatch the CSWaits, then wait until every accepted one is waiting. */
|
|
75
|
+
async gate(d, batch) {
|
|
76
|
+
await Handoff.at("gate");
|
|
77
|
+
const { expected, rest } = this.dispatchWaits(d, batch);
|
|
78
|
+
await Handoff.at("gate.wait");
|
|
79
|
+
// judged by pending counts, never by registration, which cleanup empties
|
|
80
|
+
while (this.outstanding(expected))
|
|
81
|
+
await this.changed.wait();
|
|
82
|
+
await Handoff.at("gate.open");
|
|
83
|
+
return rest;
|
|
84
|
+
}
|
|
85
|
+
/** Releases waiting CSWaits with CLEARED_STATUS: all, or those on left key's semaphore. */
|
|
86
|
+
clear(key) {
|
|
87
|
+
const done = new Set();
|
|
88
|
+
for (const [left, sem] of this.registry) {
|
|
89
|
+
if ((key !== undefined && left !== key) || done.has(sem))
|
|
90
|
+
continue;
|
|
91
|
+
done.add(sem);
|
|
92
|
+
sem.releaseAll(CLEARED_STATUS);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function csOf(env) {
|
|
97
|
+
const s = env.dispatcher.cs;
|
|
98
|
+
if (!s)
|
|
99
|
+
throw new Error("dispatcher has no CS (cs: true)");
|
|
100
|
+
return s;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Holds a pending item until every one of its lefts has been released
|
|
104
|
+
* (spec cs.md#cswait). Item: `["CSWait", lefts, requester, <pending item...>]`.
|
|
105
|
+
*/
|
|
106
|
+
export class CSWait {
|
|
107
|
+
state = null;
|
|
108
|
+
lefts = [];
|
|
109
|
+
identifier = "";
|
|
110
|
+
sem = null;
|
|
111
|
+
status = null;
|
|
112
|
+
using = false;
|
|
113
|
+
cleaned = false;
|
|
114
|
+
signalled = false;
|
|
115
|
+
async dispatch(env, args) {
|
|
116
|
+
const s = csOf(env);
|
|
117
|
+
this.state = s;
|
|
118
|
+
try {
|
|
119
|
+
if (args.length < 2)
|
|
120
|
+
throw new Error("CSWait: want lefts, requester, pending item");
|
|
121
|
+
const raw = args[0];
|
|
122
|
+
if (typeof raw !== "string")
|
|
123
|
+
throw new Error(`CSWait: lefts ${String(raw)} is not a string`);
|
|
124
|
+
const { lefts, identifier } = parseLefts(raw);
|
|
125
|
+
this.lefts = lefts;
|
|
126
|
+
this.identifier = identifier;
|
|
127
|
+
const requester = String(args[1]);
|
|
128
|
+
// join or create, in one step
|
|
129
|
+
let sem = s.ids.has(identifier) ? s.registry.get(lefts[0]) : undefined;
|
|
130
|
+
if (!sem) {
|
|
131
|
+
sem = new CompositeSemaphore(lefts);
|
|
132
|
+
s.ids.add(identifier);
|
|
133
|
+
for (const l of lefts)
|
|
134
|
+
s.registry.set(l, sem);
|
|
135
|
+
}
|
|
136
|
+
sem.users++; // created or joined: hold a share until cleanup
|
|
137
|
+
this.using = true;
|
|
138
|
+
this.sem = sem;
|
|
139
|
+
try {
|
|
140
|
+
this.status = await sem.acquire(requester, () => this.signal());
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
await this.cleanup();
|
|
144
|
+
throw e;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
this.signal(); // however dispatch ends, the gate must not wait for it
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
signal() {
|
|
152
|
+
if (this.signalled)
|
|
153
|
+
return;
|
|
154
|
+
this.signalled = true;
|
|
155
|
+
this.state?.registered(this.identifier);
|
|
156
|
+
}
|
|
157
|
+
/** Gives back this CSWait's share (once); the last user removes the registration. */
|
|
158
|
+
async cleanup() {
|
|
159
|
+
if (this.cleaned || !this.using)
|
|
160
|
+
return;
|
|
161
|
+
this.cleaned = true;
|
|
162
|
+
await Handoff.at("cswait.cleanup");
|
|
163
|
+
const s = this.state;
|
|
164
|
+
const sem = this.sem;
|
|
165
|
+
if (!s || !sem)
|
|
166
|
+
return;
|
|
167
|
+
sem.users--;
|
|
168
|
+
if (sem.users > 0)
|
|
169
|
+
return; // a later CSWait still uses it
|
|
170
|
+
const owned = s.registry.get(this.lefts[0]) === sem;
|
|
171
|
+
for (const l of this.lefts)
|
|
172
|
+
if (s.registry.get(l) === sem)
|
|
173
|
+
s.registry.delete(l);
|
|
174
|
+
if (owned)
|
|
175
|
+
s.ids.delete(this.identifier);
|
|
176
|
+
}
|
|
177
|
+
async finish(env, args) {
|
|
178
|
+
await this.cleanup();
|
|
179
|
+
if (this.status === CLEARED_STATUS)
|
|
180
|
+
return;
|
|
181
|
+
env.enqueue(args.slice(2));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/** Releases lefts (spec cs.md#csrelease). Item: `["CSRelease", lefts, <unused>, status]`. */
|
|
185
|
+
export class CSRelease {
|
|
186
|
+
async dispatch(env, args) {
|
|
187
|
+
const s = csOf(env);
|
|
188
|
+
if (args.length !== 3)
|
|
189
|
+
throw new Error(`CSRelease: want 3 arguments, got ${args.length}`);
|
|
190
|
+
const raw = args[0];
|
|
191
|
+
if (typeof raw !== "string")
|
|
192
|
+
throw new Error(`CSRelease: lefts ${String(raw)} is not a string`);
|
|
193
|
+
const status = args[2];
|
|
194
|
+
if (typeof status !== "number" || !Number.isInteger(status)) {
|
|
195
|
+
throw new Error(`CSRelease: status ${String(status)} is not an integer`);
|
|
196
|
+
}
|
|
197
|
+
await Handoff.at("semaphore.release");
|
|
198
|
+
for (const l of parseLefts(raw).lefts)
|
|
199
|
+
s.registry.get(l)?.releaseNow(l, status);
|
|
200
|
+
}
|
|
201
|
+
finish() { }
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=cs.js.map
|
package/dist/cs.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cs.js","sourceRoot":"","sources":["../src/cs.ts"],"names":[],"mappings":"AACA,OAAO,EAAwB,OAAO,EAAa,MAAM,EAAE,MAAM,YAAY,CAAC;AAC9E,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,qGAAqG;AACrG,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,CAAC,CAAC;AAEjC,wFAAwF;AACxF,MAAM,UAAU,UAAU,CAAC,CAAS;IAClC,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAChD,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAChD,CAAC;AAED,4CAA4C;AAC5C,MAAM,OAAO,OAAO;IACT,QAAQ,GAAG,IAAI,GAAG,EAA8B,CAAC,CAAC,oBAAoB;IACtE,GAAG,GAAG,IAAI,GAAG,EAAU,C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AQ;YAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;QAChG,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACvB,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;YAC5D,MAAM,IAAI,KAAK,CAAC,qBAAqB,MAAM,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;QAC3E,CAAC;QACD,MAAM,OAAO,CAAC,EAAE,CAAC,mBAAmB,CAAC,CAAC;QACtC,KAAK,MAAM,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK;YAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;IAClF,CAAC;IAED,MAAM,KAAU,CAAC;CAClB"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { CompositeSemaphore } from "./semaphore.js";
|
|
2
|
+
import { Blackboard, Env, type Deserializer, type Event, type Item, type Logger, Registry } from "./event.js";
|
|
3
|
+
/** Event ids are taken modulo this (spec queue.md#event-ids). */
|
|
4
|
+
export declare const MAX_EVENT_ID = 30000;
|
|
5
|
+
export interface DispatcherOptions {
|
|
6
|
+
blackboard?: Blackboard;
|
|
7
|
+
registry?: Registry;
|
|
8
|
+
/** Enable the composite semaphore: registers CSWait and CSRelease, and runs the CS gate. */
|
|
9
|
+
cs?: boolean;
|
|
10
|
+
logger?: Logger;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* A queue dispatch (spec queue.md): drains its queue and dispatches
|
|
14
|
+
* every item, each event in its own task. Everything runs on one
|
|
15
|
+
* thread; an event that awaits never blocks another, but one that
|
|
16
|
+
* computes without awaiting does, as any JavaScript would.
|
|
17
|
+
*/
|
|
18
|
+
export declare class Dispatcher {
|
|
19
|
+
readonly name: string;
|
|
20
|
+
readonly blackboard: Blackboard;
|
|
21
|
+
readonly registry: Registry;
|
|
22
|
+
/** The dispatch switch (spec core.md#dispatch-switch): while off, items are dropped. */
|
|
23
|
+
switch: boolean;
|
|
24
|
+
protected readonly logger: Logger;
|
|
25
|
+
protected queue: Item[];
|
|
26
|
+
protected running: boolean;
|
|
27
|
+
protected live: number;
|
|
28
|
+
protected nextId: number;
|
|
29
|
+
private wakeup;
|
|
30
|
+
private loop;
|
|
31
|
+
constructor(name: string, options?: DispatcherOptions);
|
|
32
|
+
/** Items queued and not yet taken by a drain. */
|
|
33
|
+
get queueLength(): number;
|
|
34
|
+
/** Events dispatched whose finish has not returned. */
|
|
35
|
+
get liveEvents(): number;
|
|
36
|
+
register(name: string, factory: () => Event, deserialize?: Deserializer): void;
|
|
37
|
+
/** Appends items to the queue in one batch, and wakes the dispatch. */
|
|
38
|
+
enqueue(...items: Item[]): void;
|
|
39
|
+
enqueueAll(items: Item[]): void;
|
|
40
|
+
/** Starts the drain loop (once). */
|
|
41
|
+
start(): void;
|
|
42
|
+
/** Stops after the current drain. Events already dispatched are not interrupted. */
|
|
43
|
+
stop(): void;
|
|
44
|
+
/** Resolves once the drain loop has ended. */
|
|
45
|
+
join(): Promise<void>;
|
|
46
|
+
protected wake(): void;
|
|
47
|
+
/** Resolves on the next enqueue or stop. */
|
|
48
|
+
protected idle(): Promise<void>;
|
|
49
|
+
protected run(): Promise<void>;
|
|
50
|
+
/** Deserializes and constructs an item's event, and reserves its id; throws if it fails. */
|
|
51
|
+
protected prepare(it: Item): {
|
|
52
|
+
event: Event;
|
|
53
|
+
env: Env;
|
|
54
|
+
args: unknown[];
|
|
55
|
+
};
|
|
56
|
+
/** Runs an event in its own task. */
|
|
57
|
+
protected startEvent(event: Event, env: Env, args: unknown[]): void;
|
|
58
|
+
/** Dispatch, then finish unless dispatch failed; the event is released either way. */
|
|
59
|
+
protected runEvent(event: Event, env: Env, args: unknown[]): Promise<void>;
|
|
60
|
+
/** Runs `f`; logs and returns false if it throws or rejects. */
|
|
61
|
+
protected guard(stage: string, env: Env, f: () => unknown): Promise<boolean>;
|
|
62
|
+
/** Releases waiting CSWaits without their pending items (spec cs.md#clear): all, or those on left `key`. */
|
|
63
|
+
clearCSWaits(key?: string): void;
|
|
64
|
+
/** The composite semaphore registered for `left`, if any. */
|
|
65
|
+
semaphore(left: string): CompositeSemaphore | undefined;
|
|
66
|
+
}
|