@faybl/client 4.3.1 → 5.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/src/mqtt.js CHANGED
@@ -1,66 +1,38 @@
1
- import mqtt from 'mqtt';
2
- import { waitFor } from '@faybl/utils';
1
+ import * as R from 'ramda';
2
+ import { createActor, waitFor as waitForSnapshot } from 'xstate';
3
3
 
4
+ import { createConnectionMachine } from './connectionMachine.js';
4
5
  import { createMqttHandler } from './mqttUtils.js';
5
6
  import { getMqttCredentials } from './mqttCredentials.js';
7
+ import { Err, Ok, tryCatchAsync, waitFor } from '@faybl/utils';
8
+
9
+ /**
10
+ * Where an MQTT client keeps its connection machine's actor. A symbol keeps it out of the public,
11
+ * enumerable API; tests and the parts built on top of the client reach it through this key.
12
+ */
13
+ export const CONNECTION = Symbol('faybl.connection');
6
14
 
7
15
  export const baseMqttOptions = {
8
16
  keepAlive: 30,
9
17
  reconnectPeriod: 5000,
10
- // MQTT.js stops for good after a refused CONNACK. A refusal is usually passing, such as
11
- // credentials the broker could not check yet, and the next attempt fetches fresh ones.
12
- reconnectOnConnackError: true,
13
18
  clean: true,
14
19
  };
15
20
 
16
- /**
17
- * Makes every reconnect fetch fresh credentials first, since a token from the start of the
18
- * connection has expired by then. MQTT.js reconnects by calling `client.connect` from a timer
19
- * without waiting for it, and has no asynchronous hook for credentials, so `connect` is replaced.
20
- *
21
- * The replacement never rejects. A refused login, a 401, means the session is gone: it has been
22
- * reported to `session`, and no connection is attempted until a later reconnect finds credentials
23
- * again. Any other failure is reported and the connection is attempted with the credentials it had,
24
- * so the broker decides. A reconnect that arrives while credentials are still being fetched is
25
- * skipped.
26
- */
27
- const refreshCredentialsOnConnect = (client, credentialsSource) => {
28
- const nativeConnect = client.connect.bind(client);
29
- // eslint-disable-next-line functional/no-let -- One fetch at a time across reconnects that the MQTT.js timer starts independently.
30
- let fetching = false;
31
-
32
- /* eslint-disable functional/immutable-data -- The MQTT.js client is a mutable platform object; its reconnect path calls client.connect and reads client.options, so fresh credentials can only reach it by patching those in place. */
33
- // Resolves with whether to connect.
34
- const applyCredentials = async () => {
35
- try {
36
- const { username, password } = await getMqttCredentials(credentialsSource);
37
- if (username) client.options.username = username;
38
- if (password) client.options.password = password;
39
- return true;
40
- } catch (error) {
41
- if (error.response?.status === 401) return false;
42
- credentialsSource.report(error, { source: 'credentials' });
43
- return true;
44
- }
45
- };
21
+ // A refused login means the session is gone: it has been reported to `session` on the way, and
22
+ // the connection waits for it to come back. Any other failure is the machine's to report.
23
+ const fetchCredentialsResult = (credentialsSource) =>
24
+ tryCatchAsync(async (signal) => Ok(await getMqttCredentials({ ...credentialsSource, signal })))(
25
+ (cause) =>
26
+ Err({ kind: cause?.response?.status === 401 ? 'SessionLost' : 'CredentialsFailed', cause }),
27
+ );
46
28
 
47
- client.connect = async (...args) => {
48
- if (fetching) return client;
49
- fetching = true;
50
- try {
51
- return (await applyCredentials()) ? nativeConnect(...args) : client;
52
- } finally {
53
- fetching = false;
54
- }
55
- };
56
- /* eslint-enable functional/immutable-data */
57
- };
29
+ const noCredentials = async () => Ok({});
58
30
 
59
31
  // No answer, or a 5xx, is a credentials source that is not up yet. Any other answer is
60
- // final, a 401 above all, which means the login is gone.
32
+ // final: a 401 above all, which means the login is gone, and an answer without credentials.
61
33
  const isUnavailable = (error) => {
62
34
  const status = error?.response?.status ?? error?.status;
63
- return status === undefined || status >= 500;
35
+ return error?.kind !== 'IncompleteCredentials' && (status === undefined || status >= 500);
64
36
  };
65
37
 
66
38
  // The first credentials are waited for, so a client created while the authenticator or
@@ -72,17 +44,26 @@ const waitForCredentials = (credentialsSource, interval) =>
72
44
  onRetry: (error) => credentialsSource.report(error, { source: 'credentials' }),
73
45
  });
74
46
 
47
+ /**
48
+ * Connects to the broker through `connect`, MQTT.js's `connect`, with credentials from `http`'s
49
+ * OIDC handler or the authenticator, and resolves with the client's MQTT handler.
50
+ */
75
51
  export const createMqttClient = async ({
52
+ connect,
76
53
  mqttUrl,
77
54
  authenticatorUrl,
78
- oidcHandler,
79
55
  authConfig,
80
56
  noAuth,
57
+ http = {},
81
58
  mqttOptions = {},
82
59
  report = () => undefined,
83
- session,
84
60
  }) => {
85
- const credentialsSource = { authenticatorUrl, oidcHandler, authConfig, report, session };
61
+ // Credentials from the authenticator need a fetch. Without one every attempt would fail as if the
62
+ // authenticator were down, and the wait for it would never end.
63
+ if (!noAuth && !http.oidcHandler && typeof http.fetch !== 'function') {
64
+ return Promise.reject(Error('createMqttClient needs http.fetch to get MQTT credentials'));
65
+ }
66
+ const credentialsSource = { authenticatorUrl, authConfig, http, report };
86
67
  const connectionOptions = { ...baseMqttOptions, ...mqttOptions };
87
68
  const options = {
88
69
  ...connectionOptions,
@@ -92,9 +73,26 @@ export const createMqttClient = async ({
92
73
  clientId: `fayblClient_${Math.random().toString(16).slice(2, 12)}`,
93
74
  };
94
75
 
95
- const client = mqtt.connect(mqttUrl, options);
76
+ // The connection machine reconnects, not MQTT.js, so every attempt can fetch credentials first.
77
+ const client = connect(mqttUrl, { ...options, reconnectPeriod: 0 });
96
78
  // An EventEmitter with no `error` listener throws, which would take the host process down.
97
79
  client.on('error', (error) => report(error, { source: 'mqtt' }));
98
- if (!noAuth) refreshCredentialsOnConnect(client, credentialsSource);
99
- return createMqttHandler(client, { report });
80
+ const handler = createMqttHandler(client, { report });
81
+ const connection = createActor(
82
+ createConnectionMachine({
83
+ client,
84
+ fetchCredentials: noAuth ? noCredentials : fetchCredentialsResult(credentialsSource),
85
+ resubscribe: handler.resubscribe,
86
+ close: handler.close,
87
+ report,
88
+ reconnectPeriod: connectionOptions.reconnectPeriod,
89
+ }),
90
+ );
91
+ connection.start();
92
+ const close = async () => {
93
+ connection.send({ type: 'connection.close' });
94
+ await waitForSnapshot(connection, ({ status }) => status === 'done');
95
+ };
96
+ // resubscribe is the connection machine's to call; the handler's close is what its own close runs.
97
+ return { ...R.omit(['resubscribe'], handler), close, [CONNECTION]: connection };
100
98
  };
@@ -1,31 +1,37 @@
1
1
  import { fetchCheckedJson } from './fetch.js';
2
+ import { isNonEmptyString } from './guards.js';
3
+
4
+ // The credentials come from another service; anything but a username and a password is refused
5
+ // here, since MQTT.js would connect without what is missing.
6
+ const checkedCredentials = ({ username, password }) =>
7
+ isNonEmptyString(username) && isNonEmptyString(password)
8
+ ? { username, password }
9
+ : Promise.reject(
10
+ Object.assign(
11
+ Error('MQTT credentials are incomplete: a username and a password are needed'),
12
+ { kind: 'IncompleteCredentials' },
13
+ ),
14
+ );
2
15
 
3
16
  /**
4
17
  * Resolves with the username and password for the MQTT connection, or rejects when there are none
5
18
  * to be had. There is no anonymous fallback: a connection without credentials is asked for with
6
- * `noAuth`, never the result of a failure. A 401 from the authenticator means the login session
7
- * is gone, and is reported to `session` on the way.
19
+ * `noAuth`, never the result of a failure or of an answer that lacks them. A 401 from the
20
+ * authenticator means the login session is gone, and is reported to `session` on the way.
8
21
  */
9
- export const getMqttCredentials = async ({
10
- authenticatorUrl,
11
- oidcHandler,
12
- authConfig,
13
- session,
14
- }) => {
22
+ export const getMqttCredentials = async ({ authenticatorUrl, authConfig, http = {}, signal }) => {
23
+ const { oidcHandler } = http;
15
24
  if (oidcHandler) {
16
- return {
25
+ return checkedCredentials({
17
26
  username: oidcHandler.clientId,
18
27
  password: await oidcHandler.getToken(),
19
- };
28
+ });
20
29
  }
21
30
  const id = authConfig?.clientId;
22
31
  const credentials = await fetchCheckedJson(
23
32
  `${authenticatorUrl}/getMqttCredentials`,
24
- { method: 'POST', body: JSON.stringify(id ? { id } : {}) },
25
- { session },
33
+ { method: 'POST', body: JSON.stringify(id ? { id } : {}), ...(signal ? { signal } : {}) },
34
+ http,
26
35
  );
27
- return {
28
- username: credentials.id,
29
- password: credentials.token,
30
- };
36
+ return checkedCredentials({ username: credentials?.id, password: credentials?.token });
31
37
  };
package/src/mqttUtils.js CHANGED
@@ -1,10 +1,10 @@
1
- import match from 'mqtt-match';
1
+ import mqttMatch from 'mqtt-match';
2
2
  import * as R from 'ramda';
3
3
 
4
- import { Left, Right, either, tryCatchAsync } from './utils/either.js';
4
+ import { Err, Ok, match, tryCatchAsync } from '@faybl/utils';
5
5
 
6
- const parseJson = R.tryCatch(R.pipe(JSON.parse, Right), (cause) =>
7
- Left({ kind: 'InvalidJson', cause }),
6
+ const parseJson = R.tryCatch(R.pipe(JSON.parse, Ok), (cause) =>
7
+ Err({ kind: 'InvalidJson', cause }),
8
8
  );
9
9
 
10
10
  // No `Buffer`: it is a Node global, and browsers have none. A Node Buffer is a typed array, so
@@ -24,19 +24,15 @@ const createStore = (initState = {}, reducer = () => initState) => {
24
24
  };
25
25
  };
26
26
 
27
+ // Each subscription is its own entry, so undoing one leaves another with the same callback in place.
27
28
  const actions = {
28
- add: ({ topic, callback, preCallback }) =>
29
- R.over(R.lens(R.prop(topic), R.assoc(topic)), R.append({ callback, preCallback })),
30
- remove: ({ topic, callback }) =>
31
- R.ifElse(
32
- () => R.isNil(callback),
33
- R.dissoc(topic),
34
- R.when(
35
- R.has(topic),
36
- R.pipe(
37
- R.over(R.lensProp(topic), R.reject(R.propEq(callback, 'callback'))),
38
- R.when(R.propSatisfies(R.isEmpty, topic), R.dissoc(topic)),
39
- ),
29
+ add: ({ topic, entry }) => R.over(R.lens(R.prop(topic), R.assoc(topic)), R.append(entry)),
30
+ remove: ({ topic, isRemoved }) =>
31
+ R.when(
32
+ R.has(topic),
33
+ R.pipe(
34
+ R.over(R.lensProp(topic), R.reject(isRemoved)),
35
+ R.when(R.propSatisfies(R.isEmpty, topic), R.dissoc(topic)),
40
36
  ),
41
37
  ),
42
38
  clear: () => () => ({}),
@@ -44,7 +40,7 @@ const actions = {
44
40
 
45
41
  const reducer = (state, { type, ...rest }) => actions[type]?.(rest)(state) ?? state;
46
42
 
47
- export const matchTopic = R.curryN(2, match);
43
+ export const matchTopic = R.curryN(2, mqttMatch);
48
44
 
49
45
  export const getMatchingTopics = (topic) => R.pickBy((_, key) => matchTopic(key)(topic));
50
46
 
@@ -65,7 +61,7 @@ const deliverAll = (getState, report) => async (topic, data) => {
65
61
  const messageHandler = (getState, report) => async (topic, jsonData) => {
66
62
  // An empty payload clears a retained message; there is nothing to deliver.
67
63
  if (jsonData.length === 0) return undefined;
68
- return either(({ cause }) => report(cause, { source: 'message', topic }))((data) =>
64
+ return match(({ cause }) => report(cause, { source: 'message', topic }))((data) =>
69
65
  deliverAll(getState, report)(topic, data),
70
66
  )(parseJson(jsonData));
71
67
  };
@@ -82,63 +78,114 @@ const subscriptionRefusal = (topic, qos, granted) =>
82
78
  ? Error(`MQTT subscription to ${topic} was not granted QoS ${qos}`)
83
79
  : undefined;
84
80
 
81
+ // The QoS a topic is held at: the strictest any of its subscriptions or its acknowledgement asks for.
82
+ const heldQos = (entries, acknowledgement) =>
83
+ Math.max(acknowledgement?.qos ?? 0, ...entries.map(({ qos }) => qos));
84
+
85
+ // A later, stricter acknowledgement on the same topic also settles the earlier one.
86
+ const settleWith = tryCatchAsync(async (earlier, ready) => {
87
+ await ready;
88
+ earlier.resolve();
89
+ })((error, earlier) => earlier.reject(error));
90
+
85
91
  export const createMqttHandler = (client, { report = () => undefined } = {}) => {
86
92
  const { getState, dispatch } = createStore({}, reducer);
87
- // The acknowledgement each topic was subscribed with, so a second subscription to a topic waits
88
- // for the same SUBACK rather than settling before the broker has answered.
89
- // eslint-disable-next-line functional/no-let -- Acknowledgements outlive the independent subscribe and unsubscribe calls that share them; each change replaces the object.
93
+ // Each topic's acknowledgement, so a second subscription to a topic waits for the same SUBACK
94
+ // rather than settling before the broker has answered.
95
+ // eslint-disable-next-line functional/no-let -- Acknowledgements outlive the independent subscribe, unsubscribe and SUBACK callbacks that share them; each change replaces the object.
90
96
  let acknowledgements = {};
91
97
 
98
+ const dropAcknowledgement = (topic, reason) => {
99
+ acknowledgements[topic]?.reject(reason);
100
+ acknowledgements = R.dissoc(topic, acknowledgements);
101
+ };
102
+
92
103
  const handleMessage = messageHandler(getState, report);
93
104
  client.on('message', handleMessage);
94
- const unsubscribe = (topic, callback) => {
95
- dispatch({ type: 'remove', topic, callback });
105
+ // A client that ends settles every acknowledgement still waiting; resolved ones stay resolved.
106
+ client.on('end', () =>
107
+ Object.keys(acknowledgements).forEach((topic) =>
108
+ dropAcknowledgement(topic, Error(`MQTT client closed before ${topic} was acknowledged`)),
109
+ ),
110
+ );
111
+
112
+ // MQTT.js sets `disconnecting` while it ends and `disconnected` once it has; neither comes back.
113
+ const isClosing = () => client.disconnecting || client.disconnected;
114
+
115
+ // Only the broker can refuse a subscription. An error instead of a SUBACK means the connection
116
+ // closed first: the acknowledgement keeps waiting, and the resubscription on reconnect asks again,
117
+ // unless the client is being closed, which rejects it.
118
+ const answer = (topic, qos) => (error, granted) => {
119
+ const acknowledgement = acknowledgements[topic];
120
+ if (!acknowledgement) return undefined;
121
+ if (error) return isClosing() ? dropAcknowledgement(topic, error) : undefined;
122
+ const refusal = subscriptionRefusal(topic, qos, grantedQos(granted, topic));
123
+ if (!refusal) return acknowledgement.resolve();
124
+ // A refused subscription is asked for again by the next caller.
125
+ dropAcknowledgement(topic, refusal);
126
+ return undefined;
127
+ };
128
+
129
+ // While the connection is down nothing is sent: MQTT.js would queue the SUBSCRIBE and send it
130
+ // after the reconnect, beside the resubscription that asks for every held topic anyway. A client
131
+ // that is being closed will not reconnect, so its answer is that it closed.
132
+ const sendSubscribe = (topic, qos) =>
133
+ isClosing()
134
+ ? answer(topic, qos)(Error(`MQTT client closed before ${topic} was acknowledged`))
135
+ : client.connected
136
+ ? client.subscribe(topic, { qos }, answer(topic, qos))
137
+ : undefined;
138
+
139
+ const remove = (topic, isRemoved) => {
140
+ dispatch({ type: 'remove', topic, isRemoved });
96
141
  if (getState(topic)) return;
97
- acknowledgements = R.dissoc(topic, acknowledgements);
142
+ dropAcknowledgement(
143
+ topic,
144
+ Error(`MQTT subscription to ${topic} was undone before it was acknowledged`),
145
+ );
98
146
  client.unsubscribe(topic);
99
147
  };
100
148
 
149
+ // Without a callback, every subscription on the topic goes.
150
+ const unsubscribe = (topic, callback) =>
151
+ remove(topic, callback === undefined ? R.T : (entry) => entry.callback === callback);
152
+
153
+ const add = (topic, callback, { preCallback, qos = 0 }) => {
154
+ const entry = { callback, preCallback, qos };
155
+ dispatch({ type: 'add', topic, entry });
156
+ return () => remove(topic, (candidate) => candidate === entry);
157
+ };
158
+
101
159
  const subscribe = (topic, callback, { preCallback, qos } = {}) => {
102
- client.subscribe(topic, ...(qos === undefined ? [] : [{ qos }]));
103
- dispatch({ type: 'add', topic, callback, preCallback });
104
- return () => unsubscribe(topic, callback);
160
+ if (client.connected) client.subscribe(topic, ...(qos === undefined ? [] : [{ qos }]));
161
+ return add(topic, callback, { preCallback, qos });
105
162
  };
106
163
 
107
- // Only the broker can refuse a subscription. An error instead of a SUBACK means the connection
108
- // closed first, so the request is made again once it reconnects, rather than failing. A client
109
- // that is being closed rejects. MQTT.js counts the topic as held from the first attempt and would
110
- // answer a plain retry at once with no grants; `resubscribe`, the flag it uses for its own
111
- // resubscriptions, makes it send the SUBSCRIBE so the retry waits for the broker's answer.
112
- const requestAcknowledgement = (topic, qos) =>
113
- new Promise((resolve, reject) => {
114
- const answer = (error, granted) => {
115
- if (error) return client.disconnecting ? reject(error) : client.once('connect', retry);
116
- const refusal = subscriptionRefusal(topic, qos, grantedQos(granted, topic));
117
- return refusal ? reject(refusal) : resolve();
118
- };
119
- const retry = () => client.subscribe({ [topic]: { qos }, resubscribe: true }, answer);
120
- client.subscribe(topic, { qos }, answer);
121
- });
164
+ // Called on every connect: a clean session starts with nothing, and topics subscribed while the
165
+ // connection was down were not sent. Every topic is asked for once, at the QoS it is held at;
166
+ // acknowledgements still waiting settle on these SUBACKs.
167
+ const resubscribe = () =>
168
+ Object.entries(getState()).forEach(([topic, entries]) =>
169
+ sendSubscribe(topic, heldQos(entries, acknowledgements[topic])),
170
+ );
122
171
 
123
172
  const acknowledgementFor = (topic, qos) => {
124
173
  const held = acknowledgements[topic];
125
174
  if (held && held.qos >= qos) return held.ready;
126
- const ready = requestAcknowledgement(topic, qos);
127
- acknowledgements = R.assoc(topic, { qos, ready }, acknowledgements);
128
- // A refused subscription is asked for again by the next caller.
129
- ready.catch(() => {
130
- if (acknowledgements[topic]?.ready === ready)
131
- acknowledgements = R.dissoc(topic, acknowledgements);
132
- });
175
+ const { promise: ready, resolve, reject } = Promise.withResolvers();
176
+ // Rejections are the caller's to handle through `ready`; this keeps one nobody awaits from
177
+ // being reported as unhandled.
178
+ // eslint-disable-next-line promise/prefer-await-to-then -- marks `ready` handled beside the caller's await
179
+ ready.catch(() => undefined);
180
+ if (held) void settleWith(held, ready);
181
+ acknowledgements = R.assoc(topic, { qos, ready, resolve, reject }, acknowledgements);
182
+ sendSubscribe(topic, qos);
133
183
  return ready;
134
184
  };
135
185
 
136
186
  const subscribeWithAck = (topic, callback, { qos = 0, preCallback } = {}) => {
137
- dispatch({ type: 'add', topic, callback, preCallback });
138
- return {
139
- ready: acknowledgementFor(topic, qos),
140
- unsubscribe: () => unsubscribe(topic, callback),
141
- };
187
+ const undo = add(topic, callback, { preCallback, qos });
188
+ return { ready: acknowledgementFor(topic, qos), unsubscribe: undo };
142
189
  };
143
190
 
144
191
  const publish = (topic, message, options) => client.publish(topic, toPayload(message), options);
@@ -148,10 +195,10 @@ export const createMqttHandler = (client, { report = () => undefined } = {}) =>
148
195
  await client.endAsync();
149
196
  };
150
197
 
151
- return { client, publish, subscribe, subscribeWithAck, unsubscribe, close };
198
+ return { client, publish, subscribe, subscribeWithAck, unsubscribe, resubscribe, close };
152
199
  };
153
200
 
154
- export const mqttDisabledWarning = () => {
201
+ export const mqttDisabled = () => {
155
202
  // eslint-disable-next-line functional/no-throw-statements -- Stands in for subscribe and publish when MQTT is off; returning a Result would change what those public methods return, and calling them without MQTT is a programming error at the call site.
156
203
  throw Error('MQTT is disabled');
157
204
  };
@@ -1,5 +1,7 @@
1
1
  import * as oc from 'openid-client';
2
2
 
3
+ import { tryCatchAsync } from '@faybl/utils';
4
+
3
5
  const createOidcConfig = async ({ issuerUrl, clientId, clientSecret }) => {
4
6
  // issuerUrl should be the issuer identifier, not the .well-known metadata URL
5
7
  const configuration = await oc.discovery(new URL(issuerUrl), clientId, clientSecret);
@@ -51,21 +53,21 @@ export const createOidcHandler = ({ issuerUrl, clientId, clientSecret }) => {
51
53
  let refused = false;
52
54
  /* eslint-enable functional/no-let */
53
55
 
54
- const loadConfig = async () => {
55
- const discovery = (configPromise ??= createOidcConfig({ issuerUrl, clientId, clientSecret }));
56
- try {
57
- return await discovery;
58
- } catch (error) {
59
- if (configPromise === discovery) configPromise = undefined;
60
- return Promise.reject(error);
61
- }
62
- };
56
+ const awaitDiscovery = tryCatchAsync(async (discovery) => discovery)((error, discovery) => {
57
+ if (configPromise === discovery) configPromise = undefined;
58
+ return Promise.reject(error);
59
+ });
60
+
61
+ const loadConfig = async () =>
62
+ awaitDiscovery((configPromise ??= createOidcConfig({ issuerUrl, clientId, clientSecret })));
63
63
 
64
+ // A refused token stays refused until a new one has been issued, so a failed request for one
65
+ // does not let the next call return the refused token from the cache.
64
66
  const getToken = async () => {
65
67
  const config = await loadConfig();
66
68
  const fresh = refused;
67
- refused = false;
68
69
  const tokenSet = await config.getToken({ fresh });
70
+ if (fresh) refused = false;
69
71
  return tokenSet.access_token;
70
72
  };
71
73
 
package/src/presence.js CHANGED
@@ -1,4 +1,4 @@
1
- import { mqttDisabledWarning } from './mqttUtils.js';
1
+ import { mqttDisabled } from './mqttUtils.js';
2
2
  import { assertTopicSegment, assertTopicSegments } from './topicSegment.js';
3
3
 
4
4
  const baseTopic = 'presence';
@@ -18,12 +18,12 @@ export const getPresenceApi = (mqttClient) => {
18
18
  mqttClient.unsubscribe(`${baseTopic}/${identityId}`, callback),
19
19
  );
20
20
  };
21
+ // Every id is checked before the first subscription, so a bad one leaves nothing behind.
21
22
  const subscribe = (identityIds, callback) => {
22
- const checked = toIdentityIds(identityIds);
23
- checked.forEach((identityId) =>
23
+ const undos = toIdentityIds(identityIds).map((identityId) =>
24
24
  mqttClient.subscribe(`${baseTopic}/${identityId}`, callback, { preCallback }),
25
25
  );
26
- return () => unsubscribe(checked, callback);
26
+ return () => undos.forEach((undo) => undo());
27
27
  };
28
28
 
29
29
  return {
@@ -33,8 +33,8 @@ export const getPresenceApi = (mqttClient) => {
33
33
  unsubscribe,
34
34
  }
35
35
  : {
36
- subscribe: mqttDisabledWarning,
37
- unsubscribe: mqttDisabledWarning,
36
+ subscribe: mqttDisabled,
37
+ unsubscribe: mqttDisabled,
38
38
  }),
39
39
  };
40
40
  };
package/src/procedure.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import * as R from 'ramda';
2
2
  import { createId } from '@paralleldrive/cuid2';
3
3
 
4
+ import { isPlainObject } from './guards.js';
5
+ import { mqttDisabled } from './mqttUtils.js';
4
6
  import { assertTopicSegment, topicSegmentError } from './topicSegment.js';
5
- import { tryCatchAsync } from './utils/either.js';
7
+ import { tryCatchAsync } from '@faybl/utils';
6
8
 
7
9
  export const createRequestMessage = (args) => ({
8
10
  args,
@@ -24,26 +26,44 @@ const runProcedure = tryCatchAsync(async (callback, args) =>
24
26
  createReplyMessage(await callback(args), true),
25
27
  )((error) => createReplyMessage(error?.message ?? String(error), false));
26
28
 
27
- // Settles like `promise`, or rejects once `seconds` pass first. The timer is
28
- // cleared as soon as `promise` settles.
29
- const withTimeout = (promise, seconds) =>
30
- new Promise((resolve, reject) => {
31
- const timer = setTimeout(() => {
32
- reject(new Error('Timeout while waiting for reply.'));
33
- }, seconds * 1000);
34
- const settle = async () => {
35
- try {
36
- resolve(await promise);
37
- } catch (error) {
38
- reject(error);
39
- } finally {
40
- clearTimeout(timer);
41
- }
42
- };
43
- settle();
44
- });
29
+ const DEFAULT_TIMEOUT_SECONDS = 5;
30
+
31
+ // Settles like `promise`, or rejects once `seconds` pass or `signal` aborts first. The timer and
32
+ // the abort listener are cleared as soon as it settles.
33
+ const settleWithin = async (promise, { seconds, signal }) => {
34
+ const { promise: stopped, reject } = Promise.withResolvers();
35
+ const timer = setTimeout(() => {
36
+ reject(Error('Timeout while waiting for reply.'));
37
+ }, seconds * 1000);
38
+ const abort = () => reject(signal.reason);
39
+ signal?.addEventListener('abort', abort, { once: true });
40
+ try {
41
+ return await Promise.race([promise, stopped]);
42
+ } finally {
43
+ clearTimeout(timer);
44
+ signal?.removeEventListener('abort', abort);
45
+ }
46
+ };
47
+
48
+ // `call`'s third argument: `{ timeout, signal }`, or the timeout in seconds alone.
49
+ const callOptions = (options) =>
50
+ typeof options === 'object' && Boolean(options) ? options : { timeout: options };
51
+
52
+ const timeoutError = (timeout) =>
53
+ typeof timeout === 'number' && timeout > 0 && Number.isFinite(timeout)
54
+ ? undefined
55
+ : Error(`Invalid timeout ${JSON.stringify(timeout)}: it must be a positive number of seconds`);
56
+
57
+ const malformedRequestError = (data) =>
58
+ isPlainObject(data) ? undefined : Error('Invalid procedure request: it must be a JSON object');
45
59
 
46
- export const getProcedureApi = (mqttClient, report = () => undefined) => {
60
+ // A reply is `{ ok, rep }`: `rep` is the result, or the failure's message when `ok` is false.
61
+ const isReply = (data) => isPlainObject(data) && typeof data.ok === 'boolean';
62
+ const failureMessage = (rep) => (typeof rep === 'string' ? rep : JSON.stringify(rep));
63
+
64
+ const DISABLED_API = { provide: mqttDisabled, unprovide: mqttDisabled, call: mqttDisabled };
65
+
66
+ const createProcedureApi = (mqttClient, report) => {
47
67
  const requestTopic = (rid, reqId) =>
48
68
  `${procedureBaseTopic}/${assertTopicSegment('rid', rid)}/req/${reqId}`;
49
69
  const replyTopic = (rid, reqId) =>
@@ -78,9 +98,9 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
78
98
  let replies = new Map();
79
99
  return async ({ topic, data }) => {
80
100
  const reqId = getTopicLeaf(topic);
81
- // The request id arrives from the bus, and the reply topic is built from it.
82
- const reqIdError = topicSegmentError('reqId', reqId);
83
- if (reqIdError) return report(reqIdError, { source: 'procedure', topic });
101
+ // The request id and the request arrive from the bus, and the reply topic is built from the id.
102
+ const requestError = topicSegmentError('reqId', reqId) ?? malformedRequestError(data);
103
+ if (requestError) return report(requestError, { source: 'procedure', topic });
84
104
  if (!replies.has(reqId)) {
85
105
  const reply = runProcedure(callback, data.args);
86
106
  replies = new Map([...replies, [reqId, reply]].slice(-maxRememberedReplies));
@@ -105,18 +125,29 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
105
125
  };
106
126
  };
107
127
 
108
- const call = async (rid, args = {}, timeout = 5.0) => {
128
+ const call = async (rid, args = {}, options = {}) => {
129
+ const { timeout = DEFAULT_TIMEOUT_SECONDS, signal } = callOptions(options);
130
+ const invalidTimeout = timeoutError(timeout);
131
+ if (invalidTimeout) return Promise.reject(invalidTimeout);
132
+ if (signal?.aborted) return Promise.reject(signal.reason);
109
133
  const reqId = createId();
110
134
  const replyTo = replyTopic(rid, reqId);
111
135
  const { promise: reply, resolve: resolveReply, reject: rejectReply } = Promise.withResolvers();
112
136
  // A broker could reject the reply before SUBACK completes. Keep that
113
137
  // rejection handled even if the call times out while waiting for SUBACK.
138
+ // eslint-disable-next-line promise/prefer-await-to-then -- marks it handled without awaiting it
114
139
  reply.catch(() => {});
115
- const subscription = mqttClient.subscribeWithAck(
116
- replyTo,
117
- ({ data }) => (data.ok ? resolveReply(data.rep) : rejectReply(new Error(data.rep))),
118
- procedureMqttOptions,
119
- );
140
+ const onReply = ({ topic, data }) => {
141
+ if (!isReply(data)) {
142
+ return report(Error('Invalid procedure reply: it must be { ok, rep }'), {
143
+ source: 'procedure',
144
+ topic,
145
+ });
146
+ }
147
+ const { ok, rep } = data;
148
+ return ok ? resolveReply(rep) : rejectReply(Error(failureMessage(rep)));
149
+ };
150
+ const subscription = mqttClient.subscribeWithAck(replyTo, onReply, procedureMqttOptions);
120
151
  // eslint-disable-next-line functional/no-let -- Timeout must prevent a late SUBACK from publishing an expired request.
121
152
  let active = true;
122
153
  const operation = async () => {
@@ -133,7 +164,7 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
133
164
  return reply;
134
165
  };
135
166
  try {
136
- return await withTimeout(operation(), timeout);
167
+ return await settleWithin(operation(), { seconds: timeout, signal });
137
168
  } finally {
138
169
  active = false;
139
170
  subscription.unsubscribe();
@@ -146,3 +177,10 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
146
177
  call,
147
178
  };
148
179
  };
180
+
181
+ /**
182
+ * Procedures on the bus: `provide` answers calls to a rid, `call` makes one. Without MQTT every
183
+ * method throws `MQTT is disabled`, as the other bus-facing methods do.
184
+ */
185
+ export const getProcedureApi = (mqttClient, report = () => undefined) =>
186
+ mqttClient ? createProcedureApi(mqttClient, report) : DISABLED_API;