mqtt-json-rpc 1.3.7 → 2.1.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.
@@ -0,0 +1,337 @@
1
+ /*
2
+ ** MQTT-JSON-RPC -- JSON-RPC protocol over MQTT communication
3
+ ** Copyright (c) 2018-2025 Dr. Ralf S. Engelschall <rse@engelschall.com>
4
+ **
5
+ ** Permission is hereby granted, free of charge, to any person obtaining
6
+ ** a copy of this software and associated documentation files (the
7
+ ** "Software"), to deal in the Software without restriction, including
8
+ ** without limitation the rights to use, copy, modify, merge, publish,
9
+ ** distribute, sublicense, and/or sell copies of the Software, and to
10
+ ** permit persons to whom the Software is furnished to do so, subject to
11
+ ** the following conditions:
12
+ **
13
+ ** The above copyright notice and this permission notice shall be included
14
+ ** in all copies or substantial portions of the Software.
15
+ **
16
+ ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+
25
+ /* external requirements */
26
+ import { MqttClient } from "mqtt"
27
+ import UUID from "pure-uuid"
28
+ import JSONRPC, { JsonRpcError } from "jsonrpc-lite"
29
+ import Encodr from "encodr"
30
+
31
+ /* MQTT topic making and matching */
32
+ export type TopicRequestMake = (method: string) => string
33
+ export type TopicResponseMake = (method: string, clientId: string) => string
34
+ export type TopicRequestMatch = (topic: string) => RegExpMatchArray | null
35
+ export type TopicResponseMatch = (topic: string) => RegExpMatchArray | null
36
+
37
+ /* API option type */
38
+ export interface APIOptions {
39
+ clientId: string
40
+ encoding: "json" | "cbor" | "msgpack"
41
+ timeout: number
42
+ topicRequestMake: TopicRequestMake
43
+ topicResponseMake: TopicResponseMake
44
+ topicRequestMatch: TopicRequestMatch
45
+ topicResponseMatch: TopicResponseMatch
46
+ }
47
+
48
+ /* the API class */
49
+ export default class API {
50
+ private options: APIOptions
51
+ private encodr: Encodr
52
+ private registry = new Map<string, (...params: any[]) => any>()
53
+ private requests = new Map<string, (err: any, result: any) => void>()
54
+ private subscriptions = new Map<string, number>()
55
+
56
+ /* construct API class */
57
+ constructor (
58
+ private mqtt: MqttClient,
59
+ options: Partial<APIOptions> = {}
60
+ ) {
61
+ /* determine options */
62
+ this.options = {
63
+ clientId: (new UUID(1)).format("std"),
64
+ encoding: "json",
65
+ timeout: 10 * 1000,
66
+ topicRequestMake: (method) => `${method}/request`,
67
+ topicResponseMake: (method, clientId) => `${method}/response/${clientId}`,
68
+ topicRequestMatch: (topic) => topic.match(/^(.+?)\/request$/),
69
+ topicResponseMatch: (topic) => topic.match(/^(.+?)\/response\/(.+)$/),
70
+ ...options
71
+ }
72
+
73
+ /* establish an encoder */
74
+ this.encodr = new Encodr(this.options.encoding)
75
+
76
+ /* hook into the MQTT message processing */
77
+ this.mqtt.on("message", (topic: string, message: Buffer) => {
78
+ this._onServerMessage(topic, message)
79
+ this._onClientMessage(topic, message)
80
+ })
81
+ }
82
+
83
+ /*
84
+ * RPC server/response side
85
+ */
86
+
87
+ /* check for the registration of an RPC method */
88
+ registered (method: string): boolean {
89
+ return this.registry.has(method)
90
+ }
91
+
92
+ /* register an RPC method */
93
+ register<C extends ((...params: any[]) => any)> (method: string, callback: C): Promise<void> {
94
+ if (this.registry.has(method))
95
+ throw new Error(`register: method "${method}" already registered`)
96
+ this.registry.set(method, callback)
97
+ return new Promise((resolve, reject) => {
98
+ const topic = this.options.topicRequestMake(method)
99
+ this.mqtt.subscribe(topic, { qos: 2 }, (err: Error | null, granted: any) => {
100
+ if (err)
101
+ reject(err)
102
+ else
103
+ resolve()
104
+ })
105
+ })
106
+ }
107
+
108
+ /* unregister an RPC method */
109
+ unregister (method: string): Promise<void> {
110
+ if (!this.registry.has(method))
111
+ throw new Error(`unregister: method "${method}" not registered`)
112
+ this.registry.delete(method)
113
+ return new Promise((resolve, reject) => {
114
+ const topic = this.options.topicRequestMake(method)
115
+ this.mqtt.unsubscribe(topic, (err?: Error, packet?: any) => {
116
+ if (err)
117
+ reject(err)
118
+ else
119
+ resolve()
120
+ })
121
+ })
122
+ }
123
+
124
+ /* handle incoming RPC method request */
125
+ private _onServerMessage (topic: string, message: Buffer): void {
126
+ /* ensure we handle only MQTT JSON-RPC requests */
127
+ if (this.options.topicRequestMatch(topic) === null)
128
+ return
129
+
130
+ /* try to parse payload as JSON-RPC payload */
131
+ let parsed: any
132
+ try {
133
+ parsed = JSONRPC.parseObject(this.encodr.decode(message))
134
+ }
135
+ catch (_error: any) {
136
+ return
137
+ }
138
+ if (!(typeof parsed === "object" && typeof parsed.type === "string"))
139
+ return
140
+
141
+ /* determine method from JSON-RPC payload */
142
+ const method = parsed.payload.method
143
+
144
+ /* dispatch according to JSON-RPC type */
145
+ if (parsed.type === "notification")
146
+ /* just deliver notification */
147
+ this.registry.get(method)?.(...parsed.payload.params)
148
+ else if (parsed.type === "request") {
149
+ /* deliver request and send response */
150
+ let response: Promise<any>
151
+ const handler = this.registry.get(method)
152
+ if (handler !== undefined)
153
+ response = Promise.resolve().then(() => handler(...parsed.payload.params))
154
+ else
155
+ response = Promise.reject(JsonRpcError.methodNotFound({ method, id: parsed.payload.id }))
156
+ response.then((result: any) => {
157
+ /* create JSON-RPC success response */
158
+ return JSONRPC.success(parsed.payload.id, result)
159
+ }, (error: any) => {
160
+ /* create JSON-RPC error response */
161
+ return this._buildError(parsed.payload, error)
162
+ }).then((rpcResponse: any) => {
163
+ /* send MQTT response message */
164
+ const idMatch = parsed.payload.id.match(/^(.+):.+$/)
165
+ if (idMatch === null)
166
+ throw new Error("invalid request id format")
167
+ const encoded = this.encodr.encode(rpcResponse) as string | Buffer
168
+ const clientId: string = idMatch[1]
169
+ const topic = this.options.topicResponseMake(method, clientId)
170
+ this.mqtt.publish(topic, encoded, { qos: 0 })
171
+ }).catch((err: Error) => {
172
+ this.mqtt.emit("error", err)
173
+ })
174
+ }
175
+ }
176
+
177
+ /*
178
+ * RPC client/request side
179
+ */
180
+
181
+ /* notify peer ("fire and forget") */
182
+ notify<P extends any[]> (method: string, ...params: P): void {
183
+ const topic = this.options.topicRequestMake(method)
184
+ let request: any = JSONRPC.notification(method, params)
185
+ request = this.encodr.encode(request)
186
+ this.mqtt.publish(topic, request, { qos: 0 })
187
+ }
188
+
189
+ /* call peer ("request and response") */
190
+ call<C extends ((...params: any[]) => any)> (method: string, ...params: Parameters<C>): Promise<ReturnType<C>> {
191
+ /* determine unique request id */
192
+ const rid: string = `${this.options.clientId}:${(new UUID(1)).format("std")}`
193
+
194
+ /* subscribe for response */
195
+ this._responseSubscribe(method)
196
+
197
+ /* create promise for response handling */
198
+ const promise: Promise<any> = new Promise((resolve, reject) => {
199
+ let timer: NodeJS.Timeout | null = setTimeout(() => {
200
+ this.requests.delete(rid)
201
+ this._responseUnsubscribe(method)
202
+ timer = null
203
+ reject(new Error("communication timeout"))
204
+ }, this.options.timeout!)
205
+ this.requests.set(rid, (err: any, result: any) => {
206
+ if (timer !== null) {
207
+ clearTimeout(timer)
208
+ timer = null
209
+ }
210
+ if (err) reject(err)
211
+ else resolve(result)
212
+ })
213
+ })
214
+ let request: any = JSONRPC.request(rid, method, params)
215
+
216
+ /* send MQTT request message */
217
+ const topic = this.options.topicRequestMake(method)
218
+ request = this.encodr.encode(request)
219
+ this.mqtt.publish(topic, request, { qos: 2 }, (err?: Error) => {
220
+ const callback = this.requests.get(rid)
221
+ if (err && callback !== undefined) {
222
+ /* handle request failure */
223
+ this._responseUnsubscribe(method)
224
+ callback(err, undefined)
225
+ this.requests.delete(rid)
226
+ }
227
+ })
228
+
229
+ return promise
230
+ }
231
+
232
+ /* handle incoming RPC method response */
233
+ private _onClientMessage (topic: string, message: Buffer): void {
234
+ /* ensure we handle only MQTT JSON-RPC responses */
235
+ let m: RegExpMatchArray | null
236
+ if ((m = this.options.topicResponseMatch(topic)) === null)
237
+ return
238
+
239
+ /* ensure we really handle only MQTT RPC responses for us */
240
+ const clientId = m[2]
241
+ if (clientId !== this.options.clientId)
242
+ return
243
+
244
+ /* try to parse payload as JSON-RPC payload */
245
+ let parsed: any
246
+ try {
247
+ parsed = JSONRPC.parseObject(this.encodr.decode(message))
248
+ }
249
+ catch (_error: any) {
250
+ return
251
+ }
252
+ if (!(typeof parsed === "object" && typeof parsed.type === "string"))
253
+ return
254
+
255
+ /* determine method from JSON-RPC payload */
256
+ const method = parsed.payload.method
257
+
258
+ /* dispatch according to JSON-RPC type */
259
+ if (parsed.type === "success" || parsed.type === "error") {
260
+ const rid: string = parsed.payload.id
261
+ const callback = this.requests.get(rid)
262
+ if (callback !== undefined) {
263
+ /* call callback function */
264
+ if (parsed.type === "success")
265
+ callback(undefined, parsed.payload.result)
266
+ else
267
+ callback(parsed.payload.error, undefined)
268
+
269
+ /* unsubscribe from response */
270
+ this.requests.delete(rid)
271
+ this._responseUnsubscribe(method)
272
+ }
273
+ }
274
+ }
275
+
276
+ /* subscribe to RPC response */
277
+ private _responseSubscribe (method: string): void {
278
+ const topic = this.options.topicResponseMake(method, this.options.clientId)
279
+ if (!this.subscriptions.has(topic)) {
280
+ this.subscriptions.set(topic, 0)
281
+ this.mqtt.subscribe(topic, { qos: 2 }, (err: Error | null) => {
282
+ if (err)
283
+ this.mqtt.emit("error", err)
284
+ })
285
+ }
286
+ this.subscriptions.set(topic, this.subscriptions.get(topic)! + 1)
287
+ }
288
+
289
+ /* unsubscribe from RPC response */
290
+ private _responseUnsubscribe (method: string): void {
291
+ const topic = this.options.topicResponseMake(method, this.options.clientId)
292
+ if (!this.subscriptions.has(topic))
293
+ return
294
+ this.subscriptions.set(topic, this.subscriptions.get(topic)! - 1)
295
+ if (this.subscriptions.get(topic) === 0) {
296
+ this.subscriptions.delete(topic)
297
+ this.mqtt.unsubscribe(topic, (err?: Error) => {
298
+ if (err)
299
+ this.mqtt.emit("error", err)
300
+ })
301
+ }
302
+ }
303
+
304
+ /* determine RPC error */
305
+ private _buildError (payload: any, error: any): any {
306
+ /* determine error type and build appropriate JSON-RPC error */
307
+ let rpcError: JsonRpcError
308
+ switch (typeof error) {
309
+ case "undefined":
310
+ rpcError = new JsonRpcError("undefined error", 0)
311
+ break
312
+ case "string":
313
+ rpcError = new JsonRpcError(error, -1)
314
+ break
315
+ case "number":
316
+ case "bigint":
317
+ rpcError = new JsonRpcError("application error", Number(error))
318
+ break
319
+ case "object":
320
+ if (error === null)
321
+ rpcError = new JsonRpcError("undefined error", 0)
322
+ else {
323
+ if (error instanceof JsonRpcError)
324
+ rpcError = error
325
+ else if (error instanceof Error)
326
+ rpcError = new JsonRpcError(error.toString(), -100, error)
327
+ else
328
+ rpcError = new JsonRpcError("application error", -100, error)
329
+ }
330
+ break
331
+ default:
332
+ rpcError = new JsonRpcError("unspecified error", 0, { data: error })
333
+ break
334
+ }
335
+ return JSONRPC.error(payload.id, rpcError)
336
+ }
337
+ }
package/eslint.yaml DELETED
@@ -1,66 +0,0 @@
1
- ##
2
- ## MQTT-JSON-RPC -- JSON-RPC protocol over MQTT communication
3
- ## Copyright (c) 2018-2023 Dr. Ralf S. Engelschall <rse@engelschall.com>
4
- ##
5
- ## Permission is hereby granted, free of charge, to any person obtaining
6
- ## a copy of this software and associated documentation files (the
7
- ## "Software"), to deal in the Software without restriction, including
8
- ## without limitation the rights to use, copy, modify, merge, publish,
9
- ## distribute, sublicense, and/or sell copies of the Software, and to
10
- ## permit persons to whom the Software is furnished to do so, subject to
11
- ## the following conditions:
12
- ##
13
- ## The above copyright notice and this permission notice shall be included
14
- ## in all copies or substantial portions of the Software.
15
- ##
16
- ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
- ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- ## MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
- ## IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
- ## CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
- ## TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
- ## SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
- ##
24
-
25
- ---
26
-
27
- extends:
28
- - eslint:recommended
29
- - eslint-config-standard
30
-
31
- parserOptions:
32
- ecmaVersion: 12
33
- sourceType: module
34
- ecmaFeatures:
35
- jsx: false
36
-
37
- env:
38
- browser: true
39
- node: false
40
- commonjs: true
41
- worker: true
42
- serviceworker: true
43
-
44
- globals:
45
- process: true
46
-
47
- rules:
48
- # modified rules
49
- indent: [ "error", 4, { "SwitchCase": 1 } ]
50
- linebreak-style: [ "error", "unix" ]
51
- semi: [ "error", "never" ]
52
- operator-linebreak: [ "error", "after", { "overrides": { "&&": "before", "||": "before", ":": "before" } } ]
53
- brace-style: [ "error", "stroustrup", { "allowSingleLine": true } ]
54
- quotes: [ "error", "double" ]
55
-
56
- # disabled rules
57
- no-multi-spaces: off
58
- no-multiple-empty-lines: off
59
- key-spacing: off
60
- object-property-newline: off
61
- curly: off
62
- space-in-parens: off
63
- no-console: off
64
- lines-between-class-members: off
65
- array-bracket-spacing: off
66
-