sabcom 0.0.5 → 0.0.7
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 -21
- package/README.md +97 -18
- package/build/index.cjs +79 -7
- package/build/index.cjs.map +1 -1
- package/build/index.d.ts +13 -2
- package/build/index.js +67 -7
- package/build/index.js.map +1 -1
- package/package.json +23 -15
- package/src/index.ts +122 -28
package/LICENSE
CHANGED
|
@@ -1,21 +1,201 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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 2025 Ivan Zakharchanka
|
|
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,4 +1,4 @@
|
|
|
1
|
-
# SABCOM
|
|
1
|
+
# SABCOM
|
|
2
2
|
|
|
3
3
|
[![Github Build Status][github-image]][github-url]
|
|
4
4
|
[![NPM version][npm-image]][npm-url]
|
|
@@ -11,10 +11,12 @@ A TypeScript/Node.js library for inter-thread communication using SharedArrayBuf
|
|
|
11
11
|
## Features
|
|
12
12
|
|
|
13
13
|
- **Thread-safe communication** using atomic operations
|
|
14
|
+
- **Async and sync APIs** for different use cases
|
|
14
15
|
- **Chunked data transfer** for large payloads
|
|
15
16
|
- **V8 serialization** for complex data types
|
|
16
17
|
- **Timeout handling** with configurable timeouts
|
|
17
18
|
- **Zero-copy operations** where possible
|
|
19
|
+
- **Generator-based** low-level API for custom implementations
|
|
18
20
|
|
|
19
21
|
## Installation
|
|
20
22
|
|
|
@@ -24,7 +26,7 @@ npm install sabcom
|
|
|
24
26
|
|
|
25
27
|
## Usage
|
|
26
28
|
|
|
27
|
-
###
|
|
29
|
+
### Async Example
|
|
28
30
|
|
|
29
31
|
```typescript
|
|
30
32
|
import { write, read } from 'sabcom';
|
|
@@ -32,48 +34,122 @@ import { write, read } from 'sabcom';
|
|
|
32
34
|
// Create a shared buffer (1MB)
|
|
33
35
|
const buffer = new SharedArrayBuffer(1024 * 1024);
|
|
34
36
|
|
|
35
|
-
// Writer thread
|
|
37
|
+
// Writer thread (async)
|
|
36
38
|
const data = { message: 'Hello World', numbers: [1, 2, 3, 4, 5] };
|
|
37
|
-
write(data, buffer);
|
|
39
|
+
await write(data, buffer);
|
|
38
40
|
|
|
39
|
-
// Reader thread
|
|
40
|
-
const received = read(buffer);
|
|
41
|
+
// Reader thread (async)
|
|
42
|
+
const received = await read(buffer);
|
|
41
43
|
console.log(received); // { message: 'Hello World', numbers: [1, 2, 3, 4, 5] }
|
|
42
44
|
```
|
|
43
45
|
|
|
46
|
+
### Sync Example
|
|
47
|
+
|
|
48
|
+
```typescript
|
|
49
|
+
import { writeSync, readSync } from 'sabcom';
|
|
50
|
+
|
|
51
|
+
// Writer thread (sync)
|
|
52
|
+
writeSync(data, buffer);
|
|
53
|
+
|
|
54
|
+
// Reader thread (sync)
|
|
55
|
+
const received = readSync(buffer);
|
|
56
|
+
```
|
|
57
|
+
|
|
44
58
|
### With Custom Timeout
|
|
45
59
|
|
|
46
60
|
```typescript
|
|
47
61
|
// 10 second timeout
|
|
48
|
-
write(data, buffer, 10000);
|
|
49
|
-
const received = read(buffer, 10000);
|
|
62
|
+
await write(data, buffer, { timeout: 10000 });
|
|
63
|
+
const received = await read(buffer, { timeout: 10000 });
|
|
64
|
+
|
|
65
|
+
// Sync with timeout
|
|
66
|
+
writeSync(data, buffer, { timeout: 10000 });
|
|
67
|
+
const received = readSync(buffer, { timeout: 10000 });
|
|
50
68
|
```
|
|
51
69
|
|
|
52
70
|
## API Reference
|
|
53
71
|
|
|
54
|
-
###
|
|
72
|
+
### Async Functions
|
|
55
73
|
|
|
56
|
-
|
|
74
|
+
#### `write(data: unknown, buffer: SharedArrayBuffer, options?: Options): Promise<void>`
|
|
75
|
+
|
|
76
|
+
Asynchronously writes data to the shared buffer using chunked transfer.
|
|
57
77
|
|
|
58
78
|
- `data` - Any serializable data
|
|
59
79
|
- `buffer` - SharedArrayBuffer for communication
|
|
60
|
-
- `
|
|
80
|
+
- `options` - Optional configuration object
|
|
81
|
+
- `timeout` - Timeout in milliseconds (default: 5000)
|
|
61
82
|
|
|
62
83
|
**Throws:**
|
|
63
84
|
- `Error` - On handshake or chunk timeout
|
|
64
85
|
|
|
65
|
-
|
|
86
|
+
#### `read(buffer: SharedArrayBuffer, options?: Options): Promise<unknown>`
|
|
87
|
+
|
|
88
|
+
Asynchronously reads data from the shared buffer.
|
|
66
89
|
|
|
67
|
-
|
|
90
|
+
- `buffer` - SharedArrayBuffer for communication
|
|
91
|
+
- `options` - Optional configuration object
|
|
92
|
+
- `timeout` - Timeout in milliseconds (default: 5000)
|
|
93
|
+
|
|
94
|
+
**Returns:** Promise resolving to deserialized data
|
|
95
|
+
|
|
96
|
+
**Throws:**
|
|
97
|
+
- `Error` - On timeout or integrity failure
|
|
68
98
|
|
|
69
|
-
|
|
70
|
-
|
|
99
|
+
### Sync Functions
|
|
100
|
+
|
|
101
|
+
#### `writeSync(data: unknown, buffer: SharedArrayBuffer, options?: Options): void`
|
|
102
|
+
|
|
103
|
+
Synchronously writes data to the shared buffer using chunked transfer.
|
|
104
|
+
|
|
105
|
+
- `data` - Any serializable data
|
|
106
|
+
- `buffer` - SharedArrayBuffer for communication
|
|
107
|
+
- `options` - Optional configuration object
|
|
108
|
+
- `timeout` - Timeout in milliseconds (default: 5000)
|
|
109
|
+
|
|
110
|
+
**Throws:**
|
|
111
|
+
- `Error` - On handshake or chunk timeout
|
|
112
|
+
|
|
113
|
+
#### `readSync(buffer: SharedArrayBuffer, options?: Options): unknown`
|
|
114
|
+
|
|
115
|
+
Synchronously reads data from the shared buffer.
|
|
116
|
+
|
|
117
|
+
- `buffer` - SharedArrayBuffer for communication
|
|
118
|
+
- `options` - Optional configuration object
|
|
119
|
+
- `timeout` - Timeout in milliseconds (default: 5000)
|
|
71
120
|
|
|
72
121
|
**Returns:** Deserialized data
|
|
73
122
|
|
|
74
123
|
**Throws:**
|
|
75
124
|
- `Error` - On timeout or integrity failure
|
|
76
125
|
|
|
126
|
+
### Low-level Generator Functions
|
|
127
|
+
|
|
128
|
+
#### `writeGenerator(data: unknown, buffer: SharedArrayBuffer, options?: Options): Generator<WaitRequest, void, WaitResponse>`
|
|
129
|
+
|
|
130
|
+
Generator function for custom write implementations.
|
|
131
|
+
|
|
132
|
+
#### `readGenerator(buffer: SharedArrayBuffer, options?: Options): Generator<WaitRequest, unknown, WaitResponse>`
|
|
133
|
+
|
|
134
|
+
Generator function for custom read implementations.
|
|
135
|
+
|
|
136
|
+
### Types
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
interface Options {
|
|
140
|
+
timeout?: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
interface WaitRequest {
|
|
144
|
+
target: Int32Array;
|
|
145
|
+
index: number;
|
|
146
|
+
value: number;
|
|
147
|
+
timeout?: number;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
type WaitResponse = ReturnType<typeof Atomics.wait>;
|
|
151
|
+
```
|
|
152
|
+
|
|
77
153
|
## Protocol
|
|
78
154
|
|
|
79
155
|
The library uses a header-based protocol with atomic operations:
|
|
@@ -91,13 +167,16 @@ The library uses a header-based protocol with atomic operations:
|
|
|
91
167
|
## Error Handling
|
|
92
168
|
|
|
93
169
|
- **Handshake timeout** - Reader not ready within timeout
|
|
94
|
-
- **Chunk timeout** - Individual chunk transfer timeout
|
|
170
|
+
- **Chunk timeout** - Individual chunk transfer timeout
|
|
95
171
|
- **Integrity failure** - Chunk index mismatch
|
|
96
172
|
- **Invalid state** - Unexpected semaphore state
|
|
97
173
|
|
|
98
174
|
## Thread Safety
|
|
99
175
|
|
|
100
|
-
|
|
176
|
+
- **Async functions** (`write`, `read`) use `Atomics.waitAsync()` for non-blocking operations
|
|
177
|
+
- **Sync functions** (`writeSync`, `readSync`) use `Atomics.wait()` for blocking operations
|
|
178
|
+
- All functions use `Atomics.store()` and `Atomics.notify()` for synchronization
|
|
179
|
+
- Requires SharedArrayBuffer support and proper threading context
|
|
101
180
|
|
|
102
181
|
## Requirements
|
|
103
182
|
|
|
@@ -108,7 +187,7 @@ Uses `Atomics.wait()`, `Atomics.notify()`, and `Atomics.store()` for synchroniza
|
|
|
108
187
|
|
|
109
188
|
## License
|
|
110
189
|
|
|
111
|
-
License [
|
|
190
|
+
License [Apache-2.0](./LICENSE)
|
|
112
191
|
Copyright (c) 2025 Ivan Zakharchanka
|
|
113
192
|
|
|
114
193
|
[npm-url]: https://www.npmjs.com/package/sabcom
|
package/build/index.cjs
CHANGED
|
@@ -30,8 +30,20 @@ _export(exports, {
|
|
|
30
30
|
get read () {
|
|
31
31
|
return read;
|
|
32
32
|
},
|
|
33
|
+
get readGenerator () {
|
|
34
|
+
return readGenerator;
|
|
35
|
+
},
|
|
36
|
+
get readSync () {
|
|
37
|
+
return readSync;
|
|
38
|
+
},
|
|
33
39
|
get write () {
|
|
34
40
|
return write;
|
|
41
|
+
},
|
|
42
|
+
get writeGenerator () {
|
|
43
|
+
return writeGenerator;
|
|
44
|
+
},
|
|
45
|
+
get writeSync () {
|
|
46
|
+
return writeSync;
|
|
35
47
|
}
|
|
36
48
|
});
|
|
37
49
|
const _nodev8 = require("node:v8");
|
|
@@ -55,7 +67,7 @@ var Header = /*#__PURE__*/ function(Header) {
|
|
|
55
67
|
}({});
|
|
56
68
|
const HEADER_VALUES = 1 + Math.max(Object.values(Handshake).length, Object.values(Header).length) / 2;
|
|
57
69
|
const HEADER_SIZE = Uint32Array.BYTES_PER_ELEMENT * HEADER_VALUES;
|
|
58
|
-
|
|
70
|
+
function* writeGenerator(data, buffer, { timeout = 5000 } = {}) {
|
|
59
71
|
const serialized = (0, _nodev8.serialize)(data);
|
|
60
72
|
const chunkSize = buffer.byteLength - HEADER_SIZE;
|
|
61
73
|
const totalSize = serialized.length;
|
|
@@ -66,7 +78,13 @@ const write = (data, buffer, { timeout = 5000 } = {})=>{
|
|
|
66
78
|
Atomics.store(header, SEMAPHORE, 1);
|
|
67
79
|
Atomics.notify(header, SEMAPHORE);
|
|
68
80
|
try {
|
|
69
|
-
|
|
81
|
+
const handshakeResult = yield {
|
|
82
|
+
target: header,
|
|
83
|
+
index: SEMAPHORE,
|
|
84
|
+
value: 1,
|
|
85
|
+
timeout
|
|
86
|
+
};
|
|
87
|
+
if (handshakeResult === "timed-out") {
|
|
70
88
|
throw new Error("Reader handshake timeout");
|
|
71
89
|
}
|
|
72
90
|
const payload = new Uint8Array(buffer, HEADER_SIZE);
|
|
@@ -80,17 +98,29 @@ const write = (data, buffer, { timeout = 5000 } = {})=>{
|
|
|
80
98
|
header[3] = size;
|
|
81
99
|
Atomics.store(header, SEMAPHORE, 2);
|
|
82
100
|
Atomics.notify(header, SEMAPHORE);
|
|
83
|
-
|
|
101
|
+
const chunkResult = yield {
|
|
102
|
+
target: header,
|
|
103
|
+
index: SEMAPHORE,
|
|
104
|
+
value: 2,
|
|
105
|
+
timeout
|
|
106
|
+
};
|
|
107
|
+
if (chunkResult === "timed-out") {
|
|
84
108
|
throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);
|
|
85
109
|
}
|
|
86
110
|
}
|
|
87
111
|
} finally{
|
|
88
112
|
Atomics.store(header, SEMAPHORE, 0);
|
|
89
113
|
}
|
|
90
|
-
}
|
|
91
|
-
|
|
114
|
+
}
|
|
115
|
+
function* readGenerator(buffer, { timeout = 5000 } = {}) {
|
|
92
116
|
const header = new Int32Array(buffer);
|
|
93
|
-
|
|
117
|
+
const handshakeResult = yield {
|
|
118
|
+
target: header,
|
|
119
|
+
index: SEMAPHORE,
|
|
120
|
+
value: 0,
|
|
121
|
+
timeout
|
|
122
|
+
};
|
|
123
|
+
if (handshakeResult === "timed-out") {
|
|
94
124
|
throw new Error("Handshake timeout");
|
|
95
125
|
}
|
|
96
126
|
if (header[SEMAPHORE] !== 1) {
|
|
@@ -103,7 +133,13 @@ const read = (buffer, { timeout = 5000 } = {})=>{
|
|
|
103
133
|
Atomics.notify(header, SEMAPHORE);
|
|
104
134
|
const payload = new Uint8Array(buffer, HEADER_SIZE);
|
|
105
135
|
for(let i = 0; i < totalChunks; i++){
|
|
106
|
-
|
|
136
|
+
const chunkResult = yield {
|
|
137
|
+
target: header,
|
|
138
|
+
index: SEMAPHORE,
|
|
139
|
+
value: 0,
|
|
140
|
+
timeout
|
|
141
|
+
};
|
|
142
|
+
if (chunkResult === "timed-out") {
|
|
107
143
|
throw new Error(`Writer timeout waiting for chunk ${i}`);
|
|
108
144
|
}
|
|
109
145
|
if (header[SEMAPHORE] !== 2) {
|
|
@@ -120,6 +156,42 @@ const read = (buffer, { timeout = 5000 } = {})=>{
|
|
|
120
156
|
Atomics.notify(header, SEMAPHORE);
|
|
121
157
|
}
|
|
122
158
|
return (0, _nodev8.deserialize)(data);
|
|
159
|
+
}
|
|
160
|
+
const writeSync = (data, buffer, options)=>{
|
|
161
|
+
const gen = writeGenerator(data, buffer, options);
|
|
162
|
+
let result = gen.next();
|
|
163
|
+
while(!result.done){
|
|
164
|
+
const waitResult = Atomics.wait(result.value.target, result.value.index, result.value.value, result.value.timeout);
|
|
165
|
+
result = gen.next(waitResult);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const write = async (data, buffer, options)=>{
|
|
169
|
+
const gen = writeGenerator(data, buffer, options);
|
|
170
|
+
let result = gen.next();
|
|
171
|
+
while(!result.done){
|
|
172
|
+
const request = result.value;
|
|
173
|
+
const waitResult = await Atomics.waitAsync(request.target, request.index, request.value, request.timeout).value;
|
|
174
|
+
result = gen.next(waitResult);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
const readSync = (buffer, options)=>{
|
|
178
|
+
const gen = readGenerator(buffer, options);
|
|
179
|
+
let result = gen.next();
|
|
180
|
+
while(!result.done){
|
|
181
|
+
const waitResult = Atomics.wait(result.value.target, result.value.index, result.value.value, result.value.timeout);
|
|
182
|
+
result = gen.next(waitResult);
|
|
183
|
+
}
|
|
184
|
+
return result.value;
|
|
185
|
+
};
|
|
186
|
+
const read = async (buffer, options)=>{
|
|
187
|
+
const gen = readGenerator(buffer, options);
|
|
188
|
+
let result = gen.next();
|
|
189
|
+
while(!result.done){
|
|
190
|
+
const request = result.value;
|
|
191
|
+
const waitResult = await Atomics.waitAsync(request.target, request.index, request.value, request.timeout).value;
|
|
192
|
+
result = gen.next(waitResult);
|
|
193
|
+
}
|
|
194
|
+
return result.value;
|
|
123
195
|
};
|
|
124
196
|
|
|
125
197
|
//# sourceMappingURL=index.cjs.map
|
package/build/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { serialize, deserialize } from \"node:v8\";\n\nexport const SEMAPHORE = 0;\n\nexport enum Semaphore {\n READY,\n HANDSHAKE,\n PAYLOAD,\n}\n\nexport enum Handshake {\n TOTAL_SIZE = 1,\n TOTAL_CHUNKS,\n}\n\nexport enum Header {\n CHUNK_INDEX = 1,\n CHUNK_OFFSET,\n CHUNK_SIZE,\n}\n\nexport const HEADER_VALUES =\n 1 +\n Math.max(Object.values(Handshake).length, Object.values(Header).length) / 2;\nexport const HEADER_SIZE = Uint32Array.BYTES_PER_ELEMENT * HEADER_VALUES;\n\nexport interface Options {\n timeout?: number;\n}\n\nexport const write = (\n data: unknown,\n buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {}\n) => {\n const serialized = serialize(data);\n const chunkSize = buffer.byteLength - HEADER_SIZE;\n const totalSize = serialized.length;\n const totalChunks = Math.ceil(totalSize / chunkSize);\n\n const header = new Int32Array(buffer);\n header[Handshake.TOTAL_SIZE] = totalSize;\n header[Handshake.TOTAL_CHUNKS] = totalChunks;\n\n Atomics.store(header, SEMAPHORE, Semaphore.HANDSHAKE);\n Atomics.notify(header, SEMAPHORE);\n\n try {\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.HANDSHAKE, timeout) ===\n \"timed-out\"\n ) {\n throw new Error(\"Reader handshake timeout\");\n }\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n\n for (let i = 0; i < totalChunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, totalSize);\n const size = end - start;\n\n payload.set(serialized.subarray(start, end), 0);\n\n header[Header.CHUNK_INDEX] = i;\n header[Header.CHUNK_OFFSET] = start;\n header[Header.CHUNK_SIZE] = size;\n\n Atomics.store(header, SEMAPHORE, Semaphore.PAYLOAD);\n Atomics.notify(header, SEMAPHORE);\n\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.PAYLOAD, timeout) ===\n \"timed-out\"\n ) {\n throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);\n }\n }\n } finally {\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n }\n};\n\nexport const read = (buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {}\n): unknown => {\n const header = new Int32Array(buffer);\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.READY, timeout) === \"timed-out\"\n ) {\n throw new Error(\"Handshake timeout\");\n }\n if (header[SEMAPHORE] !== Semaphore.HANDSHAKE) {\n throw new Error(\"Invalid handshake state\");\n }\n\n const totalSize = header[Handshake.TOTAL_SIZE];\n const totalChunks = header[Handshake.TOTAL_CHUNKS];\n const data = new Uint8Array(totalSize);\n\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n for (let i = 0; i < totalChunks; i++) {\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.READY, timeout) === \"timed-out\"\n ) {\n throw new Error(`Writer timeout waiting for chunk ${i}`);\n }\n // @ts-expect-error does not infer number\n if (header[SEMAPHORE] !== Semaphore.PAYLOAD) {\n throw new Error(\n `Expected payload header, received ${Semaphore[header[SEMAPHORE]]}`,\n );\n }\n const chunkIndex = header[Header.CHUNK_INDEX];\n if (i !== chunkIndex) {\n throw new Error(\n `Reader integrity failure for chunk ${chunkIndex} expected ${i}`,\n );\n }\n const offset = header[Header.CHUNK_OFFSET];\n const size = header[Header.CHUNK_SIZE];\n data.set(payload.subarray(0, size), offset);\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n }\n return deserialize(data);\n};\n"],"names":["HEADER_SIZE","HEADER_VALUES","Handshake","Header","SEMAPHORE","Semaphore","read","write","Math","max","Object","values","length","Uint32Array","BYTES_PER_ELEMENT","data","buffer","timeout","serialized","serialize","chunkSize","byteLength","totalSize","totalChunks","ceil","header","Int32Array","Atomics","store","notify","wait","Error","payload","Uint8Array","i","start","end","min","size","set","subarray","chunkIndex","offset","deserialize"],"mappings":";;;;;;;;;;;QAwBaA;eAAAA;;QAHAC;eAAAA;;QAXDC;eAAAA;;QAKAC;eAAAA;;QAbCC;eAAAA;;QAEDC;eAAAA;;QA+ECC;eAAAA;;QArDAC;eAAAA;;;wBA9B0B;AAEhC,MAAMH,YAAY;AAElB,IAAA,AAAKC,mCAAAA;;;;WAAAA;;AAML,IAAA,AAAKH,mCAAAA;;;WAAAA;;AAKL,IAAA,AAAKC,gCAAAA;;;;WAAAA;;AAML,MAAMF,gBACX,IACAO,KAAKC,GAAG,CAACC,OAAOC,MAAM,CAACT,WAAWU,MAAM,EAAEF,OAAOC,MAAM,CAACR,QAAQS,MAAM,IAAI;AACrE,MAAMZ,cAAca,YAAYC,iBAAiB,GAAGb;AA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CAAC;IAEhC,MAAMQ,SAAS,IAAIC,WAAWV;IAC9B,IACEW,QAAQG,IAAI,CAACL,QAAQrB,cAA4Ba,aAAa,aAC9D;QACA,MAAM,IAAIc,MAAM;IAClB;IACA,IAAIN,MAAM,CAACrB,UAAU,QAA0B;QAC7C,MAAM,IAAI2B,MAAM;IAClB;IAEA,MAAMT,YAAYG,MAAM,GAAsB;IAC9C,MAAMF,cAAcE,MAAM,GAAwB;IAClD,MAAMV,OAAO,IAAIkB,WAAWX;IAE5BK,QAAQC,KAAK,CAACH,QAAQrB;IACtBuB,QAAQE,MAAM,CAACJ,QAAQrB;IAEvB,MAAM4B,UAAU,IAAIC,WAAWjB,QAAQhB;IACvC,IAAK,IAAIkC,IAAI,GAAGA,IAAIX,aAAaW,IAAK;QACpC,IACEP,QAAQG,IAAI,CAACL,QAAQrB,cAA4Ba,aAAa,aAC9D;YACA,MAAM,IAAIc,MAAM,CAAC,iCAAiC,EAAEG,GAAG;QACzD;QAEA,IAAIT,MAAM,CAACrB,UAAU,QAAwB;YAC3C,MAAM,IAAI2B,MACR,CAAC,kCAAkC,EAAE1B,SAAS,CAACoB,MAAM,CAACrB,UAAU,CAAC,EAAE;QAEvE;QACA,MAAMqC,aAAahB,MAAM,GAAoB;QAC7C,IAAIS,MAAMO,YAAY;YACpB,MAAM,IAAIV,MACR,CAAC,mCAAmC,EAAEU,WAAW,UAAU,EAAEP,GAAG;QAEpE;QACA,MAAMQ,SAASjB,MAAM,GAAqB;QAC1C,MAAMa,OAAOb,MAAM,GAAmB;QACtCV,KAAKwB,GAAG,CAACP,QAAQQ,QAAQ,CAAC,GAAGF,OAAOI;QACpCf,QAAQC,KAAK,CAACH,QAAQrB;QACtBuB,QAAQE,MAAM,CAACJ,QAAQrB;IACzB;IACA,OAAOuC,IAAAA,mBAAW,EAAC5B;AACrB"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { serialize, deserialize } from \"node:v8\";\n\nexport const SEMAPHORE = 0;\n\nexport enum Semaphore {\n READY,\n HANDSHAKE,\n PAYLOAD,\n}\n\nexport enum Handshake {\n TOTAL_SIZE = 1,\n TOTAL_CHUNKS,\n}\n\nexport enum Header {\n CHUNK_INDEX = 1,\n CHUNK_OFFSET,\n CHUNK_SIZE,\n}\n\nexport const HEADER_VALUES =\n 1 +\n Math.max(Object.values(Handshake).length, Object.values(Header).length) / 2;\nexport const HEADER_SIZE = Uint32Array.BYTES_PER_ELEMENT * HEADER_VALUES;\n\nexport interface Options {\n timeout?: number;\n}\n\nexport interface WaitRequest {\n target: Int32Array;\n index: number;\n value: number;\n timeout?: number;\n}\n\nexport type WaitResponse = ReturnType<typeof Atomics.wait>;\n\nexport function* writeGenerator(\n data: unknown,\n buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {},\n): Generator<WaitRequest, void, WaitResponse> {\n const serialized = serialize(data);\n const chunkSize = buffer.byteLength - HEADER_SIZE;\n const totalSize = serialized.length;\n const totalChunks = Math.ceil(totalSize / chunkSize);\n const header = new Int32Array(buffer);\n\n header[Handshake.TOTAL_SIZE] = totalSize;\n header[Handshake.TOTAL_CHUNKS] = totalChunks;\n Atomics.store(header, SEMAPHORE, Semaphore.HANDSHAKE);\n Atomics.notify(header, SEMAPHORE);\n\n try {\n const handshakeResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.HANDSHAKE,\n timeout,\n };\n if (handshakeResult === \"timed-out\") {\n throw new Error(\"Reader handshake timeout\");\n }\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n for (let i = 0; i < totalChunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, totalSize);\n const size = end - start;\n payload.set(serialized.subarray(start, end), 0);\n header[Header.CHUNK_INDEX] = i;\n header[Header.CHUNK_OFFSET] = start;\n header[Header.CHUNK_SIZE] = size;\n Atomics.store(header, SEMAPHORE, Semaphore.PAYLOAD);\n Atomics.notify(header, SEMAPHORE);\n\n const chunkResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.PAYLOAD,\n timeout,\n };\n if (chunkResult === \"timed-out\") {\n throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);\n }\n }\n } finally {\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n }\n}\n\nexport function* readGenerator(\n buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {},\n): Generator<WaitRequest, unknown, WaitResponse> {\n const header = new Int32Array(buffer);\n\n const handshakeResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.READY,\n timeout,\n };\n if (handshakeResult === \"timed-out\") {\n throw new Error(\"Handshake timeout\");\n }\n if (header[SEMAPHORE] !== Semaphore.HANDSHAKE) {\n throw new Error(\"Invalid handshake state\");\n }\n\n const totalSize = header[Handshake.TOTAL_SIZE];\n const totalChunks = header[Handshake.TOTAL_CHUNKS];\n const data = new Uint8Array(totalSize);\n\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n for (let i = 0; i < totalChunks; i++) {\n const chunkResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.READY,\n timeout,\n };\n if (chunkResult === \"timed-out\") {\n throw new Error(`Writer timeout waiting for chunk ${i}`);\n }\n // @ts-expect-error does not infer number\n if (header[SEMAPHORE] !== Semaphore.PAYLOAD) {\n throw new Error(\n `Expected payload header, received ${Semaphore[header[SEMAPHORE]]}`,\n );\n }\n const chunkIndex = header[Header.CHUNK_INDEX];\n if (i !== chunkIndex) {\n throw new Error(\n `Reader integrity failure for chunk ${chunkIndex} expected ${i}`,\n );\n }\n const offset = header[Header.CHUNK_OFFSET];\n const size = header[Header.CHUNK_SIZE];\n data.set(payload.subarray(0, size), offset);\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n }\n return deserialize(data) as unknown;\n}\n\nexport const writeSync = (\n data: unknown,\n buffer: SharedArrayBuffer,\n options?: Options,\n) => {\n const gen = writeGenerator(data, buffer, options);\n let result = gen.next();\n while (!result.done) {\n const waitResult = Atomics.wait(\n result.value.target,\n result.value.index,\n result.value.value,\n result.value.timeout,\n );\n result = gen.next(waitResult);\n }\n};\n\nexport const write = async (\n data: unknown,\n buffer: SharedArrayBuffer,\n options?: Options,\n) => {\n const gen = writeGenerator(data, buffer, options);\n let result = gen.next();\n while (!result.done) {\n const request = result.value;\n const waitResult = await Atomics.waitAsync(\n request.target,\n request.index,\n request.value,\n request.timeout,\n ).value;\n result = gen.next(waitResult);\n }\n};\n\nexport const readSync = (\n buffer: SharedArrayBuffer,\n options?: Options,\n): unknown => {\n const gen = readGenerator(buffer, options);\n let result = gen.next();\n while (!result.done) {\n const waitResult = Atomics.wait(\n result.value.target,\n result.value.index,\n result.value.value,\n result.value.timeout,\n );\n result = gen.next(waitResult);\n }\n return result.value;\n};\n\nexport const read = async (\n buffer: SharedArrayBuffer,\n options?: Options,\n): Promise<unknown> => {\n const gen = readGenerator(buffer, options);\n let result = gen.next();\n while (!result.done) {\n const request = result.value;\n const waitResult = await Atomics.waitAsync(\n request.target,\n request.index,\n request.value,\n request.timeout,\n ).value;\n result = gen.next(waitResult);\n }\n return result.value;\n};\n"],"names":["HEADER_SIZE","HEADER_VALUES","Handshake","Header","SEMAPHORE","Semaphore","read","readGenerator","readSync","write","writeGenerator","writeSync","Math","max","Object","values","length","Uint32Array","BYTES_PER_ELEMENT","data","buffer","timeout","serialized","serialize","chunkSize","byteLength","totalSize","totalChunks","ceil","header","Int32Array","Atomics","store","notify","handshakeResult","target","index","value","Error","payload","Uint8Array","i","start","end","min","size","set","subarray","chunkResult","chunkIndex","offset","deserialize","options","gen","result","next","done","waitResult","wait","request","waitAsync"],"mappings":";;;;;;;;;;;QAwBaA;eAAAA;;QAHAC;eAAAA;;QAXDC;eAAAA;;QAKAC;eAAAA;;QAbCC;eAAAA;;QAEDC;eAAAA;;QA0MCC;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O,EACfgB,KAAK;QACPiB,SAASD,IAAIE,IAAI,CAACE;IACpB;AACF;AAEO,MAAMjD,WAAW,CACtBY,QACAgC;IAEA,MAAMC,MAAM9C,cAAca,QAAQgC;IAClC,IAAIE,SAASD,IAAIE,IAAI;IACrB,MAAO,CAACD,OAAOE,IAAI,CAAE;QACnB,MAAMC,aAAa1B,QAAQ2B,IAAI,CAC7BJ,OAAOjB,KAAK,CAACF,MAAM,EACnBmB,OAAOjB,KAAK,CAACD,KAAK,EAClBkB,OAAOjB,KAAK,CAACA,KAAK,EAClBiB,OAAOjB,KAAK,CAAChB,OAAO;QAEtBiC,SAASD,IAAIE,IAAI,CAACE;IACpB;IACA,OAAOH,OAAOjB,KAAK;AACrB;AAEO,MAAM/B,OAAO,OAClBc,QACAgC;IAEA,MAAMC,MAAM9C,cAAca,QAAQgC;IAClC,IAAIE,SAASD,IAAIE,IAAI;IACrB,MAAO,CAACD,OAAOE,IAAI,CAAE;QACnB,MAAMG,UAAUL,OAAOjB,KAAK;QAC5B,MAAMoB,aAAa,MAAM1B,QAAQ6B,SAAS,CACxCD,QAAQxB,MAAM,EACdwB,QAAQvB,KAAK,EACbuB,QAAQtB,KAAK,EACbsB,QAAQtC,OAAO,EACfgB,KAAK;QACPiB,SAASD,IAAIE,IAAI,CAACE;IACpB;IACA,OAAOH,OAAOjB,KAAK;AACrB"}
|
package/build/index.d.ts
CHANGED
|
@@ -18,5 +18,16 @@ export declare const HEADER_SIZE: number;
|
|
|
18
18
|
export interface Options {
|
|
19
19
|
timeout?: number;
|
|
20
20
|
}
|
|
21
|
-
export
|
|
22
|
-
|
|
21
|
+
export interface WaitRequest {
|
|
22
|
+
target: Int32Array;
|
|
23
|
+
index: number;
|
|
24
|
+
value: number;
|
|
25
|
+
timeout?: number;
|
|
26
|
+
}
|
|
27
|
+
export type WaitResponse = ReturnType<typeof Atomics.wait>;
|
|
28
|
+
export declare function writeGenerator(data: unknown, buffer: SharedArrayBuffer, { timeout }?: Options): Generator<WaitRequest, void, WaitResponse>;
|
|
29
|
+
export declare function readGenerator(buffer: SharedArrayBuffer, { timeout }?: Options): Generator<WaitRequest, unknown, WaitResponse>;
|
|
30
|
+
export declare const writeSync: (data: unknown, buffer: SharedArrayBuffer, options?: Options) => void;
|
|
31
|
+
export declare const write: (data: unknown, buffer: SharedArrayBuffer, options?: Options) => Promise<void>;
|
|
32
|
+
export declare const readSync: (buffer: SharedArrayBuffer, options?: Options) => unknown;
|
|
33
|
+
export declare const read: (buffer: SharedArrayBuffer, options?: Options) => Promise<unknown>;
|
package/build/index.js
CHANGED
|
@@ -19,7 +19,7 @@ export var Header = /*#__PURE__*/ function(Header) {
|
|
|
19
19
|
}({});
|
|
20
20
|
export const HEADER_VALUES = 1 + Math.max(Object.values(Handshake).length, Object.values(Header).length) / 2;
|
|
21
21
|
export const HEADER_SIZE = Uint32Array.BYTES_PER_ELEMENT * HEADER_VALUES;
|
|
22
|
-
export
|
|
22
|
+
export function* writeGenerator(data, buffer, { timeout = 5000 } = {}) {
|
|
23
23
|
const serialized = serialize(data);
|
|
24
24
|
const chunkSize = buffer.byteLength - HEADER_SIZE;
|
|
25
25
|
const totalSize = serialized.length;
|
|
@@ -30,7 +30,13 @@ export const write = (data, buffer, { timeout = 5000 } = {})=>{
|
|
|
30
30
|
Atomics.store(header, SEMAPHORE, 1);
|
|
31
31
|
Atomics.notify(header, SEMAPHORE);
|
|
32
32
|
try {
|
|
33
|
-
|
|
33
|
+
const handshakeResult = yield {
|
|
34
|
+
target: header,
|
|
35
|
+
index: SEMAPHORE,
|
|
36
|
+
value: 1,
|
|
37
|
+
timeout
|
|
38
|
+
};
|
|
39
|
+
if (handshakeResult === "timed-out") {
|
|
34
40
|
throw new Error("Reader handshake timeout");
|
|
35
41
|
}
|
|
36
42
|
const payload = new Uint8Array(buffer, HEADER_SIZE);
|
|
@@ -44,17 +50,29 @@ export const write = (data, buffer, { timeout = 5000 } = {})=>{
|
|
|
44
50
|
header[3] = size;
|
|
45
51
|
Atomics.store(header, SEMAPHORE, 2);
|
|
46
52
|
Atomics.notify(header, SEMAPHORE);
|
|
47
|
-
|
|
53
|
+
const chunkResult = yield {
|
|
54
|
+
target: header,
|
|
55
|
+
index: SEMAPHORE,
|
|
56
|
+
value: 2,
|
|
57
|
+
timeout
|
|
58
|
+
};
|
|
59
|
+
if (chunkResult === "timed-out") {
|
|
48
60
|
throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);
|
|
49
61
|
}
|
|
50
62
|
}
|
|
51
63
|
} finally{
|
|
52
64
|
Atomics.store(header, SEMAPHORE, 0);
|
|
53
65
|
}
|
|
54
|
-
}
|
|
55
|
-
export
|
|
66
|
+
}
|
|
67
|
+
export function* readGenerator(buffer, { timeout = 5000 } = {}) {
|
|
56
68
|
const header = new Int32Array(buffer);
|
|
57
|
-
|
|
69
|
+
const handshakeResult = yield {
|
|
70
|
+
target: header,
|
|
71
|
+
index: SEMAPHORE,
|
|
72
|
+
value: 0,
|
|
73
|
+
timeout
|
|
74
|
+
};
|
|
75
|
+
if (handshakeResult === "timed-out") {
|
|
58
76
|
throw new Error("Handshake timeout");
|
|
59
77
|
}
|
|
60
78
|
if (header[SEMAPHORE] !== 1) {
|
|
@@ -67,7 +85,13 @@ export const read = (buffer, { timeout = 5000 } = {})=>{
|
|
|
67
85
|
Atomics.notify(header, SEMAPHORE);
|
|
68
86
|
const payload = new Uint8Array(buffer, HEADER_SIZE);
|
|
69
87
|
for(let i = 0; i < totalChunks; i++){
|
|
70
|
-
|
|
88
|
+
const chunkResult = yield {
|
|
89
|
+
target: header,
|
|
90
|
+
index: SEMAPHORE,
|
|
91
|
+
value: 0,
|
|
92
|
+
timeout
|
|
93
|
+
};
|
|
94
|
+
if (chunkResult === "timed-out") {
|
|
71
95
|
throw new Error(`Writer timeout waiting for chunk ${i}`);
|
|
72
96
|
}
|
|
73
97
|
if (header[SEMAPHORE] !== 2) {
|
|
@@ -84,6 +108,42 @@ export const read = (buffer, { timeout = 5000 } = {})=>{
|
|
|
84
108
|
Atomics.notify(header, SEMAPHORE);
|
|
85
109
|
}
|
|
86
110
|
return deserialize(data);
|
|
111
|
+
}
|
|
112
|
+
export const writeSync = (data, buffer, options)=>{
|
|
113
|
+
const gen = writeGenerator(data, buffer, options);
|
|
114
|
+
let result = gen.next();
|
|
115
|
+
while(!result.done){
|
|
116
|
+
const waitResult = Atomics.wait(result.value.target, result.value.index, result.value.value, result.value.timeout);
|
|
117
|
+
result = gen.next(waitResult);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
export const write = async (data, buffer, options)=>{
|
|
121
|
+
const gen = writeGenerator(data, buffer, options);
|
|
122
|
+
let result = gen.next();
|
|
123
|
+
while(!result.done){
|
|
124
|
+
const request = result.value;
|
|
125
|
+
const waitResult = await Atomics.waitAsync(request.target, request.index, request.value, request.timeout).value;
|
|
126
|
+
result = gen.next(waitResult);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
export const readSync = (buffer, options)=>{
|
|
130
|
+
const gen = readGenerator(buffer, options);
|
|
131
|
+
let result = gen.next();
|
|
132
|
+
while(!result.done){
|
|
133
|
+
const waitResult = Atomics.wait(result.value.target, result.value.index, result.value.value, result.value.timeout);
|
|
134
|
+
result = gen.next(waitResult);
|
|
135
|
+
}
|
|
136
|
+
return result.value;
|
|
137
|
+
};
|
|
138
|
+
export const read = async (buffer, options)=>{
|
|
139
|
+
const gen = readGenerator(buffer, options);
|
|
140
|
+
let result = gen.next();
|
|
141
|
+
while(!result.done){
|
|
142
|
+
const request = result.value;
|
|
143
|
+
const waitResult = await Atomics.waitAsync(request.target, request.index, request.value, request.timeout).value;
|
|
144
|
+
result = gen.next(waitResult);
|
|
145
|
+
}
|
|
146
|
+
return result.value;
|
|
87
147
|
};
|
|
88
148
|
|
|
89
149
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { serialize, deserialize } from \"node:v8\";\n\nexport const SEMAPHORE = 0;\n\nexport enum Semaphore {\n READY,\n HANDSHAKE,\n PAYLOAD,\n}\n\nexport enum Handshake {\n TOTAL_SIZE = 1,\n TOTAL_CHUNKS,\n}\n\nexport enum Header {\n CHUNK_INDEX = 1,\n CHUNK_OFFSET,\n CHUNK_SIZE,\n}\n\nexport const HEADER_VALUES =\n 1 +\n Math.max(Object.values(Handshake).length, Object.values(Header).length) / 2;\nexport const HEADER_SIZE = Uint32Array.BYTES_PER_ELEMENT * HEADER_VALUES;\n\nexport interface Options {\n timeout?: number;\n}\n\nexport const write = (\n data: unknown,\n buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {}\n) => {\n const serialized = serialize(data);\n const chunkSize = buffer.byteLength - HEADER_SIZE;\n const totalSize = serialized.length;\n const totalChunks = Math.ceil(totalSize / chunkSize);\n\n const header = new Int32Array(buffer);\n header[Handshake.TOTAL_SIZE] = totalSize;\n header[Handshake.TOTAL_CHUNKS] = totalChunks;\n\n Atomics.store(header, SEMAPHORE, Semaphore.HANDSHAKE);\n Atomics.notify(header, SEMAPHORE);\n\n try {\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.HANDSHAKE, timeout) ===\n \"timed-out\"\n ) {\n throw new Error(\"Reader handshake timeout\");\n }\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n\n for (let i = 0; i < totalChunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, totalSize);\n const size = end - start;\n\n payload.set(serialized.subarray(start, end), 0);\n\n header[Header.CHUNK_INDEX] = i;\n header[Header.CHUNK_OFFSET] = start;\n header[Header.CHUNK_SIZE] = size;\n\n Atomics.store(header, SEMAPHORE, Semaphore.PAYLOAD);\n Atomics.notify(header, SEMAPHORE);\n\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.PAYLOAD, timeout) ===\n \"timed-out\"\n ) {\n throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);\n }\n }\n } finally {\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n }\n};\n\nexport const read = (buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {}\n): unknown => {\n const header = new Int32Array(buffer);\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.READY, timeout) === \"timed-out\"\n ) {\n throw new Error(\"Handshake timeout\");\n }\n if (header[SEMAPHORE] !== Semaphore.HANDSHAKE) {\n throw new Error(\"Invalid handshake state\");\n }\n\n const totalSize = header[Handshake.TOTAL_SIZE];\n const totalChunks = header[Handshake.TOTAL_CHUNKS];\n const data = new Uint8Array(totalSize);\n\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n for (let i = 0; i < totalChunks; i++) {\n if (\n Atomics.wait(header, SEMAPHORE, Semaphore.READY, timeout) === \"timed-out\"\n ) {\n throw new Error(`Writer timeout waiting for chunk ${i}`);\n }\n // @ts-expect-error does not infer number\n if (header[SEMAPHORE] !== Semaphore.PAYLOAD) {\n throw new Error(\n `Expected payload header, received ${Semaphore[header[SEMAPHORE]]}`,\n );\n }\n const chunkIndex = header[Header.CHUNK_INDEX];\n if (i !== chunkIndex) {\n throw new Error(\n `Reader integrity failure for chunk ${chunkIndex} expected ${i}`,\n );\n }\n const offset = header[Header.CHUNK_OFFSET];\n const size = header[Header.CHUNK_SIZE];\n data.set(payload.subarray(0, size), offset);\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n }\n return deserialize(data);\n};\n"],"names":["serialize","deserialize","SEMAPHORE","Semaphore","Handshake","Header","HEADER_VALUES","Math","max","Object","values","length","HEADER_SIZE","Uint32Array","BYTES_PER_ELEMENT","write","data","buffer","timeout","serialized","chunkSize","byteLength","totalSize","totalChunks","ceil","header","Int32Array","Atomics","store","notify","wait","Error","payload","Uint8Array","i","start","end","min","size","set","subarray","read","chunkIndex","offset"],"mappings":"AAAA,SAASA,SAA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,CAAC,mCAAmC,EAAEW,WAAW,UAAU,EAAER,GAAG;QAEpE;QACA,MAAMS,SAASlB,MAAM,GAAqB;QAC1C,MAAMa,OAAOb,MAAM,GAAmB;QACtCT,KAAKuB,GAAG,CAACP,QAAQQ,QAAQ,CAAC,GAAGF,OAAOK;QACpChB,QAAQC,KAAK,CAACH,QAAQvB;QACtByB,QAAQE,MAAM,CAACJ,QAAQvB;IACzB;IACA,OAAOD,YAAYe;AACrB,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { serialize, deserialize } from \"node:v8\";\n\nexport const SEMAPHORE = 0;\n\nexport enum Semaphore {\n READY,\n HANDSHAKE,\n PAYLOAD,\n}\n\nexport enum Handshake {\n TOTAL_SIZE = 1,\n TOTAL_CHUNKS,\n}\n\nexport enum Header {\n CHUNK_INDEX = 1,\n CHUNK_OFFSET,\n CHUNK_SIZE,\n}\n\nexport const HEADER_VALUES =\n 1 +\n Math.max(Object.values(Handshake).length, Object.values(Header).length) / 2;\nexport const HEADER_SIZE = Uint32Array.BYTES_PER_ELEMENT * HEADER_VALUES;\n\nexport interface Options {\n timeout?: number;\n}\n\nexport interface WaitRequest {\n target: Int32Array;\n index: number;\n value: number;\n timeout?: number;\n}\n\nexport type WaitResponse = ReturnType<typeof Atomics.wait>;\n\nexport function* writeGenerator(\n data: unknown,\n buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {},\n): Generator<WaitRequest, void, WaitResponse> {\n const serialized = serialize(data);\n const chunkSize = buffer.byteLength - HEADER_SIZE;\n const totalSize = serialized.length;\n const totalChunks = Math.ceil(totalSize / chunkSize);\n const header = new Int32Array(buffer);\n\n header[Handshake.TOTAL_SIZE] = totalSize;\n header[Handshake.TOTAL_CHUNKS] = totalChunks;\n Atomics.store(header, SEMAPHORE, Semaphore.HANDSHAKE);\n Atomics.notify(header, SEMAPHORE);\n\n try {\n const handshakeResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.HANDSHAKE,\n timeout,\n };\n if (handshakeResult === \"timed-out\") {\n throw new Error(\"Reader handshake timeout\");\n }\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n for (let i = 0; i < totalChunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, totalSize);\n const size = end - start;\n payload.set(serialized.subarray(start, end), 0);\n header[Header.CHUNK_INDEX] = i;\n header[Header.CHUNK_OFFSET] = start;\n header[Header.CHUNK_SIZE] = size;\n Atomics.store(header, SEMAPHORE, Semaphore.PAYLOAD);\n Atomics.notify(header, SEMAPHORE);\n\n const chunkResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.PAYLOAD,\n timeout,\n };\n if (chunkResult === \"timed-out\") {\n throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);\n }\n }\n } finally {\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n }\n}\n\nexport function* readGenerator(\n buffer: SharedArrayBuffer,\n { timeout = 5000 }: Options = {},\n): Generator<WaitRequest, unknown, WaitResponse> {\n const header = new Int32Array(buffer);\n\n const handshakeResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.READY,\n timeout,\n };\n if (handshakeResult === \"timed-out\") {\n throw new Error(\"Handshake timeout\");\n }\n if (header[SEMAPHORE] !== Semaphore.HANDSHAKE) {\n throw new Error(\"Invalid handshake state\");\n }\n\n const totalSize = header[Handshake.TOTAL_SIZE];\n const totalChunks = header[Handshake.TOTAL_CHUNKS];\n const data = new Uint8Array(totalSize);\n\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n\n const payload = new Uint8Array(buffer, HEADER_SIZE);\n for (let i = 0; i < totalChunks; i++) {\n const chunkResult: WaitResponse = yield {\n target: header,\n index: SEMAPHORE,\n value: Semaphore.READY,\n timeout,\n };\n if (chunkResult === \"timed-out\") {\n throw new Error(`Writer timeout waiting for chunk ${i}`);\n }\n // @ts-expect-error does not infer number\n if (header[SEMAPHORE] !== Semaphore.PAYLOAD) {\n throw new Error(\n `Expected payload header, received ${Semaphore[header[SEMAPHORE]]}`,\n );\n }\n const chunkIndex = header[Header.CHUNK_INDEX];\n if (i !== chunkIndex) {\n throw new Error(\n `Reader integrity failure for chunk ${chunkIndex} expected ${i}`,\n );\n }\n const offset = header[Header.CHUNK_OFFSET];\n const size = header[Header.CHUNK_SIZE];\n data.set(payload.subarray(0, size), offset);\n Atomics.store(header, SEMAPHORE, Semaphore.READY);\n Atomics.notify(header, SEMAPHORE);\n }\n return deserialize(data) as unknown;\n}\n\nexport const writeSync = (\n data: unknown,\n buffer: SharedArrayBuffer,\n options?: Options,\n) => {\n const gen = writeGenerator(data, buffer, options);\n let result = gen.next();\n while (!result.done) {\n const waitResult = Atomics.wait(\n result.value.target,\n result.value.index,\n result.value.value,\n result.value.timeout,\n );\n result = gen.next(waitResult);\n }\n};\n\nexport const write = async (\n data: unknown,\n buffer: SharedArrayBuffer,\n options?: Options,\n) => {\n const gen = writeGenerator(data, buffer, options);\n let result = gen.next();\n while (!result.done) {\n const request = result.value;\n const waitResult = await Atomics.waitAsync(\n request.target,\n request.index,\n request.value,\n request.timeout,\n ).value;\n result = gen.next(waitResult);\n }\n};\n\nexport const readSync = (\n buffer: SharedArrayBuffer,\n options?: Options,\n): unknown => {\n const gen = readGenerator(buffer, options);\n let result = gen.next();\n while (!result.done) {\n const waitResult = Atomics.wait(\n result.value.target,\n result.value.index,\n result.value.value,\n result.value.timeout,\n );\n result = gen.next(waitResult);\n }\n return result.value;\n};\n\nexport const read = async (\n buffer: SharedArrayBuffer,\n options?: Options,\n): Promise<unknown> => {\n const gen = readGenerator(buffer, options);\n let result = gen.next();\n while (!result.done) {\n const request = result.value;\n const waitResult = await Atomics.waitAsync(\n request.target,\n request.index,\n request.value,\n request.timeout,\n ).value;\n result = gen.next(waitResult);\n }\n return result.value;\n};\n"],"names":["serialize","deserialize","SEMAPHORE","Semaphore","Handshake","Header","HEADER_VALUES","Math","max","Object","values","length","HEADER_SIZE","Uint32Array","BYTES_PER_ELEMENT","writeGenerator","data","buffer","timeout","serialized","chunkSize","byteLength","totalSize","totalChunks","ceil","header","Int32Array","Atomics","store","notify","handshakeResult","target","index","value","Error","payload","Uint8Array","i","start","end","min","size","set","subarray","chunkResult","readGenerator","chunkIndex","offset","writeSync","options","gen","result","next","done","waitResult","wait","write","request","waitAsync","readSync","read"],"mappings":"AAAA,SAASA,SAAS,EAAEC,WAAW,QAAQ,UAAU;AAEjD,OAAO,MAAMC,YAAY,EAAE;AAE3B,OAAO,IAAA,AAAKC,mCAAAA;;;;WAAAA;MAIX;AAED,OAAO,IAAA,AAAKC,mCAAAA;;;WAAAA;MAGX;AAED,OAAO,IAAA,AAAKC,gCAAAA;;;;WAAAA;MAIX;AAED,OAAO,MAAMC,gBACX,IACAC,KAAKC,GAAG,CAACC,OAAOC,MAAM,CAACN,WAAWO,MAAM,EAAEF,OAAOC,MAAM,CAACL,QAAQM,MAAM,IAAI,EAAE;AAC9E,OAAO,MAAMC,cAAcC,YAAYC,iBAAiB,GAAGR,cAAc;AAezE,OAAO,UAAUS,eACfC,IAAa,EACbC,MAAyB,EACzB,EAAEC,UAAU,IAAI,EAAW,GAAG,CAAC,CAAC;IAEhC,MAAMC,aAAanB,UAAUgB;IAC7B,MAAMI,YAAYH,OAAOI,UAAU,GAAGT;IACtC,MAAMU,YAAYH,WAAWR,MAAM;IACnC,MAAMY,cAAchB,KAAKiB,IAAI,CAACF,YAAYF;IAC1C,MAAMK,SAAS,IAAIC,WAAWT;IAE9BQ,MAAM,GAAsB,GAAGH;IAC/BG,MAAM,GAAwB,GAAGF;IACjCI,QAAQC,KAAK,CAACH,QAAQvB;IACtByB,QAAQE,MAAM,CAACJ,QAAQvB;IAEvB,IAAI;QACF,MAAM4B,kBAAgC,MAAM;YAC1CC,QAAQN;YACRO,OAAO9B;YACP+B,KAAK;YACLf;QACF;QACA,IAAIY,oBAAoB,aAAa;YACnC,MAA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"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "A TypeScript/Node.js library for inter-thread communication using SharedArrayBuffer with atomic operations and V8 serialization",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "build/index.d.ts",
|
|
@@ -14,11 +14,6 @@
|
|
|
14
14
|
"build",
|
|
15
15
|
"src/index.ts"
|
|
16
16
|
],
|
|
17
|
-
"scripts": {
|
|
18
|
-
"build": "rm -rf build && inop src build -i __tests__ -i *.tmp.ts && tsc --declaration --emitDeclarationOnly",
|
|
19
|
-
"lint": "eslint src",
|
|
20
|
-
"test": "jest"
|
|
21
|
-
},
|
|
22
17
|
"repository": {
|
|
23
18
|
"type": "git",
|
|
24
19
|
"url": "git+https://github.com/3axap4eHko/sabcom.git"
|
|
@@ -30,9 +25,18 @@
|
|
|
30
25
|
"buffer",
|
|
31
26
|
"thread",
|
|
32
27
|
"worker",
|
|
33
|
-
"communication"
|
|
28
|
+
"communication",
|
|
29
|
+
"concurrency",
|
|
30
|
+
"parallel",
|
|
31
|
+
"multithreading",
|
|
32
|
+
"ipc",
|
|
33
|
+
"inter-process",
|
|
34
|
+
"v8",
|
|
35
|
+
"serialization",
|
|
36
|
+
"synchronization",
|
|
37
|
+
"memory"
|
|
34
38
|
],
|
|
35
|
-
"license": "
|
|
39
|
+
"license": "Apache-2.0",
|
|
36
40
|
"author": {
|
|
37
41
|
"name": "Ivan Zakharchanka",
|
|
38
42
|
"email": "3axap4eHko@gmail.com",
|
|
@@ -40,20 +44,24 @@
|
|
|
40
44
|
},
|
|
41
45
|
"devDependencies": {
|
|
42
46
|
"@eslint/js": "^9.30.0",
|
|
43
|
-
"@
|
|
44
|
-
"@types/jest": "^30.0.0",
|
|
45
|
-
"@types/node": "^24.0.6",
|
|
47
|
+
"@types/node": "^24.0.7",
|
|
46
48
|
"@typescript-eslint/eslint-plugin": "^8.35.0",
|
|
47
49
|
"@typescript-eslint/parser": "^8.35.0",
|
|
50
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
48
51
|
"eslint": "^9.30.0",
|
|
49
52
|
"eslint-config-prettier": "^10.1.5",
|
|
50
53
|
"eslint-plugin-prettier": "^5.5.1",
|
|
51
54
|
"husky": "^9.1.7",
|
|
52
55
|
"inop": "^0.7.8",
|
|
53
|
-
"jest": "^30.0.3",
|
|
54
56
|
"prettier": "^3.6.2",
|
|
55
57
|
"typescript": "^5.8.3",
|
|
56
|
-
"typescript-eslint": "^8.35.0"
|
|
58
|
+
"typescript-eslint": "^8.35.0",
|
|
59
|
+
"vitest": "^3.2.4"
|
|
57
60
|
},
|
|
58
|
-
"
|
|
59
|
-
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "rm -rf build && inop src build -i __tests__ -i *.tmp.ts && tsc --declaration --emitDeclarationOnly",
|
|
63
|
+
"lint": "eslint src",
|
|
64
|
+
"test": "vitest run",
|
|
65
|
+
"test:coverage": "vitest run --coverage"
|
|
66
|
+
}
|
|
67
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -28,66 +28,82 @@ export interface Options {
|
|
|
28
28
|
timeout?: number;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
export
|
|
31
|
+
export interface WaitRequest {
|
|
32
|
+
target: Int32Array;
|
|
33
|
+
index: number;
|
|
34
|
+
value: number;
|
|
35
|
+
timeout?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type WaitResponse = ReturnType<typeof Atomics.wait>;
|
|
39
|
+
|
|
40
|
+
export function* writeGenerator(
|
|
32
41
|
data: unknown,
|
|
33
42
|
buffer: SharedArrayBuffer,
|
|
34
|
-
{ timeout = 5000 }: Options = {}
|
|
35
|
-
)
|
|
43
|
+
{ timeout = 5000 }: Options = {},
|
|
44
|
+
): Generator<WaitRequest, void, WaitResponse> {
|
|
36
45
|
const serialized = serialize(data);
|
|
37
46
|
const chunkSize = buffer.byteLength - HEADER_SIZE;
|
|
38
47
|
const totalSize = serialized.length;
|
|
39
48
|
const totalChunks = Math.ceil(totalSize / chunkSize);
|
|
40
|
-
|
|
41
49
|
const header = new Int32Array(buffer);
|
|
50
|
+
|
|
42
51
|
header[Handshake.TOTAL_SIZE] = totalSize;
|
|
43
52
|
header[Handshake.TOTAL_CHUNKS] = totalChunks;
|
|
44
|
-
|
|
45
53
|
Atomics.store(header, SEMAPHORE, Semaphore.HANDSHAKE);
|
|
46
54
|
Atomics.notify(header, SEMAPHORE);
|
|
47
55
|
|
|
48
56
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
57
|
+
const handshakeResult: WaitResponse = yield {
|
|
58
|
+
target: header,
|
|
59
|
+
index: SEMAPHORE,
|
|
60
|
+
value: Semaphore.HANDSHAKE,
|
|
61
|
+
timeout,
|
|
62
|
+
};
|
|
63
|
+
if (handshakeResult === "timed-out") {
|
|
53
64
|
throw new Error("Reader handshake timeout");
|
|
54
65
|
}
|
|
55
66
|
|
|
56
67
|
const payload = new Uint8Array(buffer, HEADER_SIZE);
|
|
57
|
-
|
|
58
68
|
for (let i = 0; i < totalChunks; i++) {
|
|
59
69
|
const start = i * chunkSize;
|
|
60
70
|
const end = Math.min(start + chunkSize, totalSize);
|
|
61
71
|
const size = end - start;
|
|
62
|
-
|
|
63
72
|
payload.set(serialized.subarray(start, end), 0);
|
|
64
|
-
|
|
65
73
|
header[Header.CHUNK_INDEX] = i;
|
|
66
74
|
header[Header.CHUNK_OFFSET] = start;
|
|
67
75
|
header[Header.CHUNK_SIZE] = size;
|
|
68
|
-
|
|
69
76
|
Atomics.store(header, SEMAPHORE, Semaphore.PAYLOAD);
|
|
70
77
|
Atomics.notify(header, SEMAPHORE);
|
|
71
78
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
79
|
+
const chunkResult: WaitResponse = yield {
|
|
80
|
+
target: header,
|
|
81
|
+
index: SEMAPHORE,
|
|
82
|
+
value: Semaphore.PAYLOAD,
|
|
83
|
+
timeout,
|
|
84
|
+
};
|
|
85
|
+
if (chunkResult === "timed-out") {
|
|
76
86
|
throw new Error(`Reader timeout on chunk ${i}/${totalChunks - 1}`);
|
|
77
87
|
}
|
|
78
88
|
}
|
|
79
89
|
} finally {
|
|
80
90
|
Atomics.store(header, SEMAPHORE, Semaphore.READY);
|
|
81
91
|
}
|
|
82
|
-
}
|
|
92
|
+
}
|
|
83
93
|
|
|
84
|
-
export
|
|
85
|
-
|
|
86
|
-
|
|
94
|
+
export function* readGenerator(
|
|
95
|
+
buffer: SharedArrayBuffer,
|
|
96
|
+
{ timeout = 5000 }: Options = {},
|
|
97
|
+
): Generator<WaitRequest, unknown, WaitResponse> {
|
|
87
98
|
const header = new Int32Array(buffer);
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
99
|
+
|
|
100
|
+
const handshakeResult: WaitResponse = yield {
|
|
101
|
+
target: header,
|
|
102
|
+
index: SEMAPHORE,
|
|
103
|
+
value: Semaphore.READY,
|
|
104
|
+
timeout,
|
|
105
|
+
};
|
|
106
|
+
if (handshakeResult === "timed-out") {
|
|
91
107
|
throw new Error("Handshake timeout");
|
|
92
108
|
}
|
|
93
109
|
if (header[SEMAPHORE] !== Semaphore.HANDSHAKE) {
|
|
@@ -103,9 +119,13 @@ export const read = (buffer: SharedArrayBuffer,
|
|
|
103
119
|
|
|
104
120
|
const payload = new Uint8Array(buffer, HEADER_SIZE);
|
|
105
121
|
for (let i = 0; i < totalChunks; i++) {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
122
|
+
const chunkResult: WaitResponse = yield {
|
|
123
|
+
target: header,
|
|
124
|
+
index: SEMAPHORE,
|
|
125
|
+
value: Semaphore.READY,
|
|
126
|
+
timeout,
|
|
127
|
+
};
|
|
128
|
+
if (chunkResult === "timed-out") {
|
|
109
129
|
throw new Error(`Writer timeout waiting for chunk ${i}`);
|
|
110
130
|
}
|
|
111
131
|
// @ts-expect-error does not infer number
|
|
@@ -126,5 +146,79 @@ export const read = (buffer: SharedArrayBuffer,
|
|
|
126
146
|
Atomics.store(header, SEMAPHORE, Semaphore.READY);
|
|
127
147
|
Atomics.notify(header, SEMAPHORE);
|
|
128
148
|
}
|
|
129
|
-
return deserialize(data);
|
|
149
|
+
return deserialize(data) as unknown;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export const writeSync = (
|
|
153
|
+
data: unknown,
|
|
154
|
+
buffer: SharedArrayBuffer,
|
|
155
|
+
options?: Options,
|
|
156
|
+
) => {
|
|
157
|
+
const gen = writeGenerator(data, buffer, options);
|
|
158
|
+
let result = gen.next();
|
|
159
|
+
while (!result.done) {
|
|
160
|
+
const waitResult = Atomics.wait(
|
|
161
|
+
result.value.target,
|
|
162
|
+
result.value.index,
|
|
163
|
+
result.value.value,
|
|
164
|
+
result.value.timeout,
|
|
165
|
+
);
|
|
166
|
+
result = gen.next(waitResult);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
export const write = async (
|
|
171
|
+
data: unknown,
|
|
172
|
+
buffer: SharedArrayBuffer,
|
|
173
|
+
options?: Options,
|
|
174
|
+
) => {
|
|
175
|
+
const gen = writeGenerator(data, buffer, options);
|
|
176
|
+
let result = gen.next();
|
|
177
|
+
while (!result.done) {
|
|
178
|
+
const request = result.value;
|
|
179
|
+
const waitResult = await Atomics.waitAsync(
|
|
180
|
+
request.target,
|
|
181
|
+
request.index,
|
|
182
|
+
request.value,
|
|
183
|
+
request.timeout,
|
|
184
|
+
).value;
|
|
185
|
+
result = gen.next(waitResult);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export const readSync = (
|
|
190
|
+
buffer: SharedArrayBuffer,
|
|
191
|
+
options?: Options,
|
|
192
|
+
): unknown => {
|
|
193
|
+
const gen = readGenerator(buffer, options);
|
|
194
|
+
let result = gen.next();
|
|
195
|
+
while (!result.done) {
|
|
196
|
+
const waitResult = Atomics.wait(
|
|
197
|
+
result.value.target,
|
|
198
|
+
result.value.index,
|
|
199
|
+
result.value.value,
|
|
200
|
+
result.value.timeout,
|
|
201
|
+
);
|
|
202
|
+
result = gen.next(waitResult);
|
|
203
|
+
}
|
|
204
|
+
return result.value;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export const read = async (
|
|
208
|
+
buffer: SharedArrayBuffer,
|
|
209
|
+
options?: Options,
|
|
210
|
+
): Promise<unknown> => {
|
|
211
|
+
const gen = readGenerator(buffer, options);
|
|
212
|
+
let result = gen.next();
|
|
213
|
+
while (!result.done) {
|
|
214
|
+
const request = result.value;
|
|
215
|
+
const waitResult = await Atomics.waitAsync(
|
|
216
|
+
request.target,
|
|
217
|
+
request.index,
|
|
218
|
+
request.value,
|
|
219
|
+
request.timeout,
|
|
220
|
+
).value;
|
|
221
|
+
result = gen.next(waitResult);
|
|
222
|
+
}
|
|
223
|
+
return result.value;
|
|
130
224
|
};
|