@nxtedition/shared 0.0.1

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/.editorconfig ADDED
@@ -0,0 +1,12 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 2
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
10
+
11
+ [*.md]
12
+ trim_trailing_whitespace = false
@@ -0,0 +1,3 @@
1
+ #!/bin/sh
2
+ . "$(dirname "$0")/_/husky.sh"
3
+ npx lint-staged
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 nxtedition
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # shared
2
+
3
+ Ring Buffer for NodeJS cross Worker communication.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ npm i @nxtedition/shared
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```js
14
+ // index.js
15
+
16
+ import * as shared from '@nxtedition/shared'
17
+ import tp from 'timers/promise'
18
+
19
+ const writer = shared.alloc(16 * 1024 * 1024)
20
+ const reader = shared.alloc(16 * 1024 * 1024)
21
+
22
+ const worker = new Worker(new URL('worker.js', import.meta.url), {
23
+ workerData: { reader, writer },
24
+ })
25
+
26
+ const writeToWorker = shared.writer(reader)
27
+
28
+ shared.reader(writer, async (buffer) => {
29
+ console.log(`From worker ${buffer}`)
30
+ await tp.setTimeout(1e3) // Backpressure
31
+ })
32
+
33
+ while (true) {
34
+ await writeToParent(Buffer.from('Hello from parent')
35
+ }
36
+ ```
37
+
38
+ ```js
39
+ // worker.js
40
+
41
+ import * as shared from '@nxtedition/shared'
42
+ import tp from 'timers/promise'
43
+
44
+ const writeToParent = shared.writer(workerData.writer)
45
+
46
+ shared.reader(workerData.reader, (buffer) => {
47
+ console.log(`From parent ${buffer}`)
48
+ await tp.setTimeout(1e3) // Backpressure
49
+ })
50
+
51
+ while (true) {
52
+ await writeToParent(Buffer.from('Hello from worker')
53
+ }
54
+ ```
package/index.js ADDED
@@ -0,0 +1,113 @@
1
+ const WRITE_INDEX = 0
2
+ const READ_INDEX = 1
3
+
4
+ export function alloc(size) {
5
+ return {
6
+ sharedState: new SharedArrayBuffer(8),
7
+ sharedBuffer: new SharedArrayBuffer(size),
8
+ }
9
+ }
10
+
11
+ export async function reader({ sharedState, sharedBuffer }, cb) {
12
+ const state = new Int32Array(sharedState)
13
+ const buffer = Buffer.from(sharedBuffer)
14
+
15
+ let readPos = 0
16
+ let writePos = 0
17
+
18
+ while (true) {
19
+ const { async, value } = Atomics.waitAsync(state, WRITE_INDEX, writePos)
20
+ if (async) {
21
+ await value
22
+ }
23
+ writePos = Atomics.load(state, WRITE_INDEX)
24
+
25
+ while (readPos !== writePos) {
26
+ const len = buffer.readInt32LE(readPos)
27
+
28
+ if (len === -1) {
29
+ readPos = 0
30
+ } else {
31
+ const raw = buffer.slice(readPos + 4, readPos + len)
32
+ readPos += len
33
+
34
+ await cb(raw)
35
+ }
36
+
37
+ Atomics.store(state, READ_INDEX, readPos)
38
+ }
39
+
40
+ Atomics.notify(state, READ_INDEX)
41
+ }
42
+ }
43
+
44
+ export function writer({ sharedState, sharedBuffer }) {
45
+ const state = new Int32Array(sharedState)
46
+ const buffer = Buffer.from(sharedBuffer)
47
+ const size = buffer.byteLength
48
+ const queue = []
49
+
50
+ let readPos = 0
51
+ let writePos = 0
52
+ let flushing = null
53
+
54
+ function tryWrite(...raw) {
55
+ readPos = Atomics.load(state, READ_INDEX)
56
+
57
+ const len = raw.reduce((len, buf) => len + buf.byteLength, 4)
58
+
59
+ if (size - writePos < len + 4) {
60
+ if (readPos < len + 4) {
61
+ return false
62
+ }
63
+
64
+ buffer.writeInt32LE(-1, writePos)
65
+ writePos = 0
66
+ } else {
67
+ const available = writePos >= readPos ? size - writePos : readPos - writePos
68
+
69
+ if (available < len + 4) {
70
+ return false
71
+ }
72
+ }
73
+
74
+ buffer.writeInt32LE(len, writePos)
75
+ writePos += 4
76
+
77
+ for (const buf of raw) {
78
+ buffer.set(buf, writePos)
79
+ writePos += buf.byteLength
80
+ }
81
+
82
+ Atomics.store(state, WRITE_INDEX, writePos)
83
+ Atomics.notify(state, WRITE_INDEX)
84
+
85
+ return true
86
+ }
87
+
88
+ async function flush() {
89
+ while (queue.length) {
90
+ while (!tryWrite(queue[0])) {
91
+ const { async, value } = Atomics.waitAsync(state, READ_INDEX, readPos)
92
+ if (async) {
93
+ await value
94
+ }
95
+ }
96
+ queue.shift()
97
+ }
98
+
99
+ flushing = null
100
+ }
101
+
102
+ async function write(...raw) {
103
+ if (!queue.length && tryWrite(...raw)) {
104
+ return
105
+ }
106
+
107
+ queue.push(Buffer.concat(raw))
108
+
109
+ await (flushing ??= flush())
110
+ }
111
+
112
+ return write
113
+ }