@contello/store 4.1.1 → 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/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { createContelloClient, createSourceSubscription } from "@contello/client";
1
+ import { BUILT_IN_MUTATIONS, createContelloClient, createSourceMutation, createSourceMutationVariables, createSourceSubscription } from "@contello/client";
2
2
  import { concatAsync, createAsyncIterableSubject, firstAsync, keepalive, mapAsync, retryWithBackoff } from "@entwico/dash/async";
3
3
  import { ProjectedLazyMap, ProjectedMap, ProjectedValue } from "@entwico/projected";
4
4
  import { createOperationTelemetry } from "@contello/opentelemetry";
5
- import { maybeAll, maybeCatch, maybeThen, maybeThen as maybeThen$1 } from "@entwico/dash";
5
+ import { maybeAll, maybeThen } from "@entwico/dash";
6
6
  import { LRUCache } from "lru-cache";
7
7
  //#region src/generated/graphql.ts
8
8
  const MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
@@ -277,6 +277,52 @@ function createRefreshByTtlQueue() {
277
277
  } };
278
278
  }
279
279
  //#endregion
280
+ //#region src/write-buffer.ts
281
+ function createWriteBuffer() {
282
+ const parked = /* @__PURE__ */ new Map();
283
+ const awaited = /* @__PURE__ */ new Map();
284
+ return {
285
+ park(id, entity) {
286
+ if (!awaited.has(id)) parked.set(id, entity);
287
+ },
288
+ release(ids) {
289
+ for (const id of ids) parked.delete(id);
290
+ },
291
+ clear() {
292
+ parked.clear();
293
+ },
294
+ take(ids) {
295
+ const written = [];
296
+ const missing = [];
297
+ for (const id of ids) {
298
+ const entity = parked.get(id);
299
+ if (entity === void 0) missing.push(id);
300
+ else {
301
+ parked.delete(id);
302
+ written.push(entity);
303
+ }
304
+ }
305
+ return {
306
+ written,
307
+ missing
308
+ };
309
+ },
310
+ awaitingUpstream(ids) {
311
+ for (const id of ids) {
312
+ parked.delete(id);
313
+ awaited.set(id, (awaited.get(id) ?? 0) + 1);
314
+ }
315
+ return () => {
316
+ for (const id of ids) {
317
+ const count = awaited.get(id) ?? 0;
318
+ if (count > 1) awaited.set(id, count - 1);
319
+ else awaited.delete(id);
320
+ }
321
+ };
322
+ }
323
+ };
324
+ }
325
+ //#endregion
280
326
  //#region src/assets.ts
281
327
  function mapFile$1(raw) {
282
328
  return {
@@ -308,11 +354,29 @@ function createAssetsCollection(options, client, updates$, refreshByTtl) {
308
354
  run: () => runFullRefresh("ttl")
309
355
  });
310
356
  let loaded = false;
311
- const assetsSourceDoc = createSourceSubscription(schema.sources.storeAsset);
357
+ const assetSource = {
358
+ ...schema.sources.storeAsset,
359
+ mutations: BUILT_IN_MUTATIONS.asset
360
+ };
361
+ const assetsSourceDoc = createSourceSubscription(assetSource);
362
+ const writeBuffer = createWriteBuffer();
363
+ function fetchAssets(ids) {
364
+ return concatAsync(mapAsync(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source));
365
+ }
366
+ async function fetchOrTakeWritten(ids) {
367
+ if (ids === void 0) {
368
+ writeBuffer.clear();
369
+ return fetchAssets(void 0);
370
+ }
371
+ const { written, missing } = writeBuffer.take(ids);
372
+ if (missing.length === 0) return written;
373
+ const fetched = await fetchAssets(missing);
374
+ return written.length === 0 ? fetched : [...written, ...fetched];
375
+ }
312
376
  const projected = new ProjectedMap({
313
377
  key: (asset) => asset.id,
314
378
  values: (ids) => wrap("assets", async () => {
315
- const items = (await concatAsync(mapAsync(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source))).map((item) => mapAsset$1(item));
379
+ const items = (await fetchOrTakeWritten(ids)).map((item) => mapAsset$1(item));
316
380
  if (ids === void 0 && !loaded) {
317
381
  loaded = true;
318
382
  ttl.mark();
@@ -339,10 +403,11 @@ function createAssetsCollection(options, client, updates$, refreshByTtl) {
339
403
  emit(changedIds, "upstream-update");
340
404
  return;
341
405
  }
406
+ const settled = writeBuffer.awaitingUpstream(refreshIds);
342
407
  retryWithBackoff(async () => {
343
408
  await projected.refresh(refreshIds);
344
409
  emit(changedIds, "upstream-update");
345
- });
410
+ }).finally(settled);
346
411
  }
347
412
  const unsubUpdates = updates$.subscribe((batch) => {
348
413
  if (!loaded || batch.asset.length === 0) return;
@@ -351,14 +416,46 @@ function createAssetsCollection(options, client, updates$, refreshByTtl) {
351
416
  for (const event of batch.asset) if (event.mutation === "delete") deleted.push(event.id);
352
417
  else upserted.add(event.id);
353
418
  if (cache.eviction === "clear") {
419
+ writeBuffer.clear();
354
420
  projected.clear();
355
421
  return;
356
422
  }
423
+ writeBuffer.release(deleted);
357
424
  if (deleted.length > 0) projected.delete(deleted);
358
425
  runPartialRefresh([...upserted], deleted);
359
426
  });
427
+ async function runMutation(kind, values) {
428
+ const binding = assetSource.mutations?.[kind];
429
+ if (!binding) throw new Error(`@contello/store: assets cannot ${kind} — the schema exposes no ${kind} mutation for assets`);
430
+ const response = await client.execute(createSourceMutation(assetSource, kind), createSourceMutationVariables(binding, values));
431
+ if (response?.result === void 0 || response.result === null) throw new Error(`@contello/store: ${kind} on assets returned nothing`);
432
+ return response.result;
433
+ }
360
434
  return {
361
435
  instance: {
436
+ async update(input) {
437
+ const raw = await runMutation("update", { input });
438
+ writeBuffer.park(raw.id, raw);
439
+ let map;
440
+ try {
441
+ map = await projected.refresh([raw.id]);
442
+ } finally {
443
+ writeBuffer.release([raw.id]);
444
+ }
445
+ emit([raw.id], "write");
446
+ const asset = map.get(raw.id);
447
+ if (!asset) throw new Error(`@contello/store: wrote asset "${raw.id}" but it is not in the cache — a concurrent full refresh did not return it`);
448
+ return asset;
449
+ },
450
+ async delete(id) {
451
+ await runMutation("delete", {
452
+ input: { id },
453
+ id
454
+ });
455
+ writeBuffer.release([id]);
456
+ projected.delete([id]);
457
+ emit([id], "write");
458
+ },
362
459
  refresh$: channel.stream$,
363
460
  async load() {
364
461
  if (!loaded) await projected.getAllAsMap();
@@ -556,6 +653,19 @@ var DependencyCollector = class {
556
653
  function fetchCollection(source, client, ids) {
557
654
  return concatAsync(mapAsync(client.subscribe(createSourceSubscription(source), { ids }), (r) => r.source));
558
655
  }
656
+ /**
657
+ * Runs one write mutation of the source. A create/update selects the source's fragment, so the
658
+ * answer is a raw entity in exactly the shape the source subscription yields — the cache takes it
659
+ * from there. A delete only carries an id.
660
+ */
661
+ async function runMutation(source, client, name, kind, values) {
662
+ const binding = source.mutations?.[kind];
663
+ if (!binding) throw new Error(`@contello/store: collection "${name}" cannot ${kind} — the schema exposes no ${kind} mutation for model "${source.__model}"`);
664
+ const document = createSourceMutation(source, kind);
665
+ const response = await client.execute(document, createSourceMutationVariables(binding, values));
666
+ if (!response?.result) throw new Error(`@contello/store: ${kind} on collection "${name}" returned no entity`);
667
+ return response.result;
668
+ }
559
669
  function createCollection(source, options, client, updates$, resolver, refreshByTtl) {
560
670
  const opts = options ?? {};
561
671
  const mapFn = opts.map ?? ((item) => item);
@@ -574,10 +684,21 @@ function createCollection(source, options, client, updates$, resolver, refreshBy
574
684
  run: () => runFullRefresh("ttl")
575
685
  });
576
686
  let loaded = false;
687
+ const writeBuffer = createWriteBuffer();
688
+ function fetchOrTakeWritten(ids) {
689
+ if (ids === void 0) {
690
+ writeBuffer.clear();
691
+ return fetchCollection(source, client, void 0);
692
+ }
693
+ const { written, missing } = writeBuffer.take(ids);
694
+ if (missing.length === 0) return written;
695
+ if (written.length === 0) return fetchCollection(source, client, missing);
696
+ return maybeThen(fetchCollection(source, client, missing), (fetched) => [...written, ...fetched]);
697
+ }
577
698
  const projected = new ProjectedMap({
578
699
  key: (item) => item.id,
579
- values: (ids) => wrap(`collection:${_def.name}`, () => maybeThen$1(fetchCollection(source, client, ids), async (rawItems) => {
580
- const items = await maybeAll(rawItems.map((item) => dependencyCollector.createContext((ref, register) => maybeThen$1(mapFn(item, ref), (mapped) => {
700
+ values: (ids) => wrap(`collection:${_def.name}`, () => maybeThen(fetchOrTakeWritten(ids), async (rawItems) => {
701
+ const items = await maybeAll(rawItems.map((item) => dependencyCollector.createContext((ref, register) => maybeThen(mapFn(item, ref), (mapped) => {
581
702
  register(mapped.id);
582
703
  return mapped;
583
704
  }))));
@@ -614,10 +735,11 @@ function createCollection(source, options, client, updates$, resolver, refreshBy
614
735
  emit(changedIds, "upstream-update");
615
736
  return;
616
737
  }
738
+ const settled = writeBuffer.awaitingUpstream(refreshIds);
617
739
  retryWithBackoff(async () => {
618
740
  await projected.refresh(refreshIds);
619
741
  emit(changedIds, "upstream-update");
620
- });
742
+ }).finally(settled);
621
743
  }
622
744
  const unsubUpdates = updates$.subscribe((batch) => {
623
745
  if (!loaded) return;
@@ -631,15 +753,55 @@ function createCollection(source, options, client, updates$, resolver, refreshBy
631
753
  if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) return;
632
754
  if (_def.cache.eviction === "clear") {
633
755
  dependencyCollector.clear();
756
+ writeBuffer.clear();
634
757
  projected.clear();
635
758
  return;
636
759
  }
760
+ writeBuffer.release(deleted);
637
761
  for (const id of deleted) dependencyCollector.removeItem(id);
638
762
  if (deleted.length > 0) projected.delete(deleted);
639
763
  const refreshIds = upserted.union(depAffected);
640
764
  for (const id of deleted) refreshIds.delete(id);
641
765
  runPartialRefresh([...refreshIds], deleted);
642
766
  });
767
+ /** Puts a written entity into the cache through the normal refresh path and returns it mapped. */
768
+ async function takeIntoCache(entity) {
769
+ writeBuffer.park(entity.id, entity);
770
+ let map;
771
+ try {
772
+ map = await projected.refresh([entity.id]);
773
+ } finally {
774
+ writeBuffer.release([entity.id]);
775
+ }
776
+ emit([entity.id], "write");
777
+ const item = map.get(entity.id);
778
+ if (!item) throw new Error(`@contello/store: collection "${_def.name}" wrote entity "${entity.id}" but it is not in the cache — a concurrent full refresh did not return it`);
779
+ return item;
780
+ }
781
+ /**
782
+ * One method per mutation the source binds — a model the schema exposes no `createX` for has
783
+ * no `create`, matching what `CollectionWrites` types. Permission is not decided here: the
784
+ * server rejects a write the token may not run.
785
+ */
786
+ function createWrites() {
787
+ const out = {};
788
+ if (source.mutations?.create) out["create"] = async (input) => takeIntoCache(await runMutation(source, client, _def.name, "create", { input }));
789
+ if (source.mutations?.update) out["update"] = async (input) => takeIntoCache(await runMutation(source, client, _def.name, "update", { input }));
790
+ if (source.mutations?.delete) out["delete"] = async (id, options) => {
791
+ await runMutation(source, client, _def.name, "delete", {
792
+ input: {
793
+ ...options,
794
+ id
795
+ },
796
+ id
797
+ });
798
+ writeBuffer.release([id]);
799
+ dependencyCollector.removeItem(id);
800
+ projected.delete([id]);
801
+ emit([id], "write");
802
+ };
803
+ return out;
804
+ }
643
805
  return {
644
806
  instance: {
645
807
  name: _def.name,
@@ -655,7 +817,8 @@ function createCollection(source, options, client, updates$, resolver, refreshBy
655
817
  },
656
818
  async load() {
657
819
  if (!loaded) await projected.getAllAsMap();
658
- }
820
+ },
821
+ ...createWrites()
659
822
  },
660
823
  destroy() {
661
824
  unsubUpdates();
@@ -738,7 +901,7 @@ function createI18nMessagesCollection(def, client, updates$, refreshByTtl) {
738
901
  });
739
902
  }
740
903
  function emitWithCurrentIds(kind) {
741
- maybeThen$1(projected.getAll(), (msgs) => {
904
+ maybeThen(projected.getAll(), (msgs) => {
742
905
  emit(msgs.map((m) => m.id), kind);
743
906
  });
744
907
  }
@@ -935,7 +1098,7 @@ function createLazyCollection(source, options, client, updates$, resolver) {
935
1098
  });
936
1099
  const projected = new ProjectedLazyMap({
937
1100
  key: (item) => item.id,
938
- values: (keys) => wrap(`lazy-collection:${_def.name}`, () => maybeThen$1(concatAsync(mapAsync(client.subscribe(createSourceSubscription(source), { ids: keys }), (r) => r.source)), (rawItems) => maybeAll(rawItems.map((item) => dependencyCollector.createContext((ref, register) => maybeThen$1(mapFn(item, ref), (mapped) => {
1101
+ values: (keys) => wrap(`lazy-collection:${_def.name}`, () => maybeThen(concatAsync(mapAsync(client.subscribe(createSourceSubscription(source), { ids: keys }), (r) => r.source)), (rawItems) => maybeAll(rawItems.map((item) => dependencyCollector.createContext((ref, register) => maybeThen(mapFn(item, ref), (mapped) => {
939
1102
  register(mapped.id);
940
1103
  return mapped;
941
1104
  })))))),
@@ -1261,11 +1424,29 @@ function createRoutesCollection(options, client, updates$, resolver, refreshByTt
1261
1424
  const pathById = /* @__PURE__ */ new Map();
1262
1425
  const idByPath = /* @__PURE__ */ new Map();
1263
1426
  let loaded = false;
1264
- const routesSourceDoc = createSourceSubscription(schema.sources.storeRoute);
1427
+ const routeSource = {
1428
+ ...schema.sources.storeRoute,
1429
+ mutations: BUILT_IN_MUTATIONS.route
1430
+ };
1431
+ const routesSourceDoc = createSourceSubscription(routeSource);
1432
+ const writeBuffer = createWriteBuffer();
1433
+ function fetchRoutes(ids) {
1434
+ return concatAsync(mapAsync(client.subscribe(routesSourceDoc, { ids }), (data) => data.source));
1435
+ }
1436
+ async function fetchOrTakeWritten(ids) {
1437
+ if (ids === void 0) {
1438
+ writeBuffer.clear();
1439
+ return fetchRoutes(void 0);
1440
+ }
1441
+ const { written, missing } = writeBuffer.take(ids);
1442
+ if (missing.length === 0) return written;
1443
+ const fetched = await fetchRoutes(missing);
1444
+ return written.length === 0 ? fetched : [...written, ...fetched];
1445
+ }
1265
1446
  const projected = new ProjectedMap({
1266
1447
  key: (route) => route.id,
1267
1448
  values: (ids) => wrap("routes", async () => {
1268
- const items = (await concatAsync(mapAsync(client.subscribe(routesSourceDoc, { ids }), (data) => data.source))).reduce((acc, raw) => {
1449
+ const items = (await fetchOrTakeWritten(ids)).reduce((acc, raw) => {
1269
1450
  const mapped = mapRoute(raw, resolver);
1270
1451
  if (mapped) acc.push(mapped);
1271
1452
  return acc;
@@ -1320,10 +1501,11 @@ function createRoutesCollection(options, client, updates$, resolver, refreshByTt
1320
1501
  emit(changedIds, "upstream-update");
1321
1502
  return;
1322
1503
  }
1504
+ const settled = writeBuffer.awaitingUpstream(refreshIds);
1323
1505
  retryWithBackoff(async () => {
1324
1506
  await projected.refresh(refreshIds);
1325
1507
  emit(changedIds, "upstream-update");
1326
- });
1508
+ }).finally(settled);
1327
1509
  }
1328
1510
  const unsubUpdates = updates$.subscribe((batch) => {
1329
1511
  if (!loaded || batch.route.length === 0) return;
@@ -1334,9 +1516,11 @@ function createRoutesCollection(options, client, updates$, resolver, refreshByTt
1334
1516
  if (cache.eviction === "clear") {
1335
1517
  pathById.clear();
1336
1518
  idByPath.clear();
1519
+ writeBuffer.clear();
1337
1520
  projected.clear();
1338
1521
  return;
1339
1522
  }
1523
+ writeBuffer.release(deleted);
1340
1524
  for (const id of deleted) {
1341
1525
  const oldPath = pathById.get(id);
1342
1526
  if (oldPath !== void 0) {
@@ -1354,13 +1538,13 @@ function createRoutesCollection(options, client, updates$, resolver, refreshByTt
1354
1538
  return projected.get(ids);
1355
1539
  }
1356
1540
  function lookupByPathSingle(path) {
1357
- return maybeThen$1(ensureLoaded(), () => {
1541
+ return maybeThen(ensureLoaded(), () => {
1358
1542
  const id = idByPath.get(path);
1359
1543
  return id === void 0 ? void 0 : projected.get(id);
1360
1544
  });
1361
1545
  }
1362
1546
  function lookupByPaths(paths) {
1363
- return maybeThen$1(ensureLoaded(), () => {
1547
+ return maybeThen(ensureLoaded(), () => {
1364
1548
  const ids = [];
1365
1549
  for (const p of paths) {
1366
1550
  const id = idByPath.get(p);
@@ -1371,10 +1555,51 @@ function createRoutesCollection(options, client, updates$, resolver, refreshByTt
1371
1555
  }
1372
1556
  function ensureLoaded() {
1373
1557
  if (loaded) return;
1374
- return maybeThen$1(projected.getAllAsMap(), () => {});
1558
+ return maybeThen(projected.getAllAsMap(), () => {});
1559
+ }
1560
+ async function runMutation(kind, values) {
1561
+ const binding = routeSource.mutations?.[kind];
1562
+ if (!binding) throw new Error(`@contello/store: routes cannot ${kind} — the schema exposes no ${kind} mutation for routes`);
1563
+ const response = await client.execute(createSourceMutation(routeSource, kind), createSourceMutationVariables(binding, values));
1564
+ if (response?.result === void 0 || response.result === null) throw new Error(`@contello/store: ${kind} on routes returned nothing`);
1565
+ return response.result;
1566
+ }
1567
+ /** Takes a written route into the cache through the normal refresh path, keeping both indexes. */
1568
+ async function takeIntoCache(raw) {
1569
+ writeBuffer.park(raw.id, raw);
1570
+ let map;
1571
+ try {
1572
+ map = await projected.refresh([raw.id]);
1573
+ } finally {
1574
+ writeBuffer.release([raw.id]);
1575
+ }
1576
+ emit([raw.id], "write");
1577
+ const route = map.get(raw.id);
1578
+ if (!route) throw new Error(`@contello/store: wrote route "${raw.id}" but it is not in the cache — its target may not have resolved, or a concurrent full refresh did not return it`);
1579
+ return route;
1375
1580
  }
1376
1581
  return {
1377
1582
  instance: {
1583
+ async create(input) {
1584
+ return takeIntoCache(await runMutation("create", { input }));
1585
+ },
1586
+ async update(input) {
1587
+ return takeIntoCache(await runMutation("update", { input }));
1588
+ },
1589
+ async delete(id) {
1590
+ await runMutation("delete", {
1591
+ input: { id },
1592
+ id
1593
+ });
1594
+ writeBuffer.release([id]);
1595
+ const oldPath = pathById.get(id);
1596
+ if (oldPath !== void 0) {
1597
+ idByPath.delete(oldPath);
1598
+ pathById.delete(id);
1599
+ }
1600
+ projected.delete([id]);
1601
+ emit([id], "write");
1602
+ },
1378
1603
  refresh$: channel.stream$,
1379
1604
  async load() {
1380
1605
  if (!loaded) await projected.getAllAsMap();
@@ -1436,7 +1661,7 @@ function createSingleton(source, options, client, updates$, resolver, refreshByT
1436
1661
  run: () => runTtlRefresh()
1437
1662
  });
1438
1663
  let loaded = false;
1439
- const projected = new ProjectedValue({ value: () => wrap(`singleton:${_def.name}`, () => maybeThen$1(firstAsync(mapAsync(client.subscribe(createSourceSubscription(source)), (r) => r.source)), (raw) => dependencyCollector.createContext((ref, register) => maybeThen$1(mapFn(raw, ref), (mapped) => {
1664
+ const projected = new ProjectedValue({ value: () => wrap(`singleton:${_def.name}`, () => maybeThen(firstAsync(mapAsync(client.subscribe(createSourceSubscription(source)), (r) => r.source)), (raw) => dependencyCollector.createContext((ref, register) => maybeThen(mapFn(raw, ref), (mapped) => {
1440
1665
  register(itemKey);
1441
1666
  if (!loaded) {
1442
1667
  loaded = true;
@@ -1771,6 +1996,6 @@ function createStore(options) {
1771
1996
  return new Store(options);
1772
1997
  }
1773
1998
  //#endregion
1774
- export { Store, createStore, maybeCatch, maybeThen };
1999
+ export { Store, createStore };
1775
2000
 
1776
2001
  //# sourceMappingURL=index.js.map