@faybl/client 4.1.4 → 4.3.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/README.md CHANGED
@@ -20,7 +20,8 @@ const unsubscribe = client.channel.subscribe(ovens[0].channels.temperature, ({ d
20
20
  Resolves with a client once its MQTT connection is set up; the connection itself completes in the
21
21
  background, which [`connection`](#connection) follows. Rejects when the options name neither a
22
22
  valid tenant nor the endpoints needed to connect, when `onError` is not a function, or when the MQTT credentials
23
- cannot be fetched.
23
+ are refused. While their source does not answer, or answers with a 5xx, it waits for them and tries
24
+ again every `reconnectPeriod`, reporting each failure as `credentials`.
24
25
 
25
26
  | Option | Meaning |
26
27
  | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -28,7 +29,7 @@ cannot be fetched.
28
29
  | `confUrl`, `dataHistoryUrl`, `authenticatorUrl`, `mqttUrl` | Override one endpoint. Without a `tenantUrl`, only `mqttUrl` and, when the authenticator hands out the MQTT credentials, `authenticatorUrl` are required; a call that needs an endpoint left out rejects. |
29
30
  | `noMqtt` | Do not connect to MQTT. The bus-facing methods then throw `MQTT is disabled`, and datasets do not load. |
30
31
  | `noAuth` | Connect to MQTT without credentials. Without it the client never connects anonymously. |
31
- | `onError(error, { source, topic })` | Receives what goes wrong after `createClient` has resolved. See [Errors](#errors). |
32
+ | `onError(error, { source, topic })` | Receives what goes wrong where no caller is waiting, from the first credentials on. See [Errors](#errors). |
32
33
  | `authConfig` (Node) | `{ issuerUrl, clientId, clientSecret }` authenticates with the OIDC client credentials grant. With only `clientId`, see below. |
33
34
  | `useWebsocket` (Node) | Connect to MQTT over WebSocket instead of MQTTS. |
34
35
 
@@ -56,14 +57,14 @@ The client writes nothing to the console. What fails where no caller is waiting
56
57
  and is dropped without one. `source` says where it came from, and `topic` is set when one is
57
58
  involved:
58
59
 
59
- | `source` | What failed |
60
- | ------------- | ----------------------------------------------------------------------------------- |
61
- | `mqtt` | The MQTT connection: a refused connection, a keepalive timeout, a missing CONNACK. |
62
- | `session` | A request was refused with 401: the login session is gone. Once until one succeeds. |
63
- | `credentials` | Fetching MQTT credentials. The client connects with what it has and tries again. |
64
- | `message` | A message that is not JSON. An empty message clears a retained one and is not this. |
65
- | `subscriber` | A subscription's callback threw or rejected. The other subscribers still get it. |
66
- | `procedure` | A request whose request id is not a single topic level. It gets no reply. |
60
+ | `source` | What failed |
61
+ | ------------- | --------------------------------------------------------------------------------------------------------- |
62
+ | `mqtt` | The MQTT connection: a refused connection, a keepalive timeout, a missing CONNACK. |
63
+ | `session` | A request was refused with 401: the login session is gone. Once until one succeeds. |
64
+ | `credentials` | Fetching MQTT credentials. At start the client waits; later it connects with what it has and tries again. |
65
+ | `message` | A message that is not JSON. An empty message clears a retained one and is not this. |
66
+ | `subscriber` | A subscription's callback threw or rejected. The other subscribers still get it. |
67
+ | `procedure` | A request whose request id is not a single topic level. It gets no reply. |
67
68
 
68
69
  An HTTP call that gets anything but a 2xx rejects with `Request failed: <status> <statusText>`,
69
70
  and the error carries `response: { status, statusText, body }`, with the JSON body the service
@@ -225,7 +226,8 @@ broker refuses the subscription. Changes published while the connection is down
225
226
 
226
227
  `createDataset(client, spec)` returns:
227
228
 
228
- - `init()`, which resolves once loaded, or rejects with the error that stopped it.
229
+ - `init()`, which resolves once loaded, or rejects with the error that stopped it. Called again
230
+ after a rejection, it loads again.
229
231
  - `getRecords()`.
230
232
  - `subscribe(callback)` and `unsubscribe(callback)`, without a callback removing them all. A
231
233
  callback gets `{ type, rid, record, previous }` after the records have changed, with `type`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faybl/client",
3
- "version": "4.1.4",
3
+ "version": "4.3.0",
4
4
  "description": "Faybl JavaScript Client",
5
5
  "license": "MIT",
6
6
  "author": "Arcturitech",
@@ -38,6 +38,7 @@
38
38
  },
39
39
  "sideEffects": false,
40
40
  "dependencies": {
41
+ "@faybl/utils": "^2.3.0",
41
42
  "@paralleldrive/cuid2": "^3.3.0",
42
43
  "mqtt": "^5.16.1",
43
44
  "mqtt-match": "^3.0.0",
package/src/dataset.js CHANGED
@@ -170,8 +170,10 @@ export const createDataset = (client, spec) => {
170
170
  const machine = createActor(createDatasetMachine(client, spec, notify));
171
171
  return {
172
172
  machine,
173
+ // After a failed load, init starts it over, so it can be called until it resolves.
173
174
  init: async () => {
174
- machine.start();
175
+ if (machine.getSnapshot().matches('Error')) machine.send({ type: 'retry' });
176
+ else machine.start();
175
177
  await datasetLoaded(machine);
176
178
  },
177
179
  subscribe: (callback) => {
package/src/mqtt.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import mqtt from 'mqtt';
2
+ import { waitFor } from '@faybl/utils';
2
3
 
3
4
  import { createMqttHandler } from './mqttUtils.js';
4
5
  import { getMqttCredentials } from './mqttCredentials.js';
@@ -55,6 +56,22 @@ const refreshCredentialsOnConnect = (client, credentialsSource) => {
55
56
  /* eslint-enable functional/immutable-data */
56
57
  };
57
58
 
59
+ // 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.
61
+ const isUnavailable = (error) => {
62
+ const status = error?.response?.status ?? error?.status;
63
+ return status === undefined || status >= 500;
64
+ };
65
+
66
+ // The first credentials are waited for, so a client created while the authenticator or
67
+ // the identity provider is still coming up connects once it is there.
68
+ const waitForCredentials = (credentialsSource, interval) =>
69
+ waitFor(() => getMqttCredentials(credentialsSource), {
70
+ interval,
71
+ retryIf: isUnavailable,
72
+ onRetry: (error) => credentialsSource.report(error, { source: 'credentials' }),
73
+ });
74
+
58
75
  export const createMqttClient = async ({
59
76
  mqttUrl,
60
77
  authenticatorUrl,
@@ -66,10 +83,12 @@ export const createMqttClient = async ({
66
83
  session,
67
84
  }) => {
68
85
  const credentialsSource = { authenticatorUrl, oidcHandler, authConfig, report, session };
86
+ const connectionOptions = { ...baseMqttOptions, ...mqttOptions };
69
87
  const options = {
70
- ...baseMqttOptions,
71
- ...mqttOptions,
72
- ...(noAuth ? {} : await getMqttCredentials(credentialsSource)),
88
+ ...connectionOptions,
89
+ ...(noAuth
90
+ ? {}
91
+ : await waitForCredentials(credentialsSource, connectionOptions.reconnectPeriod)),
73
92
  clientId: `fayblClient_${Math.random().toString(16).slice(2, 12)}`,
74
93
  };
75
94