shared-memory-image 0.0.0-stage → 1.0.0

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/test/stress.js ADDED
@@ -0,0 +1,215 @@
1
+ // Stress suite for the addon. Usage: node test/stress.js [suite]
2
+ // torn (default): 1 writer + 2 readers, frame integrity under load
3
+ // lifecycle: create/close torture + writes through stale buffers
4
+ // adversarial: hostile args/names/sizes
5
+ // crash: SIGKILL the writer mid-publish, restart it as an opener
6
+ // Child processes switch on STRESS_ROLE (writer|reader).
7
+ 'use strict';
8
+ const { fork } = require('child_process');
9
+
10
+
11
+ const ROLE = process.env.STRESS_ROLE;
12
+ const NAME = 'StressSHM';
13
+ const W = 320, H = 240, CH = 4;
14
+ const FRAME = W * H * CH;
15
+ const MAP = FRAME + 65536;
16
+
17
+ // frame layout: [u32 index lo][u32 index hi][u32 check][hash bytes...]
18
+ function fillFrame(buf, idx) {
19
+ const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
20
+ dv.setUint32(0, idx >>> 0, true);
21
+ dv.setUint32(4, Math.floor(idx / 2 ** 32), true);
22
+ dv.setUint32(8, (0xC0FFEE ^ idx) >>> 0, true);
23
+ for (let i = 12; i < FRAME; i += 4) {
24
+ // hash of (index, position): any lost or corrupted byte breaks it
25
+ let v = (Math.imul(idx, 2654435761) ^ Math.imul(i, 40503) ^ 0x9E3779B9) >>> 0;
26
+ buf[i] = v & 0xFF; buf[i + 1] = (v >>> 8) & 0xFF;
27
+ buf[i + 2] = (v >>> 16) & 0xFF; buf[i + 3] = (v >>> 24) & 0xFF;
28
+ }
29
+ }
30
+ function verifyFrame(buf) {
31
+ const dv = new DataView(buf.buffer, buf.byteOffset, Math.min(buf.byteLength, FRAME));
32
+ const idx = dv.getUint32(0, true) + dv.getUint32(4, true) * 2 ** 32;
33
+ if (((0xC0FFEE ^ idx) >>> 0) !== dv.getUint32(8, true)) return { torn: true, at: 'hdr' };
34
+ const n = Math.min(buf.byteLength, FRAME);
35
+ for (let i = 12; i < n; i += 4) {
36
+ const v = (Math.imul(idx, 2654435761) ^ Math.imul(i, 40503) ^ 0x9E3779B9) >>> 0;
37
+ if (buf[i] !== (v & 0xFF) || buf[i + 1] !== ((v >>> 8) & 0xFF) ||
38
+ buf[i + 2] !== ((v >>> 16) & 0xFF) || buf[i + 3] !== ((v >>> 24) & 0xFF)) {
39
+ return { torn: true, at: 'data@' + i, idx };
40
+ }
41
+ }
42
+ return { torn: false, idx };
43
+ }
44
+
45
+ // ---------- child roles ----------
46
+ if (ROLE === 'writer') {
47
+ const M = require('..');
48
+ const sm = new M.SharedMemory();
49
+ sm.create(NAME, MAP, W, H, CH);
50
+ // sealed path: publishRaw copies the frame inside the seqlock section.
51
+ // STRESS_LEGACY=1 switches to fill + publishFrame, where the payload
52
+ // lands outside the section and readers can catch a torn frame
53
+ const sealed = typeof sm.publishRaw === 'function' && process.env.STRESS_LEGACY !== '1';
54
+ const local = Buffer.allocUnsafe(FRAME);
55
+ const fb = sealed ? null : sm.getFrameBuffer();
56
+ if (!sealed && (!fb || fb.length < FRAME)) { console.error('WRITER: no fb'); process.exit(3); }
57
+ const t0 = Date.now();
58
+ const DUR = +(process.env.STRESS_DUR || 20000);
59
+ let idx = 0;
60
+ while (Date.now() - t0 < DUR) {
61
+ fillFrame(sealed ? local : fb, ++idx);
62
+ if (sealed) sm.publishRaw(local, FRAME); else sm.publishFrame(FRAME);
63
+ if (idx % 500 === 0) sm.setFormat(W, H, CH); // poke the setFormat seqlock path too
64
+ if (process.env.STRESS_YIELD === '1' && idx % 3 === 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1);
65
+ }
66
+ console.log(JSON.stringify({ role: 'writer', frames: idx, sealed }));
67
+ process.exit(0);
68
+ }
69
+ if (ROLE === 'reader') {
70
+ const M = require('..');
71
+ const sm = new M.SharedMemory();
72
+ sm.create(NAME, MAP, W, H, CH); // opens the existing mapping
73
+ const t0 = Date.now();
74
+ const DUR = +(process.env.STRESS_DUR || 20000);
75
+ let read = 0, torn = 0, timeouts = 0, lastErr = null, lastIdx = -1, regress = 0, contended = 0;
76
+ const into = process.env.STRESS_INTO === '1' && typeof sm.readFrameInto === 'function';
77
+ const intoDst = into ? Buffer.allocUnsafe(FRAME) : null;
78
+ while (Date.now() - t0 < DUR) {
79
+ let frame;
80
+ try {
81
+ if (into) {
82
+ const n = sm.readFrameInto(intoDst, 100);
83
+ frame = n === null ? null : intoDst.subarray(0, n);
84
+ } else {
85
+ frame = sm.readFrame(100);
86
+ }
87
+ } catch (e) {
88
+ // by contract the addon throws after MAX_RETRIES instead of
89
+ // returning a torn frame
90
+ if (/conten/i.test(String(e))) { contended++; continue; }
91
+ lastErr = String(e); continue;
92
+ }
93
+ if (frame === null) { timeouts++; continue; }
94
+ read++;
95
+ const r = verifyFrame(frame);
96
+ if (r.torn) { torn++; if (torn < 3) console.error('READER TORN', JSON.stringify(r)); }
97
+ // equal idx is a re-read after a setFormat pulse, that is fine
98
+ else { if (r.idx < lastIdx) regress++; lastIdx = r.idx; }
99
+ }
100
+ console.log(JSON.stringify({ role: 'reader', read, torn, timeouts, contended, regress, lastErr, lastIdx }));
101
+ process.exit(0);
102
+ }
103
+
104
+ // ---------- parent suites ----------
105
+ const suites = {
106
+ // A: 1 writer + 2 readers, integrity under load
107
+ torn(done) {
108
+ const dur = 15000;
109
+ const kids = [];
110
+ const out = [];
111
+ const spawn = (role) => new Promise((res) => {
112
+ const k = fork(__filename, [], { env: { ...process.env, STRESS_ROLE: role, STRESS_DUR: String(dur), STRESS_YIELD: '1' }, stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
113
+ let buf = '';
114
+ k.stdout.on('data', d => buf += d); k.stderr.on('data', d => process.stderr.write('[kid] ' + d));
115
+ k.on('exit', (code) => res({ code, out: buf.trim() }));
116
+ kids.push(k);
117
+ });
118
+ // readers spawn first: create() opens or creates on its own, order is irrelevant
119
+ Promise.all([spawn('reader'), spawn('reader'), spawn('writer')]).then(rs => {
120
+ const ok = rs.every(r => r.code === 0);
121
+ console.log(rs.map(r => r.out.split('\n').pop()).join('\n'));
122
+ const readers = rs.slice(0, 2).map(r => JSON.parse(r.out.split('\n').pop() || '{}'));
123
+ // fail = torn data, idx strictly backwards, or a non-contention error
124
+ const bad = readers.some(r => r.torn > 0 || r.regress > 0 || (r.lastErr && !/conten/i.test(String(r.lastErr)) && r.read > 0));
125
+ console.log(`torn-suite: exit=${ok ? 'ok' : 'FAIL'} integrity=${bad ? 'FAIL' : 'ok'}`);
126
+ done(ok && !bad);
127
+ });
128
+ },
129
+
130
+ // B: create/close torture + stale buffer writes
131
+ lifecycle(done) {
132
+ const M = require('..');
133
+ const sm = new M.SharedMemory();
134
+ const ghosts = []; // buffers grabbed before close, kept alive across recreates
135
+ let crashes = 0;
136
+ try {
137
+ for (let i = 0; i < 2000; i++) {
138
+ sm.create(NAME, MAP, W, H, CH);
139
+ const fb = sm.getFrameBuffer();
140
+ if (!fb) { console.log('lifecycle: getFrameBuffer returned null at iteration ' + i); break; }
141
+ fillFrame(fb, i);
142
+ sm.publishFrame(FRAME);
143
+ const ghost = sm.getFrameBuffer();
144
+ ghosts.push(ghost);
145
+ if (ghosts.length > 50) ghosts.shift(); // keep ~50 around
146
+ sm.close();
147
+ // write through a buffer taken before close: must not fault
148
+ if (ghosts.length) { try { ghosts[0][0] = (ghosts[0][0] + 1) & 0xFF; } catch (e) { crashes++; } }
149
+ if (i % 400 === 0 && global.gc) global.gc();
150
+ }
151
+ sm.close();
152
+ console.log(`lifecycle-suite: 2000 create/publish/close cycles survived, ghosts=${ghosts.length}`);
153
+ done(true);
154
+ } catch (e) {
155
+ console.log('lifecycle-suite: exception: ' + e.message);
156
+ done(false);
157
+ }
158
+ },
159
+
160
+ // C: hostile args/names/sizes
161
+ adversarial(done) {
162
+ const M = require('..');
163
+ const sm = new M.SharedMemory();
164
+ let caught = 0, survived = 0;
165
+ const t = (label, fn) => { try { fn(); survived++; } catch (e) { caught++; if (/TypeError|Error/.test(e.constructor.name)) return; console.log('adversarial: odd exception ' + label + ': ' + e); } };
166
+ for (const sz of [0, -1, 1, 2 ** 53, 2 ** 31, 0.5, NaN, '1e6', null]) t('size=' + sz, () => sm.create('AdvSize', sz));
167
+ for (const nm of ['', 'x'.repeat(300), 'ИмяФайла', 'a\\b\\c', 'Global\\AdvNeedsRights', null, 42]) t('name', () => sm.create(nm, 1 << 20));
168
+ t('noargs', () => sm.create());
169
+ t('wrongtypes', () => sm.create({}, [], true));
170
+ sm.create('AdvOK', 1 << 20, 8, 8, 4);
171
+ for (const g of [undefined, '42', {}, { valueOf: () => 3 }, [], true, NaN, -7, 2 ** 40, Symbol('s'), 10n]) {
172
+ t('setFormat', () => sm.setFormat(g, g, g));
173
+ t('publish', () => sm.publishFrame(g));
174
+ t('readFrame', () => sm.readFrame(g));
175
+ }
176
+ t('huge-frame', () => sm.publishFrame(2 ** 40)); // > capacity: silently ignored
177
+ t('readFrame-no-evt', () => sm.readFrame(1)); // no event pulse -> null on timeout
178
+ sm.close(); t('double-close', () => sm.close());
179
+ t('use-after-close', () => sm.setFormat(1, 1, 1)); // after close methods are silent no-ops
180
+ t('fb-after-close', () => { if (sm.getFrameBuffer() !== null) throw new Error('expected null'); });
181
+ console.log(`adversarial-suite: caught=${caught} survived=${survived}, process alive`);
182
+ done(true); // a crash would be a SIGSEGV, we would never get here
183
+ },
184
+
185
+ // D: SIGKILL the writer mid-publish, restart it as an opener
186
+ crash(done) {
187
+ const M = require('..');
188
+ // keeper holds the mapping alive while the writer is dead
189
+ const keeper = new M.SharedMemory();
190
+ keeper.create(NAME, MAP, W, H, CH);
191
+ const w = fork(__filename, [], { env: { ...process.env, STRESS_ROLE: 'writer', STRESS_DUR: '60000' }, stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
192
+ let wout = ''; w.stdout.on('data', d => wout += d);
193
+ setTimeout(() => {
194
+ try { process.kill(w.pid, 'SIGKILL'); } catch (e) {}
195
+ console.log('crash-suite: writer killed (SIGKILL) mid-publish');
196
+ setTimeout(() => {
197
+ // mapping is alive (keeper holds it): the new writer must attach as an opener
198
+ const w2 = fork(__filename, [], { env: { ...process.env, STRESS_ROLE: 'writer', STRESS_DUR: '3000' }, stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
199
+ let w2out = ''; w2.stdout.on('data', d => w2out += d);
200
+ w2.on('exit', (code) => {
201
+ keeper.close();
202
+ const meta = (() => { try { const k2 = new M.SharedMemory(); k2.create(NAME, MAP); const m = k2.getMetadata(); k2.close(); return m; } catch (e) { return String(e); } })();
203
+ console.log(`crash-suite: restart exit=${code}, meta=${JSON.stringify(meta)}`);
204
+ done(code === 0);
205
+ });
206
+ }, 500);
207
+ }, 1500);
208
+ },
209
+ };
210
+
211
+ const name = process.argv[2] || 'torn';
212
+ (suites[name] || (() => { console.log('unknown suite: ' + name); process.exit(2); }))((ok) => {
213
+ console.log(ok ? 'SUITE OK' : 'SUITE FAIL');
214
+ process.exit(ok ? 0 : 1);
215
+ });
package/test/test.js ADDED
@@ -0,0 +1,70 @@
1
+ /*
2
+ Smoke test for the whole API surface.
3
+ Run: npm test
4
+ */
5
+ const assert = require('assert');
6
+ const { SharedMemory } = require('..');
7
+
8
+ const MAP = 'smi-test';
9
+
10
+ const a = new SharedMemory();
11
+ assert.strictEqual(a.create(MAP, 64 * 1024, 16, 16, 4), 'ok');
12
+
13
+ // zero-copy view: cached per mapping, full data capacity
14
+ const fb = a.getFrameBuffer();
15
+ assert.ok(Buffer.isBuffer(fb), 'getFrameBuffer must return a Buffer');
16
+ assert.strictEqual(fb.length, a.getCapacity());
17
+ assert.strictEqual(a.getFrameBuffer(), fb, 'getFrameBuffer is cached per mapping');
18
+
19
+ // sealed publish -> read back a pattern
20
+ const src = Buffer.from(fb);
21
+ for (let i = 0; i < 1024; i++) src[i] = i & 0xff;
22
+ assert.strictEqual(a.publishRaw(src, 1024), true);
23
+ a.publishFrame(1024); // pulse the event for the reader below
24
+ const frame = a.readFrame(1000);
25
+ assert.ok(Buffer.isBuffer(frame), 'readFrame must return a Buffer');
26
+ assert.strictEqual(frame.length, 1024);
27
+ for (let i = 0; i < 1024; i++) assert.strictEqual(frame[i], i & 0xff, `byte ${i} mismatch`);
28
+ // deep copy: mutating the result must not alias the mapping
29
+ frame[0] = 0xff;
30
+ assert.strictEqual(fb[0], 0, 'readFrame must return a copy, not a view');
31
+
32
+ // zero-alloc read: same bytes as readFrame
33
+ a.publishRaw(src, 1024);
34
+ const dst = Buffer.alloc(1024);
35
+ assert.strictEqual(a.readFrameInto(dst, 1000), 1024);
36
+ for (let i = 0; i < 1024; i++) assert.strictEqual(dst[i], i & 0xff);
37
+
38
+ // second instance attaches to the existing mapping (open, not create)
39
+ const b = new SharedMemory();
40
+ assert.strictEqual(b.create(MAP, 64 * 1024, 16, 16, 4), 'ok');
41
+ const meta = b.getMetadata();
42
+ assert.strictEqual(meta.width, 16);
43
+ assert.strictEqual(meta.height, 16);
44
+ assert.strictEqual(meta.channels, 4);
45
+
46
+ // setFormat bumps the seqlock and wakes readers
47
+ a.setFormat(32, 8, 4);
48
+ assert.strictEqual(b.getMetadata().width, 32);
49
+ assert.strictEqual(b.getMetadata().height, 8);
50
+
51
+ // readFrame with no pending event pulse returns null on timeout
52
+ // (setFormat pulses too, so drain first)
53
+ b.readFrame(50);
54
+ assert.strictEqual(b.readFrame(10), null);
55
+
56
+ // hostile args must not crash the process (V8 ToNumber coercion semantics)
57
+ for (const g of [undefined, null, '42', {}, { valueOf: () => 7 }, [], true, NaN, -5, Symbol('s'), 10n]) {
58
+ try { a.setFormat(g, g, g); } catch (e) { /* thrown is fine, crash is not */ }
59
+ try { a.publishFrame(g); } catch (e) { /* ditto */ }
60
+ try { a.publishRaw(g, g); } catch (e) { /* ditto */ }
61
+ }
62
+
63
+ // close: no-op second close, silent methods, null frame buffer after
64
+ a.close();
65
+ assert.strictEqual(a.close(), true);
66
+ a.setFormat(1, 1, 1); // silent, base is gone
67
+ assert.strictEqual(a.getFrameBuffer(), null);
68
+ b.close();
69
+
70
+ console.log('test: OK');