@yaks/threads 0.0.0-stage → 0.2.36
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 +202 -0
- package/README.md +130 -2
- package/_dist/graph.d.ts +12 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/mod.d.ts +7 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/roles.d.ts +17 -0
- package/_dist/roles.d.ts.map +1 -0
- package/_dist/thread.d.ts +23 -0
- package/_dist/thread.d.ts.map +1 -0
- package/_dist/types.d.ts +16 -0
- package/_dist/types.d.ts.map +1 -0
- package/_dist/worker.d.ts +1 -0
- package/_dist/worker.d.ts.map +1 -0
- package/deno.json +1 -0
- package/graph.js +83 -0
- package/graph.js.map +1 -0
- package/graph.ts +110 -0
- package/mod.js +6 -0
- package/mod.js.map +1 -0
- package/mod.ts +13 -0
- package/package.json +24 -4
- package/roles.js +49 -0
- package/roles.js.map +1 -0
- package/roles.ts +68 -0
- package/thread.js +119 -0
- package/thread.js.map +1 -0
- package/thread.ts +146 -0
- package/types.js +1 -0
- package/types.js.map +1 -0
- package/types.ts +19 -0
- package/worker.js +51 -0
- package/worker.js.map +1 -0
- package/worker.ts +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Jeff Peterson
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,131 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/threads
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A Deno or browser Worker serving a graph's roles: the ordinary effects pool, a
|
|
4
|
+
leased service, or both. The graph either has storage the thread can open itself
|
|
5
|
+
(SQLite on the box), or stays in its owning thread and is served over a
|
|
6
|
+
MessagePort (a page's RAM graph). The package declares no vocabulary.
|
|
7
|
+
|
|
8
|
+
`thread(module)` creates a lazy thread. `plan({roles, data, graph?})` gives it
|
|
9
|
+
roles and cloneable configuration. `duties(signal)` starts it and keeps serving
|
|
10
|
+
until the signal aborts; an already aborted signal requests one pass. `nudge()`
|
|
11
|
+
wakes its effect pool. Overlapping `duties()` calls are refused; a completed
|
|
12
|
+
pass can be followed by live work. `close()` stops new work, waits for in-flight
|
|
13
|
+
effects and services, closes the graph, and terminates the Worker. `end()`
|
|
14
|
+
terminates it immediately and rejects outstanding calls; the owning application
|
|
15
|
+
records any ending and releases abandoned claims where it can.
|
|
16
|
+
|
|
17
|
+
## Opening a thread
|
|
18
|
+
|
|
19
|
+
The module URL handed to `thread` exports `open(start)`. It receives `me` (a
|
|
20
|
+
fresh entity ID), `roles`, the configured `data`, and a `port` if the plan named
|
|
21
|
+
a graph. Its return value has `duties`, `nudge`, `stop`, and `close`. Keep
|
|
22
|
+
composition and runtime-specific connections in this module. CLI's
|
|
23
|
+
[`duties.ts`](../cli/duties.ts) opens its SQLite connection this way.
|
|
24
|
+
|
|
25
|
+
For a graph that stays in the page, the opening module loads its vocabulary and
|
|
26
|
+
obtains authoritative graph access with `remote(port, vocab)`:
|
|
27
|
+
|
|
28
|
+
```ts ignore
|
|
29
|
+
import { effects } from '@yaks/effects'
|
|
30
|
+
import { remote, roles, type Start } from '@yaks/threads'
|
|
31
|
+
import { handlers, vocab } from './domain.ts'
|
|
32
|
+
|
|
33
|
+
export let open = async ({ me, roles: mine, port }: Start) => {
|
|
34
|
+
if (!port) throw new Error('this thread needs the owning graph')
|
|
35
|
+
let graph = remote(port, vocab)
|
|
36
|
+
await graph.apply([{ entity: { eid: me } }])
|
|
37
|
+
let fx = effects(vocab, {
|
|
38
|
+
owner: me,
|
|
39
|
+
write: (batch) => graph.apply(batch, { trusted: true }),
|
|
40
|
+
})
|
|
41
|
+
fx.handle(handlers)
|
|
42
|
+
return roles(graph, {
|
|
43
|
+
me,
|
|
44
|
+
roles: mine,
|
|
45
|
+
fx,
|
|
46
|
+
close: () => {
|
|
47
|
+
graph.close()
|
|
48
|
+
port.close()
|
|
49
|
+
},
|
|
50
|
+
})
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The owning page supplies that graph:
|
|
55
|
+
|
|
56
|
+
```ts ignore
|
|
57
|
+
import { thread } from '@yaks/threads'
|
|
58
|
+
|
|
59
|
+
let aside = thread(new URL('./domain-thread.js', import.meta.url))
|
|
60
|
+
aside.plan({ roles: ['effects'], data: {}, graph: pageGraph })
|
|
61
|
+
let stop = new AbortController()
|
|
62
|
+
let serving = aside.duties(stop.signal)
|
|
63
|
+
// Later:
|
|
64
|
+
stop.abort()
|
|
65
|
+
await serving
|
|
66
|
+
await aside.close()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`roles(graph, options)` works `fx` for the `effects` role and takes each named
|
|
70
|
+
`services` callback under the existing @yaks/effects lease. `me` must identify
|
|
71
|
+
an entity in the owning graph before taking a service lease. `hold`, `gone`,
|
|
72
|
+
`report`, and `close` customize lease ownership, failures, and graph cleanup.
|
|
73
|
+
All requested roles must have code. The signal stops claims and asks services to
|
|
74
|
+
stop; closing waits for the effects and services already started.
|
|
75
|
+
|
|
76
|
+
## Graph access over a port
|
|
77
|
+
|
|
78
|
+
`serve(port, graph)` and `remote(port, vocab)` use @yaks/sync `portLink`.
|
|
79
|
+
`remote` supplies @yaks/graph `Access`: `read`, `rows`, `get`, `apply`, `drop`,
|
|
80
|
+
`vocab`, and `outside` detached handler reads, including pattern bindings. Write
|
|
81
|
+
options are `WriteOpts` data; graph-local trace and deferred-effect callbacks
|
|
82
|
+
stay with the owning graph. Reads ask the owning graph every time. Writes await
|
|
83
|
+
its complete `apply()` result, so its admission, preconditions, rules, stamps,
|
|
84
|
+
and effect accounting run there once; a `drop` is the owning graph's too.
|
|
85
|
+
Local-only components are available too: this is access to that graph, not its
|
|
86
|
+
server sync tier. There is no optimistic replica or raw storage write door.
|
|
87
|
+
|
|
88
|
+
A connected pair gives another thread access without copying data. The real port
|
|
89
|
+
write/read, refusals and claims are exercised in `thread_test.ts`; this example
|
|
90
|
+
also includes OS port setup and delivery.
|
|
91
|
+
|
|
92
|
+
```ts ignore
|
|
93
|
+
import { graph } from '@yaks/graph'
|
|
94
|
+
import { ram } from '@yaks/ram'
|
|
95
|
+
import { loadVocab } from '@yaks/vocab'
|
|
96
|
+
import { remote, serve } from '@yaks/threads'
|
|
97
|
+
|
|
98
|
+
let vocab = loadVocab([])
|
|
99
|
+
let owner = graph({ storage: ram(vocab), vocab })
|
|
100
|
+
let { port1, port2 } = new MessageChannel()
|
|
101
|
+
let serving = serve(port1, owner)
|
|
102
|
+
let client = remote(port2, vocab)
|
|
103
|
+
try {
|
|
104
|
+
await client.apply([{ entity: { eid: 'thread' } }])
|
|
105
|
+
await owner.get(['thread']) // the write landed in the owning graph
|
|
106
|
+
} finally {
|
|
107
|
+
client.close()
|
|
108
|
+
serving.close()
|
|
109
|
+
port1.close()
|
|
110
|
+
port2.close()
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Graph refusals retain their `Stale` and `Refused` types and details across the
|
|
115
|
+
port, so two threads claiming one run settle at the owning graph's transaction.
|
|
116
|
+
Both ends must load compatible vocabulary. These ports are for trusted code;
|
|
117
|
+
they provide no authentication or read permission filter. `serve().close()` and
|
|
118
|
+
`remote().close()` release link listeners; the caller owns the ports.
|
|
119
|
+
|
|
120
|
+
Requests use portLink's default 30 second deadline. A timeout does not cancel an
|
|
121
|
+
operation that may already have committed; do not blindly retry it. Lifecycle
|
|
122
|
+
requests wait without a deadline so a graceful drain can finish. Applications
|
|
123
|
+
bundling for browsers must make the package's `./worker` module and their
|
|
124
|
+
opening module available at their Worker/module URLs. Pass
|
|
125
|
+
`thread(openingModule, { worker: bundledWorkerUrl })` for a built Worker at a
|
|
126
|
+
different URL. The package uses only standard web APIs; the opening module
|
|
127
|
+
decides runtime compatibility.
|
|
128
|
+
|
|
129
|
+
The root exports `thread`, `serve`, `remote`, `roles`, and their types;
|
|
130
|
+
`./worker` is the shared Worker entry point. Vale's growth and painting move
|
|
131
|
+
onto this package in their own tasks.
|
package/_dist/graph.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Access } from "@yaks/graph";
|
|
2
|
+
import { type Port, type PortLink } from "@yaks/sync/port";
|
|
3
|
+
import type { Vocab } from "@yaks/vocab";
|
|
4
|
+
/** Serve this graph's authoritative operations to trusted code on a port.
|
|
5
|
+
* The caller owns the port. Every write enters this graph's apply pipeline,
|
|
6
|
+
* but for the bookkeeping it drops (@yaks/graph `Graph.drop`). */ export declare let serve: (port: Port, graph: Access) => PortLink;
|
|
7
|
+
/** Authoritative graph access whose port link can be released. */ export type Remote = Access & {
|
|
8
|
+
close: () => void;
|
|
9
|
+
};
|
|
10
|
+
/** A thread's graph access, without a replica or a second write pipeline.
|
|
11
|
+
* Load the same vocabulary here as on the owning graph. */ export declare let remote: (port: Port, vocab: Vocab) => Remote;
|
|
12
|
+
//# sourceMappingURL=graph.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.d.ts","sources":["../graph.ts"],"names":[],"mappings":"AAAA,cACE,MAAM,2BAOuB;AAE/B,SAAS,KAAK,IAAI,EAAE,KAAK,QAAQ,+BAA8C;AAC/E,cAAc,KAAK,2BAAgC;AAgCnD;;gEAEgE,GAChE,OAAO,YAAI,QAAS,MAAM,MAAM,OAAO,WAAS,SAqC5C;AAEJ,gEAAgE,GAChE,YAAY,SAAS;EAAW,aAAa,IAAI;;AAEjD;yDACyD,GACzD,OAAO,YAAI,SAAU,MAAM,MAAM,OAAO,UAAQ,OAmB/C"}
|
package/_dist/mod.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Threads serving a graph's roles, by their own connection or over a port.
|
|
2
|
+
* @module
|
|
3
|
+
*/ export { type Aside, type Plan, type Thread, thread, type ThreadOpts } from "./thread.js";
|
|
4
|
+
export { type Remote, remote, serve } from "./graph.js";
|
|
5
|
+
export { type Roles, roles, type Service } from "./roles.js";
|
|
6
|
+
export type { Host, Open, Start } from "./types.js";
|
|
7
|
+
//# sourceMappingURL=mod.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AAAA;;CAEC,GACD,SACE,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,MAAM,EACX,MAAM,EACN,KAAK,UAAU,sBACG;AACpB,SAAS,KAAK,MAAM,EAAE,MAAM,EAAE,KAAK,qBAAoB;AACvD,SAAS,KAAK,KAAK,EAAE,KAAK,EAAE,KAAK,OAAO,qBAAoB;AAC5D,cAAc,IAAI,EAAE,IAAI,EAAE,KAAK,qBAAoB"}
|
package/_dist/roles.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Access, Eid } from "@yaks/graph";
|
|
2
|
+
import { type Effects } from "@yaks/effects";
|
|
3
|
+
import type { Host } from "./types.js";
|
|
4
|
+
/** A leased duty that honors shutdown and finishes its cleanup. */ export type Service = (signal: AbortSignal) => unknown | Promise<unknown>;
|
|
5
|
+
/** Code and lifecycle options for the roles a host serves. */ export type Roles = {
|
|
6
|
+
me: Eid;
|
|
7
|
+
roles: readonly string[];
|
|
8
|
+
fx?: Effects;
|
|
9
|
+
services?: Record<string, Service>;
|
|
10
|
+
hold?: number;
|
|
11
|
+
gone?: (holder: Eid) => boolean | Promise<boolean>;
|
|
12
|
+
report?: (error: unknown, role: string) => unknown;
|
|
13
|
+
close?: () => void | Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
/** Work the ordinary effects pool and leased services under the given roles.
|
|
16
|
+
* The opening module supplies handlers and services; this owns their lifetime. */ export declare let roles: (graph: Access, opts: Roles) => Host;
|
|
17
|
+
//# sourceMappingURL=roles.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"roles.d.ts","sources":["../roles.ts"],"names":[],"mappings":"AAAA,cAAc,MAAM,EAAE,GAAG,2BAAgC;AACzD,SAAS,KAAK,OAAO,6BAAiD;AACtE,cAAc,IAAI,qBAAoB;AAEtC,iEAAiE,GACjE,YAAY,WAAW,QAAQ,gBAAgB,OAAO,GAAG,QAAQ,OAAO;AACxE,4DAA4D,GAC5D,YAAY;EACV,IAAI;EACJ,gBAAgB,MAAM;EACtB,KAAK;EACL,WAAW,OAAO,MAAM,EAAE;EAC1B,OAAO,MAAM;EACb,QAAQ,QAAQ,QAAQ,OAAO,GAAG,QAAQ,OAAO;EACjD,UAAU,OAAO,OAAO,EAAE,MAAM,MAAM,KAAK,OAAO;EAClD,cAAc,IAAI,GAAG,QAAQ,IAAI;;AAGnC;gFACgF,GAChF,OAAO,YAAI,QAAS,OAAO,QAAQ,MAAM,UAAQ,KA+ChD"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Access, Eid } from "@yaks/graph";
|
|
2
|
+
/** Duties handed to a thread, separate from the graph's owning thread. */ export type Thread = {
|
|
3
|
+
me: Eid;
|
|
4
|
+
duties: (signal: AbortSignal) => Promise<void>;
|
|
5
|
+
nudge: () => void;
|
|
6
|
+
close: () => Promise<void>;
|
|
7
|
+
};
|
|
8
|
+
/** The roles and cloneable data a thread's opening module receives. A graph
|
|
9
|
+
* here is served over a port; otherwise the module opens its own connection. */ export type Plan<T> = {
|
|
10
|
+
roles: string[];
|
|
11
|
+
data: T;
|
|
12
|
+
graph?: Access;
|
|
13
|
+
};
|
|
14
|
+
/** A lazy thread that can be planned or terminated by its owner. */ export type Aside<T> = Thread & {
|
|
15
|
+
plan: (plan: Plan<T>) => void;
|
|
16
|
+
end: () => void;
|
|
17
|
+
};
|
|
18
|
+
/** Worker location for runtimes that bundle the package. */ export type ThreadOpts = {
|
|
19
|
+
/** URL of the bundled ./worker entry point in a browser deployment. */ worker?: string | URL;
|
|
20
|
+
};
|
|
21
|
+
/** Plan now, start when duties are asked for. `module` exports `open(start)`;
|
|
22
|
+
* the same lifecycle runs with a browser Worker or a Deno Worker. */ export declare let thread: <T = unknown>(module: string | URL, opts?: ThreadOpts) => Aside<T>;
|
|
23
|
+
//# sourceMappingURL=thread.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"thread.d.ts","sources":["../thread.ts"],"names":[],"mappings":"AACA,cAAc,MAAM,EAAE,GAAG,2BAAgC;AAKzD,wEAAwE,GACxE,YAAY;EACV,IAAI;EACJ,SAAS,QAAQ,gBAAgB,QAAQ,IAAI;EAC7C,aAAa,IAAI;EACjB,aAAa,QAAQ,IAAI;;AAG3B;8EAC8E,GAC9E,YAAY,KAAK;EAAO,OAAO,MAAM;EAAI,MAAM;EAAG,QAAQ;;AAC1D,kEAAkE,GAClE,YAAY,MAAM,KAAK;EACrB,OAAO,MAAM,KAAK,OAAO,IAAI;EAC7B,WAAW,IAAI;;AAGjB,0DAA0D,GAC1D,YAAY;EACV,qEAAqE,GACrE,SAAS,MAAM,GAAG;;AAGpB;mEACmE,GACnE,OAAO,YAAI,SAAU,IAAI,OAAO,EAC9B,QAAQ,MAAM,GAAG,KACjB,OAAM,eACL,MAAM,GA+GR"}
|
package/_dist/types.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Eid } from "@yaks/graph";
|
|
2
|
+
/** The worker's opening module composes roles over a connection or `port`. */ export type Start<T = unknown> = {
|
|
3
|
+
module: string;
|
|
4
|
+
me: Eid;
|
|
5
|
+
roles: string[];
|
|
6
|
+
data: T;
|
|
7
|
+
port?: MessagePort;
|
|
8
|
+
};
|
|
9
|
+
/** Duties and cleanup composed by the opening module. */ export type Host = {
|
|
10
|
+
duties: (signal: AbortSignal, only?: readonly string[]) => Promise<void>;
|
|
11
|
+
nudge: () => void;
|
|
12
|
+
stop: () => void;
|
|
13
|
+
close: () => void | Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
/** Compose a thread host from its roles and cloneable configuration. */ export type Open<T = unknown> = (start: Start<T>) => Host | Promise<Host>;
|
|
16
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sources":["../types.ts"],"names":[],"mappings":"AAAA,cAAc,GAAG,2BAAgC;AAEjD,4EAA4E,GAC5E,YAAY,MAAM,IAAI,OAAO;EAC3B,QAAQ,MAAM;EACd,IAAI;EACJ,OAAO,MAAM;EACb,MAAM;EACN,OAAO;;AAET,uDAAuD,GACvD,YAAY;EACV,SAAS,QAAQ,aAAa,gBAAgB,MAAM,OAAO,QAAQ,IAAI;EACvE,aAAa,IAAI;EACjB,YAAY,IAAI;EAChB,aAAa,IAAI,GAAG,QAAQ,IAAI;;AAElC,sEAAsE,GACtE,YAAY,KAAK,IAAI,OAAO,KAAK,OAAO,MAAM,OAAO,OAAO,QAAQ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=worker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.d.ts","sources":[],"names":[],"mappings":""}
|
package/deno.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"compilerOptions":{"lib":["dom","esnext"]},"publish":{"exclude":["**/*_test.ts","testing.ts"]},"name":"@yaks/threads","version":"0.2.36","license":"Apache-2.0","description":"Threads serving a graph's roles, by their own connection or over a MessagePort to the graph that owns the data.","exports":{".":"./mod.ts","./worker":"./worker.ts"},"imports":{"@yaks/threads":"./mod.ts","@yaks/threads/worker":"./worker.ts"}}
|
package/graph.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { Refused, Stale } from "@yaks/graph/errors";
|
|
2
|
+
import { portLink } from "@yaks/sync/port";
|
|
3
|
+
// Error identity matters: losing a claim is a Stale refusal, not a failed run.
|
|
4
|
+
let encodeError = (cause)=>{
|
|
5
|
+
let error = cause instanceof Error ? cause : new Error(String(cause));
|
|
6
|
+
return {
|
|
7
|
+
name: error.name,
|
|
8
|
+
message: error.message,
|
|
9
|
+
stack: error.stack,
|
|
10
|
+
details: {
|
|
11
|
+
...error
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
let decodeError = (value)=>{
|
|
16
|
+
let e = value;
|
|
17
|
+
let error = e.name == 'Stale' ? new Stale(e.details.eid, e.details.comp, e.details.prop, e.details.current) : e.name == 'Refused' ? new Refused(e.message) : new Error(e.message);
|
|
18
|
+
return Object.assign(error, e.details, {
|
|
19
|
+
name: e.name,
|
|
20
|
+
stack: e.stack
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
/** Serve this graph's authoritative operations to trusted code on a port.
|
|
24
|
+
* The caller owns the port. Every write enters this graph's apply pipeline,
|
|
25
|
+
* but for the bookkeeping it drops (@yaks/graph `Graph.drop`). */ export let serve = (port, graph)=>portLink(port, {
|
|
26
|
+
encodeError,
|
|
27
|
+
receive: (method, value)=>{
|
|
28
|
+
let args = value;
|
|
29
|
+
switch(method){
|
|
30
|
+
case 'read':
|
|
31
|
+
return graph.read(...args);
|
|
32
|
+
case 'rows':
|
|
33
|
+
return graph.rows(...args);
|
|
34
|
+
case 'get':
|
|
35
|
+
return graph.get(...args);
|
|
36
|
+
case 'apply':
|
|
37
|
+
return graph.apply(...args);
|
|
38
|
+
case 'book':
|
|
39
|
+
return graph.book(...args);
|
|
40
|
+
case 'outside.read':
|
|
41
|
+
return graph.outside.read(...args);
|
|
42
|
+
case 'outside.get':
|
|
43
|
+
return graph.outside.get(...args);
|
|
44
|
+
// A graph that keeps no deletion time offers no graves.
|
|
45
|
+
case 'outside.buried':
|
|
46
|
+
return graph.outside.buried?.(...args) ?? {
|
|
47
|
+
eids: []
|
|
48
|
+
};
|
|
49
|
+
case 'outside.bindings':
|
|
50
|
+
{
|
|
51
|
+
if (!graph.outside.bindings) {
|
|
52
|
+
throw new Error('this graph evaluates no bindings');
|
|
53
|
+
}
|
|
54
|
+
return graph.outside.bindings(...args);
|
|
55
|
+
}
|
|
56
|
+
default:
|
|
57
|
+
throw new Error(`unknown graph request: ${method}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
/** A thread's graph access, without a replica or a second write pipeline.
|
|
62
|
+
* Load the same vocabulary here as on the owning graph. */ export let remote = (port, vocab)=>{
|
|
63
|
+
let link = portLink(port, {
|
|
64
|
+
decodeError
|
|
65
|
+
});
|
|
66
|
+
let ask = (method, args)=>link.request(method, args);
|
|
67
|
+
return {
|
|
68
|
+
vocab,
|
|
69
|
+
read: (...args)=>ask('read', args),
|
|
70
|
+
rows: (...args)=>ask('rows', args),
|
|
71
|
+
get: (...args)=>ask('get', args),
|
|
72
|
+
apply: (...args)=>ask('apply', args),
|
|
73
|
+
book: (...args)=>ask('book', args),
|
|
74
|
+
outside: {
|
|
75
|
+
read: (...args)=>ask('outside.read', args),
|
|
76
|
+
get: (...args)=>ask('outside.get', args),
|
|
77
|
+
bindings: (...args)=>ask('outside.bindings', args),
|
|
78
|
+
buried: (...args)=>ask('outside.buried', args)
|
|
79
|
+
},
|
|
80
|
+
close: ()=>link.close()
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
//# sourceMappingURL=graph.js.map
|
package/graph.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AASA,SAAS,OAAO,EAAE,KAAK,kCAAuC;AAC9D,SAAmC,QAAQ,+BAAoC;AAG/E,+EAA+E;AAC/E,IAAI,cAAc,CAAC;EACjB,IAAI,QAAQ,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO;EAC9D,OAAO;IACL,MAAM,MAAM,IAAI;IAChB,SAAS,MAAM,OAAO;IACtB,OAAO,MAAM,KAAK;IAClB,SAAS;MAAE,GAAG,KAAK;IAAC;EACtB;AACF;AACA,IAAI,cAAc,CAAC;EACjB,IAAI,IAAI;EAMR,IAAI,QAAQ,EAAE,IAAI,IAAI,UAClB,IAAI,MACJ,EAAE,OAAO,CAAC,GAAG,EACb,EAAE,OAAO,CAAC,IAAI,EACd,EAAE,OAAO,CAAC,IAAI,EACd,EAAE,OAAO,CAAC,OAAO,IAEjB,EAAE,IAAI,IAAI,YACV,IAAI,QAAQ,EAAE,OAAO,IACrB,IAAI,MAAM,EAAE,OAAO;EACvB,OAAO,OAAO,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE;IAAE,MAAM,EAAE,IAAI;IAAE,OAAO,EAAE,KAAK;EAAC;AACxE;AAEA;;gEAEgE,GAChE,OAAO,IAAI,QAAQ,CAAC,MAAY,QAC9B,SAAS,MAAM;IACb;IACA,SAAS,CAAC,QAAQ;MAChB,IAAI,OAAO;MACX,OAAQ;QACN,KAAK;UACH,OAAO,MAAM,IAAI,IAAI;QACvB,KAAK;UACH,OAAO,MAAM,IAAI,IAAI;QACvB,KAAK;UACH,OAAO,MAAM,GAAG,IAAI;QACtB,KAAK;UACH,OAAO,MAAM,KAAK,IAAI;QACxB,KAAK;UACH,OAAO,MAAM,IAAI,IAAI;QACvB,KAAK;UACH,OAAO,MAAM,OAAO,CAAC,IAAI,IAAI;QAC/B,KAAK;UACH,OAAO,MAAM,OAAO,CAAC,GAAG,IAAI;QAC9B,wDAAwD;QACxD,KAAK;UACH,OAAO,MAAM,OAAO,CAAC,MAAM,MACtB,SACA;YAAE,MAAM,EAAE;UAAC;QAClB,KAAK;UAAoB;YACvB,IAAI,CAAC,MAAM,OAAO,CAAC,QAAQ,EAAE;cAC3B,MAAM,IAAI,MAAM;YAClB;YACA,OAAO,MAAM,OAAO,CAAC,QAAQ,IACxB;UAEP;QACA;UACE,MAAM,IAAI,MAAM,CAAC,uBAAuB,EAAE,QAAQ;MACtD;IACF;EACF,GAAE;AAKJ;yDACyD,GACzD,OAAO,IAAI,SAAS,CAAC,MAAY;EAC/B,IAAI,OAAO,SAAS,MAAM;IAAE;EAAY;EACxC,IAAI,MAAM,CAAI,QAAgB,OAC5B,KAAK,OAAO,CAAC,QAAQ;EACvB,OAAO;IACL;IACA,MAAM,CAAC,GAAG,OAAS,IAAI,QAAQ;IAC/B,MAAM,CAAC,GAAG,OAAS,IAAI,QAAQ;IAC/B,KAAK,CAAC,GAAG,OAAS,IAAI,OAAO;IAC7B,OAAO,CAAC,GAAG,OAAS,IAAI,SAAS;IACjC,MAAM,CAAC,GAAG,OAAS,IAAI,QAAQ;IAC/B,SAAS;MACP,MAAM,CAAC,GAAG,OAAS,IAAI,gBAAgB;MACvC,KAAK,CAAC,GAAG,OAAS,IAAI,eAAe;MACrC,UAAU,CAAC,GAAG,OAAS,IAAI,oBAAoB;MAC/C,QAAQ,CAAC,GAAG,OAAS,IAAI,kBAAkB;IAC7C;IACA,OAAO,IAAM,KAAK,KAAK;EACzB;AACF,EAAC"}
|
package/graph.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Access,
|
|
3
|
+
Bundle,
|
|
4
|
+
Eid,
|
|
5
|
+
Match,
|
|
6
|
+
ReadOpts,
|
|
7
|
+
Taken,
|
|
8
|
+
WriteOpts,
|
|
9
|
+
} from 'jsr:@yaks/graph@0.2.36'
|
|
10
|
+
import { Refused, Stale } from '@yaks/graph/errors'
|
|
11
|
+
import { type Port, type PortLink, portLink } from '@yaks/sync/port'
|
|
12
|
+
import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
|
|
13
|
+
|
|
14
|
+
// Error identity matters: losing a claim is a Stale refusal, not a failed run.
|
|
15
|
+
let encodeError = (cause: unknown) => {
|
|
16
|
+
let error = cause instanceof Error ? cause : new Error(String(cause))
|
|
17
|
+
return {
|
|
18
|
+
name: error.name,
|
|
19
|
+
message: error.message,
|
|
20
|
+
stack: error.stack,
|
|
21
|
+
details: { ...error },
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
let decodeError = (value: unknown): Error => {
|
|
25
|
+
let e = value as {
|
|
26
|
+
name: string
|
|
27
|
+
message: string
|
|
28
|
+
stack?: string
|
|
29
|
+
details: Stale
|
|
30
|
+
}
|
|
31
|
+
let error = e.name == 'Stale'
|
|
32
|
+
? new Stale(
|
|
33
|
+
e.details.eid,
|
|
34
|
+
e.details.comp,
|
|
35
|
+
e.details.prop,
|
|
36
|
+
e.details.current,
|
|
37
|
+
)
|
|
38
|
+
: e.name == 'Refused'
|
|
39
|
+
? new Refused(e.message)
|
|
40
|
+
: new Error(e.message)
|
|
41
|
+
return Object.assign(error, e.details, { name: e.name, stack: e.stack })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Serve this graph's authoritative operations to trusted code on a port.
|
|
45
|
+
* The caller owns the port. Every write enters this graph's apply pipeline,
|
|
46
|
+
* but for the bookkeeping it drops (@yaks/graph `Graph.drop`). */
|
|
47
|
+
export let serve = (port: Port, graph: Access): PortLink =>
|
|
48
|
+
portLink(port, {
|
|
49
|
+
encodeError,
|
|
50
|
+
receive: (method, value) => {
|
|
51
|
+
let args = value as unknown[]
|
|
52
|
+
switch (method) {
|
|
53
|
+
case 'read':
|
|
54
|
+
return graph.read(...args as [Taken, ReadOpts?])
|
|
55
|
+
case 'rows':
|
|
56
|
+
return graph.rows(...args as [Taken, ReadOpts?])
|
|
57
|
+
case 'get':
|
|
58
|
+
return graph.get(...args as [Eid[], string[]?, ReadOpts?])
|
|
59
|
+
case 'apply':
|
|
60
|
+
return graph.apply(...args as [Bundle[], WriteOpts?])
|
|
61
|
+
case 'book':
|
|
62
|
+
return graph.book(...args as [Bundle[]])
|
|
63
|
+
case 'outside.read':
|
|
64
|
+
return graph.outside.read(...args as [Taken, ReadOpts?])
|
|
65
|
+
case 'outside.get':
|
|
66
|
+
return graph.outside.get(...args as [Eid[], string[]?])
|
|
67
|
+
// A graph that keeps no deletion time offers no graves.
|
|
68
|
+
case 'outside.buried':
|
|
69
|
+
return graph.outside.buried?.(
|
|
70
|
+
...args as [string, { after?: string; limit: number }],
|
|
71
|
+
) ?? { eids: [] }
|
|
72
|
+
case 'outside.bindings': {
|
|
73
|
+
if (!graph.outside.bindings) {
|
|
74
|
+
throw new Error('this graph evaluates no bindings')
|
|
75
|
+
}
|
|
76
|
+
return graph.outside.bindings(
|
|
77
|
+
...args as [Match[], Bundle[], string[]],
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
default:
|
|
81
|
+
throw new Error(`unknown graph request: ${method}`)
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
/** Authoritative graph access whose port link can be released. */
|
|
87
|
+
export type Remote = Access & { close: () => void }
|
|
88
|
+
|
|
89
|
+
/** A thread's graph access, without a replica or a second write pipeline.
|
|
90
|
+
* Load the same vocabulary here as on the owning graph. */
|
|
91
|
+
export let remote = (port: Port, vocab: Vocab): Remote => {
|
|
92
|
+
let link = portLink(port, { decodeError })
|
|
93
|
+
let ask = <T>(method: string, args: unknown[]): Promise<T> =>
|
|
94
|
+
link.request(method, args) as Promise<T>
|
|
95
|
+
return {
|
|
96
|
+
vocab,
|
|
97
|
+
read: (...args) => ask('read', args),
|
|
98
|
+
rows: (...args) => ask('rows', args),
|
|
99
|
+
get: (...args) => ask('get', args),
|
|
100
|
+
apply: (...args) => ask('apply', args),
|
|
101
|
+
book: (...args) => ask('book', args),
|
|
102
|
+
outside: {
|
|
103
|
+
read: (...args) => ask('outside.read', args),
|
|
104
|
+
get: (...args) => ask('outside.get', args),
|
|
105
|
+
bindings: (...args) => ask('outside.bindings', args),
|
|
106
|
+
buried: (...args) => ask('outside.buried', args),
|
|
107
|
+
},
|
|
108
|
+
close: () => link.close(),
|
|
109
|
+
}
|
|
110
|
+
}
|
package/mod.js
ADDED
package/mod.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;CAEC,GACD,SAIE,MAAM,sBAEY;AACpB,SAAsB,MAAM,EAAE,KAAK,qBAAoB;AACvD,SAAqB,KAAK,qBAAkC"}
|
package/mod.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Threads serving a graph's roles, by their own connection or over a port.
|
|
2
|
+
* @module
|
|
3
|
+
*/
|
|
4
|
+
export {
|
|
5
|
+
type Aside,
|
|
6
|
+
type Plan,
|
|
7
|
+
type Thread,
|
|
8
|
+
thread,
|
|
9
|
+
type ThreadOpts,
|
|
10
|
+
} from './thread.js'
|
|
11
|
+
export { type Remote, remote, serve } from './graph.js'
|
|
12
|
+
export { type Roles, roles, type Service } from './roles.js'
|
|
13
|
+
export type { Host, Open, Start } from './types.ts'
|
package/package.json
CHANGED
|
@@ -1,6 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yaks/threads",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.36",
|
|
4
|
+
"homepage": "https://jsr.io/@yaks/threads",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./_dist/mod.d.ts",
|
|
9
|
+
"default": "./mod.js"
|
|
10
|
+
},
|
|
11
|
+
"./worker": {
|
|
12
|
+
"types": "./_dist/worker.d.ts",
|
|
13
|
+
"default": "./worker.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@yaks/effects": "0.2.36",
|
|
19
|
+
"@yaks/fp": "0.2.36",
|
|
20
|
+
"@yaks/graph": "0.2.36",
|
|
21
|
+
"@yaks/sync": "0.2.36",
|
|
22
|
+
"@yaks/vocab": "0.2.36"
|
|
23
|
+
},
|
|
24
|
+
"description": "Threads serving a graph's roles, by their own connection or over a MessagePort to the graph that owns the data.",
|
|
25
|
+
"repository": "https://github.com/yak-sh/yak.git"
|
|
26
|
+
}
|
package/roles.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { HOLD, holding } from "@yaks/effects";
|
|
2
|
+
/** Work the ordinary effects pool and leased services under the given roles.
|
|
3
|
+
* The opening module supplies handlers and services; this owns their lifetime. */ export let roles = (graph, opts)=>{
|
|
4
|
+
let mine = [
|
|
5
|
+
...new Set(opts.roles)
|
|
6
|
+
];
|
|
7
|
+
let stopping = new AbortController();
|
|
8
|
+
let report = opts.report ?? console.error;
|
|
9
|
+
let reportPool = (error)=>report(error, 'effects');
|
|
10
|
+
for (let role of mine){
|
|
11
|
+
if (role == 'effects' ? !opts.fx : !opts.services?.[role]) {
|
|
12
|
+
throw new Error(`no code serves the thread role ${role}`);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
let closing;
|
|
16
|
+
let running = new Set();
|
|
17
|
+
let stop = ()=>{
|
|
18
|
+
stopping.abort();
|
|
19
|
+
void opts.fx?.stop().catch(reportPool);
|
|
20
|
+
};
|
|
21
|
+
return {
|
|
22
|
+
duties: (signal, only)=>{
|
|
23
|
+
if (stopping.signal.aborted) return Promise.resolve();
|
|
24
|
+
let until = AbortSignal.any([
|
|
25
|
+
signal,
|
|
26
|
+
stopping.signal
|
|
27
|
+
]);
|
|
28
|
+
let doing = Promise.all(mine.filter((r)=>!only || only.includes(r)).map((role)=>role == 'effects' ? opts.fx.work(graph, until).catch(reportPool) : holding(graph, role, {
|
|
29
|
+
holder: opts.me,
|
|
30
|
+
hold: opts.hold ?? HOLD,
|
|
31
|
+
gone: opts.gone,
|
|
32
|
+
signal: until,
|
|
33
|
+
report: (error)=>report(error, role)
|
|
34
|
+
}, opts.services[role]).catch((error)=>report(error, role)))).then(()=>{});
|
|
35
|
+
running.add(doing);
|
|
36
|
+
void doing.then(()=>running.delete(doing), ()=>running.delete(doing));
|
|
37
|
+
return doing;
|
|
38
|
+
},
|
|
39
|
+
nudge: ()=>opts.fx?.wake(),
|
|
40
|
+
stop,
|
|
41
|
+
close: ()=>closing ??= (async ()=>{
|
|
42
|
+
stop();
|
|
43
|
+
await Promise.all(running);
|
|
44
|
+
await opts.fx?.stop();
|
|
45
|
+
await opts.close?.();
|
|
46
|
+
})()
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=roles.js.map
|
package/roles.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"roles.js","sources":["./roles.ts"],"names":[],"mappings":"AACA,SAAuB,IAAI,EAAE,OAAO,6BAAkC;AAiBtE;gFACgF,GAChF,OAAO,IAAI,QAAQ,CAAC,OAAe;EACjC,IAAI,OAAO;OAAI,IAAI,IAAI,KAAK,KAAK;GAAE;EACnC,IAAI,WAAW,IAAI;EACnB,IAAI,SAAS,KAAK,MAAM,IAAI,QAAQ,KAAK;EACzC,IAAI,aAAa,CAAC,QAAmB,OAAO,OAAO;EACnD,KAAK,IAAI,QAAQ,KAAM;IACrB,IAAI,QAAQ,YAAY,CAAC,KAAK,EAAE,GAAG,CAAC,KAAK,QAAQ,EAAE,CAAC,KAAK,EAAE;MACzD,MAAM,IAAI,MAAM,CAAC,+BAA+B,EAAE,MAAM;IAC1D;EACF;EACA,IAAI;EACJ,IAAI,UAAU,IAAI;EAClB,IAAI,OAAO;IACT,SAAS,KAAK;IACd,KAAK,KAAK,EAAE,EAAE,OAAO,MAAM;EAC7B;EACA,OAAO;IACL,QAAQ,CAAC,QAAQ;MACf,IAAI,SAAS,MAAM,CAAC,OAAO,EAAE,OAAO,QAAQ,OAAO;MACnD,IAAI,QAAQ,YAAY,GAAG,CAAC;QAAC;QAAQ,SAAS,MAAM;OAAC;MACrD,IAAI,QAAQ,QAAQ,GAAG,CACrB,KAAK,MAAM,CAAC,CAAC,IAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC,IAAI,GAAG,CAAC,CAAC,OACjD,QAAQ,YACJ,KAAK,EAAE,CAAE,IAAI,CAAC,OAAO,OAAO,KAAK,CAAC,cAClC,QAAQ,OAAO,MAAM;UACrB,QAAQ,KAAK,EAAE;UACf,MAAM,KAAK,IAAI,IAAI;UACnB,MAAM,KAAK,IAAI;UACf,QAAQ;UACR,QAAQ,CAAC,QAAU,OAAO,OAAO;QACnC,GAAG,KAAK,QAAQ,AAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,QAAU,OAAO,OAAO,SAE5D,IAAI,CAAC,KAAO;MACd,QAAQ,GAAG,CAAC;MACZ,KAAK,MAAM,IAAI,CAAC,IAAM,QAAQ,MAAM,CAAC,QAAQ,IAAM,QAAQ,MAAM,CAAC;MAClE,OAAO;IACT;IACA,OAAO,IAAM,KAAK,EAAE,EAAE;IACtB;IACA,OAAO,IACL,YAAY,CAAC;QACX;QACA,MAAM,QAAQ,GAAG,CAAC;QAClB,MAAM,KAAK,EAAE,EAAE;QACf,MAAM,KAAK,KAAK;MAClB,CAAC;EACL;AACF,EAAC"}
|
package/roles.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { Access, Eid } from 'jsr:@yaks/graph@0.2.36'
|
|
2
|
+
import { type Effects, HOLD, holding } from '@yaks/effects'
|
|
3
|
+
import type { Host } from './types.ts'
|
|
4
|
+
|
|
5
|
+
/** A leased duty that honors shutdown and finishes its cleanup. */
|
|
6
|
+
export type Service = (signal: AbortSignal) => unknown | Promise<unknown>
|
|
7
|
+
/** Code and lifecycle options for the roles a host serves. */
|
|
8
|
+
export type Roles = {
|
|
9
|
+
me: Eid
|
|
10
|
+
roles: readonly string[]
|
|
11
|
+
fx?: Effects
|
|
12
|
+
services?: Record<string, Service>
|
|
13
|
+
hold?: number
|
|
14
|
+
gone?: (holder: Eid) => boolean | Promise<boolean>
|
|
15
|
+
report?: (error: unknown, role: string) => unknown
|
|
16
|
+
close?: () => void | Promise<void>
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Work the ordinary effects pool and leased services under the given roles.
|
|
20
|
+
* The opening module supplies handlers and services; this owns their lifetime. */
|
|
21
|
+
export let roles = (graph: Access, opts: Roles): Host => {
|
|
22
|
+
let mine = [...new Set(opts.roles)]
|
|
23
|
+
let stopping = new AbortController()
|
|
24
|
+
let report = opts.report ?? console.error
|
|
25
|
+
let reportPool = (error: unknown) => report(error, 'effects')
|
|
26
|
+
for (let role of mine) {
|
|
27
|
+
if (role == 'effects' ? !opts.fx : !opts.services?.[role]) {
|
|
28
|
+
throw new Error(`no code serves the thread role ${role}`)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
let closing: Promise<void> | undefined
|
|
32
|
+
let running = new Set<Promise<void>>()
|
|
33
|
+
let stop = () => {
|
|
34
|
+
stopping.abort()
|
|
35
|
+
void opts.fx?.stop().catch(reportPool)
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
duties: (signal, only) => {
|
|
39
|
+
if (stopping.signal.aborted) return Promise.resolve()
|
|
40
|
+
let until = AbortSignal.any([signal, stopping.signal])
|
|
41
|
+
let doing = Promise.all(
|
|
42
|
+
mine.filter((r) => !only || only.includes(r)).map((role) =>
|
|
43
|
+
role == 'effects'
|
|
44
|
+
? opts.fx!.work(graph, until).catch(reportPool)
|
|
45
|
+
: holding(graph, role, {
|
|
46
|
+
holder: opts.me,
|
|
47
|
+
hold: opts.hold ?? HOLD,
|
|
48
|
+
gone: opts.gone,
|
|
49
|
+
signal: until,
|
|
50
|
+
report: (error) => report(error, role),
|
|
51
|
+
}, opts.services![role]).catch((error) => report(error, role))
|
|
52
|
+
),
|
|
53
|
+
).then(() => {})
|
|
54
|
+
running.add(doing)
|
|
55
|
+
void doing.then(() => running.delete(doing), () => running.delete(doing))
|
|
56
|
+
return doing
|
|
57
|
+
},
|
|
58
|
+
nudge: () => opts.fx?.wake(),
|
|
59
|
+
stop,
|
|
60
|
+
close: () =>
|
|
61
|
+
closing ??= (async () => {
|
|
62
|
+
stop()
|
|
63
|
+
await Promise.all(running)
|
|
64
|
+
await opts.fx?.stop()
|
|
65
|
+
await opts.close?.()
|
|
66
|
+
})(),
|
|
67
|
+
}
|
|
68
|
+
}
|
package/thread.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { resolvers } from "@yaks/fp";
|
|
2
|
+
import { portLink } from "@yaks/sync/port";
|
|
3
|
+
import { serve } from "./graph.js";
|
|
4
|
+
/** Plan now, start when duties are asked for. `module` exports `open(start)`;
|
|
5
|
+
* the same lifecycle runs with a browser Worker or a Deno Worker. */ export let thread = (module, opts = {})=>{
|
|
6
|
+
let me = crypto.randomUUID();
|
|
7
|
+
let worker;
|
|
8
|
+
let link;
|
|
9
|
+
let graphLink;
|
|
10
|
+
let graphPort;
|
|
11
|
+
let planned = resolvers();
|
|
12
|
+
planned.promise.catch(()=>{});
|
|
13
|
+
let over = false;
|
|
14
|
+
let born = false;
|
|
15
|
+
let busy = false;
|
|
16
|
+
let closing;
|
|
17
|
+
let end = (error = new Error('the duty thread was ended before it closed'))=>{
|
|
18
|
+
over = true;
|
|
19
|
+
planned.reject(error);
|
|
20
|
+
link?.close(error);
|
|
21
|
+
graphLink?.close(error);
|
|
22
|
+
graphPort?.close();
|
|
23
|
+
worker?.terminate();
|
|
24
|
+
worker = undefined;
|
|
25
|
+
};
|
|
26
|
+
let spawn = (plan)=>{
|
|
27
|
+
if (over || worker || !plan.roles.length) return;
|
|
28
|
+
born = true;
|
|
29
|
+
worker = new Worker(opts.worker ?? new URL('./worker.ts', import.meta.url), {
|
|
30
|
+
type: 'module'
|
|
31
|
+
});
|
|
32
|
+
worker.onerror = (event)=>{
|
|
33
|
+
event.preventDefault();
|
|
34
|
+
end(event.error instanceof Error ? event.error : new Error(event.message));
|
|
35
|
+
};
|
|
36
|
+
link = portLink(worker);
|
|
37
|
+
let start = {
|
|
38
|
+
module: String(module),
|
|
39
|
+
me,
|
|
40
|
+
roles: plan.roles,
|
|
41
|
+
data: plan.data
|
|
42
|
+
};
|
|
43
|
+
let transfer = [];
|
|
44
|
+
if (plan.graph) {
|
|
45
|
+
let { port1, port2 } = new MessageChannel();
|
|
46
|
+
graphPort = port1;
|
|
47
|
+
graphLink = serve(port1, plan.graph);
|
|
48
|
+
start.port = port2;
|
|
49
|
+
transfer.push(port2);
|
|
50
|
+
}
|
|
51
|
+
worker.postMessage({
|
|
52
|
+
start
|
|
53
|
+
}, transfer);
|
|
54
|
+
};
|
|
55
|
+
let ask = async (method, started)=>{
|
|
56
|
+
let plan = await planned.promise;
|
|
57
|
+
if (!plan) return;
|
|
58
|
+
if (over) throw new Error('the duty thread has ended');
|
|
59
|
+
try {
|
|
60
|
+
spawn(plan);
|
|
61
|
+
if (!worker) return;
|
|
62
|
+
let running = link.request(method, undefined, {
|
|
63
|
+
timeout: null
|
|
64
|
+
});
|
|
65
|
+
started?.();
|
|
66
|
+
await running;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
end(error instanceof Error ? error : new Error(String(error)));
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
me,
|
|
74
|
+
plan: (plan)=>planned.resolve(plan),
|
|
75
|
+
duties: async (signal)=>{
|
|
76
|
+
if (busy) throw new Error('the thread is already serving duties');
|
|
77
|
+
busy = true;
|
|
78
|
+
let stop = ()=>{
|
|
79
|
+
void link?.request('stop', undefined, {
|
|
80
|
+
timeout: null
|
|
81
|
+
}).catch((error)=>end(error));
|
|
82
|
+
};
|
|
83
|
+
try {
|
|
84
|
+
if (signal.aborted) return await ask('pass');
|
|
85
|
+
signal.addEventListener('abort', stop, {
|
|
86
|
+
once: true
|
|
87
|
+
});
|
|
88
|
+
await ask('live', ()=>{
|
|
89
|
+
if (signal.aborted) stop();
|
|
90
|
+
});
|
|
91
|
+
} finally{
|
|
92
|
+
signal.removeEventListener('abort', stop);
|
|
93
|
+
busy = false;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
nudge: ()=>{
|
|
97
|
+
void link?.request('nudge', undefined, {
|
|
98
|
+
timeout: null
|
|
99
|
+
}).catch((error)=>end(error));
|
|
100
|
+
},
|
|
101
|
+
end: ()=>end(),
|
|
102
|
+
close: ()=>closing ??= (async ()=>{
|
|
103
|
+
planned.resolve(undefined);
|
|
104
|
+
if (!born) {
|
|
105
|
+
end();
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
if (over) throw new Error('the duty thread ended before closing');
|
|
110
|
+
await link.request('close', undefined, {
|
|
111
|
+
timeout: null
|
|
112
|
+
});
|
|
113
|
+
} finally{
|
|
114
|
+
end();
|
|
115
|
+
}
|
|
116
|
+
})()
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
//# sourceMappingURL=thread.js.map
|
package/thread.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"thread.js","sources":["./thread.ts"],"names":[],"mappings":"AAAA,SAAS,SAAS,wBAA6B;AAE/C,SAAwB,QAAQ,+BAAoC;AACpE,SAAS,KAAK,qBAAoB;AA0BlC;mEACmE,GACnE,OAAO,IAAI,SAAS,CAClB,QACA,OAAmB,CAAC,CAAC;EAErB,IAAI,KAAK,OAAO,UAAU;EAC1B,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI;EACJ,IAAI,UAAU;EACd,QAAQ,OAAO,CAAC,KAAK,CAAC,KAAO;EAC7B,IAAI,OAAO;EACX,IAAI,OAAO;EACX,IAAI,OAAO;EACX,IAAI;EACJ,IAAI,MAAM,CACR,QAAQ,IAAI,MAAM,6CAA6C;IAE/D,OAAO;IACP,QAAQ,MAAM,CAAC;IACf,MAAM,MAAM;IACZ,WAAW,MAAM;IACjB,WAAW;IACX,QAAQ;IACR,SAAS;EACX;EACA,IAAI,QAAQ,CAAC;IACX,IAAI,QAAQ,UAAU,CAAC,KAAK,KAAK,CAAC,MAAM,EAAE;IAC1C,OAAO;IACP,SAAS,IAAI,OACX,KAAK,MAAM,IAAI,IAAI,IAAI,eAAe,YAAY,GAAG,GACrD;MACE,MAAM;IACR;IAEF,OAAO,OAAO,GAAG,CAAC;MAChB,MAAM,cAAc;MACpB,IAAI,MAAM,KAAK,YAAY,QAAQ,MAAM,KAAK,GAAG,IAAI,MAAM,MAAM,OAAO;IAC1E;IACA,OAAO,SAAS;IAChB,IAAI,QAAkB;MACpB,QAAQ,OAAO;MACf;MACA,OAAO,KAAK,KAAK;MACjB,MAAM,KAAK,IAAI;IACjB;IACA,IAAI,WAA2B,EAAE;IACjC,IAAI,KAAK,KAAK,EAAE;MACd,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,IAAI;MAC3B,YAAY;MACZ,YAAY,MAAM,OAAO,KAAK,KAAK;MACnC,MAAM,IAAI,GAAG;MACb,SAAS,IAAI,CAAC;IAChB;IACA,OAAO,WAAW,CAAC;MAAE;IAAM,GAAG;EAChC;EACA,IAAI,MAAM,OAAO,QAAgB;IAC/B,IAAI,OAAO,MAAM,QAAQ,OAAO;IAChC,IAAI,CAAC,MAAM;IACX,IAAI,MAAM,MAAM,IAAI,MAAM;IAC1B,IAAI;MACF,MAAM;MACN,IAAI,CAAC,QAAQ;MACb,IAAI,UAAU,KAAM,OAAO,CAAC,QAAQ,WAAW;QAAE,SAAS;MAAK;MAC/D;MACA,MAAM;IACR,EAAE,OAAO,OAAO;MACd,IAAI,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO;MACtD,MAAM;IACR;EACF;EACA,OAAO;IACL;IACA,MAAM,CAAC,OAAS,QAAQ,OAAO,CAAC;IAChC,QAAQ,OAAO;MACb,IAAI,MAAM,MAAM,IAAI,MAAM;MAC1B,OAAO;MACP,IAAI,OAAO;QACT,KAAK,MAAM,QAAQ,QAAQ,WAAW;UAAE,SAAS;QAAK,GAAG,MAAM,CAC7D,QACG,IAAI;MACX;MACA,IAAI;QACF,IAAI,OAAO,OAAO,EAAE,OAAO,MAAM,IAAI;QACrC,OAAO,gBAAgB,CAAC,SAAS,MAAM;UAAE,MAAM;QAAK;QACpD,MAAM,IAAI,QAAQ;UAChB,IAAI,OAAO,OAAO,EAAE;QACtB;MACF,SAAU;QACR,OAAO,mBAAmB,CAAC,SAAS;QACpC,OAAO;MACT;IACF;IACA,OAAO;MACL,KAAK,MAAM,QAAQ,SAAS,WAAW;QAAE,SAAS;MAAK,GAAG,MAAM,CAAC,QAC/D,IAAI;IAER;IACA,KAAK,IAAM;IACX,OAAO,IACL,YAAY,CAAC;QACX,QAAQ,OAAO,CAAC;QAChB,IAAI,CAAC,MAAM;UACT;UACA;QACF;QACA,IAAI;UACF,IAAI,MAAM,MAAM,IAAI,MAAM;UAC1B,MAAM,KAAM,OAAO,CAAC,SAAS,WAAW;YAAE,SAAS;UAAK;QAC1D,SAAU;UACR;QACF;MACF,CAAC;EACL;AACF,EAAC"}
|
package/thread.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { resolvers } from '@yaks/fp'
|
|
2
|
+
import type { Access, Eid } from 'jsr:@yaks/graph@0.2.36'
|
|
3
|
+
import { type PortLink, portLink } from '@yaks/sync/port'
|
|
4
|
+
import { serve } from './graph.js'
|
|
5
|
+
import type { Start } from './types.ts'
|
|
6
|
+
|
|
7
|
+
/** Duties handed to a thread, separate from the graph's owning thread. */
|
|
8
|
+
export type Thread = {
|
|
9
|
+
me: Eid
|
|
10
|
+
duties: (signal: AbortSignal) => Promise<void>
|
|
11
|
+
nudge: () => void
|
|
12
|
+
close: () => Promise<void>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The roles and cloneable data a thread's opening module receives. A graph
|
|
16
|
+
* here is served over a port; otherwise the module opens its own connection. */
|
|
17
|
+
export type Plan<T> = { roles: string[]; data: T; graph?: Access }
|
|
18
|
+
/** A lazy thread that can be planned or terminated by its owner. */
|
|
19
|
+
export type Aside<T> = Thread & {
|
|
20
|
+
plan: (plan: Plan<T>) => void
|
|
21
|
+
end: () => void
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Worker location for runtimes that bundle the package. */
|
|
25
|
+
export type ThreadOpts = {
|
|
26
|
+
/** URL of the bundled ./worker entry point in a browser deployment. */
|
|
27
|
+
worker?: string | URL
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Plan now, start when duties are asked for. `module` exports `open(start)`;
|
|
31
|
+
* the same lifecycle runs with a browser Worker or a Deno Worker. */
|
|
32
|
+
export let thread = <T = unknown>(
|
|
33
|
+
module: string | URL,
|
|
34
|
+
opts: ThreadOpts = {},
|
|
35
|
+
): Aside<T> => {
|
|
36
|
+
let me = crypto.randomUUID() as Eid
|
|
37
|
+
let worker: Worker | undefined
|
|
38
|
+
let link: PortLink | undefined
|
|
39
|
+
let graphLink: PortLink | undefined
|
|
40
|
+
let graphPort: MessagePort | undefined
|
|
41
|
+
let planned = resolvers<Plan<T> | undefined>()
|
|
42
|
+
planned.promise.catch(() => {})
|
|
43
|
+
let over = false
|
|
44
|
+
let born = false
|
|
45
|
+
let busy = false
|
|
46
|
+
let closing: Promise<void> | undefined
|
|
47
|
+
let end = (
|
|
48
|
+
error = new Error('the duty thread was ended before it closed'),
|
|
49
|
+
) => {
|
|
50
|
+
over = true
|
|
51
|
+
planned.reject(error)
|
|
52
|
+
link?.close(error)
|
|
53
|
+
graphLink?.close(error)
|
|
54
|
+
graphPort?.close()
|
|
55
|
+
worker?.terminate()
|
|
56
|
+
worker = undefined
|
|
57
|
+
}
|
|
58
|
+
let spawn = (plan: Plan<T>) => {
|
|
59
|
+
if (over || worker || !plan.roles.length) return
|
|
60
|
+
born = true
|
|
61
|
+
worker = new Worker(
|
|
62
|
+
opts.worker ?? new URL('./worker.ts', import.meta.url),
|
|
63
|
+
{
|
|
64
|
+
type: 'module',
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
worker.onerror = (event) => {
|
|
68
|
+
event.preventDefault()
|
|
69
|
+
end(event.error instanceof Error ? event.error : new Error(event.message))
|
|
70
|
+
}
|
|
71
|
+
link = portLink(worker)
|
|
72
|
+
let start: Start<T> = {
|
|
73
|
+
module: String(module),
|
|
74
|
+
me,
|
|
75
|
+
roles: plan.roles,
|
|
76
|
+
data: plan.data,
|
|
77
|
+
}
|
|
78
|
+
let transfer: Transferable[] = []
|
|
79
|
+
if (plan.graph) {
|
|
80
|
+
let { port1, port2 } = new MessageChannel()
|
|
81
|
+
graphPort = port1
|
|
82
|
+
graphLink = serve(port1, plan.graph)
|
|
83
|
+
start.port = port2
|
|
84
|
+
transfer.push(port2)
|
|
85
|
+
}
|
|
86
|
+
worker.postMessage({ start }, transfer)
|
|
87
|
+
}
|
|
88
|
+
let ask = async (method: string, started?: () => void) => {
|
|
89
|
+
let plan = await planned.promise
|
|
90
|
+
if (!plan) return
|
|
91
|
+
if (over) throw new Error('the duty thread has ended')
|
|
92
|
+
try {
|
|
93
|
+
spawn(plan)
|
|
94
|
+
if (!worker) return
|
|
95
|
+
let running = link!.request(method, undefined, { timeout: null })
|
|
96
|
+
started?.()
|
|
97
|
+
await running
|
|
98
|
+
} catch (error) {
|
|
99
|
+
end(error instanceof Error ? error : new Error(String(error)))
|
|
100
|
+
throw error
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
me,
|
|
105
|
+
plan: (plan) => planned.resolve(plan),
|
|
106
|
+
duties: async (signal) => {
|
|
107
|
+
if (busy) throw new Error('the thread is already serving duties')
|
|
108
|
+
busy = true
|
|
109
|
+
let stop = () => {
|
|
110
|
+
void link?.request('stop', undefined, { timeout: null }).catch((
|
|
111
|
+
error,
|
|
112
|
+
) => end(error))
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
if (signal.aborted) return await ask('pass')
|
|
116
|
+
signal.addEventListener('abort', stop, { once: true })
|
|
117
|
+
await ask('live', () => {
|
|
118
|
+
if (signal.aborted) stop()
|
|
119
|
+
})
|
|
120
|
+
} finally {
|
|
121
|
+
signal.removeEventListener('abort', stop)
|
|
122
|
+
busy = false
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
nudge: () => {
|
|
126
|
+
void link?.request('nudge', undefined, { timeout: null }).catch((error) =>
|
|
127
|
+
end(error)
|
|
128
|
+
)
|
|
129
|
+
},
|
|
130
|
+
end: () => end(),
|
|
131
|
+
close: () =>
|
|
132
|
+
closing ??= (async () => {
|
|
133
|
+
planned.resolve(undefined)
|
|
134
|
+
if (!born) {
|
|
135
|
+
end()
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
try {
|
|
139
|
+
if (over) throw new Error('the duty thread ended before closing')
|
|
140
|
+
await link!.request('close', undefined, { timeout: null })
|
|
141
|
+
} finally {
|
|
142
|
+
end()
|
|
143
|
+
}
|
|
144
|
+
})(),
|
|
145
|
+
}
|
|
146
|
+
}
|
package/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=types.js.map
|
package/types.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sources":[],"names":[],"mappings":""}
|
package/types.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Eid } from 'jsr:@yaks/graph@0.2.36'
|
|
2
|
+
|
|
3
|
+
/** The worker's opening module composes roles over a connection or `port`. */
|
|
4
|
+
export type Start<T = unknown> = {
|
|
5
|
+
module: string
|
|
6
|
+
me: Eid
|
|
7
|
+
roles: string[]
|
|
8
|
+
data: T
|
|
9
|
+
port?: MessagePort
|
|
10
|
+
}
|
|
11
|
+
/** Duties and cleanup composed by the opening module. */
|
|
12
|
+
export type Host = {
|
|
13
|
+
duties: (signal: AbortSignal, only?: readonly string[]) => Promise<void>
|
|
14
|
+
nudge: () => void
|
|
15
|
+
stop: () => void
|
|
16
|
+
close: () => void | Promise<void>
|
|
17
|
+
}
|
|
18
|
+
/** Compose a thread host from its roles and cloneable configuration. */
|
|
19
|
+
export type Open<T = unknown> = (start: Start<T>) => Host | Promise<Host>
|
package/worker.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Shared Worker entry point for graph duties. @module */ import { resolvers } from "@yaks/fp";
|
|
2
|
+
import { portLink } from "@yaks/sync/port";
|
|
3
|
+
let scope = globalThis;
|
|
4
|
+
let host = resolvers();
|
|
5
|
+
host.promise.catch(()=>{});
|
|
6
|
+
let live;
|
|
7
|
+
let going = Promise.resolve();
|
|
8
|
+
let start = (event)=>{
|
|
9
|
+
let data = event.data;
|
|
10
|
+
if (!data?.start) return;
|
|
11
|
+
scope.removeEventListener('message', start);
|
|
12
|
+
let given = data.start;
|
|
13
|
+
void import(given.module).then((module)=>module.open(given)).then(host.resolve, host.reject);
|
|
14
|
+
};
|
|
15
|
+
scope.addEventListener('message', start);
|
|
16
|
+
let link = portLink(scope, {
|
|
17
|
+
receive: (method)=>{
|
|
18
|
+
if (method == 'pass') {
|
|
19
|
+
going = host.promise.then((h)=>h.duties(AbortSignal.abort()));
|
|
20
|
+
return going;
|
|
21
|
+
}
|
|
22
|
+
if (method == 'live') {
|
|
23
|
+
let signal = (live = new AbortController()).signal;
|
|
24
|
+
going = host.promise.then((h)=>{
|
|
25
|
+
if (!signal.aborted) return h.duties(signal);
|
|
26
|
+
});
|
|
27
|
+
return going;
|
|
28
|
+
}
|
|
29
|
+
if (method == 'stop') {
|
|
30
|
+
live?.abort();
|
|
31
|
+
return host.promise.then((h)=>h.stop());
|
|
32
|
+
}
|
|
33
|
+
if (method == 'nudge') return host.promise.then((h)=>h.nudge());
|
|
34
|
+
if (method == 'close') {
|
|
35
|
+
live?.abort();
|
|
36
|
+
return (async ()=>{
|
|
37
|
+
let h = await host.promise;
|
|
38
|
+
h.stop();
|
|
39
|
+
await going;
|
|
40
|
+
await h.close();
|
|
41
|
+
// Reply before closing the control link or its owning Worker.
|
|
42
|
+
setTimeout(()=>{
|
|
43
|
+
link.close();
|
|
44
|
+
scope.close();
|
|
45
|
+
}, 0);
|
|
46
|
+
})();
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`unknown thread request: ${method}`);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
//# sourceMappingURL=worker.js.map
|
package/worker.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.js","sources":["./worker.ts"],"names":[],"mappings":"AAAA,wDAAwD,GACxD,SAAS,SAAS,wBAA6B;AAC/C,SAAoB,QAAQ,+BAAoC;AAIhE,IAAI,QAAQ;AAEZ,IAAI,OAAO;AACX,KAAK,OAAO,CAAC,KAAK,CAAC,KAAO;AAC1B,IAAI;AACJ,IAAI,QAAuB,QAAQ,OAAO;AAC1C,IAAI,QAAQ,CAAC;EACX,IAAI,OAAO,AAAC,MAA0C,IAAI;EAC1D,IAAI,CAAC,MAAM,OAAO;EAClB,MAAM,mBAAmB,CAAC,WAAW;EACrC,IAAI,QAAQ,KAAK,KAAK;EACtB,KAAK,MAAM,CAAC,MAAM,MAAM,EAAE,IAAI,CAAC,CAAC,SAA2B,OAAO,IAAI,CAAC,QACpE,IAAI,CAAC,KAAK,OAAO,EAAE,KAAK,MAAM;AACnC;AACA,MAAM,gBAAgB,CAAC,WAAW;AAClC,IAAI,OAAO,SAAS,OAAO;EACzB,SAAS,CAAC;IACR,IAAI,UAAU,QAAQ;MACpB,QAAQ,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,IAAM,EAAE,MAAM,CAAC,YAAY,KAAK;MAC3D,OAAO;IACT;IACA,IAAI,UAAU,QAAQ;MACpB,IAAI,SAAS,CAAC,OAAO,IAAI,iBAAiB,EAAE,MAAM;MAClD,QAAQ,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;QACzB,IAAI,CAAC,OAAO,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC;MACvC;MACA,OAAO;IACT;IACA,IAAI,UAAU,QAAQ;MACpB,MAAM;MACN,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,IAAM,EAAE,IAAI;IACxC;IACA,IAAI,UAAU,SAAS,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC,IAAM,EAAE,KAAK;IAC9D,IAAI,UAAU,SAAS;MACrB,MAAM;MACN,OAAO,CAAC;QACN,IAAI,IAAI,MAAM,KAAK,OAAO;QAC1B,EAAE,IAAI;QACN,MAAM;QACN,MAAM,EAAE,KAAK;QACb,8DAA8D;QAC9D,WAAW;UACT,KAAK,KAAK;UACV,MAAM,KAAK;QACb,GAAG;MACL,CAAC;IACH;IACA,MAAM,IAAI,MAAM,CAAC,wBAAwB,EAAE,QAAQ;EACrD;AACF"}
|
package/worker.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Shared Worker entry point for graph duties. @module */
|
|
2
|
+
import { resolvers } from '@yaks/fp'
|
|
3
|
+
import { type Port, portLink } from '@yaks/sync/port'
|
|
4
|
+
|
|
5
|
+
import type { Host, Open, Start } from './types.ts'
|
|
6
|
+
|
|
7
|
+
let scope = globalThis as unknown as Port & { close: () => void }
|
|
8
|
+
|
|
9
|
+
let host = resolvers<Host>()
|
|
10
|
+
host.promise.catch(() => {})
|
|
11
|
+
let live: AbortController | undefined
|
|
12
|
+
let going: Promise<void> = Promise.resolve()
|
|
13
|
+
let start = (event: Event) => {
|
|
14
|
+
let data = (event as MessageEvent<{ start?: Start }>).data
|
|
15
|
+
if (!data?.start) return
|
|
16
|
+
scope.removeEventListener('message', start)
|
|
17
|
+
let given = data.start
|
|
18
|
+
void import(given.module).then((module: { open: Open }) => module.open(given))
|
|
19
|
+
.then(host.resolve, host.reject)
|
|
20
|
+
}
|
|
21
|
+
scope.addEventListener('message', start)
|
|
22
|
+
let link = portLink(scope, {
|
|
23
|
+
receive: (method) => {
|
|
24
|
+
if (method == 'pass') {
|
|
25
|
+
going = host.promise.then((h) => h.duties(AbortSignal.abort()))
|
|
26
|
+
return going
|
|
27
|
+
}
|
|
28
|
+
if (method == 'live') {
|
|
29
|
+
let signal = (live = new AbortController()).signal
|
|
30
|
+
going = host.promise.then((h) => {
|
|
31
|
+
if (!signal.aborted) return h.duties(signal)
|
|
32
|
+
})
|
|
33
|
+
return going
|
|
34
|
+
}
|
|
35
|
+
if (method == 'stop') {
|
|
36
|
+
live?.abort()
|
|
37
|
+
return host.promise.then((h) => h.stop())
|
|
38
|
+
}
|
|
39
|
+
if (method == 'nudge') return host.promise.then((h) => h.nudge())
|
|
40
|
+
if (method == 'close') {
|
|
41
|
+
live?.abort()
|
|
42
|
+
return (async () => {
|
|
43
|
+
let h = await host.promise
|
|
44
|
+
h.stop()
|
|
45
|
+
await going
|
|
46
|
+
await h.close()
|
|
47
|
+
// Reply before closing the control link or its owning Worker.
|
|
48
|
+
setTimeout(() => {
|
|
49
|
+
link.close()
|
|
50
|
+
scope.close()
|
|
51
|
+
}, 0)
|
|
52
|
+
})()
|
|
53
|
+
}
|
|
54
|
+
throw new Error(`unknown thread request: ${method}`)
|
|
55
|
+
},
|
|
56
|
+
})
|