@powerhousedao/reactor 6.2.2-dev.15 → 6.2.2-dev.17

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,10 +1,10 @@
1
- import { A as parsePagingOptions, C as DuplicateManifestError, D as DocumentDeletedError, E as ModuleNotFoundError, O as DocumentNotFoundError, S as CollectionMembershipCache, T as InvalidModuleError, _ as KyselyWriteCache, a as createForwardingPoolInstrumentation, b as createConsistencyToken, c as DuplicateOperationError, d as KyselyKeyframeStore, f as DocumentModelRegistry, g as EventBus, h as KyselyExecutionScope, i as runMigrations, j as throwIfAborted, k as matchesScope, l as OptimisticLockError, m as DriveCollectionId, n as REACTOR_SCHEMA, o as instrumentPgPool, p as SimpleJobExecutor, r as getMigrationStatus, s as KyselyOperationStore, t as DEFAULT_DRIVE_CONTAINER_TYPES, u as RevisionMismatchError, v as KyselyOperationIndex, w as DuplicateModuleError, x as createEmptyConsistencyToken, y as DocumentMetaCache } from "./drive-container-types-DpJp2AmE.js";
1
+ import { A as DocumentNotFoundError, C as RevisionMismatchError, D as ModuleNotFoundError, E as InvalidModuleError, M as parsePagingOptions, N as throwIfAborted, O as AuthorizationDeniedError, S as OptimisticLockError, T as DuplicateModuleError, _ as createConsistencyToken, a as createForwardingPoolInstrumentation, b as AppendConditionFailedError, c as KyselyKeyframeStore, d as DriveCollectionId, f as KyselyExecutionScope, g as DocumentMetaCache, h as KyselyOperationIndex, i as runMigrations, j as matchesScope, k as DocumentDeletedError, l as DocumentModelRegistry, m as KyselyWriteCache, n as REACTOR_SCHEMA, o as instrumentPgPool, p as EventBus, r as getMigrationStatus, s as KyselyOperationStore, t as DEFAULT_DRIVE_CONTAINER_TYPES, u as SimpleJobExecutor, v as createEmptyConsistencyToken, w as DuplicateManifestError, x as DuplicateOperationError, y as CollectionMembershipCache } from "./drive-container-types-DrQMmpCa.js";
2
2
  import { n as ReactorEventTypes, t as EventBusAggregateError } from "./types-DMKLa0Ok.js";
3
3
  import { i as WorkerInitFailedError, r as WorkerExitedError, t as WorkerAbortTimeoutError } from "./errors-D3S6Eysd.js";
4
- import { a as ReadModelCoordinator, i as KyselyDocumentView, n as ConsistencyTracker, o as BaseReadModel, r as makeConsistencyKey, t as KyselyDocumentIndexer } from "./document-indexer-FGJmRAdX.js";
4
+ import { a as ReadModelCoordinator, i as KyselyDocumentView, n as ConsistencyTracker, o as BaseReadModel, r as makeConsistencyKey, t as KyselyDocumentIndexer } from "./document-indexer-BY-mPXJF.js";
5
5
  import { n as errorToInfo, r as sanitizeArg, t as createForwardingLogger } from "./forwarding-logger-BBkMSxuJ.js";
6
- import { t as workerEntryPath } from "./worker-DBJOv8Gp.js";
7
- import { actions, actions as documentActions, createPresignedHeader, generateId, hashDocumentStateForScope, replayDocument } from "@powerhousedao/shared/document-model";
6
+ import { t as workerEntryPath } from "./worker-BEzk4Q1I.js";
7
+ import { actions, actions as documentActions, createPresignedHeader, decide, generateId, hashDocumentStateForScope, replayDocument } from "@powerhousedao/shared/document-model";
8
8
  import { addFile, addFolder, copyNode, deleteNode, driveCreateDocument, generateNodesCopy, getDescendants, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
9
9
  import { v4 } from "uuid";
10
10
  import { ConsoleLogger, childLogger } from "document-model";
@@ -680,6 +680,39 @@ let DocumentChangeType = /* @__PURE__ */ function(DocumentChangeType) {
680
680
  return DocumentChangeType;
681
681
  }({});
682
682
  //#endregion
683
+ //#region src/client/util.ts
684
+ const ALWAYS_READABLE_SCOPES = new Set(["auth", "document"]);
685
+ function authSubjectFromSigner(signer) {
686
+ return {
687
+ address: signer.user?.address,
688
+ key: signer.app?.key
689
+ };
690
+ }
691
+ function canReadScope(auth, subject, scope) {
692
+ return ALWAYS_READABLE_SCOPES.has(scope) || decide(auth, subject, {
693
+ verb: "read",
694
+ scope
695
+ }) === "allow";
696
+ }
697
+ function withAuthScope(view) {
698
+ if (view?.scopes && view.scopes.length > 0) return {
699
+ ...view,
700
+ scopes: [...new Set([...view.scopes, "auth"])]
701
+ };
702
+ return view;
703
+ }
704
+ function filterReadableScopes(document, subject) {
705
+ const state = document.state;
706
+ if (!state) return document;
707
+ const auth = document.state.auth;
708
+ const filtered = {};
709
+ for (const scope of Object.keys(state)) if (canReadScope(auth, subject, scope)) filtered[scope] = state[scope];
710
+ return {
711
+ ...document,
712
+ state: filtered
713
+ };
714
+ }
715
+ //#endregion
683
716
  //#region src/client/reactor-client.ts
684
717
  /**
685
718
  * ReactorClient implementation that wraps lower-level APIs to provide
@@ -711,6 +744,9 @@ var ReactorClient = class {
711
744
  this.drives = new DriveClient(this, logger, reactor, signer);
712
745
  this.logger.verbose("ReactorClient initialized");
713
746
  }
747
+ readSubject(subject) {
748
+ return subject ?? authSubjectFromSigner(this.signer);
749
+ }
714
750
  /**
715
751
  * Retrieves a list of document model modules.
716
752
  */
@@ -734,7 +770,7 @@ var ReactorClient = class {
734
770
  */
735
771
  async get(identifier, view, signal) {
736
772
  this.logger.verbose("get(@identifier, @view)", identifier, view);
737
- return await this.reactor.getByIdOrSlug(identifier, view, void 0, signal);
773
+ return filterReadableScopes(await this.reactor.getByIdOrSlug(identifier, withAuthScope(view), void 0, signal), this.readSubject(view?.subject));
738
774
  }
739
775
  /**
740
776
  * Resolves an identifier (id or slug) to the canonical document id, using the
@@ -750,8 +786,15 @@ var ReactorClient = class {
750
786
  async getOperations(documentIdentifier, view, filter, paging, signal) {
751
787
  this.logger.verbose("getOperations(@documentIdentifier, @view, @filter, @paging)", documentIdentifier, view, filter, paging);
752
788
  const documentId = await this.documentView.resolveIdOrSlug(documentIdentifier, view, void 0, signal);
753
- if (paging?.cursor && isCompositeCursor(paging.cursor)) return this.getOperationsWithCompositeCursor(documentId, view, filter, paging, signal);
789
+ const authDoc = await this.reactor.getByIdOrSlug(documentId, {
790
+ scopes: ["auth"],
791
+ branch: view?.branch
792
+ }, void 0, signal);
793
+ const subject = this.readSubject(view?.subject);
794
+ const canRead = (scope) => canReadScope(authDoc?.state.auth, subject, scope);
795
+ if (paging?.cursor && isCompositeCursor(paging.cursor)) return this.getOperationsWithCompositeCursor(documentId, view, filter, paging, signal, canRead);
754
796
  const operationsByScope = await this.reactor.getOperations(documentId, view, filter, paging, void 0, signal);
797
+ for (const scope of Object.keys(operationsByScope)) if (!canRead(scope)) delete operationsByScope[scope];
755
798
  const scopeEntries = Object.entries(operationsByScope);
756
799
  const effectivePaging = paging || {
757
800
  cursor: "0",
@@ -779,11 +822,12 @@ var ReactorClient = class {
779
822
  nextCursor: Object.keys(activeCursors).length > 0 ? encodeCompositeCursor(activeCursors) : void 0
780
823
  };
781
824
  }
782
- async getOperationsWithCompositeCursor(documentId, view, filter, paging, signal) {
825
+ async getOperationsWithCompositeCursor(documentId, view, filter, paging, signal, canRead) {
783
826
  const scopeCursors = decodeCompositeCursor(paging.cursor);
784
827
  const allOperations = [];
785
828
  const activeCursors = {};
786
829
  for (const [scopeName, cursor] of Object.entries(scopeCursors)) {
830
+ if (!canRead(scopeName)) continue;
787
831
  const scopeView = {
788
832
  ...view,
789
833
  scopes: [scopeName]
@@ -817,7 +861,7 @@ var ReactorClient = class {
817
861
  limit: 0
818
862
  }
819
863
  };
820
- return this.reactor.find({ ids: targetIds }, view, paging, void 0, signal);
864
+ return this.find({ ids: targetIds }, view, paging, signal);
821
865
  }
822
866
  /**
823
867
  * Retrieves incoming relationships of a given type to a target document.
@@ -833,14 +877,19 @@ var ReactorClient = class {
833
877
  limit: 0
834
878
  }
835
879
  };
836
- return this.reactor.find({ ids: sourceIds }, view, paging, void 0, signal);
880
+ return this.find({ ids: sourceIds }, view, paging, signal);
837
881
  }
838
882
  /**
839
883
  * Filters documents by criteria and returns a list of them
840
884
  */
841
885
  async find(search, view, paging, signal) {
842
886
  this.logger.verbose("find(@search, @view, @paging)", search, view, paging);
843
- return this.reactor.find(search, view, paging, void 0, signal);
887
+ const results = await this.reactor.find(search, withAuthScope(view), paging, void 0, signal);
888
+ const readSubject = this.readSubject(view?.subject);
889
+ return {
890
+ ...results,
891
+ results: results.results.map((doc) => filterReadableScopes(doc, readSubject))
892
+ };
844
893
  }
845
894
  /**
846
895
  * Creates a document and waits for completion
@@ -1144,6 +1193,18 @@ let JobQueueState = /* @__PURE__ */ function(JobQueueState) {
1144
1193
  return JobQueueState;
1145
1194
  }({});
1146
1195
  /**
1196
+ * How a retry is accounted against the job's retry limit.
1197
+ * - `CountAgainstLimit` (default): a fault; the job eventually exhausts its
1198
+ * retries and fails terminally.
1199
+ * - `ExemptFromLimit`: not a fault, so the attempt is not charged to the job.
1200
+ * Used for concurrency conflicts, where the retry does new work.
1201
+ */
1202
+ let RetryAccounting = /* @__PURE__ */ function(RetryAccounting) {
1203
+ RetryAccounting["CountAgainstLimit"] = "count-against-limit";
1204
+ RetryAccounting["ExemptFromLimit"] = "exempt-from-limit";
1205
+ return RetryAccounting;
1206
+ }({});
1207
+ /**
1147
1208
  * Event types for the queue system
1148
1209
  */
1149
1210
  const QueueEventTypes = { JOB_AVAILABLE: 1e4 };
@@ -1187,12 +1248,19 @@ var JobResultHandler = class {
1187
1248
  } catch {}
1188
1249
  }
1189
1250
  }
1251
+ if (result.error && AppendConditionFailedError.isError(result.error)) {
1252
+ const errorInfo = toErrorInfo(result.error);
1253
+ try {
1254
+ await this.queue.retryJob(handle.job.id, errorInfo, RetryAccounting.ExemptFromLimit);
1255
+ return;
1256
+ } catch {}
1257
+ }
1190
1258
  if (result.error && DocumentNotFoundError.isError(result.error)) {
1191
1259
  handle.defer();
1192
1260
  callbacks.deferJob(handle.job.documentId, handle.job);
1193
1261
  return;
1194
1262
  }
1195
- if (result.error && DocumentDeletedError.isError(result.error)) {
1263
+ if (result.error && (DocumentDeletedError.isError(result.error) || AuthorizationDeniedError.isError(result.error))) {
1196
1264
  const errorInfo = toErrorInfo(result.error);
1197
1265
  this.jobTracker.markFailed(handle.job.id, errorInfo, handle.job);
1198
1266
  this.eventBus.emit(ReactorEventTypes.JOB_FAILED, {
@@ -2587,7 +2655,7 @@ var InMemoryQueue = class {
2587
2655
  if (documentId) this.markJobComplete(jobId, documentId);
2588
2656
  this.jobIndex.delete(jobId);
2589
2657
  }
2590
- async retryJob(jobId, error) {
2658
+ async retryJob(jobId, error, accounting = RetryAccounting.CountAgainstLimit) {
2591
2659
  const job = this.jobIndex.get(jobId);
2592
2660
  if (!job) return;
2593
2661
  job.lastError = error;
@@ -2596,9 +2664,10 @@ var InMemoryQueue = class {
2596
2664
  this.jobIndex.delete(jobId);
2597
2665
  this.jobIdToQueueKey.delete(jobId);
2598
2666
  if (error) job.errorHistory.push(error);
2667
+ const retryCount = job.retryCount || 0;
2599
2668
  const updatedJob = {
2600
2669
  ...job,
2601
- retryCount: (job.retryCount || 0) + 1,
2670
+ retryCount: accounting === RetryAccounting.CountAgainstLimit ? retryCount + 1 : retryCount,
2602
2671
  lastError: error
2603
2672
  };
2604
2673
  await this.enqueue(updatedJob);
@@ -6769,6 +6838,7 @@ var ReactorBuilder = class {
6769
6838
  }
6770
6839
  async buildModule() {
6771
6840
  if (!this.logger) this.logger = new ConsoleLogger(["reactor"]);
6841
+ if (this.projectionShardConfig !== void 0 && this.readModelFactories.length > 0) throw new Error("withProjectionShards does not support read models registered through withReadModelFactory; projection workers cannot receive host-only factory dependencies");
6772
6842
  const resolvedSources = await resolveModelSources(this.documentModelSources);
6773
6843
  if (this.workerPool) {
6774
6844
  if (resolvedSources.manifest.length === 0) throw new Error("withWorkerPool requires at least one worker-importable document-model source ({ filePath } or { packageName }).");
@@ -6852,6 +6922,7 @@ var ReactorBuilder = class {
6852
6922
  }
6853
6923
  for (const factory of this.readModelFactories) {
6854
6924
  const readModel = await factory({
6925
+ documentModelRegistry,
6855
6926
  operationIndex,
6856
6927
  writeCache,
6857
6928
  processorManagerConsistencyTracker
@@ -6964,7 +7035,7 @@ var ReactorBuilder = class {
6964
7035
  const [{ WorkerHandle }, { createThreadTransport }, { workerEntryPath }] = await Promise.all([
6965
7036
  import("./worker-handle-B1w03nRA.js"),
6966
7037
  import("./transport-ByGviWdZ.js"),
6967
- import("./worker-DBJOv8Gp.js").then((n) => n.n)
7038
+ import("./worker-BEzk4Q1I.js").then((n) => n.n)
6968
7039
  ]);
6969
7040
  const poolConfig = {
6970
7041
  enabled: true,
@@ -7225,6 +7296,74 @@ function driveIdFromUrl(url) {
7225
7296
  return url.split("/").pop() ?? "";
7226
7297
  }
7227
7298
  //#endregion
7299
+ //#region src/decision/build-decision-model.ts
7300
+ /**
7301
+ * Reads each projection's stream through the write cache, recording the
7302
+ * revision observed. Static projections resolve first; derived projections
7303
+ * see only those and contribute a map from document id to state. Each
7304
+ * distinct stream is read once and yields one append condition entry.
7305
+ */
7306
+ async function buildDecisionModel(cache, definition, target, signal) {
7307
+ const decisionModel = definition(target);
7308
+ const projections = Object.entries(decisionModel.projections);
7309
+ const reads = /* @__PURE__ */ new Map();
7310
+ const model = {};
7311
+ for (const [key, projection] of projections) {
7312
+ if (typeof projection.query === "function") continue;
7313
+ model[key] = (await readStream(cache, projection.query, reads, signal)).state;
7314
+ }
7315
+ const staticModel = { ...model };
7316
+ for (const [key, projection] of projections) {
7317
+ if (typeof projection.query !== "function") continue;
7318
+ const queries = projection.query(staticModel);
7319
+ const value = {};
7320
+ for (const query of queries) {
7321
+ const read = await readStream(cache, query, reads, signal);
7322
+ value[query.documentId] = read.state;
7323
+ }
7324
+ model[key] = value;
7325
+ }
7326
+ return {
7327
+ model,
7328
+ appendCondition: { streams: [...reads.values()].map((read) => read.stream) }
7329
+ };
7330
+ }
7331
+ async function readStream(cache, query, reads, signal) {
7332
+ const key = `${query.documentId}:${query.scope}:${query.branch}`;
7333
+ const existing = reads.get(key);
7334
+ if (existing) return existing;
7335
+ const document = await cache.getState(query.documentId, query.scope, query.branch, void 0, signal);
7336
+ const read = {
7337
+ state: document.state[query.scope],
7338
+ stream: {
7339
+ documentId: query.documentId,
7340
+ scope: query.scope,
7341
+ branch: query.branch,
7342
+ revision: observedRevision(document, query.scope)
7343
+ }
7344
+ };
7345
+ reads.set(key, read);
7346
+ return read;
7347
+ }
7348
+ /**
7349
+ * The highest operation index the document reflects for the scope, or -1 if
7350
+ * empty. The last operation's index is the one invariant the write cache
7351
+ * guarantees; header.revision (next-index semantics) is the fallback.
7352
+ */
7353
+ function observedRevision(document, scope) {
7354
+ if (scope in document.operations) {
7355
+ const operations = document.operations[scope];
7356
+ if (operations.length > 0) return operations[operations.length - 1].index;
7357
+ }
7358
+ if (!(scope in document.header.revision)) return -1;
7359
+ return document.header.revision[scope] - 1;
7360
+ }
7361
+ //#endregion
7362
+ //#region src/read-models/interfaces.ts
7363
+ function supportsLiveReadModelRegistration(coordinator) {
7364
+ return "addReadModel" in coordinator && typeof coordinator.addReadModel === "function";
7365
+ }
7366
+ //#endregion
7228
7367
  //#region src/admin/passthrough-keyframe-store.ts
7229
7368
  const passthroughKeyframeStore = {
7230
7369
  putKeyframe: () => Promise.resolve(),
@@ -7334,6 +7473,6 @@ var DocumentIntegrityService = class {
7334
7473
  }
7335
7474
  };
7336
7475
  //#endregion
7337
- export { BaseReadModel, ChannelError, ChannelErrorSource, ChannelScheme, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, DRIVE_AUTH_ERROR_MESSAGES, DefaultSubscriptionErrorHandler, DocumentChangeType, DocumentIntegrityService, DocumentModelRegistry, DocumentModelResolver, DriveClient, DriveCollectionId, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, IntervalPollTimer, InvalidModuleError, JobAwaiter, JobExecutorEventTypes, JobStatus, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, Mailbox, ModuleNotFoundError, NullDocumentModelResolver, OptimisticLockError, PollBehavior, PollingChannelError, ProcessorManager, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, ReactorEventTypes, ReactorSubscriptionManager, ReadModelCoordinator, RelationalDbProcessor, RelationshipChangeType, RevisionMismatchError, SimpleJobExecutorManager, SyncBuilder, SyncEventTypes, SyncOperation, SyncOperationAggregateError, SyncOperationStatus, SyncStatus, SyncStatusTracker, addRelationshipAction, batchOperationsByDocument, consolidateSyncOperations, createDocumentAction, createForwardingLogger, createMutableShutdownStatus, createRelationalDb, deleteDocumentAction, documentActions, driveIdFromUrl, envelopesToSyncOperations, errorToInfo, getMigrationStatus, instrumentPgPool, isDriveAuthError, makeConsistencyKey, parseDriveUrl, parsePagingOptions, removeRelationshipAction, runMigrations, sanitizeArg, trimMailboxFromAckOrdinal, updateRelationshipAction, upgradeDocumentAction, workerEntryPath };
7476
+ export { AppendConditionFailedError, BaseReadModel, ChannelError, ChannelErrorSource, ChannelScheme, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, DRIVE_AUTH_ERROR_MESSAGES, DefaultSubscriptionErrorHandler, DocumentChangeType, DocumentIntegrityService, DocumentModelRegistry, DocumentModelResolver, DriveClient, DriveCollectionId, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, IntervalPollTimer, InvalidModuleError, JobAwaiter, JobExecutorEventTypes, JobStatus, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, Mailbox, ModuleNotFoundError, NullDocumentModelResolver, OptimisticLockError, PollBehavior, PollingChannelError, ProcessorManager, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, ReactorEventTypes, ReactorSubscriptionManager, ReadModelCoordinator, RelationalDbProcessor, RelationshipChangeType, RetryAccounting, RevisionMismatchError, SimpleJobExecutorManager, SyncBuilder, SyncEventTypes, SyncOperation, SyncOperationAggregateError, SyncOperationStatus, SyncStatus, SyncStatusTracker, addRelationshipAction, batchOperationsByDocument, buildDecisionModel, consolidateSyncOperations, createDocumentAction, createForwardingLogger, createMutableShutdownStatus, createRelationalDb, deleteDocumentAction, documentActions, driveIdFromUrl, envelopesToSyncOperations, errorToInfo, getMigrationStatus, instrumentPgPool, isDriveAuthError, makeConsistencyKey, parseDriveUrl, parsePagingOptions, removeRelationshipAction, runMigrations, sanitizeArg, supportsLiveReadModelRegistration, trimMailboxFromAckOrdinal, updateRelationshipAction, upgradeDocumentAction, workerEntryPath };
7338
7477
 
7339
7478
  //# sourceMappingURL=index.js.map