@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,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,7 +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';
7
+ import { tryCatchAsync } from '@faybl/utils';
5
8
 
6
9
  export const createRequestMessage = (args) => ({
7
10
  args,
@@ -18,34 +21,49 @@ const procedureBaseTopic = 'procedure';
18
21
  const procedureMqttOptions = { qos: 1, retain: false };
19
22
  const maxRememberedReplies = 1024;
20
23
 
21
- const runProcedure = async (callback, args) => {
24
+ // A provider's procedure is caller code: whatever it throws or rejects with becomes a failure reply.
25
+ const runProcedure = tryCatchAsync(async (callback, args) =>
26
+ createReplyMessage(await callback(args), true),
27
+ )((error) => createReplyMessage(error?.message ?? String(error), false));
28
+
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 });
22
40
  try {
23
- return createReplyMessage(await callback(args), true);
24
- } catch (error) {
25
- return createReplyMessage(error?.message ?? String(error), false);
41
+ return await Promise.race([promise, stopped]);
42
+ } finally {
43
+ clearTimeout(timer);
44
+ signal?.removeEventListener('abort', abort);
26
45
  }
27
46
  };
28
47
 
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
- });
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');
47
59
 
48
- 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) => {
49
67
  const requestTopic = (rid, reqId) =>
50
68
  `${procedureBaseTopic}/${assertTopicSegment('rid', rid)}/req/${reqId}`;
51
69
  const replyTopic = (rid, reqId) =>
@@ -80,9 +98,9 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
80
98
  let replies = new Map();
81
99
  return async ({ topic, data }) => {
82
100
  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 });
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 });
86
104
  if (!replies.has(reqId)) {
87
105
  const reply = runProcedure(callback, data.args);
88
106
  replies = new Map([...replies, [reqId, reply]].slice(-maxRememberedReplies));
@@ -107,18 +125,29 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
107
125
  };
108
126
  };
109
127
 
110
- 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);
111
133
  const reqId = createId();
112
134
  const replyTo = replyTopic(rid, reqId);
113
135
  const { promise: reply, resolve: resolveReply, reject: rejectReply } = Promise.withResolvers();
114
136
  // A broker could reject the reply before SUBACK completes. Keep that
115
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
116
139
  reply.catch(() => {});
117
- const subscription = mqttClient.subscribeWithAck(
118
- replyTo,
119
- ({ data }) => (data.ok ? resolveReply(data.rep) : rejectReply(new Error(data.rep))),
120
- procedureMqttOptions,
121
- );
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);
122
151
  // eslint-disable-next-line functional/no-let -- Timeout must prevent a late SUBACK from publishing an expired request.
123
152
  let active = true;
124
153
  const operation = async () => {
@@ -135,7 +164,7 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
135
164
  return reply;
136
165
  };
137
166
  try {
138
- return await withTimeout(operation(), timeout);
167
+ return await settleWithin(operation(), { seconds: timeout, signal });
139
168
  } finally {
140
169
  active = false;
141
170
  subscription.unsubscribe();
@@ -148,3 +177,10 @@ export const getProcedureApi = (mqttClient, report = () => undefined) => {
148
177
  call,
149
178
  };
150
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;
package/src/report.js CHANGED
@@ -1,16 +1,28 @@
1
+ import * as R from 'ramda';
2
+
1
3
  /**
2
4
  * Turns the caller's `onError` into the function every module reports through. The client writes
3
5
  * nothing to the console; without an `onError`, what it would report is dropped.
4
6
  *
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
+ * `context.source` says where the error came from: `mqtt`, `session`, `credentials`, `message`,
8
+ * `subscriber` or `procedure`. `context.topic` is set when the error concerns a topic.
9
+ *
10
+ * What a throwing onError throws is dropped too; it would otherwise escape into an MQTT.js event or
11
+ * a subscriber's delivery.
7
12
  */
8
- export const createReporter =
9
- (onError = () => undefined) =>
10
- (error, context) => {
11
- try {
13
+ export const createReporter = (onError = () => undefined) =>
14
+ R.tryCatch(
15
+ (error, context) => {
12
16
  onError(error, context);
13
- } catch {
14
- // A throwing onError would otherwise escape into an MQTT.js event or a subscriber's delivery.
15
- }
16
- };
17
+ },
18
+ () => undefined,
19
+ );
20
+
21
+ /**
22
+ * Where a client keeps its reporter for the parts built on top of it, such as datasets. A symbol
23
+ * keeps it out of the client's public, enumerable API.
24
+ */
25
+ export const REPORTER = Symbol('faybl.reporter');
26
+
27
+ // The reporter of a client, or one that drops everything for a client without one.
28
+ export const reporterOf = (client) => client?.[REPORTER] ?? (() => undefined);
package/src/session.js CHANGED
@@ -1,37 +1,35 @@
1
+ import { createSubscribers } from './subscribers.js';
2
+
1
3
  /**
2
4
  * Follows whether the caller's login is still accepted. A request refused with 401 marks the
3
5
  * session expired: it is reported to `onError` as `session` once, and subscribers get
4
6
  * `{ expired: true }`. The next request that succeeds marks it alive again. However many calls
5
- * were in flight, one expiry is one report and one change.
7
+ * were in flight, one expiry is one report and one change. A subscriber that throws is reported
8
+ * as `subscriber` and changes nothing for the request that told the session.
6
9
  */
7
10
  export const createSession = (report = () => undefined) => {
8
- /* eslint-disable functional/no-let -- The session's state and its subscribers outlive the independent requests and subscribe calls that change them; each change replaces the value. */
11
+ const subscribers = createSubscribers(report);
12
+ // eslint-disable-next-line functional/no-let -- The session's state outlives the independent requests that change it; each change replaces the value.
9
13
  let expired = false;
10
- let callbacks = [];
11
- /* eslint-enable functional/no-let */
12
-
13
- const notify = () => callbacks.forEach((callback) => callback({ expired }));
14
14
 
15
15
  const lost = (error) => {
16
16
  if (expired) return;
17
17
  expired = true;
18
18
  report(error, { source: 'session' });
19
- notify();
19
+ subscribers.notify({ expired });
20
20
  };
21
21
 
22
22
  const confirmed = () => {
23
23
  if (!expired) return;
24
24
  expired = false;
25
- notify();
25
+ subscribers.notify({ expired });
26
26
  };
27
27
 
28
28
  // Calls back at once with the current state, and again whenever it changes.
29
29
  const subscribe = (callback) => {
30
- callbacks = [...callbacks, callback];
31
- callback({ expired });
32
- return () => {
33
- callbacks = callbacks.filter((subscribed) => subscribed !== callback);
34
- };
30
+ const undo = subscribers.add(callback);
31
+ subscribers.deliver(callback, { expired });
32
+ return undo;
35
33
  };
36
34
 
37
35
  return { lost, confirmed, subscribe };
@@ -0,0 +1,39 @@
1
+ import { tryCatchAsync } from '@faybl/utils';
2
+
3
+ /**
4
+ * Calls `callback(value)` at once and keeps what it throws or rejects with from the caller: it is
5
+ * reported as `subscriber`, so one failing subscriber neither stops the others nor breaks whatever
6
+ * delivered the value.
7
+ */
8
+ export const deliverSafely = (report) =>
9
+ tryCatchAsync(async (callback, value) => {
10
+ await callback(value);
11
+ })((error) => report(error, { source: 'subscriber' }));
12
+
13
+ /**
14
+ * The callbacks subscribed to one source of values. Each subscription is its own entry, so its undo
15
+ * removes it alone even when the same callback is subscribed twice. `notify` delivers to every
16
+ * callback in subscription order, each isolated as `deliverSafely` describes.
17
+ */
18
+ export const createSubscribers = (report) => {
19
+ const deliver = deliverSafely(report);
20
+ // eslint-disable-next-line functional/no-let -- The subscriptions outlive the independent subscribe, undo and notify calls; each change replaces the array, so a delivery in progress is never altered.
21
+ let entries = [];
22
+
23
+ const add = (callback) => {
24
+ const entry = { callback };
25
+ entries = [...entries, entry];
26
+ return () => {
27
+ entries = entries.filter((candidate) => candidate !== entry);
28
+ };
29
+ };
30
+
31
+ // Without a callback, every subscription goes.
32
+ const remove = (callback) => {
33
+ entries = callback === undefined ? [] : entries.filter((entry) => entry.callback !== callback);
34
+ };
35
+
36
+ const notify = (value) => entries.forEach(({ callback }) => deliver(callback, value));
37
+
38
+ return { add, remove, notify, deliver };
39
+ };
@@ -1,3 +1,5 @@
1
+ import { describeValue } from './guards.js';
2
+
1
3
  const wildcards = ['+', '#'];
2
4
 
3
5
  const invalidReasons = [
@@ -11,8 +13,6 @@ const invalidReasons = [
11
13
  [(value) => value.startsWith('$'), "must not start with '$', which the broker reserves"],
12
14
  ];
13
15
 
14
- const describeValue = (value) => JSON.stringify(value) ?? String(value);
15
-
16
16
  const invalidReasonFor = (value) => {
17
17
  const [, reason] = invalidReasons.find(([isInvalid]) => isInvalid(value)) ?? [];
18
18
  return reason;