@graffiti-garden/wrapper-synchronize 0.0.1

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/src/index.ts ADDED
@@ -0,0 +1,315 @@
1
+ import Ajv from "ajv-draft-04";
2
+ import { Graffiti } from "@graffiti-garden/api";
3
+ import type {
4
+ GraffitiSession,
5
+ GraffitiObject,
6
+ JSONSchema4,
7
+ GraffitiStream,
8
+ } from "@graffiti-garden/api";
9
+ import type { GraffitiObjectBase } from "@graffiti-garden/api";
10
+ import { Repeater } from "@repeaterjs/repeater";
11
+ import { applyPatch } from "fast-json-patch";
12
+ import {
13
+ applyGraffitiPatch,
14
+ attemptAjvCompile,
15
+ isActorAllowedGraffitiObject,
16
+ locationToUri,
17
+ maskGraffitiObject,
18
+ unpackLocationOrUri,
19
+ } from "@graffiti-garden/implementation-local/utilities";
20
+ export type * from "@graffiti-garden/api";
21
+
22
+ export type GraffitiSynchronizeCallback = (
23
+ oldObject: GraffitiObjectBase,
24
+ newObject?: GraffitiObjectBase,
25
+ ) => void;
26
+
27
+ /**
28
+ * Wraps the [Graffiti API](https://api.graffiti.garden/classes/Graffiti.html)
29
+ * so that changes made or received in one part of an application
30
+ * are automatically routed to other parts of the application.
31
+ * This is an important tool for building responsive
32
+ * and consistent user interfaces, and is built upon to make
33
+ * the [Graffiti Vue Plugin](https://vue.graffiti.garden/variables/GraffitiPlugin.html)
34
+ * and possibly other front-end libraries in the future.
35
+ *
36
+ * Specifically, it provides the following *synchronize*
37
+ * methods for each of the following API methods:
38
+ *
39
+ * | API Method | Synchronize Method |
40
+ * |------------|--------------------|
41
+ * | {@link get} | {@link synchronizeGet} |
42
+ * | {@link discover} | {@link synchronizeDiscover} |
43
+ * | {@link recoverOrphans} | {@link synchronizeRecoverOrphans} |
44
+ *
45
+ * Whenever a change is made via {@link put}, {@link patch}, and {@link delete} or
46
+ * received from {@link get}, {@link discover}, and {@link recoverOrphans},
47
+ * those changes are forwarded to the appropriate synchronize method.
48
+ * Each synchronize method returns an iterator that streams these changes
49
+ * continually until the user calls `return` on the iterator or `break`s out of the loop,
50
+ * allowing for live updates without additional polling.
51
+ *
52
+ * Example 1: Suppose a user publishes a post using {@link put}. If the feed
53
+ * displaying that user's posts is using {@link synchronizeDiscover} to listen for changes,
54
+ * then the user's new post will instantly appear in their feed, giving the UI a
55
+ * responsive feel.
56
+ *
57
+ * Example 2: Suppose one of a user's friends changes their name. As soon as the
58
+ * user's application receives one notice of that change (using {@link get}
59
+ * or {@link discover}), then {@link synchronizeDiscover} listeners can be used to update
60
+ * all instance's of that friend's name in the user's application instantly,
61
+ * providing a consistent user experience.
62
+ *
63
+ * @groupDescription Synchronize Methods
64
+ * This group contains methods that listen for changes made via
65
+ * {@link put}, {@link patch}, and {@link delete} or fetched from
66
+ * {@link get}, {@link discover}, and {@link recoverOrphans} and then
67
+ * streams appropriate changes to provide a responsive and consistent user experience.
68
+ */
69
+ export class GraffitiSynchronize extends Graffiti {
70
+ protected readonly ajv: Ajv;
71
+ protected readonly graffiti: Graffiti;
72
+ protected readonly callbacks = new Set<GraffitiSynchronizeCallback>();
73
+
74
+ channelStats: Graffiti["channelStats"];
75
+ locationToUri: Graffiti["locationToUri"];
76
+ uriToLocation: Graffiti["uriToLocation"];
77
+ login: Graffiti["login"];
78
+ logout: Graffiti["logout"];
79
+ sessionEvents: Graffiti["sessionEvents"];
80
+
81
+ /**
82
+ * Wraps a Graffiti API instance to provide the synchronize methods.
83
+ * The GraffitiSyncrhonize class rather than the Graffiti class
84
+ * must be used for all functions for the synchronize methods to work.
85
+ */
86
+ constructor(
87
+ /**
88
+ * The [Graffiti API](https://api.graffiti.garden/classes/Graffiti.html)
89
+ * instance to wrap.
90
+ */
91
+ graffiti: Graffiti,
92
+ /**
93
+ * An optional instance of Ajv to use for validating
94
+ * objects before dispatching them to listeners.
95
+ * If not provided, a new instance of Ajv will be created.
96
+ */
97
+ ajv?: Ajv,
98
+ ) {
99
+ super();
100
+ this.ajv = ajv ?? new Ajv({ strict: false });
101
+ this.graffiti = graffiti;
102
+ this.channelStats = graffiti.channelStats.bind(graffiti);
103
+ this.locationToUri = graffiti.locationToUri.bind(graffiti);
104
+ this.uriToLocation = graffiti.uriToLocation.bind(graffiti);
105
+ this.login = graffiti.login.bind(graffiti);
106
+ this.logout = graffiti.logout.bind(graffiti);
107
+ this.sessionEvents = graffiti.sessionEvents;
108
+ }
109
+
110
+ protected synchronize<Schema extends JSONSchema4>(
111
+ matchObject: (object: GraffitiObjectBase) => boolean,
112
+ channels: string[],
113
+ schema: Schema,
114
+ session?: GraffitiSession | null,
115
+ ) {
116
+ const validate = attemptAjvCompile(this.ajv, schema);
117
+
118
+ const repeater: GraffitiStream<GraffitiObject<Schema>> = new Repeater(
119
+ async (push, stop) => {
120
+ const callback: GraffitiSynchronizeCallback = (
121
+ oldObjectRaw,
122
+ newObjectRaw,
123
+ ) => {
124
+ for (const objectRaw of [newObjectRaw, oldObjectRaw]) {
125
+ if (
126
+ objectRaw &&
127
+ matchObject(objectRaw) &&
128
+ isActorAllowedGraffitiObject(objectRaw, session)
129
+ ) {
130
+ const object = { ...objectRaw };
131
+ maskGraffitiObject(object, channels, session);
132
+ if (validate(object)) {
133
+ push({ value: object });
134
+ break;
135
+ }
136
+ }
137
+ }
138
+ };
139
+
140
+ this.callbacks.add(callback);
141
+ await stop;
142
+ this.callbacks.delete(callback);
143
+ },
144
+ );
145
+
146
+ return repeater;
147
+ }
148
+
149
+ /**
150
+ * This method has the same signature as {@link discover} but listens for
151
+ * changes made via {@link put}, {@link patch}, and {@link delete} or
152
+ * fetched from {@link get}, {@link discover}, and {@link recoverOrphans}
153
+ * and then streams appropriate changes to provide a responsive and
154
+ * consistent user experience.
155
+ *
156
+ * Unlike {@link discover}, this method continuously listens for changes
157
+ * and will not terminate unless the user calls the `return` method on the iterator
158
+ * or `break`s out of the loop.
159
+ *
160
+ * @group Synchronize Methods
161
+ */
162
+ synchronizeDiscover<Schema extends JSONSchema4>(
163
+ ...args: Parameters<typeof Graffiti.prototype.discover<Schema>>
164
+ ): GraffitiStream<GraffitiObject<Schema>> {
165
+ const [channels, schema, session] = args;
166
+ function matchObject(object: GraffitiObjectBase) {
167
+ return object.channels.some((channel) => channels.includes(channel));
168
+ }
169
+ return this.synchronize(matchObject, channels, schema, session);
170
+ }
171
+
172
+ /**
173
+ * This method has the same signature as {@link get} but
174
+ * listens for changes made via {@link put}, {@link patch}, and {@link delete} or
175
+ * fetched from {@link get}, {@link discover}, and {@link recoverOrphans} and then
176
+ * streams appropriate changes to provide a responsive and consistent user experience.
177
+ *
178
+ * Unlike {@link get}, which returns a single result, this method continuously
179
+ * listens for changes which are output as an asynchronous {@link GraffitiStream}.
180
+ *
181
+ * @group Synchronize Methods
182
+ */
183
+ synchronizeGet<Schema extends JSONSchema4>(
184
+ ...args: Parameters<typeof Graffiti.prototype.get<Schema>>
185
+ ): GraffitiStream<GraffitiObject<Schema>> {
186
+ const [locationOrUri, schema, session] = args;
187
+ function matchObject(object: GraffitiObjectBase) {
188
+ const objectUri = locationToUri(object);
189
+ const { uri } = unpackLocationOrUri(locationOrUri);
190
+ return objectUri === uri;
191
+ }
192
+ return this.synchronize(matchObject, [], schema, session);
193
+ }
194
+
195
+ /**
196
+ * This method has the same signature as {@link recoverOrphans} but
197
+ * listens for changes made via
198
+ * {@link put}, {@link patch}, and {@link delete} or fetched from
199
+ * {@link get}, {@link discover}, and {@link recoverOrphans} and then
200
+ * streams appropriate changes to provide a responsive and consistent user experience.
201
+ *
202
+ * Unlike {@link recoverOrphans}, this method continuously listens for changes
203
+ * and will not terminate unless the user calls the `return` method on the iterator
204
+ * or `break`s out of the loop.
205
+ *
206
+ * @group Synchronize Methods
207
+ */
208
+ synchronizeRecoverOrphans<Schema extends JSONSchema4>(
209
+ ...args: Parameters<typeof Graffiti.prototype.recoverOrphans<Schema>>
210
+ ): GraffitiStream<GraffitiObject<Schema>> {
211
+ const [schema, session] = args;
212
+ function matchObject(object: GraffitiObjectBase) {
213
+ return object.actor === session.actor && object.channels.length === 0;
214
+ }
215
+ return this.synchronize(matchObject, [], schema, session);
216
+ }
217
+
218
+ protected async synchronizeDispatch(
219
+ oldObject: GraffitiObjectBase,
220
+ newObject?: GraffitiObjectBase,
221
+ waitForListeners = false,
222
+ ) {
223
+ for (const callback of this.callbacks) {
224
+ callback(oldObject, newObject);
225
+ }
226
+ if (waitForListeners) {
227
+ // Wait for the listeners to receive
228
+ // their objects, before returning the operation
229
+ // that triggered them.
230
+ //
231
+ // This is important for mutators (put, patch, delete)
232
+ // to ensure the application state has been updated
233
+ // everywhere before returning, giving consistent
234
+ // feedback to the user that the operation has completed.
235
+ //
236
+ // The opposite is true for accessors (get, discover, recoverOrphans),
237
+ // where it is a weird user experience to call `get`
238
+ // in one place and have the application update
239
+ // somewhere else first. It is also less efficient.
240
+ //
241
+ // The hack is simply to await one "macro task cycle".
242
+ // We need to wait for this cycle rather than using
243
+ // `await push` in the callback, because it turns out
244
+ // that `await push` won't resolve until the following
245
+ // .next() call of the iterator, so if only
246
+ // one .next() is called, this dispatch will hang.
247
+ await new Promise((resolve) => setTimeout(resolve, 0));
248
+ }
249
+ }
250
+
251
+ get: Graffiti["get"] = async (...args) => {
252
+ const object = await this.graffiti.get(...args);
253
+ this.synchronizeDispatch(object);
254
+ return object;
255
+ };
256
+
257
+ put: Graffiti["put"] = async (...args) => {
258
+ const oldObject = await this.graffiti.put(...args);
259
+ const partialObject = args[0];
260
+ const newObject: GraffitiObjectBase = {
261
+ ...oldObject,
262
+ value: partialObject.value,
263
+ channels: partialObject.channels,
264
+ allowed: partialObject.allowed,
265
+ tombstone: false,
266
+ };
267
+ await this.synchronizeDispatch(oldObject, newObject, true);
268
+ return oldObject;
269
+ };
270
+
271
+ patch: Graffiti["patch"] = async (...args) => {
272
+ const oldObject = await this.graffiti.patch(...args);
273
+ const newObject: GraffitiObjectBase = { ...oldObject };
274
+ newObject.tombstone = false;
275
+ for (const prop of ["value", "channels", "allowed"] as const) {
276
+ applyGraffitiPatch(applyPatch, prop, args[0], newObject);
277
+ }
278
+ await this.synchronizeDispatch(oldObject, newObject, true);
279
+ return oldObject;
280
+ };
281
+
282
+ delete: Graffiti["delete"] = async (...args) => {
283
+ const oldObject = await this.graffiti.delete(...args);
284
+ await this.synchronizeDispatch(oldObject, undefined, true);
285
+ return oldObject;
286
+ };
287
+
288
+ protected objectStream<Schema extends JSONSchema4>(
289
+ iterator: ReturnType<typeof Graffiti.prototype.discover<Schema>>,
290
+ ) {
291
+ const dispatch = this.synchronizeDispatch.bind(this);
292
+ const wrapper = async function* () {
293
+ let result = await iterator.next();
294
+ while (!result.done) {
295
+ if (!result.value.error) {
296
+ dispatch(result.value.value);
297
+ }
298
+ yield result.value;
299
+ result = await iterator.next();
300
+ }
301
+ return result.value;
302
+ };
303
+ return wrapper();
304
+ }
305
+
306
+ discover: Graffiti["discover"] = (...args) => {
307
+ const iterator = this.graffiti.discover(...args);
308
+ return this.objectStream(iterator);
309
+ };
310
+
311
+ recoverOrphans: Graffiti["recoverOrphans"] = (...args) => {
312
+ const iterator = this.graffiti.recoverOrphans(...args);
313
+ return this.objectStream(iterator);
314
+ };
315
+ }