@faybl/client 0.0.0-stage → 4.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/LICENSE +21 -0
- package/README.md +246 -2
- package/package.json +67 -4
- package/src/auth.js +15 -0
- package/src/browser.js +31 -0
- package/src/channel.js +50 -0
- package/src/client.js +35 -0
- package/src/clientOptions.js +36 -0
- package/src/conf.js +82 -0
- package/src/connection.js +29 -0
- package/src/dataset.js +189 -0
- package/src/datasetRecords.js +76 -0
- package/src/fetch.js +32 -0
- package/src/index.js +52 -0
- package/src/mqtt.js +75 -0
- package/src/mqttCredentials.js +34 -0
- package/src/mqttUtils.js +115 -0
- package/src/oidcHandler.js +71 -0
- package/src/presence.js +40 -0
- package/src/procedure.js +150 -0
- package/src/report.js +16 -0
- package/src/topicSegment.js +65 -0
package/src/procedure.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import * as R from 'ramda';
|
|
2
|
+
import { createId } from '@paralleldrive/cuid2';
|
|
3
|
+
|
|
4
|
+
import { assertTopicSegment, topicSegmentError } from './topicSegment.js';
|
|
5
|
+
|
|
6
|
+
export const createRequestMessage = (args) => ({
|
|
7
|
+
args,
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
export const createReplyMessage = (reply, ok) => ({
|
|
11
|
+
rep: reply,
|
|
12
|
+
ok,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const getTopicLeaf = R.pipe(R.split('/'), R.last);
|
|
16
|
+
|
|
17
|
+
const procedureBaseTopic = 'procedure';
|
|
18
|
+
const procedureMqttOptions = { qos: 1, retain: false };
|
|
19
|
+
const maxRememberedReplies = 1024;
|
|
20
|
+
|
|
21
|
+
const runProcedure = async (callback, args) => {
|
|
22
|
+
try {
|
|
23
|
+
return createReplyMessage(await callback(args), true);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
return createReplyMessage(error?.message ?? String(error), false);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// Settles like `promise`, or rejects once `seconds` pass first. The timer is
|
|
30
|
+
// cleared as soon as `promise` settles.
|
|
31
|
+
const withTimeout = (promise, seconds) =>
|
|
32
|
+
new Promise((resolve, reject) => {
|
|
33
|
+
const timer = setTimeout(() => {
|
|
34
|
+
reject(new Error('Timeout while waiting for reply.'));
|
|
35
|
+
}, seconds * 1000);
|
|
36
|
+
const settle = async () => {
|
|
37
|
+
try {
|
|
38
|
+
resolve(await promise);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
reject(error);
|
|
41
|
+
} finally {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
settle();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
export const getProcedureApi = (mqttClient, report = () => undefined) => {
|
|
49
|
+
const requestTopic = (rid, reqId) =>
|
|
50
|
+
`${procedureBaseTopic}/${assertTopicSegment('rid', rid)}/req/${reqId}`;
|
|
51
|
+
const replyTopic = (rid, reqId) =>
|
|
52
|
+
`${procedureBaseTopic}/${assertTopicSegment('rid', rid)}/rep/${reqId}`;
|
|
53
|
+
|
|
54
|
+
// Each provider's request handler, so unproviding one callback leaves the others on the rid.
|
|
55
|
+
// eslint-disable-next-line functional/no-let -- The providers of this client, added and removed by independent provide and unprovide calls; each change replaces the array.
|
|
56
|
+
let providers = [];
|
|
57
|
+
|
|
58
|
+
const removeProviders = (isRemoved) => {
|
|
59
|
+
const removed = providers.filter(isRemoved);
|
|
60
|
+
providers = providers.filter((provider) => !isRemoved(provider));
|
|
61
|
+
return removed;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
// Without a callback, every provider on the rid goes, the way channel.unsubscribe works.
|
|
65
|
+
const unprovide = (rid, callback) => {
|
|
66
|
+
const topic = requestTopic(rid, '+');
|
|
67
|
+
if (callback === undefined) {
|
|
68
|
+
removeProviders((provider) => provider.rid === rid);
|
|
69
|
+
return mqttClient.unsubscribe(topic);
|
|
70
|
+
}
|
|
71
|
+
removeProviders((provider) => provider.rid === rid && provider.callback === callback).forEach(
|
|
72
|
+
({ handleRequest }) => mqttClient.unsubscribe(topic, handleRequest),
|
|
73
|
+
);
|
|
74
|
+
return undefined;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const createRequestHandler = (rid, callback) => {
|
|
78
|
+
// Keep recent replies so a QoS 1 redelivery does not execute a procedure twice.
|
|
79
|
+
// eslint-disable-next-line functional/no-let -- Each provider owns this bounded cache across independently delivered requests.
|
|
80
|
+
let replies = new Map();
|
|
81
|
+
return async ({ topic, data }) => {
|
|
82
|
+
const reqId = getTopicLeaf(topic);
|
|
83
|
+
// The request id arrives from the bus, and the reply topic is built from it.
|
|
84
|
+
const reqIdError = topicSegmentError('reqId', reqId);
|
|
85
|
+
if (reqIdError) return report(reqIdError, { source: 'procedure', topic });
|
|
86
|
+
if (!replies.has(reqId)) {
|
|
87
|
+
const reply = runProcedure(callback, data.args);
|
|
88
|
+
replies = new Map([...replies, [reqId, reply]].slice(-maxRememberedReplies));
|
|
89
|
+
}
|
|
90
|
+
return mqttClient.publish(
|
|
91
|
+
replyTopic(rid, reqId),
|
|
92
|
+
await replies.get(reqId),
|
|
93
|
+
procedureMqttOptions,
|
|
94
|
+
);
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const provide = (rid, callback) => {
|
|
99
|
+
const topic = requestTopic(rid, '+');
|
|
100
|
+
const handleRequest = createRequestHandler(rid, callback);
|
|
101
|
+
mqttClient.subscribe(topic, handleRequest, procedureMqttOptions);
|
|
102
|
+
const provider = { rid, callback, handleRequest };
|
|
103
|
+
providers = [...providers, provider];
|
|
104
|
+
return () => {
|
|
105
|
+
removeProviders((candidate) => candidate === provider);
|
|
106
|
+
mqttClient.unsubscribe(topic, handleRequest);
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const call = async (rid, args = {}, timeout = 5.0) => {
|
|
111
|
+
const reqId = createId();
|
|
112
|
+
const replyTo = replyTopic(rid, reqId);
|
|
113
|
+
const { promise: reply, resolve: resolveReply, reject: rejectReply } = Promise.withResolvers();
|
|
114
|
+
// A broker could reject the reply before SUBACK completes. Keep that
|
|
115
|
+
// rejection handled even if the call times out while waiting for SUBACK.
|
|
116
|
+
reply.catch(() => {});
|
|
117
|
+
const subscription = mqttClient.subscribeWithAck(
|
|
118
|
+
replyTo,
|
|
119
|
+
({ data }) => (data.ok ? resolveReply(data.rep) : rejectReply(new Error(data.rep))),
|
|
120
|
+
procedureMqttOptions,
|
|
121
|
+
);
|
|
122
|
+
// eslint-disable-next-line functional/no-let -- Timeout must prevent a late SUBACK from publishing an expired request.
|
|
123
|
+
let active = true;
|
|
124
|
+
const operation = async () => {
|
|
125
|
+
await subscription.ready;
|
|
126
|
+
if (!active) return undefined;
|
|
127
|
+
if (mqttClient.client.connected === false) {
|
|
128
|
+
return Promise.reject(Error('MQTT is disconnected; procedure request was not sent'));
|
|
129
|
+
}
|
|
130
|
+
mqttClient.publish(
|
|
131
|
+
requestTopic(rid, reqId),
|
|
132
|
+
createRequestMessage(args),
|
|
133
|
+
procedureMqttOptions,
|
|
134
|
+
);
|
|
135
|
+
return reply;
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
return await withTimeout(operation(), timeout);
|
|
139
|
+
} finally {
|
|
140
|
+
active = false;
|
|
141
|
+
subscription.unsubscribe();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
unprovide,
|
|
147
|
+
provide,
|
|
148
|
+
call,
|
|
149
|
+
};
|
|
150
|
+
};
|
package/src/report.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns the caller's `onError` into the function every module reports through. The client writes
|
|
3
|
+
* nothing to the console; without an `onError`, what it would report is dropped.
|
|
4
|
+
*
|
|
5
|
+
* `context.source` says where the error came from: `mqtt`, `credentials`, `message`, `subscriber`
|
|
6
|
+
* or `procedure`. `context.topic` is set when the error concerns a topic.
|
|
7
|
+
*/
|
|
8
|
+
export const createReporter =
|
|
9
|
+
(onError = () => undefined) =>
|
|
10
|
+
(error, context) => {
|
|
11
|
+
try {
|
|
12
|
+
onError(error, context);
|
|
13
|
+
} catch {
|
|
14
|
+
// A throwing onError would otherwise escape into an MQTT.js event or a subscriber's delivery.
|
|
15
|
+
}
|
|
16
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const wildcards = ['+', '#'];
|
|
2
|
+
|
|
3
|
+
const invalidReasons = [
|
|
4
|
+
[(value) => typeof value !== 'string', 'must be a string'],
|
|
5
|
+
[(value) => value === '', 'must not be empty'],
|
|
6
|
+
[
|
|
7
|
+
(value) => wildcards.some((wildcard) => value.includes(wildcard)),
|
|
8
|
+
`must not contain the MQTT wildcards ${wildcards.map((wildcard) => `'${wildcard}'`).join(' or ')}`,
|
|
9
|
+
],
|
|
10
|
+
[(value) => value.includes('/'), "must not contain '/', which starts a new topic level"],
|
|
11
|
+
[(value) => value.startsWith('$'), "must not start with '$', which the broker reserves"],
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
const describeValue = (value) => JSON.stringify(value) ?? String(value);
|
|
15
|
+
|
|
16
|
+
const invalidReasonFor = (value) => {
|
|
17
|
+
const [, reason] = invalidReasons.find(([isInvalid]) => isInvalid(value)) ?? [];
|
|
18
|
+
return reason;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A topic segment is one level of an MQTT topic built from a caller's identifier. Returns the Error
|
|
23
|
+
* the caller should see, or undefined when the value is usable as a segment.
|
|
24
|
+
*/
|
|
25
|
+
export const topicSegmentError = (argumentName, value) => {
|
|
26
|
+
const reason = invalidReasonFor(value);
|
|
27
|
+
return reason === undefined
|
|
28
|
+
? undefined
|
|
29
|
+
: Error(`Invalid ${argumentName} ${describeValue(value)}: it ${reason}`);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const topicSegmentsError = (argumentName, values) =>
|
|
33
|
+
Array.isArray(values) && values.length > 0
|
|
34
|
+
? values
|
|
35
|
+
.map((value, index) => topicSegmentError(`${argumentName}[${index}]`, value))
|
|
36
|
+
.find(Boolean)
|
|
37
|
+
: Error(`Invalid ${argumentName} ${describeValue(values)}: it must be a non-empty array`);
|
|
38
|
+
|
|
39
|
+
export const assertTopicSegment = (argumentName, value) => {
|
|
40
|
+
const error = topicSegmentError(argumentName, value);
|
|
41
|
+
// eslint-disable-next-line functional/no-throw-statements -- A wildcard in an identifier is a mistake at the call site, not a domain failure; a Result would change the return of every bus-facing call, and the value has to be refused before a topic is built from it.
|
|
42
|
+
if (error) throw error;
|
|
43
|
+
return value;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const notOneOfError = (argumentName, value, allowed) =>
|
|
47
|
+
allowed.includes(value)
|
|
48
|
+
? undefined
|
|
49
|
+
: Error(
|
|
50
|
+
`Invalid ${argumentName} ${describeValue(value)}: it must be one of ${allowed.map((name) => `'${name}'`).join(', ')}`,
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
export const assertTopicSegmentOneOf = (argumentName, value, allowed) => {
|
|
54
|
+
const error = notOneOfError(argumentName, value, allowed);
|
|
55
|
+
// eslint-disable-next-line functional/no-throw-statements -- See assertTopicSegment.
|
|
56
|
+
if (error) throw error;
|
|
57
|
+
return value;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export const assertTopicSegments = (argumentName, values) => {
|
|
61
|
+
const error = topicSegmentsError(argumentName, values);
|
|
62
|
+
// eslint-disable-next-line functional/no-throw-statements -- See assertTopicSegment. Every value is checked before the first subscription, so a bad one leaves no partial subscription behind.
|
|
63
|
+
if (error) throw error;
|
|
64
|
+
return values;
|
|
65
|
+
};
|