@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,39 +1,178 @@
1
+ import { Err, Ok } from '@faybl/utils';
2
+
3
+ import { describeValue, isNonEmptyString, isPlainObject } from './guards.js';
4
+
1
5
  // A host name with an optional port: every service URL is built by prefixing a
2
6
  // scheme or a subdomain, so a scheme or a path in it would produce a broken URL.
3
7
  const TENANT_HOST = /^[^\s/:]+(:\d+)?$/;
4
8
 
5
- // A service's URL under the tenant, or undefined without one.
6
- export const tenantServiceUrl = (tenantUrl, path) =>
7
- tenantUrl === undefined ? undefined : `https://${tenantUrl}${path}`;
9
+ const HTTP_SCHEMES = ['http:', 'https:'];
10
+ // A browser reaches a broker over WebSocket only.
11
+ const BROWSER_MQTT_SCHEMES = ['ws:', 'wss:'];
12
+ // Every scheme MQTT.js connects over in Node.
13
+ const MQTT_SCHEMES = [
14
+ 'mqtt:',
15
+ 'mqtts:',
16
+ 'tcp:',
17
+ 'ssl:',
18
+ 'tls:',
19
+ 'ws:',
20
+ 'wss:',
21
+ 'wx:',
22
+ 'wxs:',
23
+ 'ali:',
24
+ 'alis:',
25
+ ];
26
+ const HTTP_ENDPOINTS = ['confUrl', 'dataHistoryUrl', 'authenticatorUrl'];
27
+ const FLAGS = ['noMqtt', 'noAuth', 'useWebsocket'];
28
+
29
+ const invalid = (name, value, rule) =>
30
+ Error(`Invalid ${name} ${describeValue(value)}: it must be ${rule}`);
31
+
32
+ const hasScheme = (schemes) => (value) =>
33
+ URL.canParse(value) && schemes.includes(new URL(value).protocol);
34
+ // A path on the page's own origin, as a browser app behind the tenant's proxy may use. Node has
35
+ // no origin to resolve it against.
36
+ const isOriginPath = (value) => value.startsWith('/') && !value.startsWith('//');
37
+
38
+ const isHttpUrl = (value) => isNonEmptyString(value) && hasScheme(HTTP_SCHEMES)(value);
39
+ const isBrowserHttpEndpoint = (value) =>
40
+ isNonEmptyString(value) && (isOriginPath(value) || hasScheme(HTTP_SCHEMES)(value));
41
+
42
+ const withoutTrailingSlashes = (url) => url.replace(/\/+$/, '');
43
+
44
+ // The first rule an option breaks, as the Error createClient rejects with.
45
+ const firstError = (checks) => checks.map((check) => check()).find(Boolean);
46
+
47
+ // An option that may be left out, but must follow `rule` when given.
48
+ const optional = (isValid, rule) => (name, value) =>
49
+ value === undefined || isValid(value) ? undefined : invalid(name, value, rule);
50
+
51
+ const tenantUrlError = optional(
52
+ (value) => typeof value === 'string' && TENANT_HOST.test(value),
53
+ "a host name such as 'tenant.faybl.online', without scheme or path",
54
+ );
55
+ const mqttEndpointRule = (schemes) =>
56
+ optional(
57
+ (value) => isNonEmptyString(value) && hasScheme(schemes)(value),
58
+ `a URL with one of the schemes ${schemes.join(' ')}`,
59
+ );
60
+
61
+ // What an endpoint may be where the client runs: a browser resolves paths against the page.
62
+ const endpointRules = (browser) => ({
63
+ http: browser
64
+ ? optional(isBrowserHttpEndpoint, 'an http(s) URL or a path such as /conf')
65
+ : optional(isHttpUrl, 'an http(s) URL'),
66
+ mqtt: mqttEndpointRule(browser ? BROWSER_MQTT_SCHEMES : MQTT_SCHEMES),
67
+ });
68
+ const flagError = optional((value) => typeof value === 'boolean', 'a boolean');
69
+ const nonEmptyStringError = optional(isNonEmptyString, 'a non-empty string');
70
+ const issuerUrlError = optional(isHttpUrl, 'an http(s) URL');
71
+
72
+ const endpointErrors = (rules, options) => [
73
+ ...HTTP_ENDPOINTS.map((name) => () => rules.http(name, options[name])),
74
+ () => rules.mqtt('mqttUrl', options.mqttUrl),
75
+ ];
76
+
77
+ const flagErrors = (options) => FLAGS.map((name) => () => flagError(name, options[name]));
78
+
79
+ // A service's client credentials. With an issuerUrl the client authenticates itself, so it needs
80
+ // its secret; without one, clientId only names the identity the authenticator issues MQTT
81
+ // credentials for.
82
+ const authConfigError = (authConfig) => {
83
+ if (authConfig === undefined) return undefined;
84
+ if (!isPlainObject(authConfig)) return invalid('authConfig', authConfig, 'an object');
85
+ const { issuerUrl, clientId, clientSecret } = authConfig;
86
+ return firstError([
87
+ () => issuerUrlError('authConfig.issuerUrl', issuerUrl),
88
+ () => nonEmptyStringError('authConfig.clientId', clientId),
89
+ () =>
90
+ issuerUrl !== undefined && !isNonEmptyString(clientId)
91
+ ? Error('Invalid authConfig: an issuerUrl needs a clientId')
92
+ : undefined,
93
+ () =>
94
+ issuerUrl !== undefined && !isNonEmptyString(clientSecret)
95
+ ? Error('Invalid authConfig: an issuerUrl needs a clientSecret')
96
+ : undefined,
97
+ ]);
98
+ };
8
99
 
9
- const tenantUrlError = (tenantUrl) =>
10
- typeof tenantUrl === 'string' && TENANT_HOST.test(tenantUrl)
100
+ const onErrorError = ({ onError }) =>
101
+ onError === undefined || typeof onError === 'function'
11
102
  ? undefined
12
- : Error(
13
- `Invalid tenantUrl ${JSON.stringify(tenantUrl)}: it must be a host name such as 'tenant.faybl.online', without scheme or path`,
14
- );
103
+ : Error('Invalid onError: it must be a function');
104
+
105
+ const tenantEndpoints = (tenantUrl) =>
106
+ tenantUrl === undefined
107
+ ? {}
108
+ : {
109
+ confUrl: `https://${tenantUrl}/conf`,
110
+ dataHistoryUrl: `https://${tenantUrl}/data-history`,
111
+ authenticatorUrl: `https://${tenantUrl}/authenticator`,
112
+ };
113
+
114
+ const definedEntries = (record) =>
115
+ Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
116
+
117
+ // Every endpoint the tenant implies, overridden by the ones given, without trailing slashes.
118
+ const resolveEndpoints = (defaultMqttUrl, options) => {
119
+ const { tenantUrl, useWebsocket } = options;
120
+ const given = definedEntries({
121
+ confUrl: options.confUrl,
122
+ dataHistoryUrl: options.dataHistoryUrl,
123
+ authenticatorUrl: options.authenticatorUrl,
124
+ mqttUrl: options.mqttUrl,
125
+ });
126
+ const resolved = {
127
+ ...tenantEndpoints(tenantUrl),
128
+ ...(tenantUrl === undefined ? {} : { mqttUrl: defaultMqttUrl({ tenantUrl, useWebsocket }) }),
129
+ ...given,
130
+ };
131
+ return Object.fromEntries(
132
+ Object.entries(resolved).map(([name, url]) => [name, withoutTrailingSlashes(url)]),
133
+ );
134
+ };
15
135
 
16
136
  // Only what connecting needs is required up front: the broker, and the authenticator when it hands
17
137
  // out the MQTT credentials. Any other endpoint left out fails only the calls that use it, so a
18
138
  // service names the endpoints it talks to and no others.
19
- const requiredEndpoints = ({ noMqtt, noAuth, authConfig }) =>
20
- noMqtt ? [] : ['mqttUrl', ...(noAuth || authConfig?.issuerUrl ? [] : ['authenticatorUrl'])];
21
-
22
- const endpointsError = (options) => {
23
- if (options.tenantUrl !== undefined) return tenantUrlError(options.tenantUrl);
24
- const missing = requiredEndpoints(options).filter((name) => !options[name]);
139
+ const missingEndpointsError = (endpoints, { noMqtt, noAuth, authConfig }) => {
140
+ const required = noMqtt
141
+ ? []
142
+ : ['mqttUrl', ...(noAuth || authConfig?.issuerUrl ? [] : ['authenticatorUrl'])];
143
+ const missing = required.filter((name) => endpoints[name] === undefined);
25
144
  return missing.length === 0
26
145
  ? undefined
27
146
  : Error(`createClient needs a tenantUrl, or else ${missing.join(', ')}`);
28
147
  };
29
148
 
30
- const onErrorError = ({ onError }) =>
31
- onError === undefined || typeof onError === 'function'
32
- ? undefined
33
- : Error('Invalid onError: it must be a function');
34
-
35
149
  /**
36
- * Returns the Error createClient rejects with, or undefined when the options name either a tenant
37
- * or the endpoints the client needs to connect.
150
+ * Parses `createClient`'s options once, at the edge, into what the client is composed from: every
151
+ * endpoint resolved and normalized, and only the options this entry point supports. `browser` says
152
+ * the client runs in a page: endpoints may then be paths on its origin, the broker is reached over
153
+ * WebSocket, and `authConfig` is ignored, as there is no client credentials grant.
154
+ * `defaultMqttUrl({ tenantUrl, useWebsocket })` is the entry point's broker URL for a tenant.
155
+ *
156
+ * Resolves to `Ok(config)`, or `Err(error)` with the Error createClient rejects with.
38
157
  */
39
- export const clientOptionsError = (options) => onErrorError(options) ?? endpointsError(options);
158
+ export const parseClientOptions =
159
+ ({ browser, defaultMqttUrl }) =>
160
+ (options) => {
161
+ const rules = endpointRules(browser);
162
+ if (!isPlainObject(options)) return Err(Error('createClient options must be an object'));
163
+ const { noMqtt = false, noAuth = false, onError } = options;
164
+ const authConfig = browser ? undefined : options.authConfig;
165
+ const shapeError = firstError([
166
+ () => onErrorError(options),
167
+ () => tenantUrlError('tenantUrl', options.tenantUrl),
168
+ ...endpointErrors(rules, options),
169
+ ...flagErrors(options),
170
+ () => authConfigError(authConfig),
171
+ ]);
172
+ if (shapeError) return Err(shapeError);
173
+ const endpoints = resolveEndpoints(defaultMqttUrl, options);
174
+ const missingError = missingEndpointsError(endpoints, { noMqtt, noAuth, authConfig });
175
+ return missingError
176
+ ? Err(missingError)
177
+ : Ok({ endpoints, noMqtt, noAuth, authConfig, onError });
178
+ };
package/src/conf.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as R from 'ramda';
2
2
 
3
- import { mqttDisabledWarning } from './mqttUtils.js';
3
+ import { mqttDisabled } from './mqttUtils.js';
4
4
  import { fetchCheckedJson, missingEndpoint } from './fetch.js';
5
5
  import { assertTopicSegment, assertTopicSegmentOneOf } from './topicSegment.js';
6
6
 
@@ -38,17 +38,17 @@ const getConfTopic = (entity, operation, rid) =>
38
38
  `conf/${entityPart(entity)}/${operationPart(operation)}/${ridPart(rid)}`;
39
39
 
40
40
  export const getConfApi = (confUrl, mqttClient, http) => {
41
- const crudEntity = (entityClass, operation) => (args) => {
42
- if (!confUrl) return missingEndpoint('confUrl');
43
- return fetchCheckedJson(
44
- `${confUrl}/${entityClass}/${operation}`,
45
- {
46
- body: JSON.stringify(args),
47
- method: 'POST',
48
- },
49
- http,
50
- );
51
- };
41
+ // `signal` cancels the request.
42
+ const crudEntity =
43
+ (entityClass, operation) =>
44
+ (args, { signal } = {}) => {
45
+ if (!confUrl) return missingEndpoint('confUrl');
46
+ return fetchCheckedJson(
47
+ `${confUrl}/${entityClass}/${operation}`,
48
+ { body: JSON.stringify(args), method: 'POST', signal },
49
+ http,
50
+ );
51
+ };
52
52
 
53
53
  const entityApi = (entityClass) =>
54
54
  R.fromPairs(
@@ -75,9 +75,9 @@ export const getConfApi = (confUrl, mqttClient, http) => {
75
75
  };
76
76
 
77
77
  return {
78
- subscribe: mqttClient ? subscribeConf : mqttDisabledWarning,
79
- subscribeWithAck: mqttClient ? subscribeConfWithAck : mqttDisabledWarning,
80
- unsubscribe: mqttClient ? unsubscribeConf : mqttDisabledWarning,
78
+ subscribe: mqttClient ? subscribeConf : mqttDisabled,
79
+ subscribeWithAck: mqttClient ? subscribeConfWithAck : mqttDisabled,
80
+ unsubscribe: mqttClient ? unsubscribeConf : mqttDisabled,
81
81
  ...confApi,
82
82
  };
83
83
  };
package/src/connection.js CHANGED
@@ -1,13 +1,16 @@
1
- import { mqttDisabledWarning } from './mqttUtils.js';
1
+ import { mqttDisabled } from './mqttUtils.js';
2
+ import { deliverSafely } from './subscribers.js';
2
3
 
3
4
  const CONNECTED_BY_EVENT = { connect: true, offline: false, close: false };
4
5
  const EVENTS = Object.keys(CONNECTED_BY_EVENT);
5
6
 
6
7
  /**
7
8
  * Follows the MQTT connection. The callback gets `{ connected }` at once with the current state, and
8
- * again whenever it changes; the repeated `close` events of a reconnect loop are not passed on.
9
+ * again whenever it changes; the repeated `close` events of a reconnect loop are not passed on. A
10
+ * callback that throws is reported as `subscriber`, and never reaches MQTT.js's event emitter.
9
11
  */
10
- export const getConnectionApi = (mqttClient) => {
12
+ export const getConnectionApi = (mqttClient, report = () => undefined) => {
13
+ const deliver = deliverSafely(report);
11
14
  const subscribe = (callback) => {
12
15
  const { client } = mqttClient;
13
16
  // eslint-disable-next-line functional/no-let -- Each subscription remembers what it last passed on, across events MQTT.js emits independently.
@@ -17,13 +20,13 @@ export const getConnectionApi = (mqttClient) => {
17
20
  () => {
18
21
  if (CONNECTED_BY_EVENT[event] === connected) return;
19
22
  connected = CONNECTED_BY_EVENT[event];
20
- callback({ connected });
23
+ deliver(callback, { connected });
21
24
  },
22
25
  ]);
23
26
  listeners.forEach(([event, listener]) => client.on(event, listener));
24
- callback({ connected });
27
+ deliver(callback, { connected });
25
28
  return () => listeners.forEach(([event, listener]) => client.off(event, listener));
26
29
  };
27
30
 
28
- return { subscribe: mqttClient ? subscribe : mqttDisabledWarning };
31
+ return { subscribe: mqttClient ? subscribe : mqttDisabled };
29
32
  };
@@ -0,0 +1,137 @@
1
+ import { fromCallback, fromPromise, setup } from 'xstate';
2
+
3
+ const BROKER_EVENTS = { connect: 'broker.connected', close: 'broker.closed', end: 'broker.ended' };
4
+
5
+ // MQTT.js events as machine events. A client that is already connected when the machine starts
6
+ // emits no `connect`, so it is reported at once.
7
+ const brokerActor = (client) =>
8
+ fromCallback(({ sendBack }) => {
9
+ const listeners = Object.entries(BROKER_EVENTS).map(([event, type]) => [
10
+ event,
11
+ () => sendBack({ type }),
12
+ ]);
13
+ listeners.forEach(([event, listener]) => client.on(event, listener));
14
+ if (client.connected) sendBack({ type: 'broker.connected' });
15
+ return () => listeners.forEach(([event, listener]) => client.off(event, listener));
16
+ });
17
+
18
+ /**
19
+ * The MQTT connection's lifecycle once its client exists. MQTT.js does not reconnect by itself
20
+ * (`reconnectPeriod: 0`); this machine does, so fresh credentials are fetched before each attempt.
21
+ *
22
+ * A dropped connection waits `reconnectPeriod`, fetches credentials, and reconnects with them; a
23
+ * failed fetch is reported and the attempt made with the credentials it had, so the broker decides.
24
+ * A refused login waits for the next period instead of connecting. Closing at any point cancels
25
+ * the fetch, so a client closed meanwhile is never opened again. Every connect resubscribes,
26
+ * the first one included: a clean session leaves the broker with none of the client's
27
+ * subscriptions, and the handler sends none while the connection is down.
28
+ *
29
+ * `fetchCredentials(signal)` resolves with a Result: `Ok({ username, password })`, or `Err` whose
30
+ * `kind` is `SessionLost` for a refused login, anything else for a failed fetch.
31
+ */
32
+ export const createConnectionMachine = ({
33
+ client,
34
+ fetchCredentials,
35
+ resubscribe,
36
+ close,
37
+ report,
38
+ reconnectPeriod,
39
+ }) =>
40
+ setup({
41
+ actors: {
42
+ broker: brokerActor(client),
43
+ fetchCredentials: fromPromise(async ({ signal }) => fetchCredentials(signal)),
44
+ close: fromPromise(close),
45
+ },
46
+ actions: {
47
+ // eslint-disable-next-line functional/immutable-data -- MQTT.js reads the credentials for its CONNECT from the client's own mutable options; there is no other way in.
48
+ applyCredentials: (_, credentials) => Object.assign(client.options, credentials),
49
+ reportCredentials: (_, { cause }) => report(cause, { source: 'credentials' }),
50
+ // Without the stores MQTT.js starts with empty ones: QoS 1 publishes still in flight or
51
+ // queued while offline would be dropped and their callbacks never called.
52
+ reconnect: () =>
53
+ client.reconnect({
54
+ incomingStore: client.incomingStore,
55
+ outgoingStore: client.outgoingStore,
56
+ }),
57
+ resubscribe: () => resubscribe(),
58
+ reportCloseFailure: ({ event: { error } }) => report(error, { source: 'mqtt' }),
59
+ },
60
+ guards: {
61
+ isGranted: ({ event: { output } }) => output.ok,
62
+ isSessionLost: ({ event: { output } }) => output.error?.kind === 'SessionLost',
63
+ isReconnectDisabled: () => !(reconnectPeriod > 0),
64
+ },
65
+ delays: { RECONNECT_DELAY: () => reconnectPeriod },
66
+ }).createMachine({
67
+ id: 'connection',
68
+ initial: 'Live',
69
+ states: {
70
+ Live: {
71
+ invoke: { src: 'broker' },
72
+ initial: 'Connecting',
73
+ on: { 'connection.close': 'Closing', 'broker.ended': 'Closed' },
74
+ states: {
75
+ Connecting: {
76
+ tags: ['connecting'],
77
+ on: { 'broker.connected': 'Connected', 'broker.closed': 'Waiting' },
78
+ },
79
+ Connected: {
80
+ tags: ['connected'],
81
+ entry: 'resubscribe',
82
+ on: { 'broker.closed': 'Waiting' },
83
+ },
84
+ Waiting: {
85
+ tags: ['reconnecting'],
86
+ always: { guard: 'isReconnectDisabled', target: 'Disconnected' },
87
+ after: { RECONNECT_DELAY: 'Authorizing' },
88
+ },
89
+ Authorizing: {
90
+ tags: ['reconnecting'],
91
+ invoke: {
92
+ src: 'fetchCredentials',
93
+ onDone: [
94
+ {
95
+ guard: 'isGranted',
96
+ target: 'Reconnecting',
97
+ actions: {
98
+ type: 'applyCredentials',
99
+ params: ({ event: { output } }) => output.value,
100
+ },
101
+ },
102
+ { guard: 'isSessionLost', target: 'SessionExpired' },
103
+ {
104
+ target: 'Reconnecting',
105
+ actions: {
106
+ type: 'reportCredentials',
107
+ params: ({ event: { output } }) => output.error,
108
+ },
109
+ },
110
+ ],
111
+ },
112
+ },
113
+ Reconnecting: {
114
+ tags: ['reconnecting'],
115
+ entry: 'reconnect',
116
+ on: {
117
+ 'broker.connected': 'Connected',
118
+ 'broker.closed': 'Waiting',
119
+ },
120
+ },
121
+ SessionExpired: {
122
+ tags: ['expired'],
123
+ after: { RECONNECT_DELAY: 'Authorizing' },
124
+ },
125
+ Disconnected: { tags: ['disconnected'] },
126
+ },
127
+ },
128
+ Closing: {
129
+ invoke: {
130
+ src: 'close',
131
+ onDone: 'Closed',
132
+ onError: { target: 'Closed', actions: 'reportCloseFailure' },
133
+ },
134
+ },
135
+ Closed: { type: 'final' },
136
+ },
137
+ });
package/src/dataset.js CHANGED
@@ -2,16 +2,28 @@ import * as R from 'ramda';
2
2
  import {
3
3
  assign,
4
4
  createActor,
5
- createMachine,
6
5
  enqueueActions,
7
6
  fromCallback,
8
7
  fromPromise,
8
+ setup,
9
9
  spawnChild,
10
10
  stopChild,
11
11
  waitFor,
12
12
  } from 'xstate';
13
13
 
14
14
  import { applyChange, compileFilter, createRecordMatcher, projectWith } from './datasetRecords.js';
15
+ import { isPlainObject } from './guards.js';
16
+ import { reporterOf } from './report.js';
17
+ import { createSubscribers } from './subscribers.js';
18
+ import { Err, Ok, map, match, tryCatchAsync } from '@faybl/utils';
19
+
20
+ /**
21
+ * @typedef {{ type: 'subscribed' }} SubscribedEvent
22
+ * @typedef {{ type: 'subscription.failed', error: Error }} SubscriptionFailedEvent
23
+ * @typedef {{ type: 'change', operation: string, rid: string, record: object }} ChangeEvent
24
+ * @typedef {{ type: 'retry' }} RetryEvent
25
+ * @typedef {SubscribedEvent | SubscriptionFailedEvent | ChangeEvent | RetryEvent} DatasetEvent
26
+ */
15
27
 
16
28
  const SUBSCRIPTION_ID = 'subscription';
17
29
 
@@ -19,31 +31,38 @@ const SUBSCRIPTION_ID = 'subscription';
19
31
  // made while the dataset reads is held rather than lost.
20
32
  const subscriptionActor = (client, entity) =>
21
33
  fromCallback(({ sendBack }) => {
22
- try {
23
- const { ready, unsubscribe } = client.conf.subscribeWithAck({
24
- entity,
25
- callback: ({ operation, rid, record }) =>
26
- sendBack({ type: 'change', operation, rid, record }),
27
- });
28
- const whenReady = async () => {
29
- try {
30
- await ready;
31
- sendBack({ type: 'subscribed' });
32
- } catch (error) {
33
- sendBack({ type: 'subscription.failed', error });
34
- }
35
- };
36
- whenReady();
37
- return unsubscribe;
38
- } catch (error) {
39
- sendBack({ type: 'subscription.failed', error });
40
- return undefined;
41
- }
34
+ const failed = (error) => sendBack({ type: 'subscription.failed', error });
35
+ const whenReady = tryCatchAsync(async (ready) => {
36
+ await ready;
37
+ sendBack({ type: 'subscribed' });
38
+ })(failed);
39
+ return R.tryCatch(
40
+ () => {
41
+ const { ready, unsubscribe } = client.conf.subscribeWithAck({
42
+ entity,
43
+ callback: ({ operation, rid, record }) =>
44
+ sendBack({ type: 'change', operation, rid, record }),
45
+ });
46
+ whenReady(ready);
47
+ return unsubscribe;
48
+ },
49
+ (error) => {
50
+ failed(error);
51
+ return undefined;
52
+ },
53
+ )();
42
54
  });
43
55
 
56
+ // What conf answers a read with comes from another service: a list of records, or a failure.
57
+ const parseRecords = (records) =>
58
+ Array.isArray(records) && records.every(isPlainObject)
59
+ ? Ok(records)
60
+ : Err(Error('Conf answered the dataset read with something other than a list of records'));
61
+
44
62
  /**
45
63
  * `Init` subscribes, waits for the acknowledgement, then reads. Changes that arrive meanwhile are
46
- * held and applied on top of what was read, and only then is the dataset `Idle`.
64
+ * held and applied on top of what was read, and only then is the dataset `Idle`. Leaving `Loading`
65
+ * cancels the read.
47
66
  */
48
67
  const machineConfig = {
49
68
  id: 'dataset',
@@ -57,7 +76,7 @@ const machineConfig = {
57
76
  states: {
58
77
  Checking: {
59
78
  always: [
60
- { guard: 'hasInvalidFilter', target: '#dataset.Error', actions: 'setFilterError' },
79
+ { guard: 'hasInvalidSpec', target: '#dataset.Error', actions: 'setSpecError' },
61
80
  { target: 'Subscribing' },
62
81
  ],
63
82
  },
@@ -71,7 +90,10 @@ const machineConfig = {
71
90
  Loading: {
72
91
  invoke: {
73
92
  src: 'fetchRecords',
74
- onDone: { target: '#dataset.Idle', actions: 'setRecords' },
93
+ onDone: [
94
+ { guard: 'isLoaded', target: '#dataset.Idle', actions: 'setRecords' },
95
+ { target: '#dataset.Error', actions: 'setReadError' },
96
+ ],
75
97
  onError: { target: '#dataset.Error', actions: 'setError' },
76
98
  },
77
99
  },
@@ -94,10 +116,17 @@ const readArgsFor = ({ rids, filter, projection, ...rest }) => ({
94
116
  ...(projection ? { projection } : {}),
95
117
  });
96
118
 
119
+ // A spec the dataset cannot follow, found before anything is subscribed: an entity conf does not
120
+ // have, or a filter that cannot be evaluated outside MongoDB.
121
+ const specErrorMessage = (client, entity, compiledFilter) =>
122
+ typeof client.conf?.[entity]?.read === 'function'
123
+ ? match(R.prop('message'))(() => undefined)(compiledFilter)
124
+ : `Invalid dataset entity ${JSON.stringify(entity)}: conf has no such entity`;
125
+
97
126
  /**
98
127
  * A dataset holds the records of one entity that its `rids` and `filter` describe, at start and
99
128
  * after every change conf publishes. `filter` is a MongoDB filter, evaluated on each changed record
100
- * as conf evaluates it on a read. `recordFilter` from earlier versions is ignored.
129
+ * as conf evaluates it on a read. A `recordFilter` in the spec is ignored.
101
130
  */
102
131
  export const createDatasetMachine = (client, spec, onChange = () => undefined) => {
103
132
  const {
@@ -112,41 +141,54 @@ export const createDatasetMachine = (client, spec, onChange = () => undefined) =
112
141
  const readArgs = readArgsFor({ ...rest, rids, filter, projection: readProjection });
113
142
 
114
143
  const compiled = compileFilter(filter);
144
+ const specError = specErrorMessage(client, entity, compiled);
115
145
  const change = applyChange({
116
- matches: compiled.ok ? createRecordMatcher({ rids, test: compiled.value }) : R.F,
146
+ matches: match(() => R.F)((test) => createRecordMatcher({ rids, test }))(compiled),
117
147
  transform: R.pipe(readProjection ? projectWith(readProjection) : R.identity, recordTransform),
118
148
  });
119
149
  const applyAll = (records, changes) =>
120
150
  changes.reduce((current, event) => change(current, event).records, records);
121
151
 
122
- return createMachine(machineConfig, {
152
+ // Every way a read fails, an HTTP failure, an unreachable service or a cancelled request, is the
153
+ // dataset's `Error` outcome.
154
+ const readRecords = tryCatchAsync(async (signal) =>
155
+ parseRecords(await client.conf[entity].read(readArgs, { signal })),
156
+ )((error) => Err(error));
157
+
158
+ return setup({
123
159
  actors: {
124
- fetchRecords: fromPromise(async () => client.conf[entity].read(readArgs)),
160
+ subscription: subscriptionActor(client, entity),
161
+ // recordTransform is the caller's code: what it throws is a defect, which onError takes.
162
+ fetchRecords: fromPromise(async ({ signal }) =>
163
+ map(R.map(recordTransform))(await readRecords(signal)),
164
+ ),
125
165
  },
126
166
  actions: {
127
- subscribe: spawnChild(subscriptionActor(client, entity), { id: SUBSCRIPTION_ID }),
167
+ subscribe: spawnChild('subscription', { id: SUBSCRIPTION_ID }),
128
168
  unsubscribe: stopChild(SUBSCRIPTION_ID),
129
169
  clearRecords: assign({ records: [], held: [] }),
130
- hold: assign({ held: ({ context: { held }, event }) => R.append(event, held) }),
170
+ hold: assign({ held: ({ context: { held }, event }) => [...held, event] }),
131
171
  setError: assign({ error: ({ event: { error } }) => error }),
132
- setFilterError: assign({ error: () => Error(compiled.message) }),
172
+ setReadError: assign({ error: ({ event: { output } }) => output.error }),
173
+ setSpecError: assign({ error: () => Error(specError) }),
133
174
  clearError: assign({ error: undefined }),
134
175
  setRecords: assign({
135
- records: ({ context: { held }, event: { output } }) =>
136
- applyAll(R.map(recordTransform)(output), held),
176
+ records: ({ context: { held }, event: { output } }) => applyAll(output.value, held),
137
177
  held: [],
138
178
  }),
179
+ // Subscribers run after the transition, so getRecords already returns what they are told.
180
+ notifyChange: (_, { notification }) => queueMicrotask(() => onChange(notification)),
139
181
  applyChange: enqueueActions(({ context: { records }, event, enqueue }) => {
140
182
  const { records: next, notification } = change(records, event);
141
183
  enqueue.assign({ records: next });
142
- // Subscribers run after the transition, so getRecords already returns what they are told.
143
- if (notification) enqueue(() => queueMicrotask(() => onChange(notification)));
184
+ if (notification) enqueue({ type: 'notifyChange', params: { notification } });
144
185
  }),
145
186
  },
146
187
  guards: {
147
- hasInvalidFilter: () => !compiled.ok,
188
+ hasInvalidSpec: () => specError !== undefined,
189
+ isLoaded: ({ event: { output } }) => output.ok,
148
190
  },
149
- });
191
+ }).createMachine(machineConfig);
150
192
  };
151
193
 
152
194
  /**
@@ -163,28 +205,32 @@ export const datasetLoaded = async (datasetRef) => {
163
205
  : snapshot.context.records;
164
206
  };
165
207
 
208
+ /**
209
+ * A dataset with its own subscribers. A subscriber that throws is reported to the client's
210
+ * `onError` as `subscriber`, and the others are still told.
211
+ */
166
212
  export const createDataset = (client, spec) => {
167
- // eslint-disable-next-line functional/no-let -- The dataset owns its subscriber list across independent subscribe, unsubscribe and machine events; each change replaces the array, so a list being iterated is never altered.
168
- let callbacks = [];
169
- const notify = (notification) => callbacks.forEach((callback) => callback(notification));
170
- const machine = createActor(createDatasetMachine(client, spec, notify));
213
+ const subscribers = createSubscribers(reporterOf(client));
214
+ const machine = createActor(createDatasetMachine(client, spec, subscribers.notify));
171
215
  return {
172
216
  machine,
173
- // After a failed load, init starts it over, so it can be called until it resolves.
217
+ // After a failed load, init starts it over, so it can be called until it resolves. A stopped
218
+ // dataset no longer follows conf, so it does not pretend to load.
174
219
  init: async () => {
175
- if (machine.getSnapshot().matches('Error')) machine.send({ type: 'retry' });
176
- else machine.start();
220
+ const snapshot = machine.getSnapshot();
221
+ if (snapshot.status === 'stopped') {
222
+ return Promise.reject(Error('The dataset was stopped; create a new one to load again'));
223
+ }
224
+ snapshot.matches('Error') ? machine.send({ type: 'retry' }) : machine.start();
177
225
  await datasetLoaded(machine);
226
+ return undefined;
178
227
  },
179
- subscribe: (callback) => {
180
- callbacks = R.append(callback)(callbacks);
181
- },
182
- unsubscribe: (callback) => {
183
- callbacks = callback ? R.without([callback])(callbacks) : [];
184
- },
228
+ // Returns the function that undoes this subscription.
229
+ subscribe: subscribers.add,
230
+ unsubscribe: subscribers.remove,
185
231
  getRecords: () => machine.getSnapshot().context.records,
186
232
  stop: () => {
187
- callbacks = [];
233
+ subscribers.remove();
188
234
  machine.stop();
189
235
  },
190
236
  };