@platformatic/itc 2.0.0-alpha.3

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,201 @@
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 [yyyy] [name of copyright owner]
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 ADDED
@@ -0,0 +1,38 @@
1
+ # @platformatic/itc
2
+
3
+ Inter-Thread Communication (ITC) is a library for managing communication between threads in a multi-threaded application.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @platformatic/itc
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ const { MessageChannel } = require('node:worker_threads')
15
+ const { ITC } = require('@platformatic/itc')
16
+ const { port1, port2 } = new MessageChannel()
17
+
18
+
19
+ // thread 1
20
+ const itc1 = new ITC({ port: port1 })
21
+
22
+ itc1.handle('get-users', async (request) => {
23
+ return [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
24
+ })
25
+
26
+ itc1.listen()
27
+
28
+ // thread 2
29
+ const itc2 = new ITC({ port: port2 })
30
+ itc2.listen()
31
+
32
+ const users = await itc2.send('get-users')
33
+ console.log(users)
34
+ ```
35
+
36
+ ## License
37
+
38
+ Apache 2.0
@@ -0,0 +1,3 @@
1
+ 'use strict'
2
+
3
+ module.exports = require('neostandard')({ ts: true })
package/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { EventEmitter } from 'node:events'
2
+ import { MessagePort } from 'node:worker_threads'
3
+
4
+ export interface ITCConstructorOptions {
5
+ port: MessagePort;
6
+ }
7
+
8
+ export class ITC extends EventEmitter {
9
+ constructor (options: ITCConstructorOptions)
10
+
11
+ send (name: string, message: any): Promise<any>
12
+ notify (name: string, message: any): void
13
+ handle (message: string, handler: (data: any) => Promise<any>): void
14
+ listen (): void
15
+ close (): void
16
+ }
17
+
18
+ declare module '@platformatic/itc' {
19
+ export { ITC }
20
+ }
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ 'use strict'
2
+
3
+ const ITC = require('./lib/itc')
4
+
5
+ module.exports = { ITC }
@@ -0,0 +1,38 @@
1
+ import { MessagePort } from 'node:worker_threads'
2
+ import { expectError, expectType } from 'tsd'
3
+ import { ITC, ITCConstructorOptions } from './index'
4
+
5
+ const mockPort = {} as MessagePort
6
+
7
+ const options: ITCConstructorOptions = { port: mockPort }
8
+ expectType<ITCConstructorOptions>(options)
9
+
10
+ const itc = new ITC({ port: mockPort })
11
+ expectType<ITC>(itc)
12
+
13
+ expectType<Promise<any>>(itc.send('testMessage', { key: 'value' }))
14
+ expectType<void>(itc.notify('testMessage', { key: 'value' }))
15
+ expectType<void>(
16
+ itc.handle('testMessage', async (data) => {
17
+ return { key: 'value' }
18
+ })
19
+ )
20
+ expectType<void>(itc.listen())
21
+ expectType<void>(itc.close())
22
+
23
+ expectError(itc.send(123, { key: 'value' })) // send name must be a string
24
+ expectError(itc.notify(123, { key: 'value' })) // send name must be a string
25
+ expectError(
26
+ itc.handle(123, async (data) => {
27
+ return { key: 'value' }
28
+ })
29
+ ) // handle message must be a string
30
+ expectError(
31
+ itc.handle('testMessage', (data) => {
32
+ return 'string'
33
+ })
34
+ ) // handler must return a Promise
35
+
36
+ itc.on('unhandledError', (error: Error) => {
37
+ expectType<Error>(error)
38
+ })
package/lib/errors.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict'
2
+
3
+ const createError = require('@fastify/error')
4
+
5
+ const ERROR_PREFIX = 'PLT_ITC'
6
+
7
+ module.exports = {
8
+ HandlerFailed: createError(
9
+ `${ERROR_PREFIX}_HANDLER_FAILED`,
10
+ 'Handler failed with error: %s'
11
+ ),
12
+ HandlerNotFound: createError(
13
+ `${ERROR_PREFIX}_HANDLER_NOT_FOUND`,
14
+ 'Handler not found for request: "%s"'
15
+ ),
16
+ PortAlreadyListening: createError(
17
+ `${ERROR_PREFIX}_ALREADY_LISTENING`,
18
+ 'ITC is already listening'
19
+ ),
20
+ SendBeforeListen: createError(
21
+ `${ERROR_PREFIX}_SEND_BEFORE_LISTEN`,
22
+ 'ITC cannot send requests before listening'
23
+ ),
24
+ InvalidRequestVersion: createError(
25
+ `${ERROR_PREFIX}_INVALID_REQUEST_VERSION`,
26
+ 'Invalid ITC request version: "%s"'
27
+ ),
28
+ InvalidResponseVersion: createError(
29
+ `${ERROR_PREFIX}_INVALID_RESPONSE_VERSION`,
30
+ 'Invalid ITC response version: "%s"'
31
+ ),
32
+ MissingRequestName: createError(
33
+ `${ERROR_PREFIX}_MISSING_REQUEST_NAME`,
34
+ 'ITC request name is missing'
35
+ ),
36
+ MissingResponseName: createError(
37
+ `${ERROR_PREFIX}_MISSING_RESPONSE_NAME`,
38
+ 'ITC response name is missing'
39
+ ),
40
+ MissingRequestReqId: createError(
41
+ `${ERROR_PREFIX}_MISSING_REQUEST_REQ_ID`,
42
+ 'ITC request reqId is missing'
43
+ ),
44
+ MissingResponseReqId: createError(
45
+ `${ERROR_PREFIX}_MISSING_RESPONSE_REQ_ID`,
46
+ 'ITC response reqId is missing'
47
+ ),
48
+ RequestNameIsNotString: createError(
49
+ `${ERROR_PREFIX}_REQUEST_NAME_IS_NOT_STRING`,
50
+ 'ITC request name is not a string: "%s"'
51
+ ),
52
+ MessagePortClosed: createError(
53
+ `${ERROR_PREFIX}_MESSAGE_PORT_CLOSED`,
54
+ 'ITC MessagePort is closed'
55
+ ),
56
+ }
package/lib/itc.js ADDED
@@ -0,0 +1,245 @@
1
+ 'use strict'
2
+
3
+ const { randomUUID } = require('node:crypto')
4
+ const { EventEmitter, once } = require('node:events')
5
+ const errors = require('./errors.js')
6
+
7
+ const PLT_ITC_REQUEST_TYPE = 'PLT_ITC_REQUEST'
8
+ const PLT_ITC_RESPONSE_TYPE = 'PLT_ITC_RESPONSE'
9
+ const PLT_ITC_NOTIFICATION_TYPE = 'PLT_ITC_NOTIFICATION'
10
+ const PLT_ITC_UNHANDLED_ERROR_TYPE = 'PLT_ITC_UNHANDLED_ERROR'
11
+ const PLT_ITC_VERSION = '1.0.0'
12
+
13
+ class ITC extends EventEmitter {
14
+ #requestEmitter
15
+ #handlers
16
+ #listening
17
+ #handling
18
+ #closePromise
19
+ #closeAfterCurrentRequest
20
+
21
+ constructor ({ port }) {
22
+ super()
23
+
24
+ this.port = port
25
+ this.#requestEmitter = new EventEmitter()
26
+ this.#handlers = new Map()
27
+ this.#listening = false
28
+ this.#handling = false
29
+ this.#closeAfterCurrentRequest = false
30
+
31
+ // Make sure the emitter handle a lot of listeners at once before raising a warning
32
+ this.#requestEmitter.setMaxListeners(1e3)
33
+ }
34
+
35
+ async send (name, message) {
36
+ if (!this.#listening) {
37
+ throw new errors.SendBeforeListen()
38
+ }
39
+
40
+ const request = this.#generateRequest(name, message)
41
+ this.port.postMessage(request)
42
+
43
+ const responsePromise = once(this.#requestEmitter, request.reqId).then(([response]) => response)
44
+
45
+ const { error, data } = await Promise.race([responsePromise, this.#closePromise])
46
+
47
+ if (error !== null) throw error
48
+ return data
49
+ }
50
+
51
+ async notify (name, message) {
52
+ this.port.postMessage(this.#generateNotification(name, message))
53
+ }
54
+
55
+ handle (message, handler) {
56
+ this.#handlers.set(message, handler)
57
+ }
58
+
59
+ listen () {
60
+ if (this.#listening) {
61
+ throw new errors.PortAlreadyListening()
62
+ }
63
+ this.#listening = true
64
+
65
+ this.port.on('message', message => {
66
+ const messageType = message.type
67
+ if (messageType === PLT_ITC_REQUEST_TYPE) {
68
+ this.#handleRequest(message)
69
+ return
70
+ }
71
+ if (messageType === PLT_ITC_RESPONSE_TYPE) {
72
+ this.#handleResponse(message)
73
+ return
74
+ }
75
+ if (messageType === PLT_ITC_NOTIFICATION_TYPE) {
76
+ this.emit(message.name, message.data)
77
+ }
78
+ if (messageType === PLT_ITC_UNHANDLED_ERROR_TYPE) {
79
+ this.emit('unhandledError', message.error)
80
+ }
81
+ })
82
+
83
+ this.#closePromise = once(this.port, 'close').then(() => {
84
+ this.#listening = false
85
+ const error = new errors.MessagePortClosed()
86
+ return { error, data: null }
87
+ })
88
+ }
89
+
90
+ close () {
91
+ if (this.#handling) {
92
+ this.#closeAfterCurrentRequest = true
93
+ return
94
+ }
95
+
96
+ this.port.close()
97
+ }
98
+
99
+ async #handleRequest (raw) {
100
+ let request = null
101
+ let handler = null
102
+ let response = null
103
+
104
+ this.#handling = true
105
+
106
+ try {
107
+ request = this.#parseRequest(raw)
108
+ handler = this.#handlers.get(request.name)
109
+
110
+ if (handler === undefined) {
111
+ throw new errors.HandlerNotFound(request.name)
112
+ }
113
+
114
+ const result = await handler(request.data)
115
+ response = this.#generateResponse(request, null, result)
116
+ } catch (error) {
117
+ if (!request) {
118
+ response = this.#generateUnhandledErrorResponse(error)
119
+ } else if (!handler) {
120
+ response = this.#generateResponse(request, error, null)
121
+ } else {
122
+ const failedError = new errors.HandlerFailed(error.message)
123
+ failedError.handlerError = error
124
+ // This is needed as the code might be lost when sending the message over the port
125
+ failedError.handlerErrorCode = error.code
126
+
127
+ response = this.#generateResponse(request, failedError, null)
128
+ }
129
+ } finally {
130
+ this.#handling = false
131
+ }
132
+
133
+ this.port.postMessage(response)
134
+
135
+ if (this.#closeAfterCurrentRequest) {
136
+ this.close()
137
+ }
138
+ }
139
+
140
+ #parseRequest (request) {
141
+ if (request.reqId === undefined) {
142
+ throw new errors.MissingRequestReqId()
143
+ }
144
+ if (request.version !== PLT_ITC_VERSION) {
145
+ throw new errors.InvalidRequestVersion(request.version)
146
+ }
147
+ if (request.name === undefined) {
148
+ throw new errors.MissingRequestName()
149
+ }
150
+ return request
151
+ }
152
+
153
+ #handleResponse (response) {
154
+ try {
155
+ response = this.#parseResponse(response)
156
+ } catch (error) {
157
+ response = this.#generateUnhandledErrorResponse(error)
158
+ this.port.postMessage(response)
159
+ return
160
+ }
161
+
162
+ const reqId = response.reqId
163
+ this.#requestEmitter.emit(reqId, response)
164
+ }
165
+
166
+ #parseResponse (response) {
167
+ if (response.reqId === undefined) {
168
+ throw new errors.MissingResponseReqId()
169
+ }
170
+ if (response.version !== PLT_ITC_VERSION) {
171
+ throw new errors.InvalidResponseVersion(response.version)
172
+ }
173
+ if (response.name === undefined) {
174
+ throw new errors.MissingResponseName()
175
+ }
176
+ return response
177
+ }
178
+
179
+ #generateRequest (name, data) {
180
+ if (typeof name !== 'string') {
181
+ throw new errors.RequestNameIsNotString(name.toString())
182
+ }
183
+
184
+ if (typeof data === 'object') {
185
+ data = this.#sanitize(data)
186
+ }
187
+
188
+ return {
189
+ type: PLT_ITC_REQUEST_TYPE,
190
+ version: PLT_ITC_VERSION,
191
+ reqId: randomUUID(),
192
+ name,
193
+ data,
194
+ }
195
+ }
196
+
197
+ #generateResponse (request, error, data) {
198
+ return {
199
+ type: PLT_ITC_RESPONSE_TYPE,
200
+ version: PLT_ITC_VERSION,
201
+ reqId: request.reqId,
202
+ name: request.name,
203
+ error,
204
+ data,
205
+ }
206
+ }
207
+
208
+ #generateNotification (name, data) {
209
+ return {
210
+ type: PLT_ITC_NOTIFICATION_TYPE,
211
+ version: PLT_ITC_VERSION,
212
+ name,
213
+ data,
214
+ }
215
+ }
216
+
217
+ #generateUnhandledErrorResponse (error) {
218
+ return {
219
+ type: PLT_ITC_UNHANDLED_ERROR_TYPE,
220
+ version: PLT_ITC_VERSION,
221
+ error,
222
+ data: null,
223
+ }
224
+ }
225
+
226
+ #sanitize (data) {
227
+ const sanitizedObject = {}
228
+ for (const key in data) {
229
+ const value = data[key]
230
+ const type = typeof value
231
+
232
+ if (type === 'object') {
233
+ sanitizedObject[key] = this.#sanitize(value)
234
+ continue
235
+ }
236
+
237
+ if (type !== 'function' && type !== 'symbol') {
238
+ sanitizedObject[key] = value
239
+ }
240
+ }
241
+ return sanitizedObject
242
+ }
243
+ }
244
+
245
+ module.exports = ITC
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@platformatic/itc",
3
+ "version": "2.0.0-alpha.3",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "author": "Matteo Collina <hello@matteocollina.com>",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/platformatic/platformatic.git"
10
+ },
11
+ "license": "Apache-2.0",
12
+ "bugs": {
13
+ "url": "https://github.com/platformatic/platformatic/issues"
14
+ },
15
+ "homepage": "https://github.com/platformatic/platformatic#readme",
16
+ "devDependencies": {
17
+ "@types/node": "^20.14.11",
18
+ "borp": "^0.17.0",
19
+ "eslint": "9",
20
+ "neostandard": "^0.11.1",
21
+ "tsd": "^0.31.0",
22
+ "typescript": "^5.5.4"
23
+ },
24
+ "dependencies": {
25
+ "@fastify/error": "^3.4.1"
26
+ },
27
+ "scripts": {
28
+ "test": "npm run lint && borp --timeout=180000 --concurrency=1 --coverage && tsd",
29
+ "lint": "eslint"
30
+ }
31
+ }
package/test/helper.js ADDED
@@ -0,0 +1,31 @@
1
+ 'use strict'
2
+
3
+ const { randomUUID } = require('node:crypto')
4
+
5
+ function generateItcRequest (request) {
6
+ return {
7
+ type: 'PLT_ITC_REQUEST',
8
+ reqId: randomUUID(),
9
+ version: '1.0.0',
10
+ name: 'test-command',
11
+ data: { test: 'test-req-message' },
12
+ ...request,
13
+ }
14
+ }
15
+
16
+ function generateItcResponse (response) {
17
+ return {
18
+ type: 'PLT_ITC_RESPONSE',
19
+ reqId: randomUUID(),
20
+ version: '1.0.0',
21
+ name: 'test-command',
22
+ error: null,
23
+ data: { test: 'test-req-message' },
24
+ ...response,
25
+ }
26
+ }
27
+
28
+ module.exports = {
29
+ generateItcRequest,
30
+ generateItcResponse,
31
+ }
@@ -0,0 +1,436 @@
1
+ 'use strict'
2
+
3
+ const assert = require('node:assert/strict')
4
+ const { once } = require('node:events')
5
+ const { test } = require('node:test')
6
+ const { setTimeout: sleep } = require('node:timers/promises')
7
+ const { MessageChannel } = require('node:worker_threads')
8
+ const { ITC } = require('../index.js')
9
+ const { generateItcRequest, generateItcResponse } = require('./helper.js')
10
+
11
+ test('should send a request between threads', async t => {
12
+ const { port1, port2 } = new MessageChannel()
13
+
14
+ const itc1 = new ITC({ port: port1 })
15
+ const itc2 = new ITC({ port: port2 })
16
+
17
+ const requestName = 'test-command'
18
+ const testRequest = { test: 'test-req-message' }
19
+ const testResponse = { test: 'test-res-message' }
20
+
21
+ const requests = []
22
+ itc2.handle(requestName, async request => {
23
+ requests.push(request)
24
+ return testResponse
25
+ })
26
+
27
+ itc1.listen()
28
+ itc2.listen()
29
+
30
+ t.after(() => itc1.close())
31
+ t.after(() => itc2.close())
32
+
33
+ const response = await itc1.send(requestName, testRequest)
34
+ assert.deepStrictEqual(response, testResponse)
35
+ assert.deepStrictEqual(requests, [testRequest])
36
+ })
37
+
38
+ test('should support close while replying to a message', async t => {
39
+ const { port1, port2 } = new MessageChannel()
40
+
41
+ const itc1 = new ITC({ port: port1 })
42
+ const itc2 = new ITC({ port: port2 })
43
+
44
+ const requestName = 'test-command'
45
+ const testRequest = { test: 'test-req-message' }
46
+ const testResponse = { test: 'test-res-message' }
47
+
48
+ const requests = []
49
+ itc2.handle(requestName, async request => {
50
+ requests.push(request)
51
+ itc2.close()
52
+ return testResponse
53
+ })
54
+
55
+ itc1.listen()
56
+ itc2.listen()
57
+
58
+ t.after(() => itc1.close())
59
+ t.after(() => itc2.close())
60
+
61
+ const response = await itc1.send(requestName, testRequest)
62
+ assert.deepStrictEqual(response, testResponse)
63
+ assert.deepStrictEqual(requests, [testRequest])
64
+ })
65
+
66
+ test('should throw an error if send req before listen', async t => {
67
+ const { port1 } = new MessageChannel()
68
+
69
+ const itc = new ITC({ port: port1 })
70
+ t.after(() => itc.close())
71
+
72
+ try {
73
+ await itc.send('test', 'test-request')
74
+ assert.fail('Expected an error to be thrown')
75
+ } catch (error) {
76
+ assert.strictEqual(error.code, 'PLT_ITC_SEND_BEFORE_LISTEN')
77
+ assert.strictEqual(error.message, 'ITC cannot send requests before listening')
78
+ }
79
+ })
80
+
81
+ test('should throw an error if request name is not a string', async t => {
82
+ const { port1 } = new MessageChannel()
83
+
84
+ const itc = new ITC({ port: port1 })
85
+ t.after(() => itc.close())
86
+
87
+ itc.listen()
88
+
89
+ try {
90
+ await itc.send(true, 'test-request')
91
+ assert.fail('Expected an error to be thrown')
92
+ } catch (error) {
93
+ assert.strictEqual(error.code, 'PLT_ITC_REQUEST_NAME_IS_NOT_STRING')
94
+ assert.strictEqual(error.message, 'ITC request name is not a string: "true"')
95
+ }
96
+ })
97
+
98
+ test('should send a notification between threads', async t => {
99
+ const { port1, port2 } = new MessageChannel()
100
+
101
+ const itc1 = new ITC({ port: port1 })
102
+ const itc2 = new ITC({ port: port2 })
103
+
104
+ const notificationName = 'notification'
105
+ const testNotification = { test: 'test-notification' }
106
+
107
+ t.after(() => itc2.close())
108
+ await itc2.listen()
109
+
110
+ await itc1.notify(notificationName, testNotification)
111
+ const [receivedNotification] = await once(itc2, notificationName)
112
+ assert.deepStrictEqual(testNotification, receivedNotification)
113
+ })
114
+
115
+ test('should throw if call listen twice', async t => {
116
+ const { port1 } = new MessageChannel()
117
+
118
+ const itc = new ITC({ port: port1 })
119
+ t.after(() => itc.close())
120
+
121
+ itc.listen()
122
+
123
+ try {
124
+ itc.listen()
125
+ assert.fail('Expected an error to be thrown')
126
+ } catch (error) {
127
+ assert.strictEqual(error.code, 'PLT_ITC_ALREADY_LISTENING')
128
+ assert.strictEqual(error.message, 'ITC is already listening')
129
+ }
130
+ })
131
+
132
+ test('should throw an error if handler fails', async t => {
133
+ const { port1, port2 } = new MessageChannel()
134
+
135
+ const itc1 = new ITC({ port: port1 })
136
+ const itc2 = new ITC({ port: port2 })
137
+
138
+ const requestName = 'test-command'
139
+
140
+ itc2.handle(requestName, async () => {
141
+ throw new Error('test-error')
142
+ })
143
+
144
+ itc1.listen()
145
+ itc2.listen()
146
+
147
+ t.after(() => itc1.close())
148
+ t.after(() => itc2.close())
149
+
150
+ try {
151
+ await itc1.send(requestName, 'test-request')
152
+ assert.fail('Expected an error to be thrown')
153
+ } catch (error) {
154
+ assert.strictEqual(error.code, 'PLT_ITC_HANDLER_FAILED')
155
+ assert.strictEqual(error.message, 'Handler failed with error: test-error')
156
+ assert.strictEqual(error.handlerError.message, 'test-error')
157
+ }
158
+ })
159
+
160
+ test('should throw if handler is not found', async t => {
161
+ const { port1, port2 } = new MessageChannel()
162
+
163
+ const itc1 = new ITC({ port: port1 })
164
+ const itc2 = new ITC({ port: port2 })
165
+
166
+ const requestName = 'test-command'
167
+
168
+ itc1.listen()
169
+ itc2.listen()
170
+
171
+ t.after(() => itc1.close())
172
+ t.after(() => itc2.close())
173
+
174
+ try {
175
+ await itc1.send(requestName, 'test-request')
176
+ assert.fail('Expected an error to be thrown')
177
+ } catch (error) {
178
+ assert.strictEqual(error.code, 'PLT_ITC_HANDLER_NOT_FOUND')
179
+ assert.strictEqual(error.message, 'Handler not found for request: "test-command"')
180
+ }
181
+ })
182
+
183
+ test('should skip non-platformatic message', async t => {
184
+ const { port1, port2 } = new MessageChannel()
185
+
186
+ const itc1 = new ITC({ port: port1 })
187
+ const itc2 = new ITC({ port: port2 })
188
+
189
+ const requests = []
190
+ itc1.handle('test', async request => {
191
+ requests.push(request)
192
+ })
193
+
194
+ itc1.listen()
195
+ itc2.listen()
196
+
197
+ t.after(() => itc1.close())
198
+ t.after(() => itc2.close())
199
+
200
+ port2.postMessage({ type: 'test' })
201
+ port2.postMessage({ type: 'platformatic' })
202
+ port2.postMessage({ type: 'test' })
203
+
204
+ await itc2.send('test', 'test-message')
205
+
206
+ assert.deepStrictEqual(requests, ['test-message'])
207
+ })
208
+
209
+ test('should emit unhandledError if request version is wrong', (t, done) => {
210
+ const { port1, port2 } = new MessageChannel()
211
+
212
+ const itc1 = new ITC({ port: port1 })
213
+ const itc2 = new ITC({ port: port2 })
214
+
215
+ t.after(() => itc1.close())
216
+ t.after(() => itc2.close())
217
+
218
+ itc1.listen()
219
+ itc2.listen()
220
+
221
+ itc2.on('unhandledError', error => {
222
+ assert.strictEqual(error.code, 'PLT_ITC_INVALID_REQUEST_VERSION')
223
+ assert.strictEqual(error.message, 'Invalid ITC request version: "0.0.0"')
224
+ done()
225
+ })
226
+
227
+ const itcRequest = generateItcRequest({ version: '0.0.0' })
228
+ port2.postMessage(itcRequest)
229
+ })
230
+
231
+ test('should emit unhandledError if request reqId is missing', (t, done) => {
232
+ const { port1, port2 } = new MessageChannel()
233
+
234
+ const itc1 = new ITC({ port: port1 })
235
+ const itc2 = new ITC({ port: port2 })
236
+
237
+ t.after(() => itc1.close())
238
+ t.after(() => itc2.close())
239
+
240
+ itc1.listen()
241
+ itc2.listen()
242
+
243
+ itc2.on('unhandledError', error => {
244
+ assert.strictEqual(error.code, 'PLT_ITC_MISSING_REQUEST_REQ_ID')
245
+ assert.strictEqual(error.message, 'ITC request reqId is missing')
246
+ done()
247
+ })
248
+
249
+ const itcRequest = generateItcRequest()
250
+ delete itcRequest.reqId
251
+
252
+ port2.postMessage(itcRequest)
253
+ })
254
+
255
+ test('should emit unhandledError if request name is missing', (t, done) => {
256
+ const { port1, port2 } = new MessageChannel()
257
+
258
+ const itc1 = new ITC({ port: port1 })
259
+ const itc2 = new ITC({ port: port2 })
260
+
261
+ t.after(() => itc1.close())
262
+ t.after(() => itc2.close())
263
+
264
+ itc1.listen()
265
+ itc2.listen()
266
+
267
+ itc2.on('unhandledError', error => {
268
+ assert.strictEqual(error.code, 'PLT_ITC_MISSING_REQUEST_NAME')
269
+ assert.strictEqual(error.message, 'ITC request name is missing')
270
+ done()
271
+ })
272
+
273
+ const itcRequest = generateItcRequest()
274
+ delete itcRequest.name
275
+
276
+ port2.postMessage(itcRequest)
277
+ })
278
+
279
+ test('should emit unhandledError if response version is wrong', (t, done) => {
280
+ const { port1, port2 } = new MessageChannel()
281
+
282
+ const itc1 = new ITC({ port: port1 })
283
+ const itc2 = new ITC({ port: port2 })
284
+
285
+ t.after(() => itc1.close())
286
+ t.after(() => itc2.close())
287
+
288
+ itc1.listen()
289
+ itc2.listen()
290
+
291
+ itc2.on('unhandledError', error => {
292
+ assert.strictEqual(error.code, 'PLT_ITC_INVALID_RESPONSE_VERSION')
293
+ assert.strictEqual(error.message, 'Invalid ITC response version: "0.0.0"')
294
+ done()
295
+ })
296
+
297
+ const itcResponse = generateItcResponse({ version: '0.0.0' })
298
+ port2.postMessage(itcResponse)
299
+ })
300
+
301
+ test('should emit unhandledError if response reqId is missing', (t, done) => {
302
+ const { port1, port2 } = new MessageChannel()
303
+
304
+ const itc1 = new ITC({ port: port1 })
305
+ const itc2 = new ITC({ port: port2 })
306
+
307
+ t.after(() => itc1.close())
308
+ t.after(() => itc2.close())
309
+
310
+ itc1.listen()
311
+ itc2.listen()
312
+
313
+ itc2.on('unhandledError', error => {
314
+ assert.strictEqual(error.code, 'PLT_ITC_MISSING_RESPONSE_REQ_ID')
315
+ assert.strictEqual(error.message, 'ITC response reqId is missing')
316
+ done()
317
+ })
318
+
319
+ const itcResponse = generateItcResponse()
320
+ delete itcResponse.reqId
321
+
322
+ port2.postMessage(itcResponse)
323
+ })
324
+
325
+ test('should emit unhandledError if response name is missing', (t, done) => {
326
+ const { port1, port2 } = new MessageChannel()
327
+
328
+ const itc1 = new ITC({ port: port1 })
329
+ const itc2 = new ITC({ port: port2 })
330
+
331
+ t.after(() => itc1.close())
332
+ t.after(() => itc2.close())
333
+
334
+ itc1.listen()
335
+ itc2.listen()
336
+
337
+ itc2.on('unhandledError', error => {
338
+ assert.strictEqual(error.code, 'PLT_ITC_MISSING_RESPONSE_NAME')
339
+ assert.strictEqual(error.message, 'ITC response name is missing')
340
+ done()
341
+ })
342
+
343
+ const itcResponse = generateItcResponse()
344
+ delete itcResponse.name
345
+
346
+ port2.postMessage(itcResponse)
347
+ })
348
+
349
+ test('should sanitize a request before sending', async t => {
350
+ const { port1, port2 } = new MessageChannel()
351
+
352
+ const itc1 = new ITC({ port: port1 })
353
+ const itc2 = new ITC({ port: port2 })
354
+
355
+ const requestName = 'test-command'
356
+ const testRequest = {
357
+ test: 'test-req-message',
358
+ foo: () => {},
359
+ bar: Symbol('test'),
360
+ nested: {
361
+ test: 'test-req-message',
362
+ foo: () => {},
363
+ bar: Symbol('test'),
364
+ },
365
+ }
366
+ const testResponse = { test: 'test-res-message' }
367
+
368
+ const requests = []
369
+ itc2.handle(requestName, async request => {
370
+ requests.push(request)
371
+ return testResponse
372
+ })
373
+
374
+ itc1.listen()
375
+ itc2.listen()
376
+
377
+ t.after(() => itc1.close())
378
+ t.after(() => itc2.close())
379
+
380
+ const response = await itc1.send(requestName, testRequest)
381
+ assert.deepStrictEqual(response, testResponse)
382
+ assert.deepStrictEqual(requests, [
383
+ {
384
+ test: 'test-req-message',
385
+ nested: { test: 'test-req-message' },
386
+ },
387
+ ])
388
+ })
389
+
390
+ test('should throw if receiver ITC port was closed', async t => {
391
+ const { port1, port2 } = new MessageChannel()
392
+
393
+ const itc1 = new ITC({ port: port1 })
394
+ const itc2 = new ITC({ port: port2 })
395
+
396
+ const requestName = 'test-command'
397
+ const testRequest = { test: 'test-req-message' }
398
+
399
+ itc2.handle(requestName, async () => {
400
+ await sleep(10000)
401
+ assert.fail('Handler should not be called')
402
+ })
403
+
404
+ itc1.listen()
405
+ itc2.listen()
406
+
407
+ t.after(() => itc1.close())
408
+ t.after(() => itc2.close())
409
+
410
+ port2.close()
411
+
412
+ try {
413
+ await itc1.send(requestName, testRequest)
414
+ assert.fail('Expected an error to be thrown')
415
+ } catch (error) {
416
+ assert.strictEqual(error.code, 'PLT_ITC_MESSAGE_PORT_CLOSED')
417
+ assert.strictEqual(error.message, 'ITC MessagePort is closed')
418
+ }
419
+ })
420
+
421
+ test('should throw if sender ITC port was closed', async t => {
422
+ const { port1 } = new MessageChannel()
423
+
424
+ const itc = new ITC({ port: port1 })
425
+ itc.listen()
426
+
427
+ port1.close()
428
+
429
+ try {
430
+ await itc.send('test-command', 'test-req-message')
431
+ assert.fail('Expected an error to be thrown')
432
+ } catch (error) {
433
+ assert.strictEqual(error.code, 'PLT_ITC_MESSAGE_PORT_CLOSED')
434
+ assert.strictEqual(error.message, 'ITC MessagePort is closed')
435
+ }
436
+ })