@stevvvns/act 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 stevvvns
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,91 @@
1
+ # act
2
+
3
+ To define an actor, put it in its own directory and do something like:
4
+
5
+ **`test/index.js`**
6
+ ```javascript
7
+ import actor from 'act/actor.js';
8
+
9
+ actor({
10
+ hello(name) {
11
+ return `hey, ${name}`;
12
+ }
13
+ });
14
+ ```
15
+
16
+ Then, define a config file for your actor(s):
17
+
18
+ **`config.js`**
19
+ ```javascript
20
+ import { resolve } from 'node:path';
21
+
22
+ const mod = x => resolve('.', x);
23
+ export default {
24
+ defaultTimeout: '10s',
25
+ maxMailbox: 500,
26
+ actors: {
27
+ test: {
28
+ mode: 'fork',
29
+ module: mod('test')
30
+ },
31
+ },
32
+ log: console.log
33
+ };
34
+ ```
35
+
36
+ Finally, to use the forked service:
37
+
38
+ **`entry.js`**
39
+ ```javascript
40
+ import act from '../src/index.js';
41
+ import config from './config.js';
42
+
43
+ const sys = await act(config);
44
+ console.log(await sys.test.hello('jerks').timeout('30s')); // optional timeout override
45
+ sys.shutdown();
46
+ ```
47
+
48
+ ## Remote Actors
49
+
50
+ ***You MUST firewall your remote actors so that only your app may access them, it is not safe to leave the port open!***
51
+
52
+ The actor **`test/index.js`** and **`entry.js`** are exactly the same as above.
53
+
54
+ On the remote server, you need to define a config file for the actors you plan to serve:
55
+
56
+ **`actors.js`**
57
+ ```javascript
58
+ import { resolve } from 'node:path';
59
+
60
+ const mod = x => resolve(process.cwd(), x);
61
+ export default {
62
+ log: console.log,
63
+ listen: '0.0.0.0',
64
+ actors: {
65
+ remoteTest: mod('test'),
66
+ maxMailbox: 500
67
+ }
68
+ }
69
+ ```
70
+
71
+ Next, you need to run `remote-service.js` from this package as a service, with the path to the above config as an argument:
72
+
73
+ `$ node node_modules/act/remote-service.js actors.js`
74
+
75
+ You should do this with something like supervisord to have some fault tolerance.
76
+
77
+ After running the service, modify the `config.js` file for the controlling service to specify the host:
78
+
79
+ **`config.js`**
80
+ ```javascript
81
+ export default {
82
+ defaultTimeout: '10s',
83
+ actors: {
84
+ test: {
85
+ mode: 'remote',
86
+ host: 'localhost' # or wherever, note the dire warning above about firewalling this
87
+ },
88
+ },
89
+ log: console.log
90
+ };
91
+ ```
@@ -0,0 +1,12 @@
1
+ import js from "@eslint/js";
2
+ import globals from "globals";
3
+ import { defineConfig } from "eslint/config";
4
+
5
+ export default defineConfig([
6
+ {
7
+ files: ["src/*.{js,mjs,cjs}"],
8
+ plugins: { js },
9
+ extends: ["js/recommended"],
10
+ languageOptions: { globals: globals.node }
11
+ },
12
+ ]);
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@stevvvns/act",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "main": "index.js",
6
+ "directories": {
7
+ "test": "test"
8
+ },
9
+ "scripts": {
10
+ "lint": "npx eslint src --fix; npx prettier src --single-quote --write"
11
+ },
12
+ "author": "",
13
+ "license": "MIT",
14
+ "description": "",
15
+ "dependencies": {
16
+ "@msgpack/msgpack": "^3.1.3",
17
+ "ms": "^2.1.3"
18
+ },
19
+ "devDependencies": {
20
+ "@eslint/js": "^10.0.1",
21
+ "eslint": "^10.2.0",
22
+ "globals": "^17.5.0"
23
+ }
24
+ }
package/src/actor.js ADDED
@@ -0,0 +1,27 @@
1
+ import { encode, decode } from '@msgpack/msgpack';
2
+
3
+ export default function actor(callbacks) {
4
+ const reply = (msg) => {
5
+ process.send(Object.values(encode(msg)));
6
+ };
7
+
8
+ process.on('message', async (msg) => {
9
+ if (msg === 'exit') {
10
+ process.exit(0);
11
+ }
12
+ const [id, mtd, args] = decode(msg);
13
+ if (!callbacks[mtd]) {
14
+ reply([id, 'error', `no such method ${mtd}`]);
15
+ return;
16
+ }
17
+ try {
18
+ if (Math.random() > 0.8) {
19
+ //throw new Error('crash');
20
+ }
21
+ reply([id, 'ok', await callbacks[mtd](...args)]);
22
+ } catch (ex) {
23
+ reply([id, 'error', ex.toString()]);
24
+ throw ex;
25
+ }
26
+ });
27
+ }
package/src/index.js ADDED
@@ -0,0 +1,294 @@
1
+ import { fork } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { encode, decode } from '@msgpack/msgpack';
4
+ import { createConnection } from 'node:net';
5
+ import toMs from 'ms';
6
+ import { EventEmitter } from 'node:events';
7
+
8
+ export class DurableSocket extends EventEmitter {
9
+ constructor({
10
+ host,
11
+ port,
12
+ log,
13
+ name,
14
+ initialDelay = 100,
15
+ maxDelay = 10000,
16
+ factor = 2,
17
+ downRetries = 20,
18
+ }) {
19
+ super();
20
+ this.host = host;
21
+ this.port = port;
22
+ this.log = log;
23
+ this.name = name;
24
+ this.initialDelay = this.reconnectDelay = initialDelay;
25
+ this.maxDelay = maxDelay;
26
+ this.factor = factor;
27
+ this.downRetries = downRetries;
28
+
29
+ this.connect();
30
+ }
31
+
32
+ connect() {
33
+ if (this.destroyed) {
34
+ return;
35
+ }
36
+
37
+ this.socket = createConnection({
38
+ host: this.host,
39
+ port: this.port,
40
+ });
41
+
42
+ this.socket.on('connect', () => {
43
+ this.retries = 0;
44
+ this.connected = true;
45
+ this.reconnectDelay = this.initialDelay;
46
+ this.log({ evt: 'remote connected', name: this.name });
47
+ this.emit('connect');
48
+ });
49
+
50
+ this.socket.on('data', (data) => {
51
+ this.emit('data', data);
52
+ });
53
+
54
+ this.socket.on('error', (err) => {
55
+ this.log({ evt: 'remote error', name: this.name, err });
56
+ this.emit('error', err);
57
+ });
58
+
59
+ this.socket.on('close', (err) => {
60
+ this.connected = false;
61
+ this.socket = null;
62
+
63
+ this.emit('close', err);
64
+
65
+ if (!this.destroyed) {
66
+ this.scheduleReconnect();
67
+ }
68
+ });
69
+ }
70
+
71
+ write(chunk) {
72
+ if (this.destroyed) {
73
+ throw new Error('socket destroyed');
74
+ }
75
+
76
+ if (this.connected && this.socket?.writable) {
77
+ return this.socket.write(chunk);
78
+ }
79
+
80
+ throw new Error('not connected');
81
+ }
82
+
83
+ destroy() {
84
+ this.destroyed = true;
85
+ if (this.reconnectTimer) {
86
+ clearTimeout(this.reconnectTimer);
87
+ }
88
+
89
+ this.socket?.destroy();
90
+ }
91
+
92
+ scheduleReconnect() {
93
+ if (this.reconnectTimer) {
94
+ return;
95
+ }
96
+ if (++this.retries > this.downRetries) {
97
+ this.emit('down');
98
+ this.log({ evt: 'remote down', name: this.name });
99
+ }
100
+ this.log({ evt: 'remote reconnect', name: this.name });
101
+ this.reconnectTimer = setTimeout(() => {
102
+ this.reconnectTimer = null;
103
+ this.connect();
104
+ }, this.reconnectDelay);
105
+ this.reconnectDelay =
106
+ Math.min(this.reconnectDelay * this.factor, this.maxDelay) +
107
+ (0.8 + Math.random() * 0.4);
108
+ }
109
+ }
110
+
111
+ export default async function act(config) {
112
+ const log = config.log ? config.log : () => {};
113
+ const rv = {};
114
+ const dispatch = {};
115
+ const defaultMaxMailbox = config.maxMailbox ?? 500;
116
+ const defaultPort = config.remotePort ?? 22327;
117
+ const maxMb = {};
118
+ let shuttingDown = false;
119
+ const timeout = (() => {
120
+ if (!config.defaultTimeout) {
121
+ return 1000;
122
+ }
123
+ if (typeof config.defaultTimeout === 'string') {
124
+ return toMs(config.defaultTimeout);
125
+ }
126
+ return config.defaultTimeout;
127
+ })();
128
+ const procs = {};
129
+ const timeouts = {};
130
+
131
+ function shutdown() {
132
+ if (!shuttingDown) {
133
+ log({ evt: 'shutdown' });
134
+ shuttingDown = true;
135
+ }
136
+ for (const [name, inFlight] of Object.entries(dispatch)) {
137
+ if (Object.values(inFlight).length === 0) {
138
+ log({ evt: 'exit', name });
139
+ procs[name].send('exit');
140
+ } else {
141
+ log({ evt: 'drain', name });
142
+ }
143
+ }
144
+ }
145
+ function handleResponse(name, payload) {
146
+ const [id, status, resp] = payload;
147
+ if (timeouts[id]) {
148
+ clearTimeout(timeouts[id]);
149
+ delete timeouts[id];
150
+ }
151
+ log({ evt: 'incoming', name, id, status, resp });
152
+ if (!dispatch[name][id]) {
153
+ log({ evt: 'internal error', name, type: 'received unexpected message' });
154
+ return;
155
+ }
156
+ dispatch[name][id][status === 'ok' ? 'resolve' : 'reject'](resp);
157
+ delete dispatch[name][id];
158
+ if (shuttingDown) {
159
+ shutdown();
160
+ }
161
+ }
162
+
163
+ log({ evt: 'startup', defaultTimeout: timeout });
164
+ for (const [name, settings] of Object.entries(config.actors)) {
165
+ if (name === 'shutdown') {
166
+ throw new Error('"shutdown" is a reserved name');
167
+ }
168
+ if (!['fork', 'remote'].includes(settings.mode)) {
169
+ throw new Error(`${name}: unhandled mode ${settings.mode}`);
170
+ }
171
+ log({ evt: 'register', name, ...settings });
172
+ maxMb[name] = settings.maxMailbox ?? defaultMaxMailbox;
173
+ dispatch[name] = {};
174
+
175
+ function handleRequest({ send, checkConnected }) {
176
+ return new Proxy(
177
+ {},
178
+ {
179
+ get(_, mtd) {
180
+ return (...args) => {
181
+ const id = randomUUID();
182
+ const pr = new Promise((resolve, reject) => {
183
+ if (shuttingDown) {
184
+ return;
185
+ }
186
+ if (Object.keys(dispatch[name]).length >= maxMb[name]) {
187
+ log({ evt: 'full mailbox', name, max: maxMb[name] });
188
+ return reject('mailbox full');
189
+ }
190
+ if (checkConnected && !procs[name].connected) {
191
+ for (const [id, { reject }] of Object.entries(
192
+ dispatch[name],
193
+ )) {
194
+ if (timeouts[id]) {
195
+ clearTimeout(timeouts.id);
196
+ }
197
+ reject('disconnected');
198
+ }
199
+ dispatch[name] = {};
200
+ procs[name] = fork(settings.module);
201
+ procs[name].on('message', (msg) =>
202
+ handleResponse(name, decode(msg)),
203
+ );
204
+ return reject('disconnected');
205
+ }
206
+ dispatch[name][id] = { resolve, reject };
207
+ log({ evt: 'outgoing', name, id, mtd, args });
208
+ send(id, mtd, args);
209
+ });
210
+ const reaper = () => {
211
+ if (dispatch[name][id]) {
212
+ dispatch[name][id].reject('actor timed out');
213
+ }
214
+ };
215
+ timeouts[id] = setTimeout(reaper, timeout);
216
+ pr.timeout = (num) => {
217
+ clearTimeout(timeouts[id]);
218
+ const asMs = typeof num === 'string' ? toMs(num) : num;
219
+ timeouts[id] = setTimeout(reaper, asMs);
220
+ return pr;
221
+ };
222
+ return pr;
223
+ };
224
+ },
225
+ },
226
+ );
227
+ }
228
+
229
+ if (settings.mode === 'fork') {
230
+ procs[name] = fork(settings.module);
231
+ procs[name].on('message', (msg) => handleResponse(name, decode(msg)));
232
+
233
+ rv[name] = handleRequest({
234
+ send(id, mtd, args) {
235
+ procs[name].send(Object.values(encode([id, mtd, args])));
236
+ },
237
+ checkConnected: true,
238
+ });
239
+ continue;
240
+ }
241
+ // TODO could share a socket for same host/port w/ different actors, but meh
242
+ await new Promise((resolve, reject) => {
243
+ const port = settings.port ?? defaultPort;
244
+ const host = settings.host ?? 'localhost';
245
+ const sock = new DurableSocket({ host, port, log, name });
246
+ sock.on('error', (err) => {
247
+ if (!sock.connected) {
248
+ reject(`failed to connect: ${err}`);
249
+ }
250
+ });
251
+ procs[name] = {
252
+ send(msg) {
253
+ if (msg === 'exit') {
254
+ sock.destroy();
255
+ return;
256
+ }
257
+ sock.write(encode(msg));
258
+ },
259
+ };
260
+ sock.on('data', (msg) => {
261
+ const [op, payload] = decode(msg);
262
+ log({ evt: 'incoming', remote: true, name, op, payload });
263
+ if (op === 'ensure') {
264
+ if (payload.status === 'ok') {
265
+ resolve();
266
+ } else {
267
+ reject(`misconfiguration: ${host}:${port} cannot service ${name}`);
268
+ }
269
+ } else if (op === 'call') {
270
+ handleResponse(name, payload);
271
+ } else if (op === 'crash') {
272
+ for (const [id, { reject }] of Object.entries(dispatch[name])) {
273
+ if (timeouts[id]) {
274
+ clearTimeout(timeouts.id);
275
+ }
276
+ reject('disconnected');
277
+ }
278
+ dispatch[payload] = {};
279
+ }
280
+ });
281
+ sock.on('connect', () => {
282
+ procs[name].send(['ensure', name]);
283
+ });
284
+ });
285
+ // TODO move mailbox restriction to remote-service, dedupe with fork proxy
286
+ rv[name] = handleRequest({
287
+ send(id, mtd, args) {
288
+ procs[name].send(['call', [id, name, mtd, args]]);
289
+ },
290
+ });
291
+ }
292
+ rv.shutdown = shutdown;
293
+ return rv;
294
+ }
@@ -0,0 +1,56 @@
1
+ import { createServer } from 'node:net';
2
+ import { resolve } from 'node:path';
3
+ import { fork } from 'node:child_process';
4
+ import { encode, decode } from '@msgpack/msgpack';
5
+
6
+ if (process.argv.length !== 3) {
7
+ console.error(
8
+ 'you must provide a path to a configuration file as an argument',
9
+ );
10
+ process.exit(1);
11
+ }
12
+ const config = (await import(resolve(process.cwd(), process.argv[2]))).default;
13
+ const host = config.listen ?? '127.0.0.1';
14
+ if (!['127.0.0.1', 'localhost'].includes(host)) {
15
+ console.warn(
16
+ 'WARNING: it is dangerous to use this service without firewalling it so that only your application(s) can access it!',
17
+ );
18
+ }
19
+ const log = config.log ? config.log : () => {};
20
+ const actors = {};
21
+ for (const [name, path] of Object.entries(config.actors)) {
22
+ log({ evt: 'register', name, path });
23
+ actors[name] = fork(path);
24
+ }
25
+
26
+ createServer((sock) => {
27
+ sock.on('data', async (msg) => {
28
+ const [op, payload] = decode(msg);
29
+ log({ evt: 'rcv', op, payload });
30
+ if (op === 'ensure') {
31
+ sock.write(
32
+ encode([
33
+ 'ensure',
34
+ { status: actors[payload] ? 'ok' : 'na', name: payload },
35
+ ]),
36
+ );
37
+ if (actors[payload]) {
38
+ actors[payload].on('message', (msg) => {
39
+ sock.write(encode(['call', decode(msg)]));
40
+ });
41
+ }
42
+ }
43
+ if (op === 'call') {
44
+ const [id, name, mtd, args] = payload;
45
+ if (!actors[name].connected) {
46
+ actors[name] = fork(config.actors[name]);
47
+ actors[name].on('message', (msg) => {
48
+ sock.write(encode(['call', decode(msg)]));
49
+ });
50
+ sock.write(encode(['crash', { name }]));
51
+ return;
52
+ }
53
+ actors[name].send(Object.values(encode([id, mtd, args])));
54
+ }
55
+ });
56
+ }).listen(config.port ? parseInt(config.port) : 22327, host);
package/src/t ADDED
@@ -0,0 +1,87 @@
1
+ # remote
2
+ return (...args) => {
3
+ const id = randomUUID();
4
+ const pr = new Promise((resolve, reject) => {
5
+ if (shuttingDown) {
6
+ return;
7
+ }
8
+ if (Object.keys(dispatch[name]).length >= maxMb[name]) {
9
+ log({ evt: 'full mailbox', name, max: maxMb[name] });
10
+ return reject('mailbox full');
11
+ }
12
+ dispatch[name][id] = { resolve, reject };
13
+ log({ evt: 'outgoing', remote: true, name, id, mtd, args });
14
+ try {
15
+ ##
16
+ procs[name].send(['call', [id, name, mtd, args]]);
17
+ ##
18
+ }
19
+ catch (ex) {
20
+ reject(ex);
21
+ }
22
+ });
23
+ const reaper = () => {
24
+ if (dispatch[name][id]) {
25
+ dispatch[name][id].reject('actor timed out');
26
+ }
27
+ };
28
+ timeouts[id] = setTimeout(reaper, timeout);
29
+ pr.timeout = num => {
30
+ clearTimeout(timeouts[id]);
31
+ const asMs = typeof num === 'string' ? toMs(num) : num;
32
+ timeouts[id] = setTimeout(reaper, asMs);
33
+ return pr;
34
+ };
35
+ return pr;
36
+ };
37
+
38
+ # fork
39
+ return (...args) => {
40
+ const id = randomUUID();
41
+ const pr = new Promise((resolve, reject) => {
42
+ if (shuttingDown) {
43
+ return;
44
+ }
45
+ if (Object.keys(dispatch[name]).length >= maxMb[name]) {
46
+ log({ evt: 'full mailbox', name, max: maxMb[name] });
47
+ return reject('mailbox full');
48
+ }
49
+ ### fork only
50
+ if (!procs[name].connected) {
51
+ for (const [id, { reject }] of Object.entries(dispatch[name])) {
52
+ if (timeouts[id]) {
53
+ clearTimeout(timeouts.id);
54
+ }
55
+ reject('disconnected');
56
+ }
57
+ dispatch[name] = {};
58
+ procs[name] = fork(settings.module);
59
+ procs[name].on('message', msg => handleResponse(name, decode(msg)));
60
+ return reject('disconnected');
61
+ }
62
+ ###
63
+ dispatch[name][id] = { resolve, reject };
64
+ log({ evt: 'outgoing', name, id, mtd, args });
65
+ try {
66
+ ##
67
+ procs[name].send(Object.values(encode([id, mtd, args])));
68
+ ##
69
+ }
70
+ catch (ex) {
71
+ reject(ex);
72
+ }
73
+ });
74
+ const reaper = () => {
75
+ if (dispatch[name][id]) {
76
+ dispatch[name][id].reject('actor timed out');
77
+ }
78
+ };
79
+ timeouts[id] = setTimeout(reaper, timeout);
80
+ pr.timeout = num => {
81
+ clearTimeout(timeouts[id]);
82
+ const asMs = typeof num === 'string' ? toMs(num) : num;
83
+ timeouts[id] = setTimeout(reaper, asMs);
84
+ return pr;
85
+ };
86
+ return pr;
87
+ };