@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/README.md +46 -35
- package/package.json +17 -11
- package/src/auth.js +3 -2
- package/src/browser.js +11 -32
- package/src/channel.js +8 -12
- package/src/client.js +14 -18
- package/src/clientFactory.js +45 -0
- package/src/clientOptions.js +161 -22
- package/src/conf.js +15 -15
- package/src/connection.js +9 -6
- package/src/connectionMachine.js +137 -0
- package/src/dataset.js +97 -53
- package/src/datasetRecords.js +6 -6
- package/src/fetch.js +9 -9
- package/src/guards.js +9 -0
- package/src/index.js +10 -51
- package/src/mqtt.js +52 -54
- package/src/mqttCredentials.js +22 -16
- package/src/mqttUtils.js +103 -56
- package/src/oidcHandler.js +12 -10
- package/src/presence.js +6 -6
- package/src/procedure.js +68 -30
- package/src/report.js +11 -2
- package/src/session.js +11 -13
- package/src/subscribers.js +39 -0
- package/src/topicSegment.js +2 -2
- package/src/utils/either.js +0 -35
package/src/conf.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as R from 'ramda';
|
|
2
2
|
|
|
3
|
-
import {
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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 :
|
|
79
|
-
subscribeWithAck: mqttClient ? subscribeConfWithAck :
|
|
80
|
-
unsubscribe: mqttClient ? unsubscribeConf :
|
|
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 {
|
|
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
|
|
23
|
+
deliver(callback, { connected });
|
|
21
24
|
},
|
|
22
25
|
]);
|
|
23
26
|
listeners.forEach(([event, listener]) => client.on(event, listener));
|
|
24
|
-
callback
|
|
27
|
+
deliver(callback, { connected });
|
|
25
28
|
return () => listeners.forEach(([event, listener]) => client.off(event, listener));
|
|
26
29
|
};
|
|
27
30
|
|
|
28
|
-
return { subscribe: mqttClient ? subscribe :
|
|
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,17 +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 {
|
|
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
|
+
*/
|
|
16
27
|
|
|
17
28
|
const SUBSCRIPTION_ID = 'subscription';
|
|
18
29
|
|
|
@@ -20,31 +31,38 @@ const SUBSCRIPTION_ID = 'subscription';
|
|
|
20
31
|
// made while the dataset reads is held rather than lost.
|
|
21
32
|
const subscriptionActor = (client, entity) =>
|
|
22
33
|
fromCallback(({ sendBack }) => {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
+
)();
|
|
43
54
|
});
|
|
44
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
|
+
|
|
45
62
|
/**
|
|
46
63
|
* `Init` subscribes, waits for the acknowledgement, then reads. Changes that arrive meanwhile are
|
|
47
|
-
* 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.
|
|
48
66
|
*/
|
|
49
67
|
const machineConfig = {
|
|
50
68
|
id: 'dataset',
|
|
@@ -58,7 +76,7 @@ const machineConfig = {
|
|
|
58
76
|
states: {
|
|
59
77
|
Checking: {
|
|
60
78
|
always: [
|
|
61
|
-
{ guard: '
|
|
79
|
+
{ guard: 'hasInvalidSpec', target: '#dataset.Error', actions: 'setSpecError' },
|
|
62
80
|
{ target: 'Subscribing' },
|
|
63
81
|
],
|
|
64
82
|
},
|
|
@@ -72,7 +90,10 @@ const machineConfig = {
|
|
|
72
90
|
Loading: {
|
|
73
91
|
invoke: {
|
|
74
92
|
src: 'fetchRecords',
|
|
75
|
-
onDone:
|
|
93
|
+
onDone: [
|
|
94
|
+
{ guard: 'isLoaded', target: '#dataset.Idle', actions: 'setRecords' },
|
|
95
|
+
{ target: '#dataset.Error', actions: 'setReadError' },
|
|
96
|
+
],
|
|
76
97
|
onError: { target: '#dataset.Error', actions: 'setError' },
|
|
77
98
|
},
|
|
78
99
|
},
|
|
@@ -95,10 +116,17 @@ const readArgsFor = ({ rids, filter, projection, ...rest }) => ({
|
|
|
95
116
|
...(projection ? { projection } : {}),
|
|
96
117
|
});
|
|
97
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
|
+
|
|
98
126
|
/**
|
|
99
127
|
* A dataset holds the records of one entity that its `rids` and `filter` describe, at start and
|
|
100
128
|
* after every change conf publishes. `filter` is a MongoDB filter, evaluated on each changed record
|
|
101
|
-
* as conf evaluates it on a read. `recordFilter`
|
|
129
|
+
* as conf evaluates it on a read. A `recordFilter` in the spec is ignored.
|
|
102
130
|
*/
|
|
103
131
|
export const createDatasetMachine = (client, spec, onChange = () => undefined) => {
|
|
104
132
|
const {
|
|
@@ -113,42 +141,54 @@ export const createDatasetMachine = (client, spec, onChange = () => undefined) =
|
|
|
113
141
|
const readArgs = readArgsFor({ ...rest, rids, filter, projection: readProjection });
|
|
114
142
|
|
|
115
143
|
const compiled = compileFilter(filter);
|
|
116
|
-
const
|
|
144
|
+
const specError = specErrorMessage(client, entity, compiled);
|
|
117
145
|
const change = applyChange({
|
|
118
|
-
matches:
|
|
146
|
+
matches: match(() => R.F)((test) => createRecordMatcher({ rids, test }))(compiled),
|
|
119
147
|
transform: R.pipe(readProjection ? projectWith(readProjection) : R.identity, recordTransform),
|
|
120
148
|
});
|
|
121
149
|
const applyAll = (records, changes) =>
|
|
122
150
|
changes.reduce((current, event) => change(current, event).records, records);
|
|
123
151
|
|
|
124
|
-
|
|
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({
|
|
125
159
|
actors: {
|
|
126
|
-
|
|
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
|
+
),
|
|
127
165
|
},
|
|
128
166
|
actions: {
|
|
129
|
-
subscribe: spawnChild(
|
|
167
|
+
subscribe: spawnChild('subscription', { id: SUBSCRIPTION_ID }),
|
|
130
168
|
unsubscribe: stopChild(SUBSCRIPTION_ID),
|
|
131
169
|
clearRecords: assign({ records: [], held: [] }),
|
|
132
|
-
hold: assign({ held: ({ context: { held }, event }) =>
|
|
170
|
+
hold: assign({ held: ({ context: { held }, event }) => [...held, event] }),
|
|
133
171
|
setError: assign({ error: ({ event: { error } }) => error }),
|
|
134
|
-
|
|
172
|
+
setReadError: assign({ error: ({ event: { output } }) => output.error }),
|
|
173
|
+
setSpecError: assign({ error: () => Error(specError) }),
|
|
135
174
|
clearError: assign({ error: undefined }),
|
|
136
175
|
setRecords: assign({
|
|
137
|
-
records: ({ context: { held }, event: { output } }) =>
|
|
138
|
-
applyAll(R.map(recordTransform)(output), held),
|
|
176
|
+
records: ({ context: { held }, event: { output } }) => applyAll(output.value, held),
|
|
139
177
|
held: [],
|
|
140
178
|
}),
|
|
179
|
+
// Subscribers run after the transition, so getRecords already returns what they are told.
|
|
180
|
+
notifyChange: (_, { notification }) => queueMicrotask(() => onChange(notification)),
|
|
141
181
|
applyChange: enqueueActions(({ context: { records }, event, enqueue }) => {
|
|
142
182
|
const { records: next, notification } = change(records, event);
|
|
143
183
|
enqueue.assign({ records: next });
|
|
144
|
-
|
|
145
|
-
if (notification) enqueue(() => queueMicrotask(() => onChange(notification)));
|
|
184
|
+
if (notification) enqueue({ type: 'notifyChange', params: { notification } });
|
|
146
185
|
}),
|
|
147
186
|
},
|
|
148
187
|
guards: {
|
|
149
|
-
|
|
188
|
+
hasInvalidSpec: () => specError !== undefined,
|
|
189
|
+
isLoaded: ({ event: { output } }) => output.ok,
|
|
150
190
|
},
|
|
151
|
-
});
|
|
191
|
+
}).createMachine(machineConfig);
|
|
152
192
|
};
|
|
153
193
|
|
|
154
194
|
/**
|
|
@@ -165,28 +205,32 @@ export const datasetLoaded = async (datasetRef) => {
|
|
|
165
205
|
: snapshot.context.records;
|
|
166
206
|
};
|
|
167
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
|
+
*/
|
|
168
212
|
export const createDataset = (client, spec) => {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
const notify = (notification) => callbacks.forEach((callback) => callback(notification));
|
|
172
|
-
const machine = createActor(createDatasetMachine(client, spec, notify));
|
|
213
|
+
const subscribers = createSubscribers(reporterOf(client));
|
|
214
|
+
const machine = createActor(createDatasetMachine(client, spec, subscribers.notify));
|
|
173
215
|
return {
|
|
174
216
|
machine,
|
|
175
|
-
// 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.
|
|
176
219
|
init: async () => {
|
|
177
|
-
|
|
178
|
-
|
|
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();
|
|
179
225
|
await datasetLoaded(machine);
|
|
226
|
+
return undefined;
|
|
180
227
|
},
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
unsubscribe: (callback) => {
|
|
185
|
-
callbacks = callback ? R.without([callback])(callbacks) : [];
|
|
186
|
-
},
|
|
228
|
+
// Returns the function that undoes this subscription.
|
|
229
|
+
subscribe: subscribers.add,
|
|
230
|
+
unsubscribe: subscribers.remove,
|
|
187
231
|
getRecords: () => machine.getSnapshot().context.records,
|
|
188
232
|
stop: () => {
|
|
189
|
-
|
|
233
|
+
subscribers.remove();
|
|
190
234
|
machine.stop();
|
|
191
235
|
},
|
|
192
236
|
};
|
package/src/datasetRecords.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as R from 'ramda';
|
|
2
2
|
import sift from 'sift';
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { Err, Ok } from '@faybl/utils';
|
|
5
5
|
|
|
6
6
|
const isNonEmpty = R.complement(R.isEmpty);
|
|
7
7
|
const keysToInclude = R.pipe(R.pickBy(Boolean), R.keys);
|
|
@@ -23,19 +23,19 @@ export const projectWith = (projection) =>
|
|
|
23
23
|
// `$where` runs JavaScript; a dataset filter only describes data. sift passes the operation's
|
|
24
24
|
// name fourth, after its parameters, the query that owns it and the options.
|
|
25
25
|
const refuseOperation = (...[, , , name]) => {
|
|
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
|
|
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.
|
|
27
27
|
throw Error(`Unsupported operation: ${name}`);
|
|
28
28
|
};
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
31
|
* Compiles a MongoDB filter into a test on a record, the same query language conf reads with.
|
|
32
|
-
* An operation sift cannot evaluate, such as `$text`, fails the compilation:
|
|
33
|
-
* `{ kind: 'InvalidFilter', message, cause }` instead of
|
|
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.
|
|
34
34
|
*/
|
|
35
35
|
export const compileFilter = R.tryCatch(
|
|
36
|
-
(filter = {}) =>
|
|
36
|
+
(filter = {}) => Ok(sift(filter, { operations: { $where: refuseOperation } })),
|
|
37
37
|
(cause) =>
|
|
38
|
-
|
|
38
|
+
Err({ kind: 'InvalidFilter', message: `Invalid dataset filter: ${cause.message}`, cause }),
|
|
39
39
|
);
|
|
40
40
|
|
|
41
41
|
export const createRecordMatcher =
|
package/src/fetch.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as R from 'ramda';
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { Err, Ok, match, tryCatchAsync } from '@faybl/utils';
|
|
4
4
|
|
|
5
5
|
// Every request carries a JSON body, so the content type is set here rather than by each caller.
|
|
6
6
|
// Asking for JSON makes the login proxy answer an expired session with 401 instead of a redirect
|
|
@@ -19,31 +19,31 @@ const withToken = async (options, oidcHandler) =>
|
|
|
19
19
|
? R.assocPath(['headers', 'Authorization'])(`Bearer ${await oidcHandler.getToken()}`)(options)
|
|
20
20
|
: options;
|
|
21
21
|
|
|
22
|
-
const readJson = tryCatchAsync(async (response) =>
|
|
23
|
-
|
|
22
|
+
const readJson = tryCatchAsync(async (response) => Ok(await response.json()))((cause) =>
|
|
23
|
+
Err({ kind: 'InvalidJson', cause }),
|
|
24
24
|
);
|
|
25
25
|
|
|
26
26
|
// A failed response need not carry JSON, say an HTML error page from a proxy; its body is then {}.
|
|
27
27
|
const requestFailure = async (response) => {
|
|
28
28
|
const { status, statusText } = response;
|
|
29
|
-
const body =
|
|
29
|
+
const body = match(() => ({}))(R.identity)(await readJson(response));
|
|
30
30
|
return Object.assign(Error(`Request failed: ${status} ${statusText}`), {
|
|
31
31
|
response: { status, statusText, body },
|
|
32
32
|
});
|
|
33
33
|
};
|
|
34
34
|
|
|
35
35
|
/**
|
|
36
|
-
* Sends a JSON request and resolves with the JSON response. A 401 with a client
|
|
37
|
-
* gets one more try with a fresh token, since the cached one may have been
|
|
38
|
-
* 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.
|
|
39
39
|
*/
|
|
40
|
-
export const fetchCheckedJson = async (url, options, { oidcHandler, session }
|
|
40
|
+
export const fetchCheckedJson = async (url, options, { fetch, oidcHandler, session }) => {
|
|
41
41
|
// Cookies go along so a browser client is authenticated by its login session.
|
|
42
42
|
const jsonOptions = {
|
|
43
43
|
...R.mergeDeepRight({ headers: JSON_HEADERS }, options),
|
|
44
44
|
credentials: 'include',
|
|
45
45
|
};
|
|
46
|
-
const send = async () =>
|
|
46
|
+
const send = async () => fetch(url, await withToken(jsonOptions, oidcHandler));
|
|
47
47
|
|
|
48
48
|
const retryWithFreshToken = async (first) => {
|
|
49
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
|
|
1
|
+
import mqtt from 'mqtt';
|
|
2
2
|
|
|
3
|
-
import {
|
|
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
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
+
});
|