@faybl/client 4.3.0 → 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.
@@ -1,6 +1,8 @@
1
1
  import * as R from 'ramda';
2
2
  import sift from 'sift';
3
3
 
4
+ import { Err, Ok } from '@faybl/utils';
5
+
4
6
  const isNonEmpty = R.complement(R.isEmpty);
5
7
  const keysToInclude = R.pipe(R.pickBy(Boolean), R.keys);
6
8
  const keysToExclude = R.pipe(R.pickBy(R.complement(Boolean)), R.keys);
@@ -21,21 +23,20 @@ export const projectWith = (projection) =>
21
23
  // `$where` runs JavaScript; a dataset filter only describes data. sift passes the operation's
22
24
  // name fourth, after its parameters, the query that owns it and the options.
23
25
  const refuseOperation = (...[, , , name]) => {
24
- // eslint-disable-next-line functional/no-throw-statements -- sift's operation API reports an operation it cannot build by throwing; compileFilter turns it into a Result.
26
+ // eslint-disable-next-line functional/no-throw-statements -- sift's operation API reports an operation it cannot build by throwing; compileFilter turns it into an Err.
25
27
  throw Error(`Unsupported operation: ${name}`);
26
28
  };
27
29
 
28
30
  /**
29
31
  * Compiles a MongoDB filter into a test on a record, the same query language conf reads with.
30
- * An operation sift cannot evaluate, such as `$text`, fails the compilation.
32
+ * An operation sift cannot evaluate, such as `$text`, fails the compilation: an Err of
33
+ * `{ kind: 'InvalidFilter', message, cause }` instead of an Ok of the test.
31
34
  */
32
- export const compileFilter = (filter = {}) => {
33
- try {
34
- return { ok: true, value: sift(filter, { operations: { $where: refuseOperation } }) };
35
- } catch (error) {
36
- return { ok: false, message: `Invalid dataset filter: ${error.message}` };
37
- }
38
- };
35
+ export const compileFilter = R.tryCatch(
36
+ (filter = {}) => Ok(sift(filter, { operations: { $where: refuseOperation } })),
37
+ (cause) =>
38
+ Err({ kind: 'InvalidFilter', message: `Invalid dataset filter: ${cause.message}`, cause }),
39
+ );
39
40
 
40
41
  export const createRecordMatcher =
41
42
  ({ rids, test }) =>
package/src/fetch.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as R from 'ramda';
2
- import { biAsync } from 'tri-fp';
2
+
3
+ import { Err, Ok, match, tryCatchAsync } from '@faybl/utils';
3
4
 
4
5
  // Every request carries a JSON body, so the content type is set here rather than by each caller.
5
6
  // Asking for JSON makes the login proxy answer an expired session with 401 instead of a redirect
@@ -18,26 +19,31 @@ const withToken = async (options, oidcHandler) =>
18
19
  ? R.assocPath(['headers', 'Authorization'])(`Bearer ${await oidcHandler.getToken()}`)(options)
19
20
  : options;
20
21
 
22
+ const readJson = tryCatchAsync(async (response) => Ok(await response.json()))((cause) =>
23
+ Err({ kind: 'InvalidJson', cause }),
24
+ );
25
+
26
+ // A failed response need not carry JSON, say an HTML error page from a proxy; its body is then {}.
21
27
  const requestFailure = async (response) => {
22
28
  const { status, statusText } = response;
23
- const [err, json] = await biAsync(response.json.bind(response))();
29
+ const body = match(() => ({}))(R.identity)(await readJson(response));
24
30
  return Object.assign(Error(`Request failed: ${status} ${statusText}`), {
25
- response: { status, statusText, body: err ? {} : json },
31
+ response: { status, statusText, body },
26
32
  });
27
33
  };
28
34
 
29
35
  /**
30
- * Sends a JSON request and resolves with the JSON response. A 401 with a client credentials token
31
- * gets one more try with a fresh token, since the cached one may have been revoked or rotated; a
32
- * 401 that stands is reported to `session` and rejects like any other failure.
36
+ * Sends a JSON request through `fetch` and resolves with the JSON response. A 401 with a client
37
+ * credentials token gets one more try with a fresh token, since the cached one may have been
38
+ * revoked or rotated; a 401 that stands is reported to `session` and rejects like any other failure.
33
39
  */
34
- export const fetchCheckedJson = async (url, options, { oidcHandler, session } = {}) => {
40
+ export const fetchCheckedJson = async (url, options, { fetch, oidcHandler, session }) => {
35
41
  // Cookies go along so a browser client is authenticated by its login session.
36
42
  const jsonOptions = {
37
43
  ...R.mergeDeepRight({ headers: JSON_HEADERS }, options),
38
44
  credentials: 'include',
39
45
  };
40
- const send = async () => globalThis.fetch(url, await withToken(jsonOptions, oidcHandler));
46
+ const send = async () => fetch(url, await withToken(jsonOptions, oidcHandler));
41
47
 
42
48
  const retryWithFreshToken = async (first) => {
43
49
  if (first.status !== UNAUTHORIZED || !oidcHandler) return first;
package/src/guards.js ADDED
@@ -0,0 +1,9 @@
1
+ // Shape checks for values that arrive from outside: options, the bus, other services.
2
+
3
+ export const isPlainObject = (value) =>
4
+ typeof value === 'object' && Boolean(value) && !Array.isArray(value);
5
+
6
+ export const isNonEmptyString = (value) => typeof value === 'string' && value !== '';
7
+
8
+ // A value as an error message shows it: JSON where it has one, else its string form.
9
+ export const describeValue = (value) => JSON.stringify(value) ?? String(value);
package/src/index.js CHANGED
@@ -1,56 +1,15 @@
1
- import * as R from 'ramda';
1
+ import mqtt from 'mqtt';
2
2
 
3
- import { clientOptionsError, tenantServiceUrl } from './clientOptions.js';
4
- import { createClient as createServerClient } from './client.js';
5
- import { createMqttClient } from './mqtt.js';
3
+ import { createClientFactory } from './clientFactory.js';
6
4
  import { createOidcHandler } from './oidcHandler.js';
7
- import { createReporter } from './report.js';
8
- import { createSession } from './session.js';
9
5
 
10
6
  export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
11
7
 
12
- const createMqttUrl = ({ tenantUrl, useWebsocket }) =>
13
- useWebsocket ? `wss://ws.${tenantUrl}` : `mqtts://mqtt.${tenantUrl}`;
14
-
15
- export const createClient = async (options = {}) => {
16
- const optionsError = clientOptionsError(options);
17
- if (optionsError) return Promise.reject(optionsError);
18
- const {
19
- tenantUrl,
20
- confUrl,
21
- dataHistoryUrl,
22
- mqttUrl,
23
- authenticatorUrl,
24
- noMqtt,
25
- authConfig,
26
- useWebsocket,
27
- noAuth,
28
- onError,
29
- } = options;
30
-
31
- const report = createReporter(onError);
32
- const session = createSession(report);
33
- const oidcHandler = R.prop('issuerUrl')(authConfig) ? createOidcHandler(authConfig) : undefined;
34
-
35
- const mqttClient = noMqtt
36
- ? undefined
37
- : await createMqttClient({
38
- mqttUrl: mqttUrl || createMqttUrl({ tenantUrl, useWebsocket }),
39
- authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
40
- oidcHandler,
41
- authConfig,
42
- noAuth,
43
- report,
44
- session,
45
- });
46
-
47
- return createServerClient({
48
- authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
49
- confUrl: confUrl || tenantServiceUrl(tenantUrl, '/conf'),
50
- dataHistoryUrl: dataHistoryUrl || tenantServiceUrl(tenantUrl, '/data-history'),
51
- mqttClient,
52
- oidcHandler,
53
- session,
54
- report,
55
- });
56
- };
8
+ export const createClient = createClientFactory({
9
+ connectMqtt: mqtt.connect,
10
+ // Looked up on each call, so the fetch in place when a request is made is the one used.
11
+ fetch: (...args) => globalThis.fetch(...args),
12
+ createOidcHandler,
13
+ defaultMqttUrl: ({ tenantUrl, useWebsocket }) =>
14
+ useWebsocket ? `wss://ws.${tenantUrl}` : `mqtts://mqtt.${tenantUrl}`,
15
+ });
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,8 +1,11 @@
1
- import match from 'mqtt-match';
1
+ import mqttMatch from 'mqtt-match';
2
2
  import * as R from 'ramda';
3
- import { bi } from 'tri-fp';
4
3
 
5
- const safeJsonParse = bi(JSON.parse);
4
+ import { Err, Ok, match, tryCatchAsync } from '@faybl/utils';
5
+
6
+ const parseJson = R.tryCatch(R.pipe(JSON.parse, Ok), (cause) =>
7
+ Err({ kind: 'InvalidJson', cause }),
8
+ );
6
9
 
7
10
  // No `Buffer`: it is a Node global, and browsers have none. A Node Buffer is a typed array, so
8
11
  // binary passes through on either side.
@@ -21,19 +24,15 @@ const createStore = (initState = {}, reducer = () => initState) => {
21
24
  };
22
25
  };
23
26
 
27
+ // Each subscription is its own entry, so undoing one leaves another with the same callback in place.
24
28
  const actions = {
25
- add: ({ topic, callback, preCallback }) =>
26
- R.over(R.lens(R.prop(topic), R.assoc(topic)), R.append({ callback, preCallback })),
27
- remove: ({ topic, callback }) =>
28
- R.ifElse(
29
- () => R.isNil(callback),
30
- R.dissoc(topic),
31
- R.when(
32
- R.has(topic),
33
- R.pipe(
34
- R.over(R.lensProp(topic), R.reject(R.propEq(callback, 'callback'))),
35
- R.when(R.propSatisfies(R.isEmpty, topic), R.dissoc(topic)),
36
- ),
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)),
37
36
  ),
38
37
  ),
39
38
  clear: () => () => ({}),
@@ -41,32 +40,30 @@ const actions = {
41
40
 
42
41
  const reducer = (state, { type, ...rest }) => actions[type]?.(rest)(state) ?? state;
43
42
 
44
- export const matchTopic = R.curryN(2, match);
43
+ export const matchTopic = R.curryN(2, mqttMatch);
45
44
 
46
45
  export const getMatchingTopics = (topic) => R.pickBy((_, key) => matchTopic(key)(topic));
47
46
 
48
47
  // A subscriber's failure is reported and stays its own: it neither reaches the
49
48
  // other subscribers nor escapes as an unhandled rejection.
50
- const deliver =
51
- (report) =>
52
- async ({ callback, preCallback }, message) => {
53
- try {
54
- const payload = preCallback ? await preCallback(message) : message;
55
- await callback(payload);
56
- } catch (error) {
57
- report(error, { source: 'subscriber', topic: message.topic });
58
- }
59
- };
49
+ const deliver = (report) =>
50
+ tryCatchAsync(async ({ callback, preCallback }, message) => {
51
+ const payload = preCallback ? await preCallback(message) : message;
52
+ await callback(payload);
53
+ })((error, _, { topic }) => report(error, { source: 'subscriber', topic }));
60
54
 
55
+ const deliverAll = (getState, report) => async (topic, data) => {
56
+ const subscribers = R.pipe(getState, getMatchingTopics(topic), R.values, R.flatten)();
57
+ await Promise.all(subscribers.map((subscriber) => deliver(report)(subscriber, { topic, data })));
58
+ };
59
+
60
+ // onError gets the parser's own SyntaxError, as it does any other failure.
61
61
  const messageHandler = (getState, report) => async (topic, jsonData) => {
62
62
  // An empty payload clears a retained message; there is nothing to deliver.
63
63
  if (jsonData.length === 0) return undefined;
64
- const [error, data] = safeJsonParse(jsonData);
65
-
66
- if (error) return report(error, { source: 'message', topic });
67
- const subscribers = R.pipe(getState, getMatchingTopics(topic), R.values, R.flatten)();
68
- await Promise.all(subscribers.map((subscriber) => deliver(report)(subscriber, { topic, data })));
69
- return undefined;
64
+ return match(({ cause }) => report(cause, { source: 'message', topic }))((data) =>
65
+ deliverAll(getState, report)(topic, data),
66
+ )(parseJson(jsonData));
70
67
  };
71
68
 
72
69
  // A SUBACK return code of 0x80 or above refuses the subscription.
@@ -81,63 +78,114 @@ const subscriptionRefusal = (topic, qos, granted) =>
81
78
  ? Error(`MQTT subscription to ${topic} was not granted QoS ${qos}`)
82
79
  : undefined;
83
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
+
84
91
  export const createMqttHandler = (client, { report = () => undefined } = {}) => {
85
92
  const { getState, dispatch } = createStore({}, reducer);
86
- // The acknowledgement each topic was subscribed with, so a second subscription to a topic waits
87
- // for the same SUBACK rather than settling before the broker has answered.
88
- // 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.
89
96
  let acknowledgements = {};
90
97
 
98
+ const dropAcknowledgement = (topic, reason) => {
99
+ acknowledgements[topic]?.reject(reason);
100
+ acknowledgements = R.dissoc(topic, acknowledgements);
101
+ };
102
+
91
103
  const handleMessage = messageHandler(getState, report);
92
104
  client.on('message', handleMessage);
93
- const unsubscribe = (topic, callback) => {
94
- 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 });
95
141
  if (getState(topic)) return;
96
- acknowledgements = R.dissoc(topic, acknowledgements);
142
+ dropAcknowledgement(
143
+ topic,
144
+ Error(`MQTT subscription to ${topic} was undone before it was acknowledged`),
145
+ );
97
146
  client.unsubscribe(topic);
98
147
  };
99
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
+
100
159
  const subscribe = (topic, callback, { preCallback, qos } = {}) => {
101
- client.subscribe(topic, ...(qos === undefined ? [] : [{ qos }]));
102
- dispatch({ type: 'add', topic, callback, preCallback });
103
- return () => unsubscribe(topic, callback);
160
+ if (client.connected) client.subscribe(topic, ...(qos === undefined ? [] : [{ qos }]));
161
+ return add(topic, callback, { preCallback, qos });
104
162
  };
105
163
 
106
- // Only the broker can refuse a subscription. An error instead of a SUBACK means the connection
107
- // closed first, so the request is made again once it reconnects, rather than failing. A client
108
- // that is being closed rejects. MQTT.js counts the topic as held from the first attempt and would
109
- // answer a plain retry at once with no grants; `resubscribe`, the flag it uses for its own
110
- // resubscriptions, makes it send the SUBSCRIBE so the retry waits for the broker's answer.
111
- const requestAcknowledgement = (topic, qos) =>
112
- new Promise((resolve, reject) => {
113
- const answer = (error, granted) => {
114
- if (error) return client.disconnecting ? reject(error) : client.once('connect', retry);
115
- const refusal = subscriptionRefusal(topic, qos, grantedQos(granted, topic));
116
- return refusal ? reject(refusal) : resolve();
117
- };
118
- const retry = () => client.subscribe({ [topic]: { qos }, resubscribe: true }, answer);
119
- client.subscribe(topic, { qos }, answer);
120
- });
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
+ );
121
171
 
122
172
  const acknowledgementFor = (topic, qos) => {
123
173
  const held = acknowledgements[topic];
124
174
  if (held && held.qos >= qos) return held.ready;
125
- const ready = requestAcknowledgement(topic, qos);
126
- acknowledgements = R.assoc(topic, { qos, ready }, acknowledgements);
127
- // A refused subscription is asked for again by the next caller.
128
- ready.catch(() => {
129
- if (acknowledgements[topic]?.ready === ready)
130
- acknowledgements = R.dissoc(topic, acknowledgements);
131
- });
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);
132
183
  return ready;
133
184
  };
134
185
 
135
186
  const subscribeWithAck = (topic, callback, { qos = 0, preCallback } = {}) => {
136
- dispatch({ type: 'add', topic, callback, preCallback });
137
- return {
138
- ready: acknowledgementFor(topic, qos),
139
- unsubscribe: () => unsubscribe(topic, callback),
140
- };
187
+ const undo = add(topic, callback, { preCallback, qos });
188
+ return { ready: acknowledgementFor(topic, qos), unsubscribe: undo };
141
189
  };
142
190
 
143
191
  const publish = (topic, message, options) => client.publish(topic, toPayload(message), options);
@@ -147,10 +195,10 @@ export const createMqttHandler = (client, { report = () => undefined } = {}) =>
147
195
  await client.endAsync();
148
196
  };
149
197
 
150
- return { client, publish, subscribe, subscribeWithAck, unsubscribe, close };
198
+ return { client, publish, subscribe, subscribeWithAck, unsubscribe, resubscribe, close };
151
199
  };
152
200
 
153
- export const mqttDisabledWarning = () => {
201
+ export const mqttDisabled = () => {
154
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.
155
203
  throw Error('MQTT is disabled');
156
204
  };