├── .husky ├── .gitignore └── pre-commit ├── .gitignore ├── test ├── includes │ └── export-42.js └── hoverlord.test.js ├── jest.config.js ├── .prettierrc.js ├── babel.config.json ├── .github ├── dependabot.yml └── workflows │ └── node.js.yml ├── .eslintrc.js ├── LICENSE.md ├── package.json ├── supervisor └── index.js ├── README.md └── index.js /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .eslintcache 3 | -------------------------------------------------------------------------------- /test/includes/export-42.js: -------------------------------------------------------------------------------- 1 | module.exports = 42; 2 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | transform: {} 3 | }; 4 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npm run pre-commit -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "trailingComma": "all", 3 | "tabWidth": 2, 4 | "semi": true, 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /babel.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/env", 5 | { 6 | "useBuiltIns": "usage", 7 | "corejs": "3.6.5" 8 | } 9 | ] 10 | ], 11 | "plugins": ["@babel/plugin-syntax-class-properties"] 12 | } 13 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | time: '04:00' 8 | open-pull-requests-limit: 10 9 | versioning-strategy: increase 10 | labels: 11 | - kind/DEPENDENCIES 12 | - status/CR-NEEDED 13 | 14 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | commonjs: true, 4 | es2021: true, 5 | node: true, 6 | 'jest/globals': true, 7 | }, 8 | extends: 'eslint:recommended', 9 | plugins: ['jest'], 10 | parser: '@babel/eslint-parser', 11 | parserOptions: { 12 | ecmaVersion: 12, 13 | }, 14 | rules: {}, 15 | }; 16 | -------------------------------------------------------------------------------- /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Node.js CI 5 | 6 | on: [pull_request] 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [14.x, 16.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | - run: npm ci 24 | - run: npm run lint 25 | - run: npm test 26 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2020 Alessio Biancalana 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hoverlord", 3 | "version": "0.1.0", 4 | "description": "Actor modeling library and concurrency primitives for NodeJS", 5 | "main": "index.js", 6 | "scripts": { 7 | "lint": "eslint .", 8 | "pre-commit": "lint-staged", 9 | "test": "jest", 10 | "postinstall": "husky install" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/dottorblaster/hoverlord.git" 15 | }, 16 | "keywords": [ 17 | "concurrency", 18 | "actor", 19 | "actor", 20 | "modeling" 21 | ], 22 | "author": "Alessio Biancalana", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/dottorblaster/hoverlord/issues" 26 | }, 27 | "homepage": "https://github.com/dottorblaster/hoverlord#readme", 28 | "devDependencies": { 29 | "@babel/core": "7.22.10", 30 | "@babel/eslint-parser": "7.22.15", 31 | "@babel/plugin-syntax-class-properties": "7.12.13", 32 | "@babel/preset-env": "7.22.10", 33 | "eslint": "8.47.0", 34 | "eslint-plugin-jest": "27.2.3", 35 | "husky": "8.0.3", 36 | "jest": "29.6.2", 37 | "lint-staged": "14.0.0", 38 | "prettier": "3.0.1" 39 | }, 40 | "lint-staged": { 41 | "*.js": [ 42 | "eslint --cache --fix", 43 | "prettier --write" 44 | ], 45 | "*.json": [ 46 | "prettier --write" 47 | ] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /supervisor/index.js: -------------------------------------------------------------------------------- 1 | class Supervisor { 2 | processes = {}; 3 | 4 | remove(name) { 5 | if (this.isNamePresent(name)) { 6 | const { processes } = this; 7 | delete processes[name]; 8 | } 9 | return this.processes; 10 | } 11 | 12 | store(name, newProcess) { 13 | const { processes } = this; 14 | this.processes = { 15 | ...processes, 16 | [name]: newProcess, 17 | }; 18 | } 19 | 20 | isNamePresent(name) { 21 | return Object.prototype.hasOwnProperty.call(this.processes, name); 22 | } 23 | 24 | getProcessByName(name) { 25 | if (this.isNamePresent(name)) { 26 | return this.processes[name]; 27 | } 28 | } 29 | 30 | getProcess(recipient) { 31 | return typeof recipient === 'string' 32 | ? this.getProcessByName(recipient) 33 | : this.getProcessByThreadId(recipient); 34 | } 35 | 36 | getProcessByThreadId(id) { 37 | for (const name in this.processes) { 38 | if (this.processes[name].threadId === id) { 39 | return this.processes[name]; 40 | } 41 | } 42 | } 43 | 44 | send(recipient, payload) { 45 | const process = this.getProcess(recipient); 46 | 47 | if (process) { 48 | process.postMessage(payload); 49 | return true; 50 | } 51 | 52 | return false; 53 | } 54 | 55 | shutdown() { 56 | for (const name in this.processes) { 57 | this.processes[name].terminate(); 58 | } 59 | } 60 | } 61 | 62 | const createSupervisor = () => new Supervisor(); 63 | 64 | module.exports = { createSupervisor }; 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hoverlord 2 | 3 | Actor model library and concurrency primitives for NodeJS. 4 | 5 | ## Usage 6 | 7 | Here's a code snippet, make good use of it. 8 | 9 | ```js 10 | const http = require('http'); 11 | const { spawn, send } = require('hoverlord'); 12 | 13 | spawn(({ receive }) => { 14 | receive((_state, { content }) => { 15 | console.log(`log: ${content}`); 16 | }); 17 | }, 'logger'); 18 | 19 | spawn(({ receive, send }) => { 20 | return receive((state, message) => { 21 | switch (message.content) { 22 | case 'ping': 23 | const newState = state + 1; 24 | send('logger', newState); 25 | return newState; 26 | default: 27 | return state; 28 | } 29 | }, 0); 30 | }, 'stateReducer'); 31 | 32 | http 33 | .createServer((req, res) => { 34 | send('stateReducer', 'ping'); 35 | res.writeHead(200); 36 | res.end(`Current process\n ${process.pid}`); 37 | }) 38 | .listen(4000); 39 | ``` 40 | 41 | ## But wait: what the heck is the actor model anyway? 42 | 43 | [Wikipedia](https://en.wikipedia.org/wiki/Actor_model) summarizes it this way: 44 | 45 | > The actor model in computer science is a mathematical model of concurrent computation that treats actor as the universal primitive of concurrent computation. In response to a message it receives, an actor can: make local decisions, create more actors, send more messages, and determine how to respond to the next message received. Actors may modify their own private state, but can only affect each other indirectly through messaging (removing the need for lock-based synchronization). 46 | 47 | To make it a bit simpler: you've got your "actors", independent software entities that only can communicate through messages, and are declared in the form of pure functions. 48 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const { 2 | Worker, 3 | isMainThread, 4 | parentPort, 5 | threadId, 6 | } = require('worker_threads'); 7 | const crypto = require('crypto'); 8 | 9 | const { createSupervisor } = require('./supervisor'); 10 | 11 | const masterSupervisor = isMainThread ? createSupervisor() : null; 12 | 13 | const isFromWorker = (payload) => Boolean(payload.fromWorker); 14 | 15 | const createFingerprint = () => crypto.randomBytes(64).toString('hex'); 16 | 17 | const createWorkerContent = (job, sharedVarNames) => { 18 | let sharedVarsCode = ''; 19 | const currentFileNameAsString = JSON.stringify(__filename); 20 | if(sharedVarNames.length > 0) { 21 | sharedVarsCode = ` 22 | let {${sharedVarNames.join(",")}} = require('worker_threads').workerData; 23 | `; 24 | } 25 | return ` 26 | ${sharedVarsCode} 27 | (${job.toString()})(require(${currentFileNameAsString})); 28 | `; 29 | } 30 | 31 | const spawn = (job, name, vars = {}) => { 32 | return new Promise((resolve) => { 33 | const workerContent = createWorkerContent(job, Object.keys(vars)); 34 | const actor = new Worker(workerContent, { eval: true, workerData: vars }); 35 | actor.on('message', (payload) => { 36 | if (isFromWorker(payload)) { 37 | const { recipient } = payload; 38 | masterSupervisor.send(recipient, payload); 39 | } 40 | }); 41 | masterSupervisor.store(name, actor); 42 | resolve(actor); 43 | }); 44 | }; 45 | 46 | const receive = (reducer, startState = undefined) => { 47 | let state = startState; 48 | parentPort.on('message', (message) => { 49 | state = reducer(state, message); 50 | }); 51 | }; 52 | 53 | const send = (recipient, content) => { 54 | if (isMainThread) { 55 | masterSupervisor.send(recipient, { content }); 56 | } else { 57 | parentPort.postMessage({ fromWorker: true, recipient, content }); 58 | } 59 | }; 60 | 61 | const reply = (request, response) => { 62 | const { fingerprint: requestFingerprint, sender: requestSender } = request; 63 | const message = { 64 | requestSender, 65 | content: response, 66 | recipient: requestSender, 67 | fingerprint: requestFingerprint, 68 | sender: threadId, 69 | fromWorker: !isMainThread, 70 | }; 71 | 72 | if (isMainThread) { 73 | masterSupervisor.send(message); 74 | } else { 75 | parentPort.postMessage(message); 76 | } 77 | }; 78 | 79 | const call = (recipient, messageContent) => { 80 | return new Promise((resolve) => { 81 | const fingerprint = createFingerprint(); 82 | 83 | const message = { 84 | recipient, 85 | fingerprint, 86 | content: messageContent, 87 | sender: threadId, 88 | fromWorker: !isMainThread, 89 | }; 90 | 91 | if (isMainThread) { 92 | const actor = masterSupervisor.getProcess(recipient); 93 | const callback = (payload) => { 94 | if (payload.fingerprint === fingerprint) { 95 | resolve(payload); 96 | actor.off('message', callback); 97 | } 98 | }; 99 | actor.on('message', callback); 100 | masterSupervisor.send(recipient, message); 101 | } else { 102 | const callback = (payload) => { 103 | if (payload.fingerprint === fingerprint) { 104 | resolve(payload); 105 | parentPort.off('message', callback); 106 | } 107 | }; 108 | parentPort.on('message', callback); 109 | parentPort.postMessage(message); 110 | } 111 | }); 112 | }; 113 | 114 | const shutdown = (supervisor = masterSupervisor) => { 115 | supervisor.shutdown(); 116 | }; 117 | 118 | module.exports = { 119 | spawn, 120 | receive, 121 | send, 122 | call, 123 | reply, 124 | shutdown, 125 | createSupervisor, 126 | masterSupervisor, 127 | }; 128 | -------------------------------------------------------------------------------- /test/hoverlord.test.js: -------------------------------------------------------------------------------- 1 | const { spawn, call, send, shutdown } = require('./../index'); 2 | 3 | const findDuplicates = (arr) => 4 | arr.filter((item, index) => arr.indexOf(item) != index); 5 | 6 | describe('hoverlord', () => { 7 | it('can call from the main process', async () => { 8 | await spawn(({ receive, reply }) => { 9 | return receive((state, message) => { 10 | switch (message.content) { 11 | case 'ping': 12 | return state + 1; 13 | case 'pang': 14 | reply(message, state); 15 | return state; 16 | default: 17 | return state; 18 | } 19 | }, 0); 20 | }, 'demoActor'); 21 | send('demoActor', 'ping'); 22 | send('demoActor', 'ping'); 23 | send('demoActor', 'ping'); 24 | send('demoActor', 'ping'); 25 | 26 | const { content: result } = await call('demoActor', 'pang'); 27 | shutdown(); 28 | expect(result).toBe(4); 29 | }); 30 | 31 | it('can call a process from another process', async () => { 32 | await spawn(({ receive, reply }) => { 33 | return receive( 34 | (state, message) => { 35 | if ( 36 | Object.prototype.hasOwnProperty.call(message.content, 'fakeCount') 37 | ) { 38 | reply(message, state); 39 | return message.content; 40 | } 41 | if (message.content === 'inspect') { 42 | reply(message, state); 43 | } 44 | return state; 45 | }, 46 | [1, 2, 3], 47 | ); 48 | }, 'statefulActor'); 49 | 50 | await spawn(({ receive, reply, call }) => { 51 | return receive((state, message) => { 52 | switch (message.content) { 53 | case 'do_the_call': { 54 | const newState = { fakeCount: 1000 }; 55 | call('statefulActor', newState).then(({ content }) => { 56 | reply(message, ['done', content]); 57 | }); 58 | return null; 59 | } 60 | default: 61 | return state; 62 | } 63 | }); 64 | }, 'caller'); 65 | 66 | const { 67 | content: [callerResponse, remoteState], 68 | } = await call('caller', 'do_the_call'); 69 | 70 | const { content: result, fromWorker } = await call( 71 | 'statefulActor', 72 | 'inspect', 73 | ); 74 | 75 | shutdown(); 76 | 77 | expect(callerResponse).toBe('done'); 78 | expect(remoteState).toEqual([1, 2, 3]); 79 | expect(fromWorker).toBe(true); 80 | expect(result).toEqual({ fakeCount: 1000 }); 81 | }); 82 | 83 | it('should not create duplicate fingerprints', async () => { 84 | await spawn(({ receive, reply }) => { 85 | return receive((_, message) => { 86 | const [term, count] = message.content; 87 | if (term === 'ping') { 88 | reply(message, ['pong', count]); 89 | } 90 | }); 91 | }, 'receiver'); 92 | 93 | let fingerprints = []; 94 | 95 | for (let i = 0; i < 10000; i++) { 96 | const response = await call('receiver', ['ping', i]); 97 | fingerprints.push(response.fingerprint); 98 | expect(response.content).toEqual(['pong', i]); 99 | } 100 | 101 | shutdown(); 102 | 103 | const duplicates = [...new Set(findDuplicates(fingerprints))]; 104 | expect(duplicates).toHaveLength(0); 105 | }); 106 | 107 | it('should be able to include files', async () => { 108 | await spawn(({ receive, reply }) => { 109 | return receive((_, message) => { 110 | const answer = require('./test/includes/export-42'); 111 | const [term] = message.content; 112 | if (term === 'ping') { 113 | reply(message, ['pong', answer]); 114 | } 115 | }); 116 | }, 'receiver'); 117 | 118 | const response = await call('receiver', ['ping']); 119 | 120 | shutdown(); 121 | 122 | expect(response.content).toEqual(['pong', 42]); 123 | }); 124 | 125 | it('can send message to process by threadId', async () => { 126 | const process = await spawn(({ receive, reply }) => { 127 | return receive((state, message) => { 128 | switch (message.content) { 129 | case 'ping': 130 | return state + 1; 131 | case 'pang': 132 | reply(message, state); 133 | return state; 134 | default: 135 | return state; 136 | } 137 | }, 0); 138 | }, 'test'); 139 | 140 | send(process.threadId, 'ping'); 141 | send(process.threadId, 'ping'); 142 | send(process.threadId, 'ping'); 143 | 144 | const { content: result } = await call('test', 'pang'); 145 | 146 | shutdown(); 147 | 148 | expect(result).toBe(3); 149 | }); 150 | 151 | it('should pass the target object to the job', async () => { 152 | const object1 = { 153 | simpleKey1: 'simpleValue1', 154 | }; 155 | const object2 = { 156 | simpleKey2: 'simpleValue2', 157 | }; 158 | 159 | await spawn( 160 | ({ receive, reply }) => { 161 | return receive((_, message) => { 162 | const [term] = message.content; 163 | if (term === 'ping') { 164 | reply(message, ['pong', object1.simpleKey1, object2.simpleKey2]); 165 | } 166 | }); 167 | }, 168 | 'receiver', 169 | { object1, object2 }, 170 | ); 171 | 172 | const response = await call('receiver', ['ping']); 173 | 174 | shutdown(); 175 | 176 | expect(response.content).toEqual(['pong', 'simpleValue1', 'simpleValue2']); 177 | }); 178 | 179 | it('should call process by name or trhead-id', async () => { 180 | const process = await spawn(({ receive, reply }) => { 181 | return receive((_, message) => { 182 | const [term] = message.content; 183 | if (term === 'ping') { 184 | reply(message, ['pong', `I'm Process`]); 185 | } 186 | }); 187 | }, 'processName'); 188 | 189 | const responseByName = await call('processName', ['ping']); 190 | const responseByThreadId = await call(process.threadId, ['ping']); 191 | 192 | shutdown(); 193 | 194 | expect(responseByName.content).toEqual(['pong', `I'm Process`]); 195 | expect(responseByThreadId.content).toEqual(responseByName.content); 196 | }); 197 | }); 198 | --------------------------------------------------------------------------------