@powerhousedao/reactor-api 6.2.3-dev.75 → 6.2.3-dev.77
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/{base-document-models-BGt__Ctn.mjs → base-document-models-Dh70m9Bh.mjs} +4 -4
- package/dist/{base-document-models-BGt__Ctn.mjs.map → base-document-models-Dh70m9Bh.mjs.map} +1 -1
- package/dist/index.d.mts +205 -11
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +656 -285
- package/dist/index.mjs.map +1 -1
- package/dist/{package-subgraph-check-C5S8yvBI.mjs → package-subgraph-check-DhCWO3YR.mjs} +4 -4
- package/dist/{package-subgraph-check-C5S8yvBI.mjs.map → package-subgraph-check-DhCWO3YR.mjs.map} +1 -1
- package/dist/{pglite-node-BOFT_yUj.mjs → pglite-node-BMux5A2Y.mjs} +4 -4
- package/dist/{pglite-node-BOFT_yUj.mjs.map → pglite-node-BMux5A2Y.mjs.map} +1 -1
- package/dist/src/graphql/subgraph-types.mjs +1 -1
- package/dist/src/packages/vite-loader.mjs +1 -1
- package/dist/src/pglite/pglite-node.mjs +3 -3
- package/dist/{subgraph-extraction-cSpPp3Hq.mjs → subgraph-extraction-zUDn2zX_.mjs} +239 -13
- package/dist/subgraph-extraction-zUDn2zX_.mjs.map +1 -0
- package/package.json +13 -13
- package/dist/subgraph-extraction-cSpPp3Hq.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="560dd033-eac1-581d-a504-0117f3526f86")}catch(e){}}();
|
|
3
3
|
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
|
|
4
|
-
import { A as
|
|
5
|
-
import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-
|
|
4
|
+
import { A as CanonicalDocumentIdResolutionError, C as loadSubgraphs, D as RequestClientBinder, E as callerSubject, F as AuthEvaluationUnsupportedError, I as AuthenticationRequiredError, L as ForbiddenError, M as AuthorizationPolicy, N as AuthorizedDocumentHandle, O as AuthService, P as createAuthorizationService, R as MalformedStoredOperationError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as createCanonicalDocumentIdResolver, k as createCredentialInvalidator, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests, z as RefusalNotRecordedError } from "./subgraph-extraction-zUDn2zX_.mjs";
|
|
5
|
+
import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-Dh70m9Bh.mjs";
|
|
6
6
|
import { n as createApolloFetchHandler } from "./adapter-gateway-apollo-D-EdZ4e-.mjs";
|
|
7
7
|
import { d as PGLITE_UTC_PARSERS, i as resolvePgliteFsync, r as createDurableNodeFs } from "./error-info-CCQcLAcW.mjs";
|
|
8
|
-
import { f as openCurrentPgliteForVerify, p as preparePgliteDataDir } from "./pglite-node-
|
|
8
|
+
import { f as openCurrentPgliteForVerify, p as preparePgliteDataDir } from "./pglite-node-BMux5A2Y.mjs";
|
|
9
9
|
import { findPackageJSON, isBuiltin } from "node:module";
|
|
10
10
|
import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
|
|
11
11
|
import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
|
|
12
12
|
import { gql } from "graphql-tag";
|
|
13
13
|
import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, validateSchema, valueFromASTUntyped, visit } from "graphql";
|
|
14
|
-
import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, CATCH_UP_LOAD_WINDOW_MS, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, isCatchUpLevel, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState } from "@powerhousedao/reactor";
|
|
14
|
+
import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, CATCH_UP_LOAD_WINDOW_MS, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, FacadeWriteClient, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, isCatchUpLevel, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState, warnOnce } from "@powerhousedao/reactor";
|
|
15
15
|
import { deserializeSignature, readPeerManifest, serializeSignature, setName, withSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
16
16
|
import { fetchDelegationCredential, resolveSwitchboardEndpoint } from "@renown/sdk";
|
|
17
|
-
import { ConsoleLogger, childLogger } from "document-model";
|
|
18
17
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
18
|
+
import { ConsoleLogger, childLogger } from "document-model";
|
|
19
19
|
import path, { isAbsolute, join } from "node:path";
|
|
20
20
|
import { match } from "path-to-regexp";
|
|
21
21
|
import posix from "node:path/posix";
|
|
@@ -1683,6 +1683,21 @@ function ActionInputSchema() {
|
|
|
1683
1683
|
function ChannelMetaInputSchema() {
|
|
1684
1684
|
return z$1.object({ id: z$1.string() });
|
|
1685
1685
|
}
|
|
1686
|
+
function ConsistencyCoordinateInputSchema() {
|
|
1687
|
+
return z$1.object({
|
|
1688
|
+
branch: z$1.string(),
|
|
1689
|
+
documentId: z$1.string(),
|
|
1690
|
+
operationIndex: z$1.number(),
|
|
1691
|
+
scope: z$1.string()
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
function ConsistencyTokenInputSchema() {
|
|
1695
|
+
return z$1.object({
|
|
1696
|
+
coordinates: z$1.array(z$1.lazy(() => ConsistencyCoordinateInputSchema())),
|
|
1697
|
+
createdAtUtcIso: z$1.string(),
|
|
1698
|
+
version: z$1.number()
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1686
1701
|
function DocumentOperationsFilterInputSchema() {
|
|
1687
1702
|
return z$1.object({
|
|
1688
1703
|
actionTypes: z$1.array(z$1.string()).nullish(),
|
|
@@ -2981,42 +2996,84 @@ function isDriveContainerType(documentType) {
|
|
|
2981
2996
|
//#endregion
|
|
2982
2997
|
//#region src/graphql/reactor/resolvers.ts
|
|
2983
2998
|
const REACTOR_DRIVE_DOCUMENT_TYPE = "powerhouse/reactor-drive";
|
|
2999
|
+
/** The branch a mutation applies to when the caller names none. */
|
|
3000
|
+
const DEFAULT_BRANCH = "main";
|
|
3001
|
+
/** The `Query.<field>` coordinates handed the write client outside a mutation. */
|
|
3002
|
+
const WRITE_CLIENT_QUERIES = Object.entries({
|
|
3003
|
+
evaluateActions: "write",
|
|
3004
|
+
pollSyncEnvelopes: "syncManager",
|
|
3005
|
+
syncHolds: "syncManager",
|
|
3006
|
+
peerAgreement: "syncManager",
|
|
3007
|
+
jobStatus: "read"
|
|
3008
|
+
}).filter(([, binding]) => binding === "write").map(([field]) => field);
|
|
3009
|
+
/** The reactor-drive client a reactor-drive parent needs, or the refusal. */
|
|
3010
|
+
function requireReactorDriveClient(reactorDriveClient) {
|
|
3011
|
+
if (!reactorDriveClient) throw new GraphQLError("Reactor-drive parent encountered but no reactorDriveClient is configured on this switchboard");
|
|
3012
|
+
return reactorDriveClient;
|
|
3013
|
+
}
|
|
2984
3014
|
/**
|
|
2985
|
-
*
|
|
2986
|
-
*
|
|
2987
|
-
*
|
|
3015
|
+
* Adds a document to a drive parent and returns what to read back once the
|
|
3016
|
+
* write is readable. Reactor-drive parents go through the reactor-drive
|
|
3017
|
+
* client, which still has the facade's waiting shape.
|
|
2988
3018
|
*/
|
|
2989
|
-
function
|
|
2990
|
-
if (
|
|
2991
|
-
|
|
2992
|
-
return
|
|
3019
|
+
async function addFileToDrive(clients, driveType, driveId, document, reactorDriveClient) {
|
|
3020
|
+
if (driveType === REACTOR_DRIVE_DOCUMENT_TYPE) {
|
|
3021
|
+
const added = await requireReactorDriveClient(reactorDriveClient).addFile(driveId, document);
|
|
3022
|
+
return {
|
|
3023
|
+
documentId: added.header.id,
|
|
3024
|
+
branch: added.header.branch || DEFAULT_BRANCH
|
|
3025
|
+
};
|
|
3026
|
+
}
|
|
3027
|
+
return (await clients.write.drives.addFile(driveId, document)).readable;
|
|
3028
|
+
}
|
|
3029
|
+
/** Removes a drive parent's node, waiting until the removal is readable. */
|
|
3030
|
+
async function removeNodeFromDrive(clients, driveType, driveId, nodeId, reactorDriveClient) {
|
|
3031
|
+
if (driveType === REACTOR_DRIVE_DOCUMENT_TYPE) {
|
|
3032
|
+
await requireReactorDriveClient(reactorDriveClient).removeNode(driveId, nodeId);
|
|
3033
|
+
return;
|
|
2993
3034
|
}
|
|
2994
|
-
|
|
3035
|
+
await (await clients.write.drives.removeNode(driveId, nodeId)).readable;
|
|
2995
3036
|
}
|
|
2996
3037
|
/**
|
|
2997
|
-
* A mutation's document
|
|
2998
|
-
*
|
|
3038
|
+
* A mutation's document read back on the read half, as the caller, bounded by
|
|
3039
|
+
* the write's token: `read.get(receipt.documentId, { subject, branch },
|
|
3040
|
+
* undefined, receipt.token)`. A caller who may write but not read gets it
|
|
3041
|
+
* stripped.
|
|
2999
3042
|
*/
|
|
3000
|
-
async function readAsCaller(
|
|
3001
|
-
if (!subject) return document;
|
|
3043
|
+
async function readAsCaller(read, receipt, subject, branch) {
|
|
3002
3044
|
try {
|
|
3003
|
-
return await
|
|
3045
|
+
return await read.get(receipt.documentId, {
|
|
3004
3046
|
subject,
|
|
3005
|
-
branch
|
|
3006
|
-
});
|
|
3047
|
+
branch: branch ?? receipt.branch
|
|
3048
|
+
}, void 0, receipt.token);
|
|
3007
3049
|
} catch (error) {
|
|
3008
3050
|
throw new GraphQLError(`Failed to read the document back: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3009
3051
|
}
|
|
3010
3052
|
}
|
|
3053
|
+
/** The token a read waits for, or none; only version 1 tokens exist. */
|
|
3054
|
+
function toConsistencyToken(input) {
|
|
3055
|
+
if (!input) return;
|
|
3056
|
+
if (input.version !== 1) throw new GraphQLError(`Unsupported consistency token version ${input.version}`, { extensions: { code: "BAD_USER_INPUT" } });
|
|
3057
|
+
return {
|
|
3058
|
+
version: 1,
|
|
3059
|
+
createdAtUtcIso: input.createdAtUtcIso,
|
|
3060
|
+
coordinates: input.coordinates.map((coordinate) => ({
|
|
3061
|
+
documentId: coordinate.documentId,
|
|
3062
|
+
scope: coordinate.scope,
|
|
3063
|
+
branch: coordinate.branch,
|
|
3064
|
+
operationIndex: coordinate.operationIndex
|
|
3065
|
+
}))
|
|
3066
|
+
};
|
|
3067
|
+
}
|
|
3011
3068
|
/** The defaults `create` gives a new document; the parent must already be gated. */
|
|
3012
|
-
async function createDefaults(
|
|
3013
|
-
const [signaturePolicy, protocolVersions] = await Promise.all([
|
|
3069
|
+
async function createDefaults(read, parentIdOrSlug) {
|
|
3070
|
+
const [signaturePolicy, protocolVersions] = await Promise.all([read.getCreateSignaturePolicy(), read.getCreateProtocolVersions(parentIdOrSlug)]);
|
|
3014
3071
|
return {
|
|
3015
3072
|
signaturePolicy,
|
|
3016
3073
|
protocolVersions
|
|
3017
3074
|
};
|
|
3018
3075
|
}
|
|
3019
|
-
async function documentModels(
|
|
3076
|
+
async function documentModels(read, args) {
|
|
3020
3077
|
const namespace = fromInputMaybe(args.namespace);
|
|
3021
3078
|
let paging;
|
|
3022
3079
|
if (args.paging) {
|
|
@@ -3029,7 +3086,7 @@ async function documentModels(reactorClient, args) {
|
|
|
3029
3086
|
}
|
|
3030
3087
|
let result;
|
|
3031
3088
|
try {
|
|
3032
|
-
result = await
|
|
3089
|
+
result = await read.getDocumentModelModules(namespace, paging);
|
|
3033
3090
|
} catch (error) {
|
|
3034
3091
|
throw new GraphQLError(`Failed to fetch document models: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3035
3092
|
}
|
|
@@ -3039,22 +3096,23 @@ async function documentModels(reactorClient, args) {
|
|
|
3039
3096
|
throw new GraphQLError(`Failed to convert document models to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3040
3097
|
}
|
|
3041
3098
|
}
|
|
3042
|
-
async function document(
|
|
3099
|
+
async function document(read, args, subject) {
|
|
3043
3100
|
let view = subject ? { subject } : void 0;
|
|
3044
3101
|
if (args.view) view = {
|
|
3045
3102
|
subject,
|
|
3046
3103
|
branch: fromInputMaybe(args.view.branch),
|
|
3047
3104
|
scopes: toMutableArray(fromInputMaybe(args.view.scopes))
|
|
3048
3105
|
};
|
|
3106
|
+
const token = toConsistencyToken(args.consistency);
|
|
3049
3107
|
let result;
|
|
3050
3108
|
try {
|
|
3051
|
-
result = await
|
|
3109
|
+
result = await read.get(args.idOrSlug, view, void 0, token);
|
|
3052
3110
|
} catch (error) {
|
|
3053
3111
|
throw new GraphQLError(`Failed to fetch document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3054
3112
|
}
|
|
3055
3113
|
let children;
|
|
3056
3114
|
try {
|
|
3057
|
-
children = await
|
|
3115
|
+
children = await read.getOutgoingRelationships(args.idOrSlug, "child", view, void 0, void 0, token);
|
|
3058
3116
|
} catch (error) {
|
|
3059
3117
|
throw new GraphQLError(`Failed to fetch children: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3060
3118
|
}
|
|
@@ -3067,7 +3125,7 @@ async function document(reactorClient, args, subject) {
|
|
|
3067
3125
|
throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3068
3126
|
}
|
|
3069
3127
|
}
|
|
3070
|
-
async function documentOutgoingRelationships(
|
|
3128
|
+
async function documentOutgoingRelationships(read, args, subject) {
|
|
3071
3129
|
let view = subject ? { subject } : void 0;
|
|
3072
3130
|
if (args.view) view = {
|
|
3073
3131
|
subject,
|
|
@@ -3085,7 +3143,7 @@ async function documentOutgoingRelationships(reactorClient, args, subject) {
|
|
|
3085
3143
|
}
|
|
3086
3144
|
let result;
|
|
3087
3145
|
try {
|
|
3088
|
-
result = await
|
|
3146
|
+
result = await read.getOutgoingRelationships(args.sourceIdOrSlug, args.relationshipType, view, paging, void 0, toConsistencyToken(args.consistency));
|
|
3089
3147
|
} catch (error) {
|
|
3090
3148
|
throw new GraphQLError(`Failed to fetch outgoing relationships: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3091
3149
|
}
|
|
@@ -3095,7 +3153,7 @@ async function documentOutgoingRelationships(reactorClient, args, subject) {
|
|
|
3095
3153
|
throw new GraphQLError(`Failed to convert outgoing relationships to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3096
3154
|
}
|
|
3097
3155
|
}
|
|
3098
|
-
async function documentIncomingRelationships(
|
|
3156
|
+
async function documentIncomingRelationships(read, args, subject) {
|
|
3099
3157
|
let view = subject ? { subject } : void 0;
|
|
3100
3158
|
if (args.view) view = {
|
|
3101
3159
|
subject,
|
|
@@ -3113,7 +3171,7 @@ async function documentIncomingRelationships(reactorClient, args, subject) {
|
|
|
3113
3171
|
}
|
|
3114
3172
|
let result;
|
|
3115
3173
|
try {
|
|
3116
|
-
result = await
|
|
3174
|
+
result = await read.getIncomingRelationships(args.targetIdOrSlug, args.relationshipType, view, paging, void 0, toConsistencyToken(args.consistency));
|
|
3117
3175
|
} catch (error) {
|
|
3118
3176
|
throw new GraphQLError(`Failed to fetch incoming relationships: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3119
3177
|
}
|
|
@@ -3123,12 +3181,12 @@ async function documentIncomingRelationships(reactorClient, args, subject) {
|
|
|
3123
3181
|
throw new GraphQLError(`Failed to convert incoming relationships to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3124
3182
|
}
|
|
3125
3183
|
}
|
|
3126
|
-
async function documentOutgoingRelationshipEdges(
|
|
3184
|
+
async function documentOutgoingRelationshipEdges(read, args, subject) {
|
|
3127
3185
|
const view = toRelationshipViewFilter(args.view, subject);
|
|
3128
3186
|
const paging = toRelationshipPagingOptions(args.paging);
|
|
3129
3187
|
let result;
|
|
3130
3188
|
try {
|
|
3131
|
-
result = await
|
|
3189
|
+
result = await read.getOutgoingRelationshipEdges(args.sourceIdOrSlug, fromInputMaybe(args.relationshipType), view, paging, void 0, toConsistencyToken(args.consistency));
|
|
3132
3190
|
} catch (error) {
|
|
3133
3191
|
throw new GraphQLError(`Failed to fetch outgoing relationship edges: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3134
3192
|
}
|
|
@@ -3138,12 +3196,12 @@ async function documentOutgoingRelationshipEdges(reactorClient, args, subject) {
|
|
|
3138
3196
|
throw new GraphQLError(`Failed to convert outgoing relationship edges to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3139
3197
|
}
|
|
3140
3198
|
}
|
|
3141
|
-
async function documentIncomingRelationshipEdges(
|
|
3199
|
+
async function documentIncomingRelationshipEdges(read, args, subject) {
|
|
3142
3200
|
const view = toRelationshipViewFilter(args.view, subject);
|
|
3143
3201
|
const paging = toRelationshipPagingOptions(args.paging);
|
|
3144
3202
|
let result;
|
|
3145
3203
|
try {
|
|
3146
|
-
result = await
|
|
3204
|
+
result = await read.getIncomingRelationshipEdges(args.targetIdOrSlug, fromInputMaybe(args.relationshipType), view, paging, void 0, toConsistencyToken(args.consistency));
|
|
3147
3205
|
} catch (error) {
|
|
3148
3206
|
throw new GraphQLError(`Failed to fetch incoming relationship edges: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3149
3207
|
}
|
|
@@ -3171,7 +3229,7 @@ function toRelationshipPagingOptions(input) {
|
|
|
3171
3229
|
limit: limit || 10
|
|
3172
3230
|
};
|
|
3173
3231
|
}
|
|
3174
|
-
async function findDocuments(
|
|
3232
|
+
async function findDocuments(read, args, subject) {
|
|
3175
3233
|
let view = subject ? { subject } : void 0;
|
|
3176
3234
|
if (args.view) view = {
|
|
3177
3235
|
subject,
|
|
@@ -3193,7 +3251,7 @@ async function findDocuments(reactorClient, args, subject) {
|
|
|
3193
3251
|
};
|
|
3194
3252
|
let result;
|
|
3195
3253
|
try {
|
|
3196
|
-
result = await
|
|
3254
|
+
result = await read.find(search, view, paging, void 0, toConsistencyToken(args.consistency));
|
|
3197
3255
|
} catch (error) {
|
|
3198
3256
|
throw new GraphQLError(`Failed to find documents: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3199
3257
|
}
|
|
@@ -3231,10 +3289,10 @@ function unknownJob(jobId) {
|
|
|
3231
3289
|
}
|
|
3232
3290
|
};
|
|
3233
3291
|
}
|
|
3234
|
-
async function jobStatus(
|
|
3292
|
+
async function jobStatus(read, args, serves, readable = serves) {
|
|
3235
3293
|
let result;
|
|
3236
3294
|
try {
|
|
3237
|
-
result = await
|
|
3295
|
+
result = await read.getJobStatus(args.jobId);
|
|
3238
3296
|
} catch (error) {
|
|
3239
3297
|
throw new GraphQLError(`Failed to fetch job status: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3240
3298
|
}
|
|
@@ -3254,7 +3312,7 @@ async function jobStatus(reactorClient, args, serves, readable = serves) {
|
|
|
3254
3312
|
throw new GraphQLError(`Failed to convert job status to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3255
3313
|
}
|
|
3256
3314
|
}
|
|
3257
|
-
async function documentOperations(
|
|
3315
|
+
async function documentOperations(read, args, subject) {
|
|
3258
3316
|
let view = subject ? { subject } : void 0;
|
|
3259
3317
|
const branch = fromInputMaybe(args.filter.branch);
|
|
3260
3318
|
const scopes = toMutableArray(fromInputMaybe(args.filter.scopes));
|
|
@@ -3285,7 +3343,7 @@ async function documentOperations(reactorClient, args, subject) {
|
|
|
3285
3343
|
}
|
|
3286
3344
|
let result;
|
|
3287
3345
|
try {
|
|
3288
|
-
result = await
|
|
3346
|
+
result = await read.getOperations(args.filter.documentIdOrSlug, view, operationFilter, paging);
|
|
3289
3347
|
} catch (error) {
|
|
3290
3348
|
throw new GraphQLError(`Failed to fetch document operations: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3291
3349
|
}
|
|
@@ -3308,7 +3366,7 @@ async function documentOperations(reactorClient, args, subject) {
|
|
|
3308
3366
|
* A reactor without authEnforcement raises the named error, which becomes an
|
|
3309
3367
|
* "unsupported" code rather than a denial.
|
|
3310
3368
|
*/
|
|
3311
|
-
async function evaluateActions(
|
|
3369
|
+
async function evaluateActions(write, args, subject) {
|
|
3312
3370
|
const branch = fromInputMaybe(args.branch) ?? "main";
|
|
3313
3371
|
const candidates = args.candidates.map((candidate) => ({
|
|
3314
3372
|
scope: candidate.scope,
|
|
@@ -3317,7 +3375,7 @@ async function evaluateActions(reactorClient, args, subject) {
|
|
|
3317
3375
|
}));
|
|
3318
3376
|
let result;
|
|
3319
3377
|
try {
|
|
3320
|
-
result = await
|
|
3378
|
+
result = await write.evaluateActions(args.documentIdOrSlug, branch, candidates, subject);
|
|
3321
3379
|
} catch (error) {
|
|
3322
3380
|
if (AuthEnforcementDisabledError.isError(error)) throw new AuthEvaluationUnsupportedError();
|
|
3323
3381
|
throw new GraphQLError(`Failed to evaluate actions: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
@@ -3332,11 +3390,11 @@ async function evaluateActions(reactorClient, args, subject) {
|
|
|
3332
3390
|
}
|
|
3333
3391
|
const isDocumentNotFound = (error) => error instanceof Error && error.name === "DocumentNotFoundError";
|
|
3334
3392
|
/** Refuses a slug another document holds: the reactor would move it to the new one. */
|
|
3335
|
-
async function assertSlugAvailable(
|
|
3393
|
+
async function assertSlugAvailable(read, slug, documentId) {
|
|
3336
3394
|
if (!slug || slug === documentId) return;
|
|
3337
3395
|
let holder;
|
|
3338
3396
|
try {
|
|
3339
|
-
const id = await
|
|
3397
|
+
const id = await read.resolveIdOrSlug(slug);
|
|
3340
3398
|
if (id === documentId) return;
|
|
3341
3399
|
holder = `document ${id}`;
|
|
3342
3400
|
} catch (error) {
|
|
@@ -3345,65 +3403,65 @@ async function assertSlugAvailable(reactorClient, slug, documentId) {
|
|
|
3345
3403
|
}
|
|
3346
3404
|
throw new GraphQLError(`The slug "${slug}" is taken by ${holder}; choose another.`);
|
|
3347
3405
|
}
|
|
3348
|
-
async function createDocument(
|
|
3406
|
+
async function createDocument(clients, args, reactorDriveClient, subject) {
|
|
3349
3407
|
if (!args.document || typeof args.document !== "object") throw new GraphQLError("Invalid document: must be an object");
|
|
3350
3408
|
const document = args.document;
|
|
3351
3409
|
if (!document.header || typeof document.header !== "object") throw new GraphQLError("Invalid document: missing or invalid header");
|
|
3352
3410
|
const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
|
|
3353
|
-
await assertSlugAvailable(
|
|
3354
|
-
let
|
|
3411
|
+
await assertSlugAvailable(clients.read, document.header.slug, document.header.id);
|
|
3412
|
+
let receipt;
|
|
3355
3413
|
try {
|
|
3356
3414
|
if (parentIdOrSlug) {
|
|
3357
|
-
const parent = await
|
|
3358
|
-
if (isDriveContainerType(parent.header.documentType))
|
|
3359
|
-
else
|
|
3360
|
-
} else
|
|
3415
|
+
const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
|
|
3416
|
+
if (isDriveContainerType(parent.header.documentType)) receipt = await addFileToDrive(clients, parent.header.documentType, parent.header.id, document, reactorDriveClient);
|
|
3417
|
+
else receipt = await (await clients.write.create(document, parentIdOrSlug)).readable;
|
|
3418
|
+
} else receipt = await (await clients.write.create(document)).readable;
|
|
3361
3419
|
} catch (error) {
|
|
3362
3420
|
throw new GraphQLError(`Failed to create document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3363
3421
|
}
|
|
3364
|
-
result = await readAsCaller(
|
|
3422
|
+
const result = await readAsCaller(clients.read, receipt, subject);
|
|
3365
3423
|
try {
|
|
3366
3424
|
return toGqlPhDocument(result);
|
|
3367
3425
|
} catch (error) {
|
|
3368
3426
|
throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3369
3427
|
}
|
|
3370
3428
|
}
|
|
3371
|
-
async function createEmptyDocument(
|
|
3429
|
+
async function createEmptyDocument(clients, args, reactorDriveClient, subject) {
|
|
3372
3430
|
const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
|
|
3373
3431
|
const name = fromInputMaybe(args.name);
|
|
3374
|
-
let
|
|
3432
|
+
let receipt;
|
|
3375
3433
|
try {
|
|
3376
3434
|
if (parentIdOrSlug) {
|
|
3377
|
-
const parent = await
|
|
3435
|
+
const parent = await clients.read.get(parentIdOrSlug, subject && { subject });
|
|
3378
3436
|
if (isDriveContainerType(parent.header.documentType)) {
|
|
3379
|
-
const module = await
|
|
3380
|
-
const document = withSignaturePolicy(module.utils.createDocument(), await
|
|
3437
|
+
const module = await clients.read.getDocumentModelModule(args.documentType);
|
|
3438
|
+
const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
|
|
3381
3439
|
if (name) document.header.name = name;
|
|
3382
|
-
|
|
3383
|
-
} else
|
|
3384
|
-
} else
|
|
3440
|
+
receipt = await addFileToDrive(clients, parent.header.documentType, parent.header.id, document, reactorDriveClient);
|
|
3441
|
+
} else receipt = await (await clients.write.createEmpty(args.documentType, { parentIdentifier: parentIdOrSlug })).readable;
|
|
3442
|
+
} else receipt = await (await clients.write.createEmpty(args.documentType, {})).readable;
|
|
3385
3443
|
} catch (error) {
|
|
3386
3444
|
throw new GraphQLError(`Failed to create empty document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3387
3445
|
}
|
|
3388
|
-
result = await readAsCaller(
|
|
3446
|
+
const result = await readAsCaller(clients.read, receipt, subject);
|
|
3389
3447
|
try {
|
|
3390
3448
|
return toGqlPhDocument(result);
|
|
3391
3449
|
} catch (error) {
|
|
3392
3450
|
throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3393
3451
|
}
|
|
3394
3452
|
}
|
|
3395
|
-
async function createDocumentWithInitialState(
|
|
3453
|
+
async function createDocumentWithInitialState(clients, args, reactorDriveClient, subject) {
|
|
3396
3454
|
const parentIdOrSlug = fromInputMaybe(args.parentIdOrSlug);
|
|
3397
3455
|
const name = fromInputMaybe(args.name);
|
|
3398
3456
|
const slug = fromInputMaybe(args.slug);
|
|
3399
3457
|
const preferredEditor = fromInputMaybe(args.preferredEditor);
|
|
3400
3458
|
let module;
|
|
3401
3459
|
try {
|
|
3402
|
-
module = await
|
|
3460
|
+
module = await clients.read.getDocumentModelModule(args.documentType);
|
|
3403
3461
|
} catch (error) {
|
|
3404
3462
|
throw new GraphQLError(`Document model not found for type ${args.documentType}: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3405
3463
|
}
|
|
3406
|
-
const document = withSignaturePolicy(module.utils.createDocument(), await
|
|
3464
|
+
const document = withSignaturePolicy(module.utils.createDocument(), await clients.read.getCreateSignaturePolicy());
|
|
3407
3465
|
const allowedScopes = new Set(Object.keys(module.documentModel.global.specifications.at(-1)?.state ?? {}));
|
|
3408
3466
|
const state = document.state;
|
|
3409
3467
|
for (const [scope, scopeState] of Object.entries(args.initialState)) if (allowedScopes.has(scope) && scope in state) state[scope] = {
|
|
@@ -3412,64 +3470,62 @@ async function createDocumentWithInitialState(reactorClient, args, reactorDriveC
|
|
|
3412
3470
|
};
|
|
3413
3471
|
if (name) document.header.name = name;
|
|
3414
3472
|
if (slug) {
|
|
3415
|
-
await assertSlugAvailable(
|
|
3473
|
+
await assertSlugAvailable(clients.read, slug);
|
|
3416
3474
|
document.header.slug = slug;
|
|
3417
3475
|
}
|
|
3418
3476
|
if (preferredEditor) document.header.meta = {
|
|
3419
3477
|
...document.header.meta,
|
|
3420
3478
|
preferredEditor
|
|
3421
3479
|
};
|
|
3422
|
-
let
|
|
3480
|
+
let receipt;
|
|
3423
3481
|
if (parentIdOrSlug) {
|
|
3424
3482
|
let parent;
|
|
3425
3483
|
try {
|
|
3426
|
-
parent = await
|
|
3484
|
+
parent = await clients.read.get(parentIdOrSlug, subject && { subject });
|
|
3427
3485
|
} catch (error) {
|
|
3428
3486
|
throw new GraphQLError(`Parent document not found: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3429
3487
|
}
|
|
3430
|
-
if (isDriveContainerType(parent.header.documentType)) {
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
} else try {
|
|
3438
|
-
result = await reactorClient.create(document, parentIdOrSlug);
|
|
3488
|
+
if (isDriveContainerType(parent.header.documentType)) try {
|
|
3489
|
+
receipt = await addFileToDrive(clients, parent.header.documentType, parent.header.id, document, reactorDriveClient);
|
|
3490
|
+
} catch (error) {
|
|
3491
|
+
throw new GraphQLError(`Failed to create document in drive: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3492
|
+
}
|
|
3493
|
+
else try {
|
|
3494
|
+
receipt = await (await clients.write.create(document, parentIdOrSlug)).readable;
|
|
3439
3495
|
} catch (error) {
|
|
3440
3496
|
throw new GraphQLError(`Failed to create document with parent: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3441
3497
|
}
|
|
3442
3498
|
} else try {
|
|
3443
|
-
|
|
3499
|
+
receipt = await (await clients.write.create(document)).readable;
|
|
3444
3500
|
} catch (error) {
|
|
3445
3501
|
throw new GraphQLError(`Failed to create document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3446
3502
|
}
|
|
3447
|
-
result = await readAsCaller(
|
|
3503
|
+
const result = await readAsCaller(clients.read, receipt, subject);
|
|
3448
3504
|
try {
|
|
3449
3505
|
return toGqlPhDocument(result);
|
|
3450
3506
|
} catch (error) {
|
|
3451
3507
|
throw new GraphQLError(`Failed to convert created document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3452
3508
|
}
|
|
3453
3509
|
}
|
|
3454
|
-
/** The branch a mutation applies to when the caller names none. */
|
|
3455
|
-
const DEFAULT_BRANCH = "main";
|
|
3456
3510
|
/**
|
|
3457
|
-
* Applies actions to a document and waits for the result
|
|
3511
|
+
* Applies actions to a document and waits for the result: the write half
|
|
3512
|
+
* submits, the read half reads the document back with the write's token.
|
|
3458
3513
|
*
|
|
3459
3514
|
* The wire form of `IReactorClient.execute`, and named for it. Takes the actions
|
|
3460
3515
|
* already coerced against `ActionInput`, so the only conversion left is the one
|
|
3461
3516
|
* the schema cannot express: a signature travels as one string, and verification
|
|
3462
3517
|
* reads it as the tuple it was.
|
|
3463
3518
|
*/
|
|
3464
|
-
async function execute(
|
|
3519
|
+
async function execute(clients, args, subject) {
|
|
3465
3520
|
const actions = toSubmittableActions(args.actions);
|
|
3466
3521
|
const branch = fromInputMaybe(args.branch) ?? DEFAULT_BRANCH;
|
|
3467
|
-
let
|
|
3522
|
+
let receipt;
|
|
3468
3523
|
try {
|
|
3469
|
-
|
|
3524
|
+
receipt = await (await clients.write.execute(args.documentIdOrSlug, branch, actions)).readable;
|
|
3470
3525
|
} catch (error) {
|
|
3471
3526
|
throw new GraphQLError(`Failed to execute actions: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3472
3527
|
}
|
|
3528
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3473
3529
|
try {
|
|
3474
3530
|
return toGqlPhDocument(result);
|
|
3475
3531
|
} catch (error) {
|
|
@@ -3483,15 +3539,21 @@ async function execute(reactorClient, args, subject) {
|
|
|
3483
3539
|
* `IReactorClient.executeAsync`. A job handed back from a submission has no
|
|
3484
3540
|
* result yet, which is why `JobInfo.result` is nullable.
|
|
3485
3541
|
*/
|
|
3486
|
-
async function executeAsync(
|
|
3542
|
+
async function executeAsync(clients, args) {
|
|
3487
3543
|
const actions = toSubmittableActions(args.actions);
|
|
3488
3544
|
const branch = fromInputMaybe(args.branch) ?? DEFAULT_BRANCH;
|
|
3489
|
-
let
|
|
3545
|
+
let jobId;
|
|
3490
3546
|
try {
|
|
3491
|
-
|
|
3547
|
+
jobId = (await clients.write.execute(args.documentIdOrSlug, branch, actions)).jobId;
|
|
3492
3548
|
} catch (error) {
|
|
3493
3549
|
throw new GraphQLError(`Failed to submit actions: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3494
3550
|
}
|
|
3551
|
+
let job;
|
|
3552
|
+
try {
|
|
3553
|
+
job = await clients.read.getJobStatus(jobId);
|
|
3554
|
+
} catch (error) {
|
|
3555
|
+
throw new GraphQLError(`Failed to read the submitted job: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3556
|
+
}
|
|
3495
3557
|
return toGqlJobInfo(job);
|
|
3496
3558
|
}
|
|
3497
3559
|
/** Authorized as a create, so only createDocument's own shape is accepted. */
|
|
@@ -3530,7 +3592,7 @@ function batchCreationOf(jobs) {
|
|
|
3530
3592
|
* dependents, so a failure is reported per job as a FAILED entry rather than a
|
|
3531
3593
|
* thrown error, which would lose what did commit.
|
|
3532
3594
|
*/
|
|
3533
|
-
async function executeBatch(
|
|
3595
|
+
async function executeBatch(write, args) {
|
|
3534
3596
|
const jobs = args.jobs.map((job) => ({
|
|
3535
3597
|
key: job.key,
|
|
3536
3598
|
documentId: job.documentIdOrSlug,
|
|
@@ -3539,17 +3601,7 @@ async function executeBatch(reactorClient, args) {
|
|
|
3539
3601
|
actions: toSubmittableActions(job.actions),
|
|
3540
3602
|
dependsOn: [...job.dependsOn]
|
|
3541
3603
|
}));
|
|
3542
|
-
|
|
3543
|
-
try {
|
|
3544
|
-
outcome = await reactorClient.executeBatch({ jobs });
|
|
3545
|
-
} catch (error) {
|
|
3546
|
-
if (!BatchJobFailedError.isError(error)) {
|
|
3547
|
-
const message = error instanceof Error ? error.message : "Unknown error";
|
|
3548
|
-
throw new GraphQLError(`Failed to execute batch: ${message}. Jobs dispatched before the failure may have committed.`);
|
|
3549
|
-
}
|
|
3550
|
-
outcome = error;
|
|
3551
|
-
}
|
|
3552
|
-
const settled = BatchJobFailedError.isError(outcome) ? outcome.jobs : await readBackJobs(reactorClient, jobs, outcome);
|
|
3604
|
+
const settled = await settleBatch(write, jobs);
|
|
3553
3605
|
try {
|
|
3554
3606
|
return { jobs: jobs.map((job) => {
|
|
3555
3607
|
if (!Object.hasOwn(settled, job.key)) throw new Error(`no job came back for plan key "${job.key}"`);
|
|
@@ -3563,20 +3615,38 @@ async function executeBatch(reactorClient, args) {
|
|
|
3563
3615
|
throw new GraphQLError(`Failed to convert batch result to GraphQL: ${message}`);
|
|
3564
3616
|
}
|
|
3565
3617
|
}
|
|
3566
|
-
/**
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3618
|
+
/**
|
|
3619
|
+
* Submits the batch and waits for every job to settle, handing back each job's
|
|
3620
|
+
* final state by plan key: from the receipts when all reached READ_READY, from
|
|
3621
|
+
* the failure when one FAILED (which carries every job's state).
|
|
3622
|
+
*/
|
|
3623
|
+
async function settleBatch(write, jobs) {
|
|
3624
|
+
const failed = (error) => {
|
|
3625
|
+
const message = error instanceof Error ? error.message : "Unknown error";
|
|
3626
|
+
throw new GraphQLError(`Failed to execute batch: ${message}. Jobs dispatched before the failure may have committed.`);
|
|
3627
|
+
};
|
|
3628
|
+
let batch;
|
|
3629
|
+
try {
|
|
3630
|
+
batch = await write.executeBatch({ jobs });
|
|
3631
|
+
} catch (error) {
|
|
3632
|
+
if (BatchJobFailedError.isError(error)) return error.jobs;
|
|
3633
|
+
return failed(error);
|
|
3634
|
+
}
|
|
3635
|
+
let receipts;
|
|
3636
|
+
try {
|
|
3637
|
+
receipts = await batch.readable;
|
|
3638
|
+
} catch (error) {
|
|
3639
|
+
if (BatchJobFailedError.isError(error)) return error.jobs;
|
|
3640
|
+
return failed(error);
|
|
3641
|
+
}
|
|
3642
|
+
const settled = {};
|
|
3643
|
+
for (const job of jobs) {
|
|
3644
|
+
if (!Object.hasOwn(receipts, job.key)) throw new GraphQLError(`Batch result is missing plan key "${job.key}"; the reactor returned jobs for [${Object.keys(receipts).join(", ")}]`);
|
|
3645
|
+
settled[job.key] = receipts[job.key].job;
|
|
3646
|
+
}
|
|
3647
|
+
return settled;
|
|
3578
3648
|
}
|
|
3579
|
-
async function mutateDocument(
|
|
3649
|
+
async function mutateDocument(clients, args, subject) {
|
|
3580
3650
|
let validatedActions;
|
|
3581
3651
|
try {
|
|
3582
3652
|
validatedActions = validateActions(args.actions);
|
|
@@ -3585,19 +3655,20 @@ async function mutateDocument(reactorClient, args, subject) {
|
|
|
3585
3655
|
throw new GraphQLError(`Action validation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3586
3656
|
}
|
|
3587
3657
|
const branch = args.view?.branch ?? "main";
|
|
3588
|
-
let
|
|
3658
|
+
let receipt;
|
|
3589
3659
|
try {
|
|
3590
|
-
|
|
3660
|
+
receipt = await (await clients.write.execute(args.documentIdentifier, branch, validatedActions)).readable;
|
|
3591
3661
|
} catch (error) {
|
|
3592
3662
|
throw new GraphQLError(`Failed to mutate document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3593
3663
|
}
|
|
3664
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3594
3665
|
try {
|
|
3595
3666
|
return toGqlPhDocument(result);
|
|
3596
3667
|
} catch (error) {
|
|
3597
3668
|
throw new GraphQLError(`Failed to convert mutated document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3598
3669
|
}
|
|
3599
3670
|
}
|
|
3600
|
-
async function mutateDocumentAsync(
|
|
3671
|
+
async function mutateDocumentAsync(write, args) {
|
|
3601
3672
|
let validatedActions;
|
|
3602
3673
|
try {
|
|
3603
3674
|
validatedActions = validateActions(args.actions);
|
|
@@ -3606,103 +3677,103 @@ async function mutateDocumentAsync(reactorClient, args) {
|
|
|
3606
3677
|
throw new GraphQLError(`Action validation failed: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3607
3678
|
}
|
|
3608
3679
|
const branch = args.view?.branch ?? "main";
|
|
3609
|
-
let result;
|
|
3610
3680
|
try {
|
|
3611
|
-
|
|
3681
|
+
return (await write.execute(args.documentIdentifier, branch, validatedActions)).jobId;
|
|
3612
3682
|
} catch (error) {
|
|
3613
3683
|
throw new GraphQLError(`Failed to submit document mutation: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3614
3684
|
}
|
|
3615
|
-
return result.id;
|
|
3616
3685
|
}
|
|
3617
|
-
async function renameDocument(
|
|
3686
|
+
async function renameDocument(clients, args, signal, subject) {
|
|
3618
3687
|
const branch = fromInputMaybe(args.branch);
|
|
3619
|
-
let
|
|
3688
|
+
let receipt;
|
|
3620
3689
|
try {
|
|
3621
|
-
|
|
3690
|
+
receipt = await (await clients.write.rename(args.documentIdOrSlug, args.name, branch, signal)).readable;
|
|
3622
3691
|
} catch (error) {
|
|
3623
3692
|
throw new GraphQLError(`Failed to rename document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3624
3693
|
}
|
|
3625
|
-
result = await readAsCaller(
|
|
3694
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3626
3695
|
try {
|
|
3627
3696
|
return toGqlPhDocument(result);
|
|
3628
3697
|
} catch (error) {
|
|
3629
3698
|
throw new GraphQLError(`Failed to convert renamed document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3630
3699
|
}
|
|
3631
3700
|
}
|
|
3632
|
-
async function setPreferredEditor(
|
|
3701
|
+
async function setPreferredEditor(clients, args, signal, subject) {
|
|
3633
3702
|
const branch = fromInputMaybe(args.branch);
|
|
3634
3703
|
const preferredEditor = fromInputMaybe(args.preferredEditor) ?? null;
|
|
3635
|
-
let
|
|
3704
|
+
let receipt;
|
|
3636
3705
|
try {
|
|
3637
|
-
|
|
3706
|
+
receipt = await (await clients.write.setPreferredEditor(args.documentIdOrSlug, preferredEditor, branch, signal)).readable;
|
|
3638
3707
|
} catch (error) {
|
|
3639
3708
|
throw new GraphQLError(`Failed to set preferred editor: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3640
3709
|
}
|
|
3641
|
-
result = await readAsCaller(
|
|
3710
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3642
3711
|
try {
|
|
3643
3712
|
return toGqlPhDocument(result);
|
|
3644
3713
|
} catch (error) {
|
|
3645
3714
|
throw new GraphQLError(`Failed to convert updated document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3646
3715
|
}
|
|
3647
3716
|
}
|
|
3648
|
-
async function addRelationship(
|
|
3717
|
+
async function addRelationship(clients, args, subject) {
|
|
3649
3718
|
const branch = fromInputMaybe(args.branch);
|
|
3650
3719
|
const metadata = fromInputMaybe(args.metadata);
|
|
3651
|
-
let
|
|
3720
|
+
let receipt;
|
|
3652
3721
|
try {
|
|
3653
|
-
|
|
3722
|
+
receipt = await (await clients.write.addRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, metadata, branch)).readable;
|
|
3654
3723
|
} catch (error) {
|
|
3655
3724
|
throw new GraphQLError(`Failed to add relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3656
3725
|
}
|
|
3657
|
-
result = await readAsCaller(
|
|
3726
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3658
3727
|
try {
|
|
3659
3728
|
return toGqlPhDocument(result);
|
|
3660
3729
|
} catch (error) {
|
|
3661
3730
|
throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3662
3731
|
}
|
|
3663
3732
|
}
|
|
3664
|
-
async function updateRelationship(
|
|
3733
|
+
async function updateRelationship(clients, args, subject) {
|
|
3665
3734
|
const branch = fromInputMaybe(args.branch);
|
|
3666
3735
|
const metadata = fromInputMaybe(args.metadata) ?? null;
|
|
3667
|
-
let
|
|
3736
|
+
let receipt;
|
|
3668
3737
|
try {
|
|
3669
|
-
|
|
3738
|
+
receipt = await (await clients.write.updateRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, metadata, branch)).readable;
|
|
3670
3739
|
} catch (error) {
|
|
3671
3740
|
throw new GraphQLError(`Failed to update relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3672
3741
|
}
|
|
3673
|
-
result = await readAsCaller(
|
|
3742
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3674
3743
|
try {
|
|
3675
3744
|
return toGqlPhDocument(result);
|
|
3676
3745
|
} catch (error) {
|
|
3677
3746
|
throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3678
3747
|
}
|
|
3679
3748
|
}
|
|
3680
|
-
async function removeRelationship(
|
|
3749
|
+
async function removeRelationship(clients, args, subject) {
|
|
3681
3750
|
const branch = fromInputMaybe(args.branch);
|
|
3682
|
-
let
|
|
3751
|
+
let receipt;
|
|
3683
3752
|
try {
|
|
3684
|
-
|
|
3753
|
+
receipt = await (await clients.write.removeRelationship(args.sourceIdOrSlug, args.targetIdOrSlug, args.relationshipType, branch)).readable;
|
|
3685
3754
|
} catch (error) {
|
|
3686
3755
|
throw new GraphQLError(`Failed to remove relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3687
3756
|
}
|
|
3688
|
-
result = await readAsCaller(
|
|
3757
|
+
const result = await readAsCaller(clients.read, receipt, subject, branch);
|
|
3689
3758
|
try {
|
|
3690
3759
|
return toGqlPhDocument(result);
|
|
3691
3760
|
} catch (error) {
|
|
3692
3761
|
throw new GraphQLError(`Failed to convert document to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3693
3762
|
}
|
|
3694
3763
|
}
|
|
3695
|
-
async function moveRelationship(
|
|
3764
|
+
async function moveRelationship(clients, args, subject) {
|
|
3696
3765
|
const branch = fromInputMaybe(args.branch);
|
|
3697
|
-
let
|
|
3766
|
+
let removed;
|
|
3767
|
+
let added;
|
|
3698
3768
|
try {
|
|
3699
|
-
|
|
3769
|
+
const handles = await clients.write.moveRelationship(args.sourceParentIdOrSlug, args.targetParentIdOrSlug, args.targetIdOrSlug, args.relationshipType, branch);
|
|
3770
|
+
[removed, added] = await Promise.all([handles.removed.readable, handles.added.readable]);
|
|
3700
3771
|
} catch (error) {
|
|
3701
3772
|
throw new GraphQLError(`Failed to move relationship: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3702
3773
|
}
|
|
3703
|
-
result = {
|
|
3704
|
-
source: await readAsCaller(
|
|
3705
|
-
target: await readAsCaller(
|
|
3774
|
+
const result = {
|
|
3775
|
+
source: await readAsCaller(clients.read, removed, subject, branch),
|
|
3776
|
+
target: await readAsCaller(clients.read, added, subject, branch)
|
|
3706
3777
|
};
|
|
3707
3778
|
try {
|
|
3708
3779
|
return {
|
|
@@ -3713,25 +3784,25 @@ async function moveRelationship(reactorClient, args, subject) {
|
|
|
3713
3784
|
throw new GraphQLError(`Failed to convert documents to GraphQL: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3714
3785
|
}
|
|
3715
3786
|
}
|
|
3716
|
-
async function deleteDocument(
|
|
3787
|
+
async function deleteDocument(clients, args, reactorDriveClient) {
|
|
3717
3788
|
const propagate = toReactorPropagationMode(args.propagate);
|
|
3718
3789
|
try {
|
|
3719
|
-
const driveParent = (await
|
|
3790
|
+
const driveParent = (await clients.read.getIncomingRelationships(args.idOrSlug, "child")).results.find((p) => isDriveContainerType(p.header.documentType));
|
|
3720
3791
|
if (driveParent) {
|
|
3721
|
-
const
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
} else await reactorClient.deleteDocument(args.idOrSlug, propagate);
|
|
3792
|
+
const documentId = await clients.read.resolveIdOrSlug(args.idOrSlug);
|
|
3793
|
+
await removeNodeFromDrive(clients, driveParent.header.documentType, driveParent.header.id, documentId, reactorDriveClient);
|
|
3794
|
+
} else await (await clients.write.deleteDocument(args.idOrSlug, propagate)).readable;
|
|
3725
3795
|
return true;
|
|
3726
3796
|
} catch (error) {
|
|
3727
3797
|
throw new GraphQLError(`Failed to delete document: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
3728
3798
|
}
|
|
3729
3799
|
}
|
|
3730
|
-
async function deleteDocuments(
|
|
3800
|
+
async function deleteDocuments(write, args) {
|
|
3731
3801
|
const propagate = toReactorPropagationMode(args.propagate);
|
|
3732
3802
|
const idsOrSlugs = [...args.idsOrSlugs];
|
|
3733
3803
|
try {
|
|
3734
|
-
await
|
|
3804
|
+
const handles = await write.deleteDocuments(idsOrSlugs, propagate);
|
|
3805
|
+
await Promise.all(handles.map((handle) => handle.readable));
|
|
3735
3806
|
return true;
|
|
3736
3807
|
} catch (error) {
|
|
3737
3808
|
throw new GraphQLError(`Failed to delete documents: ${error instanceof Error ? error.message : "Unknown error"}`);
|
|
@@ -4086,8 +4157,9 @@ async function pushSyncEnvelopes(syncManager, args) {
|
|
|
4086
4157
|
//#endregion
|
|
4087
4158
|
//#region src/graphql/document-model-subgraph.ts
|
|
4088
4159
|
/**
|
|
4089
|
-
*
|
|
4090
|
-
*
|
|
4160
|
+
* Auto-generates GraphQL queries and mutations for a document model. Queries
|
|
4161
|
+
* read through `ctx.clients.read`; mutations write through `ctx.clients.write`
|
|
4162
|
+
* and read their document back with the write's token.
|
|
4091
4163
|
*/
|
|
4092
4164
|
var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
4093
4165
|
documentModel;
|
|
@@ -4112,6 +4184,19 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4112
4184
|
const documentName = getDocumentModelSchemaName(this.documentModel.documentModel.global);
|
|
4113
4185
|
return this.resolvers[`${documentName}Mutations`];
|
|
4114
4186
|
}
|
|
4187
|
+
/**
|
|
4188
|
+
* Refuses a model operation on a document of another type. Asked of the
|
|
4189
|
+
* write half (`describe`), which answers for what the write path sees.
|
|
4190
|
+
*/
|
|
4191
|
+
async #assertDocumentType(clients, documentId, requested, documentType) {
|
|
4192
|
+
let target;
|
|
4193
|
+
try {
|
|
4194
|
+
target = await clients.write.describe(documentId);
|
|
4195
|
+
} catch (error) {
|
|
4196
|
+
throw new GraphQLError(error instanceof Error ? error.message : "Document not found");
|
|
4197
|
+
}
|
|
4198
|
+
if (target.documentType !== documentType) throw new GraphQLError(`Document with id ${requested} is not of type ${documentType}`);
|
|
4199
|
+
}
|
|
4115
4200
|
/** Drops the items the host's own ACL refuses the caller. */
|
|
4116
4201
|
async #readableItems(page, ctx) {
|
|
4117
4202
|
return {
|
|
@@ -4177,7 +4262,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4177
4262
|
const idOrSlug = requireOneOf(args, "idOrSlug", "identifier");
|
|
4178
4263
|
const { view } = args;
|
|
4179
4264
|
if (!idOrSlug) throw new GraphQLError("Document identifier is required");
|
|
4180
|
-
const result = await document(this.
|
|
4265
|
+
const result = await document(this.clientsOf(ctx).read, {
|
|
4181
4266
|
idOrSlug,
|
|
4182
4267
|
view
|
|
4183
4268
|
}, this.viewSubject(ctx));
|
|
@@ -4187,7 +4272,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4187
4272
|
},
|
|
4188
4273
|
documents: async (_, args, ctx) => {
|
|
4189
4274
|
const { paging } = args;
|
|
4190
|
-
const result = await findDocuments(this.
|
|
4275
|
+
const result = await findDocuments(this.clientsOf(ctx).read, {
|
|
4191
4276
|
search: { type: documentType },
|
|
4192
4277
|
paging
|
|
4193
4278
|
}, this.viewSubject(ctx));
|
|
@@ -4195,7 +4280,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4195
4280
|
},
|
|
4196
4281
|
findDocuments: async (_, args, ctx) => {
|
|
4197
4282
|
const { search, view, paging } = args;
|
|
4198
|
-
const result = await findDocuments(this.
|
|
4283
|
+
const result = await findDocuments(this.clientsOf(ctx).read, {
|
|
4199
4284
|
search: {
|
|
4200
4285
|
type: documentType,
|
|
4201
4286
|
parentId: search?.parentId
|
|
@@ -4209,7 +4294,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4209
4294
|
const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
|
|
4210
4295
|
const { relationshipType, view, paging } = args;
|
|
4211
4296
|
const handle = await this.assertCanRead(sourceIdOrSlug, ctx);
|
|
4212
|
-
const result = await documentOutgoingRelationships(this.
|
|
4297
|
+
const result = await documentOutgoingRelationships(this.clientsOf(ctx).read, {
|
|
4213
4298
|
sourceIdOrSlug: handle.fetchIdentifier,
|
|
4214
4299
|
relationshipType,
|
|
4215
4300
|
view,
|
|
@@ -4226,7 +4311,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4226
4311
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
4227
4312
|
const { relationshipType, view, paging } = args;
|
|
4228
4313
|
const handle = await this.assertCanRead(targetIdOrSlug, ctx);
|
|
4229
|
-
const result = await documentIncomingRelationships(this.
|
|
4314
|
+
const result = await documentIncomingRelationships(this.clientsOf(ctx).read, {
|
|
4230
4315
|
targetIdOrSlug: handle.fetchIdentifier,
|
|
4231
4316
|
relationshipType,
|
|
4232
4317
|
view,
|
|
@@ -4244,7 +4329,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4244
4329
|
else this.assertCanCreate(ctx);
|
|
4245
4330
|
const withHeader = !!(initialState || preferredEditor || slug);
|
|
4246
4331
|
let createdDoc;
|
|
4247
|
-
if (withHeader) createdDoc = await createDocumentWithInitialState(this.
|
|
4332
|
+
if (withHeader) createdDoc = await createDocumentWithInitialState(this.clientsOf(ctx), {
|
|
4248
4333
|
documentType,
|
|
4249
4334
|
parentIdOrSlug,
|
|
4250
4335
|
name,
|
|
@@ -4252,20 +4337,24 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4252
4337
|
preferredEditor,
|
|
4253
4338
|
initialState: initialState ?? {}
|
|
4254
4339
|
}, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
|
|
4255
|
-
else createdDoc = await createEmptyDocument(this.
|
|
4340
|
+
else createdDoc = await createEmptyDocument(this.clientsOf(ctx), {
|
|
4256
4341
|
documentType,
|
|
4257
4342
|
parentIdOrSlug,
|
|
4258
4343
|
name
|
|
4259
4344
|
}, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
|
|
4260
4345
|
if (ctx.user?.address && createdDoc?.id) await this.documentPermissionService?.initializeDocumentProtection(createdDoc.id, ctx.user.address, this.authorizationService.config.defaultProtection);
|
|
4261
|
-
if (!withHeader && name && createdDoc.name !== name)
|
|
4346
|
+
if (!withHeader && name && createdDoc.name !== name) {
|
|
4347
|
+
const clients = this.clientsOf(ctx);
|
|
4348
|
+
const renamed = await clients.write.execute(createdDoc.id, "main", [setName(name)]);
|
|
4349
|
+
return toGqlPhDocument(await readAsCaller(clients.read, await renamed.readable, this.viewSubject(ctx)));
|
|
4350
|
+
}
|
|
4262
4351
|
return createdDoc;
|
|
4263
4352
|
},
|
|
4264
4353
|
createEmptyDocument: async (_, args, ctx) => {
|
|
4265
4354
|
let parentIdOrSlug = optionalOneOf(args, "parentIdOrSlug", "parentIdentifier");
|
|
4266
4355
|
if (parentIdOrSlug) parentIdOrSlug = (await this.assertCanWrite(parentIdOrSlug, ctx)).fetchIdentifier;
|
|
4267
4356
|
else this.assertCanCreate(ctx);
|
|
4268
|
-
const result = await createEmptyDocument(this.
|
|
4357
|
+
const result = await createEmptyDocument(this.clientsOf(ctx), {
|
|
4269
4358
|
documentType,
|
|
4270
4359
|
parentIdOrSlug
|
|
4271
4360
|
}, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
|
|
@@ -4277,24 +4366,28 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
|
|
|
4277
4366
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "docId");
|
|
4278
4367
|
const { input } = args;
|
|
4279
4368
|
const effectiveDocId = (await this.assertCanExecuteOperation(documentIdOrSlug, op.name, ctx)).fetchIdentifier;
|
|
4280
|
-
|
|
4369
|
+
const clients = this.clientsOf(ctx);
|
|
4370
|
+
await this.#assertDocumentType(clients, effectiveDocId, documentIdOrSlug, documentType);
|
|
4281
4371
|
const action = this.documentModel.actions[camelCase(op.name)];
|
|
4282
4372
|
if (!action) throw new GraphQLError(`Action ${op.name} not found`);
|
|
4373
|
+
let receipt;
|
|
4283
4374
|
try {
|
|
4284
|
-
|
|
4375
|
+
receipt = await (await clients.write.execute(effectiveDocId, "main", [action(input)])).readable;
|
|
4285
4376
|
} catch (error) {
|
|
4286
4377
|
throw new GraphQLError(error instanceof Error ? error.message : `Failed to ${op.name}`);
|
|
4287
4378
|
}
|
|
4379
|
+
return toGqlPhDocument(await readAsCaller(clients.read, receipt, this.viewSubject(ctx)));
|
|
4288
4380
|
};
|
|
4289
4381
|
mutations[`${camelCase(op.name)}Async`] = async (_, args, ctx) => {
|
|
4290
4382
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "docId");
|
|
4291
4383
|
const { input } = args;
|
|
4292
4384
|
const effectiveDocId = (await this.assertCanExecuteOperation(documentIdOrSlug, op.name, ctx)).fetchIdentifier;
|
|
4293
|
-
|
|
4385
|
+
const clients = this.clientsOf(ctx);
|
|
4386
|
+
await this.#assertDocumentType(clients, effectiveDocId, documentIdOrSlug, documentType);
|
|
4294
4387
|
const action = this.documentModel.actions[camelCase(op.name)];
|
|
4295
4388
|
if (!action) throw new GraphQLError(`Action ${op.name} not found`);
|
|
4296
4389
|
try {
|
|
4297
|
-
return (await
|
|
4390
|
+
return (await clients.write.execute(effectiveDocId, "main", [action(input)])).jobId;
|
|
4298
4391
|
} catch (error) {
|
|
4299
4392
|
throw new GraphQLError(error instanceof Error ? error.message : `Failed to ${op.name}`);
|
|
4300
4393
|
}
|
|
@@ -5304,7 +5397,11 @@ var GraphQLManager = class {
|
|
|
5304
5397
|
path;
|
|
5305
5398
|
httpServer;
|
|
5306
5399
|
wsServer;
|
|
5307
|
-
|
|
5400
|
+
#readClient;
|
|
5401
|
+
#facade;
|
|
5402
|
+
#clients;
|
|
5403
|
+
/** What a context carries before its operation is known: no write. */
|
|
5404
|
+
#unboundClients;
|
|
5308
5405
|
relationalDb;
|
|
5309
5406
|
analyticsStore;
|
|
5310
5407
|
syncManager;
|
|
@@ -5325,7 +5422,11 @@ var GraphQLManager = class {
|
|
|
5325
5422
|
this.path = options.path;
|
|
5326
5423
|
this.httpServer = options.httpServer;
|
|
5327
5424
|
this.wsServer = options.wsServer;
|
|
5328
|
-
|
|
5425
|
+
const { read, write } = resolveClientHalves(options);
|
|
5426
|
+
this.#readClient = read;
|
|
5427
|
+
this.#facade = options.reactorClient;
|
|
5428
|
+
this.#clients = new RequestClientBinder(read, write);
|
|
5429
|
+
this.#unboundClients = this.#clients.unboundClients();
|
|
5329
5430
|
this.relationalDb = options.relationalDb;
|
|
5330
5431
|
this.analyticsStore = options.analyticsStore;
|
|
5331
5432
|
this.syncManager = options.syncManager;
|
|
@@ -5356,7 +5457,7 @@ var GraphQLManager = class {
|
|
|
5356
5457
|
logger: options.logger,
|
|
5357
5458
|
report: options.reportError
|
|
5358
5459
|
};
|
|
5359
|
-
this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this
|
|
5460
|
+
this.driveOwnershipCache = new DriveOwnershipCache(options.driveStore ?? this.#readClient);
|
|
5360
5461
|
this.#wsRouter = new SubgraphWsRouter({
|
|
5361
5462
|
order: (subgraphs) => this.#byClaimPriority(subgraphs),
|
|
5362
5463
|
logger: this.logger
|
|
@@ -5369,7 +5470,7 @@ var GraphQLManager = class {
|
|
|
5369
5470
|
await this.driveOwnershipCache.init();
|
|
5370
5471
|
this.#driveMiddleware = createDriveFetchMiddleware(this.driveOwnershipCache);
|
|
5371
5472
|
this.logger.debug(`Drive ownership cache populated with ${this.driveOwnershipCache.size()} drives`);
|
|
5372
|
-
const models = (await this.
|
|
5473
|
+
const models = (await this.#readClient.getDocumentModelModules()).results;
|
|
5373
5474
|
if (!models.find((it) => it.documentModel.global.name === "DocumentDrive")) throw new Error("DocumentDrive model required");
|
|
5374
5475
|
await this.gatewayAdapter.start(this.httpServer);
|
|
5375
5476
|
this.httpAdapter.setupMiddleware({ bodyLimit: "50mb" });
|
|
@@ -5382,7 +5483,7 @@ var GraphQLManager = class {
|
|
|
5382
5483
|
if (!driveIdOrSlug) return Response.json({ error: "Drive ID or slug is required" }, { status: 400 });
|
|
5383
5484
|
const user = getAuthContext(request)?.user;
|
|
5384
5485
|
try {
|
|
5385
|
-
const driveDoc = await this.
|
|
5486
|
+
const driveDoc = await this.#readClient.get(driveIdOrSlug, { subject: callerSubject(user) });
|
|
5386
5487
|
if (!await this.authorizationService.canRead(driveDoc.header.id, user?.address)) {
|
|
5387
5488
|
this.logger.debug(`Drive read refused: ${driveIdOrSlug}`);
|
|
5388
5489
|
return Response.json({ error: "Drive not found" }, { status: 404 });
|
|
@@ -5420,7 +5521,7 @@ var GraphQLManager = class {
|
|
|
5420
5521
|
}
|
|
5421
5522
|
async #regenerateDocumentModelSubgraphs() {
|
|
5422
5523
|
try {
|
|
5423
|
-
const models = (await this.
|
|
5524
|
+
const models = (await this.#readClient.getDocumentModelModules()).results;
|
|
5424
5525
|
this.cachedDocumentModels = this.#admitModels(models);
|
|
5425
5526
|
const registeredNames = await this.#setupDocumentModelSubgraphs("graphql", this.cachedDocumentModels);
|
|
5426
5527
|
await this.#pruneOrigin(DOCUMENT_MODEL_ORIGIN, registeredNames);
|
|
@@ -5465,7 +5566,8 @@ var GraphQLManager = class {
|
|
|
5465
5566
|
http: this.scopeForPackage(CORE_PACKAGE_NAME),
|
|
5466
5567
|
relationalDb: this.relationalDb,
|
|
5467
5568
|
analyticsStore: this.analyticsStore,
|
|
5468
|
-
|
|
5569
|
+
readClient: this.#readClient,
|
|
5570
|
+
reactorClient: this.#facade,
|
|
5469
5571
|
graphqlManager: this,
|
|
5470
5572
|
syncManager: this.syncManager,
|
|
5471
5573
|
path: this.path,
|
|
@@ -5819,7 +5921,8 @@ var GraphQLManager = class {
|
|
|
5819
5921
|
http: this.scopeForPackage(packageName ?? "@powerhousedao/reactor-api"),
|
|
5820
5922
|
relationalDb: this.relationalDb,
|
|
5821
5923
|
analyticsStore: this.analyticsStore,
|
|
5822
|
-
|
|
5924
|
+
readClient: this.#readClient,
|
|
5925
|
+
reactorClient: this.#facade,
|
|
5823
5926
|
graphqlManager: this,
|
|
5824
5927
|
syncManager: this.syncManager,
|
|
5825
5928
|
path: this.path,
|
|
@@ -6000,7 +6103,8 @@ var GraphQLManager = class {
|
|
|
6000
6103
|
db: this.relationalDb,
|
|
6001
6104
|
...this.getAdditionalContextFields(),
|
|
6002
6105
|
driveId,
|
|
6003
|
-
user: authCtx?.user
|
|
6106
|
+
user: authCtx?.user,
|
|
6107
|
+
clients: this.#unboundClients
|
|
6004
6108
|
});
|
|
6005
6109
|
};
|
|
6006
6110
|
}
|
|
@@ -6014,7 +6118,8 @@ var GraphQLManager = class {
|
|
|
6014
6118
|
headers: connectionParams,
|
|
6015
6119
|
db: this.relationalDb,
|
|
6016
6120
|
...this.getAdditionalContextFields(),
|
|
6017
|
-
user
|
|
6121
|
+
user,
|
|
6122
|
+
clients: this.#unboundClients
|
|
6018
6123
|
})
|
|
6019
6124
|
});
|
|
6020
6125
|
}
|
|
@@ -6081,7 +6186,7 @@ var GraphQLManager = class {
|
|
|
6081
6186
|
} else this.#unmountSubgraph(cached.subgraph, supergraph);
|
|
6082
6187
|
}
|
|
6083
6188
|
const generated = this.#generated();
|
|
6084
|
-
const schema = createSchema(this.cachedDocumentModels, subgraph
|
|
6189
|
+
const schema = createSchema(this.cachedDocumentModels, this.#boundResolvers(subgraph), subgraph.typeDefs, this.#schemaOptions(subgraph));
|
|
6085
6190
|
const rawHandler = await this.gatewayAdapter.createHandler(schema, this.#makeContextFactory());
|
|
6086
6191
|
if (!subgraphsMap.get(supergraph)?.includes(subgraph)) continue;
|
|
6087
6192
|
if (generated !== this.#generated()) continue;
|
|
@@ -6179,8 +6284,21 @@ var GraphQLManager = class {
|
|
|
6179
6284
|
});
|
|
6180
6285
|
return claims;
|
|
6181
6286
|
}
|
|
6287
|
+
/**
|
|
6288
|
+
* The subgraph's resolvers, each handed the context for the operation it runs
|
|
6289
|
+
* in: `ctx.clients.write` only in a mutation, or in a query field a core
|
|
6290
|
+
* subgraph declares in `writeSideQueries`.
|
|
6291
|
+
*/
|
|
6292
|
+
#boundResolvers(subgraph) {
|
|
6293
|
+
const writeSide = subgraph.writeSideQueries && this.#isCore(subgraph) ? new Set(subgraph.writeSideQueries) : void 0;
|
|
6294
|
+
return this.#clients.bindResolvers(subgraph.resolvers, writeSide);
|
|
6295
|
+
}
|
|
6296
|
+
#isCore(subgraph) {
|
|
6297
|
+
for (const subgraphs of this.coreSubgraphsMap.values()) if (subgraphs.includes(subgraph)) return true;
|
|
6298
|
+
return false;
|
|
6299
|
+
}
|
|
6182
6300
|
#buildSubgraphSchemaModule(subgraph) {
|
|
6183
|
-
return buildSubgraphSchemaModule(this.cachedDocumentModels, subgraph
|
|
6301
|
+
return buildSubgraphSchemaModule(this.cachedDocumentModels, this.#boundResolvers(subgraph), subgraph.typeDefs, this.#schemaOptions(subgraph));
|
|
6184
6302
|
}
|
|
6185
6303
|
#getSubgraphDefinitions() {
|
|
6186
6304
|
const subgraphs = this.#getSupergraphSubgraphs();
|
|
@@ -6320,6 +6438,26 @@ function subscriptionOwners(subgraphs, schema) {
|
|
|
6320
6438
|
return tags;
|
|
6321
6439
|
};
|
|
6322
6440
|
}
|
|
6441
|
+
/**
|
|
6442
|
+
* The client halves a manager runs on: the ones passed, or, from a deprecated
|
|
6443
|
+
* facade, its own halves. A facade without halves (an older implementation)
|
|
6444
|
+
* is itself the read half and is adapted for writes.
|
|
6445
|
+
*/
|
|
6446
|
+
function resolveClientHalves(options) {
|
|
6447
|
+
if (options.readClient && options.writeClient) return {
|
|
6448
|
+
read: options.readClient,
|
|
6449
|
+
write: options.writeClient
|
|
6450
|
+
};
|
|
6451
|
+
const facade = options.reactorClient;
|
|
6452
|
+
if (!facade) throw new Error("GraphQLManager needs readClient and writeClient (or a reactorClient)");
|
|
6453
|
+
warnOnce("GraphQLManagerOptions.reactorClient", "Pass readClient and writeClient; the facade is kept for subgraphs only.");
|
|
6454
|
+
const read = facade.read;
|
|
6455
|
+
const write = facade.write;
|
|
6456
|
+
return {
|
|
6457
|
+
read: options.readClient ?? (typeof read?.get === "function" ? read : facade),
|
|
6458
|
+
write: options.writeClient ?? (typeof write?.execute === "function" ? write : new FacadeWriteClient(facade))
|
|
6459
|
+
};
|
|
6460
|
+
}
|
|
6323
6461
|
//#endregion
|
|
6324
6462
|
//#region src/graphql/inspection/resolvers.ts
|
|
6325
6463
|
function operatorRequired() {
|
|
@@ -6509,11 +6647,11 @@ var InspectionSubgraph = class extends BaseSubgraph {
|
|
|
6509
6647
|
readerFor(ctx) {
|
|
6510
6648
|
const subject = this.viewSubject(ctx);
|
|
6511
6649
|
return {
|
|
6512
|
-
find: (search, view, paging) => this.
|
|
6650
|
+
find: (search, view, paging) => this.clientsOf(ctx).read.find(search, {
|
|
6513
6651
|
...view,
|
|
6514
6652
|
subject
|
|
6515
6653
|
}, paging),
|
|
6516
|
-
get: (id, view) => this.
|
|
6654
|
+
get: (id, view) => this.clientsOf(ctx).read.get(id, {
|
|
6517
6655
|
...view,
|
|
6518
6656
|
subject
|
|
6519
6657
|
})
|
|
@@ -6526,12 +6664,12 @@ var InspectionSubgraph = class extends BaseSubgraph {
|
|
|
6526
6664
|
};
|
|
6527
6665
|
let served;
|
|
6528
6666
|
try {
|
|
6529
|
-
served = await this.
|
|
6667
|
+
served = await this.clientsOf(ctx).read.isServed(identifier, view);
|
|
6530
6668
|
} catch {
|
|
6531
6669
|
return;
|
|
6532
6670
|
}
|
|
6533
6671
|
if (!served) return;
|
|
6534
|
-
const document = await this.
|
|
6672
|
+
const document = await this.clientsOf(ctx).read.get(identifier, view);
|
|
6535
6673
|
return {
|
|
6536
6674
|
id: document.header.id,
|
|
6537
6675
|
scopes: new Set(Object.keys(document.state ?? {}))
|
|
@@ -7230,11 +7368,11 @@ function subjectKey(subject) {
|
|
|
7230
7368
|
* would gate every subscriber as the host.
|
|
7231
7369
|
*/
|
|
7232
7370
|
var DocumentChangeFeed = class {
|
|
7233
|
-
|
|
7371
|
+
read;
|
|
7234
7372
|
#pubSub = new PubSub();
|
|
7235
7373
|
#feeds = /* @__PURE__ */ new Map();
|
|
7236
|
-
constructor(
|
|
7237
|
-
this.
|
|
7374
|
+
constructor(read) {
|
|
7375
|
+
this.read = read;
|
|
7238
7376
|
}
|
|
7239
7377
|
subscribe(subject) {
|
|
7240
7378
|
const key = subjectKey(subject);
|
|
@@ -7270,7 +7408,7 @@ var DocumentChangeFeed = class {
|
|
|
7270
7408
|
return;
|
|
7271
7409
|
}
|
|
7272
7410
|
const view = { subject };
|
|
7273
|
-
const unsubscribe = this.
|
|
7411
|
+
const unsubscribe = this.read.subscribe({}, (event) => {
|
|
7274
7412
|
const payload = {
|
|
7275
7413
|
documentChanges: event,
|
|
7276
7414
|
search: {},
|
|
@@ -7294,14 +7432,14 @@ var DocumentChangeFeed = class {
|
|
|
7294
7432
|
}
|
|
7295
7433
|
};
|
|
7296
7434
|
const activeJobSubscriptions = /* @__PURE__ */ new Map();
|
|
7297
|
-
function ensureJobSubscription(
|
|
7435
|
+
function ensureJobSubscription(read, jobId) {
|
|
7298
7436
|
let subscription = activeJobSubscriptions.get(jobId);
|
|
7299
7437
|
if (!subscription) {
|
|
7300
7438
|
let isCancelled = false;
|
|
7301
7439
|
let timeoutId;
|
|
7302
7440
|
const poll = async () => {
|
|
7303
7441
|
if (isCancelled) return;
|
|
7304
|
-
const jobInfo = await
|
|
7442
|
+
const jobInfo = await read.getJobStatus(jobId);
|
|
7305
7443
|
const payload = {
|
|
7306
7444
|
jobChanges: {
|
|
7307
7445
|
jobId: jobInfo.id,
|
|
@@ -7357,9 +7495,11 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7357
7495
|
}
|
|
7358
7496
|
name = "r";
|
|
7359
7497
|
hasSubscriptions = true;
|
|
7498
|
+
/** See {@link resolvers.WRITE_SIDE_QUERIES}. */
|
|
7499
|
+
writeSideQueries = WRITE_CLIENT_QUERIES.map((field) => `Query.${field}`);
|
|
7360
7500
|
#documentChanges;
|
|
7361
7501
|
get documentChanges() {
|
|
7362
|
-
this.#documentChanges ??= new DocumentChangeFeed(this.
|
|
7502
|
+
this.#documentChanges ??= new DocumentChangeFeed(this.readClient);
|
|
7363
7503
|
return this.#documentChanges;
|
|
7364
7504
|
}
|
|
7365
7505
|
/**
|
|
@@ -7382,10 +7522,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7382
7522
|
* decide whether to invalidate the drive-ownership cache after a
|
|
7383
7523
|
* successful delete.
|
|
7384
7524
|
*/
|
|
7385
|
-
async #resolveDriveId(identifier) {
|
|
7525
|
+
async #resolveDriveId(identifier, ctx) {
|
|
7386
7526
|
try {
|
|
7387
|
-
const
|
|
7388
|
-
if (isDriveContainerType(
|
|
7527
|
+
const target = await this.clientsOf(ctx).write.describe(identifier);
|
|
7528
|
+
if (isDriveContainerType(target.documentType)) return target.documentId;
|
|
7389
7529
|
return;
|
|
7390
7530
|
} catch {
|
|
7391
7531
|
return;
|
|
@@ -7496,7 +7636,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7496
7636
|
timestampFrom: args.filter?.timestampFrom,
|
|
7497
7637
|
timestampTo: args.filter?.timestampTo
|
|
7498
7638
|
};
|
|
7499
|
-
return await documentOperations(this.
|
|
7639
|
+
return await documentOperations(this.clientsOf(ctx).read, {
|
|
7500
7640
|
filter,
|
|
7501
7641
|
paging: args.paging
|
|
7502
7642
|
}, this.viewSubject(ctx));
|
|
@@ -7506,10 +7646,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7506
7646
|
}
|
|
7507
7647
|
} },
|
|
7508
7648
|
Query: {
|
|
7509
|
-
documentModels: async (_parent, args) => {
|
|
7649
|
+
documentModels: async (_parent, args, ctx) => {
|
|
7510
7650
|
this.logger.debug("documentModels(@args)", args);
|
|
7511
7651
|
try {
|
|
7512
|
-
return await documentModels(this.
|
|
7652
|
+
return await documentModels(this.clientsOf(ctx).read, args);
|
|
7513
7653
|
} catch (error) {
|
|
7514
7654
|
this.logger.error("Error in documentModels: @Error", error);
|
|
7515
7655
|
throw error;
|
|
@@ -7520,9 +7660,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7520
7660
|
try {
|
|
7521
7661
|
const idOrSlug = requireOneOf(args, "idOrSlug", "identifier");
|
|
7522
7662
|
const handle = await this.assertCanRead(idOrSlug, ctx);
|
|
7523
|
-
return await document(this.
|
|
7663
|
+
return await document(this.clientsOf(ctx).read, {
|
|
7524
7664
|
idOrSlug: handle.fetchIdentifier,
|
|
7525
|
-
view: args.view
|
|
7665
|
+
view: args.view,
|
|
7666
|
+
consistency: args.consistency
|
|
7526
7667
|
}, this.viewSubject(ctx));
|
|
7527
7668
|
} catch (error) {
|
|
7528
7669
|
this.logger.error("Error in document: @Error", error);
|
|
@@ -7534,11 +7675,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7534
7675
|
try {
|
|
7535
7676
|
const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
|
|
7536
7677
|
const handle = await this.assertCanRead(sourceIdOrSlug, ctx);
|
|
7537
|
-
return await documentOutgoingRelationships(this.
|
|
7678
|
+
return await documentOutgoingRelationships(this.clientsOf(ctx).read, {
|
|
7538
7679
|
sourceIdOrSlug: handle.fetchIdentifier,
|
|
7539
7680
|
relationshipType: args.relationshipType,
|
|
7540
7681
|
view: args.view,
|
|
7541
|
-
paging: args.paging
|
|
7682
|
+
paging: args.paging,
|
|
7683
|
+
consistency: args.consistency
|
|
7542
7684
|
}, this.viewSubject(ctx));
|
|
7543
7685
|
} catch (error) {
|
|
7544
7686
|
this.logger.error("Error in documentOutgoingRelationships: @Error", error);
|
|
@@ -7550,11 +7692,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7550
7692
|
try {
|
|
7551
7693
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
7552
7694
|
const handle = await this.assertCanRead(targetIdOrSlug, ctx);
|
|
7553
|
-
const result = await documentIncomingRelationships(this.
|
|
7695
|
+
const result = await documentIncomingRelationships(this.clientsOf(ctx).read, {
|
|
7554
7696
|
targetIdOrSlug: handle.fetchIdentifier,
|
|
7555
7697
|
relationshipType: args.relationshipType,
|
|
7556
7698
|
view: args.view,
|
|
7557
|
-
paging: args.paging
|
|
7699
|
+
paging: args.paging,
|
|
7700
|
+
consistency: args.consistency
|
|
7558
7701
|
}, this.viewSubject(ctx));
|
|
7559
7702
|
return {
|
|
7560
7703
|
...result,
|
|
@@ -7570,11 +7713,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7570
7713
|
try {
|
|
7571
7714
|
const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
|
|
7572
7715
|
const handle = await this.assertCanRead(sourceIdOrSlug, ctx);
|
|
7573
|
-
const result = await documentOutgoingRelationshipEdges(this.
|
|
7716
|
+
const result = await documentOutgoingRelationshipEdges(this.clientsOf(ctx).read, {
|
|
7574
7717
|
sourceIdOrSlug: handle.fetchIdentifier,
|
|
7575
7718
|
relationshipType: args.relationshipType,
|
|
7576
7719
|
view: args.view,
|
|
7577
|
-
paging: args.paging
|
|
7720
|
+
paging: args.paging,
|
|
7721
|
+
consistency: args.consistency
|
|
7578
7722
|
}, this.viewSubject(ctx));
|
|
7579
7723
|
return await this.filterRelationshipEdges(result, "targetId", ctx);
|
|
7580
7724
|
} catch (error) {
|
|
@@ -7587,11 +7731,12 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7587
7731
|
try {
|
|
7588
7732
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
7589
7733
|
const handle = await this.assertCanRead(targetIdOrSlug, ctx);
|
|
7590
|
-
const result = await documentIncomingRelationshipEdges(this.
|
|
7734
|
+
const result = await documentIncomingRelationshipEdges(this.clientsOf(ctx).read, {
|
|
7591
7735
|
targetIdOrSlug: handle.fetchIdentifier,
|
|
7592
7736
|
relationshipType: args.relationshipType,
|
|
7593
7737
|
view: args.view,
|
|
7594
|
-
paging: args.paging
|
|
7738
|
+
paging: args.paging,
|
|
7739
|
+
consistency: args.consistency
|
|
7595
7740
|
}, this.viewSubject(ctx));
|
|
7596
7741
|
return await this.filterRelationshipEdges(result, "sourceId", ctx);
|
|
7597
7742
|
} catch (error) {
|
|
@@ -7602,7 +7747,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7602
7747
|
findDocuments: async (_parent, args, ctx) => {
|
|
7603
7748
|
this.logger.debug("findDocuments(@args)", args);
|
|
7604
7749
|
try {
|
|
7605
|
-
const result = await findDocuments(this.
|
|
7750
|
+
const result = await findDocuments(this.clientsOf(ctx).read, {
|
|
7606
7751
|
...args,
|
|
7607
7752
|
search: args.search ?? {}
|
|
7608
7753
|
}, this.viewSubject(ctx));
|
|
@@ -7628,7 +7773,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7628
7773
|
}
|
|
7629
7774
|
return decision;
|
|
7630
7775
|
};
|
|
7631
|
-
return await jobStatus(this.
|
|
7776
|
+
return await jobStatus(this.clientsOf(ctx).read, args, readable, readable);
|
|
7632
7777
|
} catch (error) {
|
|
7633
7778
|
this.logger.error("Error in jobStatus: @Error", error);
|
|
7634
7779
|
throw error;
|
|
@@ -7651,7 +7796,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7651
7796
|
try {
|
|
7652
7797
|
const parentIdOrSlug = args.parentIdOrSlug ?? void 0;
|
|
7653
7798
|
if (parentIdOrSlug !== void 0 && !await this.listsDocument(parentIdOrSlug, ctx)) throw new ForbiddenError("to read this document");
|
|
7654
|
-
return await createDefaults(this.
|
|
7799
|
+
return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug);
|
|
7655
7800
|
} catch (error) {
|
|
7656
7801
|
this.logger.error("Error in createDefaults: @Error", error);
|
|
7657
7802
|
throw error;
|
|
@@ -7665,7 +7810,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7665
7810
|
documentIdOrSlug,
|
|
7666
7811
|
documentId
|
|
7667
7812
|
}, "documentIdOrSlug", "documentId"), ctx);
|
|
7668
|
-
return await documentOperations(this.
|
|
7813
|
+
return await documentOperations(this.clientsOf(ctx).read, {
|
|
7669
7814
|
filter: {
|
|
7670
7815
|
...filter,
|
|
7671
7816
|
documentIdOrSlug: handle.fetchIdentifier
|
|
@@ -7689,7 +7834,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7689
7834
|
try {
|
|
7690
7835
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
|
|
7691
7836
|
const handle = await this.assertCanRead(documentIdOrSlug, ctx);
|
|
7692
|
-
return await evaluateActions(this.
|
|
7837
|
+
return await evaluateActions(this.clientsOf(ctx).write, {
|
|
7693
7838
|
documentIdOrSlug: handle.fetchIdentifier,
|
|
7694
7839
|
branch: args.branch,
|
|
7695
7840
|
candidates: args.candidates
|
|
@@ -7754,10 +7899,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7754
7899
|
try {
|
|
7755
7900
|
const parentIdOrSlug = optionalOneOf(args, "parentIdOrSlug", "parentIdentifier");
|
|
7756
7901
|
if (parentIdOrSlug) {
|
|
7757
|
-
const parent = await document(this.
|
|
7902
|
+
const parent = await document(this.clientsOf(ctx).read, { idOrSlug: parentIdOrSlug });
|
|
7758
7903
|
await this.assertCanWriteCanonical(parent.document.id, ctx);
|
|
7759
7904
|
} else this.assertCanCreate(ctx);
|
|
7760
|
-
const result = await createDocument(this.
|
|
7905
|
+
const result = await createDocument(this.clientsOf(ctx), {
|
|
7761
7906
|
document: args.document,
|
|
7762
7907
|
parentIdOrSlug
|
|
7763
7908
|
}, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
|
|
@@ -7774,10 +7919,10 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7774
7919
|
try {
|
|
7775
7920
|
const parentIdOrSlug = optionalOneOf(args, "parentIdOrSlug", "parentIdentifier");
|
|
7776
7921
|
if (parentIdOrSlug) {
|
|
7777
|
-
const parent = await document(this.
|
|
7922
|
+
const parent = await document(this.clientsOf(ctx).read, { idOrSlug: parentIdOrSlug });
|
|
7778
7923
|
await this.assertCanWriteCanonical(parent.document.id, ctx);
|
|
7779
7924
|
} else this.assertCanCreate(ctx);
|
|
7780
|
-
const result = await createEmptyDocument(this.
|
|
7925
|
+
const result = await createEmptyDocument(this.clientsOf(ctx), {
|
|
7781
7926
|
documentType: args.documentType,
|
|
7782
7927
|
parentIdOrSlug
|
|
7783
7928
|
}, this.graphqlManager.reactorDriveClient, this.viewSubject(ctx));
|
|
@@ -7794,7 +7939,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7794
7939
|
try {
|
|
7795
7940
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
|
|
7796
7941
|
const handle = await this.assertCanExecuteOperations(documentIdOrSlug, args.actions, ctx);
|
|
7797
|
-
return await execute(this.
|
|
7942
|
+
return await execute(this.clientsOf(ctx), {
|
|
7798
7943
|
documentIdOrSlug: handle.fetchIdentifier,
|
|
7799
7944
|
actions: args.actions,
|
|
7800
7945
|
branch: args.branch
|
|
@@ -7809,7 +7954,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7809
7954
|
try {
|
|
7810
7955
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
|
|
7811
7956
|
const handle = await this.assertCanExecuteOperations(documentIdOrSlug, args.actions, ctx);
|
|
7812
|
-
return await executeAsync(this.
|
|
7957
|
+
return await executeAsync(this.clientsOf(ctx), {
|
|
7813
7958
|
documentIdOrSlug: handle.fetchIdentifier,
|
|
7814
7959
|
actions: args.actions,
|
|
7815
7960
|
branch: args.branch
|
|
@@ -7826,7 +7971,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7826
7971
|
if (creation) {
|
|
7827
7972
|
if (creation.linkedFrom.length > 0) for (const parent of creation.linkedFrom) await this.assertCanWrite(parent, ctx);
|
|
7828
7973
|
else this.assertCanCreate(ctx);
|
|
7829
|
-
const result = await executeBatch(this.
|
|
7974
|
+
const result = await executeBatch(this.clientsOf(ctx).write, { jobs: args.jobs });
|
|
7830
7975
|
if (result.jobs.some((entry) => entry.job.status !== "READ_READY")) return result;
|
|
7831
7976
|
if (isDriveContainerType(creation.documentType)) this.graphqlManager.driveOwnershipCache.add(creation.documentId);
|
|
7832
7977
|
if (ctx.user?.address) await this.documentPermissionService?.initializeDocumentProtection(creation.documentId, ctx.user.address, this.authorizationService.config.defaultProtection);
|
|
@@ -7840,7 +7985,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7840
7985
|
documentIdOrSlug: handle.fetchIdentifier
|
|
7841
7986
|
});
|
|
7842
7987
|
}
|
|
7843
|
-
return await executeBatch(this.
|
|
7988
|
+
return await executeBatch(this.clientsOf(ctx).write, { jobs });
|
|
7844
7989
|
} catch (error) {
|
|
7845
7990
|
this.logger.error("Error in executeBatch(@args): @Error", args, error);
|
|
7846
7991
|
throw error;
|
|
@@ -7850,7 +7995,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7850
7995
|
this.logger.debug("mutateDocument(@args)", args);
|
|
7851
7996
|
try {
|
|
7852
7997
|
const handle = await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
|
|
7853
|
-
return await mutateDocument(this.
|
|
7998
|
+
return await mutateDocument(this.clientsOf(ctx), {
|
|
7854
7999
|
...args,
|
|
7855
8000
|
documentIdentifier: handle.fetchIdentifier
|
|
7856
8001
|
}, this.viewSubject(ctx));
|
|
@@ -7863,7 +8008,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7863
8008
|
this.logger.debug("mutateDocumentAsync(@args)", args);
|
|
7864
8009
|
try {
|
|
7865
8010
|
const handle = await this.assertCanExecuteOperations(args.documentIdentifier, args.actions, ctx);
|
|
7866
|
-
return await mutateDocumentAsync(this.
|
|
8011
|
+
return await mutateDocumentAsync(this.clientsOf(ctx).write, {
|
|
7867
8012
|
...args,
|
|
7868
8013
|
documentIdentifier: handle.fetchIdentifier
|
|
7869
8014
|
});
|
|
@@ -7877,7 +8022,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7877
8022
|
try {
|
|
7878
8023
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
|
|
7879
8024
|
const handle = await this.assertCanWrite(documentIdOrSlug, ctx);
|
|
7880
|
-
return await renameDocument(this.
|
|
8025
|
+
return await renameDocument(this.clientsOf(ctx), {
|
|
7881
8026
|
documentIdOrSlug: handle.fetchIdentifier,
|
|
7882
8027
|
name: args.name,
|
|
7883
8028
|
branch: args.branch
|
|
@@ -7892,7 +8037,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7892
8037
|
try {
|
|
7893
8038
|
const documentIdOrSlug = requireOneOf(args, "documentIdOrSlug", "documentIdentifier");
|
|
7894
8039
|
const handle = await this.assertCanWrite(documentIdOrSlug, ctx);
|
|
7895
|
-
return await setPreferredEditor(this.
|
|
8040
|
+
return await setPreferredEditor(this.clientsOf(ctx), {
|
|
7896
8041
|
documentIdOrSlug: handle.fetchIdentifier,
|
|
7897
8042
|
preferredEditor: args.preferredEditor,
|
|
7898
8043
|
branch: args.branch
|
|
@@ -7908,7 +8053,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7908
8053
|
const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
|
|
7909
8054
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
7910
8055
|
const handle = await this.assertCanWrite(sourceIdOrSlug, ctx);
|
|
7911
|
-
return await addRelationship(this.
|
|
8056
|
+
return await addRelationship(this.clientsOf(ctx), {
|
|
7912
8057
|
sourceIdOrSlug: handle.fetchIdentifier,
|
|
7913
8058
|
targetIdOrSlug,
|
|
7914
8059
|
relationshipType: args.relationshipType,
|
|
@@ -7926,7 +8071,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7926
8071
|
const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
|
|
7927
8072
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
7928
8073
|
const handle = await this.assertCanWrite(sourceIdOrSlug, ctx);
|
|
7929
|
-
return await updateRelationship(this.
|
|
8074
|
+
return await updateRelationship(this.clientsOf(ctx), {
|
|
7930
8075
|
sourceIdOrSlug: handle.fetchIdentifier,
|
|
7931
8076
|
targetIdOrSlug,
|
|
7932
8077
|
relationshipType: args.relationshipType,
|
|
@@ -7944,7 +8089,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7944
8089
|
const sourceIdOrSlug = requireOneOf(args, "sourceIdOrSlug", "sourceIdentifier");
|
|
7945
8090
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
7946
8091
|
const handle = await this.assertCanWrite(sourceIdOrSlug, ctx);
|
|
7947
|
-
return await removeRelationship(this.
|
|
8092
|
+
return await removeRelationship(this.clientsOf(ctx), {
|
|
7948
8093
|
sourceIdOrSlug: handle.fetchIdentifier,
|
|
7949
8094
|
targetIdOrSlug,
|
|
7950
8095
|
relationshipType: args.relationshipType,
|
|
@@ -7963,7 +8108,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7963
8108
|
const targetIdOrSlug = requireOneOf(args, "targetIdOrSlug", "targetIdentifier");
|
|
7964
8109
|
const sourceHandle = await this.assertCanWrite(sourceParentIdOrSlug, ctx);
|
|
7965
8110
|
const targetHandle = await this.assertCanWrite(targetParentIdOrSlug, ctx);
|
|
7966
|
-
return await moveRelationship(this.
|
|
8111
|
+
return await moveRelationship(this.clientsOf(ctx), {
|
|
7967
8112
|
sourceParentIdOrSlug: sourceHandle.fetchIdentifier,
|
|
7968
8113
|
targetParentIdOrSlug: targetHandle.fetchIdentifier,
|
|
7969
8114
|
targetIdOrSlug,
|
|
@@ -7979,8 +8124,8 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7979
8124
|
this.logger.debug("deleteDocument(@args)", args);
|
|
7980
8125
|
try {
|
|
7981
8126
|
const idOrSlug = (await this.assertCanWrite(requireOneOf(args, "idOrSlug", "identifier"), ctx)).fetchIdentifier;
|
|
7982
|
-
const driveIdToInvalidate = await this.#resolveDriveId(idOrSlug);
|
|
7983
|
-
const result = await deleteDocument(this.
|
|
8127
|
+
const driveIdToInvalidate = await this.#resolveDriveId(idOrSlug, ctx);
|
|
8128
|
+
const result = await deleteDocument(this.clientsOf(ctx), {
|
|
7984
8129
|
idOrSlug,
|
|
7985
8130
|
propagate: args.propagate
|
|
7986
8131
|
}, this.graphqlManager.reactorDriveClient);
|
|
@@ -7999,7 +8144,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
7999
8144
|
const handle = await this.assertCanWrite(idOrSlug, ctx);
|
|
8000
8145
|
idsOrSlugs.push(handle.fetchIdentifier);
|
|
8001
8146
|
}
|
|
8002
|
-
return await deleteDocuments(this.
|
|
8147
|
+
return await deleteDocuments(this.clientsOf(ctx).write, {
|
|
8003
8148
|
idsOrSlugs,
|
|
8004
8149
|
propagate: args.propagate
|
|
8005
8150
|
});
|
|
@@ -8102,7 +8247,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
|
|
|
8102
8247
|
subscribe: (rootValue, args, ctx, info) => {
|
|
8103
8248
|
this.logger.debug("jobChanges(@args) subscription started", args);
|
|
8104
8249
|
return withFilter(() => {
|
|
8105
|
-
ensureJobSubscription(this.
|
|
8250
|
+
ensureJobSubscription(this.clientsOf(ctx).read, args.jobId);
|
|
8106
8251
|
return getPubSub().asyncIterableIterator(SUBSCRIPTION_TRIGGERS.JOB_CHANGES);
|
|
8107
8252
|
}, async (payload, filterArgs, filterCtx) => {
|
|
8108
8253
|
if (!payload || !filterArgs) return false;
|
|
@@ -8136,10 +8281,10 @@ const ADMIN_USERS = getAdminUsers();
|
|
|
8136
8281
|
//#endregion
|
|
8137
8282
|
//#region src/graphql/system/version.ts
|
|
8138
8283
|
function getVersion() {
|
|
8139
|
-
return "6.2.3-dev.
|
|
8284
|
+
return "6.2.3-dev.77";
|
|
8140
8285
|
}
|
|
8141
8286
|
function getGitHash() {
|
|
8142
|
-
return "
|
|
8287
|
+
return "52245e43cb7435650abfe72241eaa787ce5757b7";
|
|
8143
8288
|
}
|
|
8144
8289
|
function getGitUrl() {
|
|
8145
8290
|
return buildTreeUrl(getGitHash());
|
|
@@ -9911,12 +10056,22 @@ var StaticMigrationProvider = class {
|
|
|
9911
10056
|
}
|
|
9912
10057
|
};
|
|
9913
10058
|
/**
|
|
10059
|
+
* The schema unqualified names resolve to, where these migrations have always
|
|
10060
|
+
* kept their bookkeeping tables. Named explicitly because Kysely, given no
|
|
10061
|
+
* schema, treats a lock table in any schema (the attachment store creates
|
|
10062
|
+
* one in its own) as present and then fails to find it unqualified.
|
|
10063
|
+
*/
|
|
10064
|
+
async function currentSchema(db) {
|
|
10065
|
+
return (await sql`select current_schema() as schema`.execute(db)).rows[0]?.schema ?? "public";
|
|
10066
|
+
}
|
|
10067
|
+
/**
|
|
9914
10068
|
* Run all pending migrations
|
|
9915
10069
|
*/
|
|
9916
10070
|
async function runMigrations(db) {
|
|
9917
10071
|
const { error, results } = await new Migrator({
|
|
9918
10072
|
db,
|
|
9919
|
-
provider: new StaticMigrationProvider()
|
|
10073
|
+
provider: new StaticMigrationProvider(),
|
|
10074
|
+
migrationTableSchema: await currentSchema(db)
|
|
9920
10075
|
}).migrateToLatest();
|
|
9921
10076
|
results?.forEach((result) => {
|
|
9922
10077
|
if (result.status === "Error") console.error(`Failed to execute migration "${result.migrationName}"`);
|
|
@@ -10028,6 +10183,122 @@ async function createRenownCredentialVerifier(config = {}) {
|
|
|
10028
10183
|
};
|
|
10029
10184
|
}
|
|
10030
10185
|
//#endregion
|
|
10186
|
+
//#region src/services/permission-cache.ts
|
|
10187
|
+
/**
|
|
10188
|
+
* Everything an authorization decision reads about one document: its
|
|
10189
|
+
* protection flag (the configured default when it has no protection row), its
|
|
10190
|
+
* owner, the users' grant levels and the users granted each operation.
|
|
10191
|
+
* Addresses are stored lowercase, as the permission service writes them.
|
|
10192
|
+
*/
|
|
10193
|
+
var DocumentPermissionSnapshot = class {
|
|
10194
|
+
documentId;
|
|
10195
|
+
isProtected;
|
|
10196
|
+
ownerAddress;
|
|
10197
|
+
grants;
|
|
10198
|
+
operationGrants;
|
|
10199
|
+
constructor(documentId, isProtected, ownerAddress, grants, operationGrants) {
|
|
10200
|
+
this.documentId = documentId;
|
|
10201
|
+
this.isProtected = isProtected;
|
|
10202
|
+
this.ownerAddress = ownerAddress;
|
|
10203
|
+
this.grants = grants;
|
|
10204
|
+
this.operationGrants = operationGrants;
|
|
10205
|
+
}
|
|
10206
|
+
grantLevel(userAddress) {
|
|
10207
|
+
return this.grants.get(userAddress.toLowerCase()) ?? null;
|
|
10208
|
+
}
|
|
10209
|
+
isOperationRestricted(operationType) {
|
|
10210
|
+
return (this.operationGrants.get(operationType)?.size ?? 0) > 0;
|
|
10211
|
+
}
|
|
10212
|
+
hasOperationGrant(operationType, userAddress) {
|
|
10213
|
+
return this.operationGrants.get(operationType)?.has(userAddress.toLowerCase()) ?? false;
|
|
10214
|
+
}
|
|
10215
|
+
};
|
|
10216
|
+
const DEFAULT_PERMISSION_CACHE_TTL_MS = 3e4;
|
|
10217
|
+
const DEFAULT_PERMISSION_CACHE_OPTIONS = {
|
|
10218
|
+
ttlMs: DEFAULT_PERMISSION_CACHE_TTL_MS,
|
|
10219
|
+
maxEntries: 1e4,
|
|
10220
|
+
now: () => Date.now()
|
|
10221
|
+
};
|
|
10222
|
+
var PermissionCacheEntry = class {
|
|
10223
|
+
snapshot;
|
|
10224
|
+
expiresAt;
|
|
10225
|
+
constructor(snapshot, expiresAt) {
|
|
10226
|
+
this.snapshot = snapshot;
|
|
10227
|
+
this.expiresAt = expiresAt;
|
|
10228
|
+
}
|
|
10229
|
+
};
|
|
10230
|
+
/**
|
|
10231
|
+
* Per-process cache of document permission snapshots, keyed by document id.
|
|
10232
|
+
*
|
|
10233
|
+
* Filled on miss from the store, invalidated by the permission service after
|
|
10234
|
+
* each of its own writes, and expired after `ttlMs` as the safety net for
|
|
10235
|
+
* writes made by another process (another switchboard instance on the same
|
|
10236
|
+
* database) until cross-instance invalidation exists.
|
|
10237
|
+
*
|
|
10238
|
+
* A load that overlaps an invalidation still answers its caller but is not
|
|
10239
|
+
* stored, so a read that started before a write commits cannot repopulate
|
|
10240
|
+
* the cache with the pre-write rows.
|
|
10241
|
+
*/
|
|
10242
|
+
var PermissionCache = class {
|
|
10243
|
+
#load;
|
|
10244
|
+
#options;
|
|
10245
|
+
#entries = /* @__PURE__ */ new Map();
|
|
10246
|
+
#epoch = 0;
|
|
10247
|
+
constructor(load, options = DEFAULT_PERMISSION_CACHE_OPTIONS) {
|
|
10248
|
+
this.#load = load;
|
|
10249
|
+
this.#options = options;
|
|
10250
|
+
}
|
|
10251
|
+
get size() {
|
|
10252
|
+
return this.#entries.size;
|
|
10253
|
+
}
|
|
10254
|
+
async get(documentId) {
|
|
10255
|
+
return (await this.getMany([documentId])).get(documentId);
|
|
10256
|
+
}
|
|
10257
|
+
/** Snapshots for every id, loading the missing and expired ones in one batch. */
|
|
10258
|
+
async getMany(documentIds) {
|
|
10259
|
+
const now = this.#options.now();
|
|
10260
|
+
const result = /* @__PURE__ */ new Map();
|
|
10261
|
+
const missing = [];
|
|
10262
|
+
for (const documentId of new Set(documentIds)) {
|
|
10263
|
+
const entry = this.#entries.get(documentId);
|
|
10264
|
+
if (entry && entry.expiresAt > now) {
|
|
10265
|
+
this.#entries.delete(documentId);
|
|
10266
|
+
this.#entries.set(documentId, entry);
|
|
10267
|
+
result.set(documentId, entry.snapshot);
|
|
10268
|
+
} else missing.push(documentId);
|
|
10269
|
+
}
|
|
10270
|
+
if (missing.length === 0) return result;
|
|
10271
|
+
const epoch = this.#epoch;
|
|
10272
|
+
const loaded = await this.#load(missing);
|
|
10273
|
+
const storable = this.#options.ttlMs > 0 && epoch === this.#epoch;
|
|
10274
|
+
const expiresAt = this.#options.now() + this.#options.ttlMs;
|
|
10275
|
+
for (const documentId of missing) {
|
|
10276
|
+
const snapshot = loaded.get(documentId);
|
|
10277
|
+
if (!snapshot) throw new Error(`Permission snapshot loader returned no snapshot for ${documentId}`);
|
|
10278
|
+
result.set(documentId, snapshot);
|
|
10279
|
+
if (storable) this.#store(documentId, new PermissionCacheEntry(snapshot, expiresAt));
|
|
10280
|
+
}
|
|
10281
|
+
return result;
|
|
10282
|
+
}
|
|
10283
|
+
invalidate(documentId) {
|
|
10284
|
+
this.#epoch++;
|
|
10285
|
+
this.#entries.delete(documentId);
|
|
10286
|
+
}
|
|
10287
|
+
clear() {
|
|
10288
|
+
this.#epoch++;
|
|
10289
|
+
this.#entries.clear();
|
|
10290
|
+
}
|
|
10291
|
+
#store(documentId, entry) {
|
|
10292
|
+
this.#entries.delete(documentId);
|
|
10293
|
+
while (this.#entries.size >= this.#options.maxEntries) {
|
|
10294
|
+
const oldest = this.#entries.keys().next();
|
|
10295
|
+
if (oldest.done) break;
|
|
10296
|
+
this.#entries.delete(oldest.value);
|
|
10297
|
+
}
|
|
10298
|
+
this.#entries.set(documentId, entry);
|
|
10299
|
+
}
|
|
10300
|
+
};
|
|
10301
|
+
//#endregion
|
|
10031
10302
|
//#region src/services/document-permission.service.ts
|
|
10032
10303
|
/**
|
|
10033
10304
|
* Service for managing document-level permissions.
|
|
@@ -10043,16 +10314,23 @@ async function createRenownCredentialVerifier(config = {}) {
|
|
|
10043
10314
|
var DocumentPermissionService = class {
|
|
10044
10315
|
db;
|
|
10045
10316
|
config;
|
|
10046
|
-
|
|
10317
|
+
/**
|
|
10318
|
+
* Serves the reads authorization decisions make (protection, owner, grant
|
|
10319
|
+
* level, operation grants). Every write through this service invalidates
|
|
10320
|
+
* the document it touched.
|
|
10321
|
+
*/
|
|
10322
|
+
permissionCache;
|
|
10323
|
+
constructor(db, config = { defaultProtection: false }, cacheOptions = DEFAULT_PERMISSION_CACHE_OPTIONS) {
|
|
10047
10324
|
this.db = db;
|
|
10048
10325
|
this.config = config;
|
|
10326
|
+
this.permissionCache = new PermissionCache((documentIds) => this.loadPermissionSnapshots(documentIds), cacheOptions);
|
|
10049
10327
|
}
|
|
10050
10328
|
/**
|
|
10051
10329
|
* Get the permission level for a user on a specific document.
|
|
10052
10330
|
* Returns null if no permission is set.
|
|
10053
10331
|
*/
|
|
10054
10332
|
async getUserPermission(documentId, userAddress) {
|
|
10055
|
-
return (await this.
|
|
10333
|
+
return (await this.permissionCache.get(documentId)).grantLevel(userAddress);
|
|
10056
10334
|
}
|
|
10057
10335
|
/**
|
|
10058
10336
|
* Get all permissions for a document
|
|
@@ -10097,7 +10375,7 @@ var DocumentPermissionService = class {
|
|
|
10097
10375
|
permission,
|
|
10098
10376
|
grantedBy: grantedBy.toLowerCase(),
|
|
10099
10377
|
updatedAt: now
|
|
10100
|
-
})).execute();
|
|
10378
|
+
})).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10101
10379
|
return await this.db.selectFrom("DocumentPermission").select([
|
|
10102
10380
|
"documentId",
|
|
10103
10381
|
"userAddress",
|
|
@@ -10111,14 +10389,14 @@ var DocumentPermissionService = class {
|
|
|
10111
10389
|
* Revoke a user's permission on a document
|
|
10112
10390
|
*/
|
|
10113
10391
|
async revokePermission(documentId, userAddress) {
|
|
10114
|
-
await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).execute();
|
|
10392
|
+
await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10115
10393
|
}
|
|
10116
10394
|
/**
|
|
10117
10395
|
* Delete all permissions for a document (used when deleting a document)
|
|
10118
10396
|
*/
|
|
10119
10397
|
async deleteAllDocumentPermissions(documentId) {
|
|
10120
|
-
const permissions = await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).returning("id").execute();
|
|
10121
|
-
const operations = await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).returning("id").execute();
|
|
10398
|
+
const permissions = await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10399
|
+
const operations = await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10122
10400
|
return {
|
|
10123
10401
|
DocumentPermission: permissions.length,
|
|
10124
10402
|
OperationUserPermission: operations.length
|
|
@@ -10126,7 +10404,7 @@ var DocumentPermissionService = class {
|
|
|
10126
10404
|
}
|
|
10127
10405
|
/** Delete a document's protection row, which names its owner. */
|
|
10128
10406
|
async deleteDocumentProtection(documentId) {
|
|
10129
|
-
return (await this.db.deleteFrom("DocumentProtection").where("documentId", "=", documentId).returning("documentId").execute()).length;
|
|
10407
|
+
return (await this.db.deleteFrom("DocumentProtection").where("documentId", "=", documentId).returning("documentId").execute().finally(() => this.permissionCache.invalidate(documentId))).length;
|
|
10130
10408
|
}
|
|
10131
10409
|
/** Every row that names the address, for a subject access request. */
|
|
10132
10410
|
async rowsForAddress(address) {
|
|
@@ -10166,7 +10444,7 @@ var DocumentPermissionService = class {
|
|
|
10166
10444
|
"documentId",
|
|
10167
10445
|
"operationType",
|
|
10168
10446
|
"userAddress"
|
|
10169
|
-
]).doNothing()).execute();
|
|
10447
|
+
]).doNothing()).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10170
10448
|
return await this.db.selectFrom("OperationUserPermission").select([
|
|
10171
10449
|
"documentId",
|
|
10172
10450
|
"operationType",
|
|
@@ -10179,7 +10457,7 @@ var DocumentPermissionService = class {
|
|
|
10179
10457
|
* Revoke a user's permission to execute an operation
|
|
10180
10458
|
*/
|
|
10181
10459
|
async revokeOperationPermission(documentId, operationType, userAddress) {
|
|
10182
|
-
await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", userAddress.toLowerCase()).execute();
|
|
10460
|
+
await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10183
10461
|
}
|
|
10184
10462
|
/**
|
|
10185
10463
|
* Get all users with permission to execute an operation
|
|
@@ -10197,24 +10475,20 @@ var DocumentPermissionService = class {
|
|
|
10197
10475
|
* Whether an operation-permission row exists for the user on this operation.
|
|
10198
10476
|
*/
|
|
10199
10477
|
async hasOperationGrant(documentId, operationType, userAddress) {
|
|
10200
|
-
|
|
10201
|
-
return !!await this.db.selectFrom("OperationUserPermission").select("userAddress").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", normalizedAddress).executeTakeFirst();
|
|
10478
|
+
return (await this.permissionCache.get(documentId)).hasOperationGrant(operationType, userAddress);
|
|
10202
10479
|
}
|
|
10203
10480
|
/**
|
|
10204
10481
|
* Check if an operation has any permissions set (is restricted)
|
|
10205
10482
|
*/
|
|
10206
10483
|
async isOperationRestricted(documentId, operationType) {
|
|
10207
|
-
|
|
10208
|
-
return userPermCount !== void 0 && Number(userPermCount.count) > 0;
|
|
10484
|
+
return (await this.permissionCache.get(documentId)).isOperationRestricted(operationType);
|
|
10209
10485
|
}
|
|
10210
10486
|
/**
|
|
10211
10487
|
* Check if a specific document has a protection row set to true.
|
|
10212
10488
|
* Falls back to `config.defaultProtection` if no row exists.
|
|
10213
10489
|
*/
|
|
10214
10490
|
async isDocumentProtected(documentId) {
|
|
10215
|
-
|
|
10216
|
-
if (row === void 0) return this.config.defaultProtection;
|
|
10217
|
-
return row.protected;
|
|
10491
|
+
return (await this.permissionCache.get(documentId)).isProtected;
|
|
10218
10492
|
}
|
|
10219
10493
|
/**
|
|
10220
10494
|
* Walk the parent chain: if the document itself or any ancestor is protected, return true.
|
|
@@ -10223,12 +10497,62 @@ var DocumentPermissionService = class {
|
|
|
10223
10497
|
async isProtectedWithAncestors(documentId, getParentIds) {
|
|
10224
10498
|
const allIds = await this.collectAncestorIds(documentId, getParentIds);
|
|
10225
10499
|
if (allIds.length === 0) return this.config.defaultProtection;
|
|
10226
|
-
const
|
|
10227
|
-
const
|
|
10228
|
-
for (const id of allIds) if (protectionMap.get(id) ?? this.config.defaultProtection) return true;
|
|
10500
|
+
const snapshots = await this.permissionCache.getMany(allIds);
|
|
10501
|
+
for (const snapshot of snapshots.values()) if (snapshot.isProtected) return true;
|
|
10229
10502
|
return false;
|
|
10230
10503
|
}
|
|
10231
10504
|
/**
|
|
10505
|
+
* Reads the permission rows of the given documents from the store, three
|
|
10506
|
+
* queries for the whole batch. The permission cache's loader.
|
|
10507
|
+
*/
|
|
10508
|
+
async loadPermissionSnapshots(documentIds) {
|
|
10509
|
+
const protections = await this.db.selectFrom("DocumentProtection").select([
|
|
10510
|
+
"documentId",
|
|
10511
|
+
"protected",
|
|
10512
|
+
"ownerAddress"
|
|
10513
|
+
]).where("documentId", "in", documentIds).execute();
|
|
10514
|
+
const grants = await this.db.selectFrom("DocumentPermission").select([
|
|
10515
|
+
"documentId",
|
|
10516
|
+
"userAddress",
|
|
10517
|
+
"permission"
|
|
10518
|
+
]).where("documentId", "in", documentIds).execute();
|
|
10519
|
+
const operationGrants = await this.db.selectFrom("OperationUserPermission").select([
|
|
10520
|
+
"documentId",
|
|
10521
|
+
"operationType",
|
|
10522
|
+
"userAddress"
|
|
10523
|
+
]).where("documentId", "in", documentIds).execute();
|
|
10524
|
+
const protectionById = new Map(protections.map((row) => [row.documentId, row]));
|
|
10525
|
+
const grantsById = /* @__PURE__ */ new Map();
|
|
10526
|
+
for (const row of grants) {
|
|
10527
|
+
let byUser = grantsById.get(row.documentId);
|
|
10528
|
+
if (!byUser) {
|
|
10529
|
+
byUser = /* @__PURE__ */ new Map();
|
|
10530
|
+
grantsById.set(row.documentId, byUser);
|
|
10531
|
+
}
|
|
10532
|
+
byUser.set(row.userAddress, row.permission);
|
|
10533
|
+
}
|
|
10534
|
+
const operationsById = /* @__PURE__ */ new Map();
|
|
10535
|
+
for (const row of operationGrants) {
|
|
10536
|
+
let byOperation = operationsById.get(row.documentId);
|
|
10537
|
+
if (!byOperation) {
|
|
10538
|
+
byOperation = /* @__PURE__ */ new Map();
|
|
10539
|
+
operationsById.set(row.documentId, byOperation);
|
|
10540
|
+
}
|
|
10541
|
+
let users = byOperation.get(row.operationType);
|
|
10542
|
+
if (!users) {
|
|
10543
|
+
users = /* @__PURE__ */ new Set();
|
|
10544
|
+
byOperation.set(row.operationType, users);
|
|
10545
|
+
}
|
|
10546
|
+
users.add(row.userAddress);
|
|
10547
|
+
}
|
|
10548
|
+
const snapshots = /* @__PURE__ */ new Map();
|
|
10549
|
+
for (const documentId of documentIds) {
|
|
10550
|
+
const protection = protectionById.get(documentId);
|
|
10551
|
+
snapshots.set(documentId, new DocumentPermissionSnapshot(documentId, protection?.protected ?? this.config.defaultProtection, protection?.ownerAddress ?? null, grantsById.get(documentId) ?? /* @__PURE__ */ new Map(), operationsById.get(documentId) ?? /* @__PURE__ */ new Map()));
|
|
10552
|
+
}
|
|
10553
|
+
return snapshots;
|
|
10554
|
+
}
|
|
10555
|
+
/**
|
|
10232
10556
|
* Collect all ancestor IDs (including the document itself) with cycle detection.
|
|
10233
10557
|
*/
|
|
10234
10558
|
async collectAncestorIds(documentId, getParentIds) {
|
|
@@ -10257,13 +10581,13 @@ var DocumentPermissionService = class {
|
|
|
10257
10581
|
}).onConflict((oc) => oc.column("documentId").doUpdateSet({
|
|
10258
10582
|
protected: isProtected,
|
|
10259
10583
|
updatedAt: now
|
|
10260
|
-
})).execute();
|
|
10584
|
+
})).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10261
10585
|
}
|
|
10262
10586
|
/**
|
|
10263
10587
|
* Get the owner address for a document, or null if not set.
|
|
10264
10588
|
*/
|
|
10265
10589
|
async getDocumentOwner(documentId) {
|
|
10266
|
-
return (await this.
|
|
10590
|
+
return (await this.permissionCache.get(documentId)).ownerAddress;
|
|
10267
10591
|
}
|
|
10268
10592
|
/**
|
|
10269
10593
|
* Upsert owner address for a document.
|
|
@@ -10280,7 +10604,7 @@ var DocumentPermissionService = class {
|
|
|
10280
10604
|
}).onConflict((oc) => oc.column("documentId").doUpdateSet({
|
|
10281
10605
|
ownerAddress: normalizedAddress,
|
|
10282
10606
|
updatedAt: now
|
|
10283
|
-
})).execute();
|
|
10607
|
+
})).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10284
10608
|
}
|
|
10285
10609
|
/**
|
|
10286
10610
|
* Initialize protection for a newly created document.
|
|
@@ -10299,7 +10623,7 @@ var DocumentPermissionService = class {
|
|
|
10299
10623
|
}).onConflict((oc) => oc.column("documentId").doUpdateSet({
|
|
10300
10624
|
ownerAddress: normalizedAddress,
|
|
10301
10625
|
updatedAt: now
|
|
10302
|
-
})).execute();
|
|
10626
|
+
})).execute().finally(() => this.permissionCache.invalidate(documentId));
|
|
10303
10627
|
await this.grantPermission(documentId, normalizedAddress, "ADMIN", normalizedAddress);
|
|
10304
10628
|
}
|
|
10305
10629
|
/**
|
|
@@ -10326,11 +10650,12 @@ var DocumentPermissionService = class {
|
|
|
10326
10650
|
* a document's parents are the sources of its incoming "child"
|
|
10327
10651
|
* relationships. Lookup failures resolve to "no parents" so a relationship
|
|
10328
10652
|
* store outage degrades to no inherited permissions rather than an error.
|
|
10653
|
+
* Reads through the read half: the indexer it asks is post-commit, as it was.
|
|
10329
10654
|
*/
|
|
10330
|
-
function createGetParentIdsFn(
|
|
10655
|
+
function createGetParentIdsFn(read) {
|
|
10331
10656
|
return async (documentId) => {
|
|
10332
10657
|
try {
|
|
10333
|
-
return (await
|
|
10658
|
+
return (await read.getIncomingRelationships(documentId, "child")).results.map((doc) => doc.header.id);
|
|
10334
10659
|
} catch {
|
|
10335
10660
|
return [];
|
|
10336
10661
|
}
|
|
@@ -10716,13 +11041,15 @@ function resolveGatewayAdapterType(logger) {
|
|
|
10716
11041
|
/**
|
|
10717
11042
|
* Sets up the subgraph manager and registers subgraphs
|
|
10718
11043
|
*/
|
|
10719
|
-
async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer,
|
|
11044
|
+
async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
|
|
10720
11045
|
const graphqlManager = new GraphQLManager({
|
|
10721
11046
|
wsCredentialRecheckIntervalMs: resolveWsCredentialRecheckIntervalMs(process.env.WS_CREDENTIAL_RECHECK_INTERVAL_MS, logger),
|
|
10722
11047
|
path: config.basePath,
|
|
10723
11048
|
httpServer,
|
|
10724
11049
|
wsServer,
|
|
10725
|
-
|
|
11050
|
+
readClient: clients.read,
|
|
11051
|
+
writeClient: clients.write,
|
|
11052
|
+
reactorClient: clients.client,
|
|
10726
11053
|
relationalDb,
|
|
10727
11054
|
analyticsStore,
|
|
10728
11055
|
syncManager,
|
|
@@ -10900,16 +11227,12 @@ async function _setupCommonInfrastructure(options) {
|
|
|
10900
11227
|
const dbClosers = [];
|
|
10901
11228
|
const { relationalDb, analyticsStore, closers: analyticsClosers } = await initializeDatabaseAndAnalytics(options.dbPath, options.pgliteFactory, logger);
|
|
10902
11229
|
dbClosers.push(...analyticsClosers);
|
|
10903
|
-
|
|
10904
|
-
|
|
10905
|
-
|
|
10906
|
-
|
|
10907
|
-
|
|
10908
|
-
|
|
10909
|
-
documentPermissionService = new DocumentPermissionService(db, { defaultProtection });
|
|
10910
|
-
logger.info("Document permission service initialized");
|
|
10911
|
-
}
|
|
10912
|
-
const policy = documentPermissionService ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN;
|
|
11230
|
+
const documentPermissionService = options.documentPermissionService;
|
|
11231
|
+
const ownDocumentPermissions = !documentPermissionService && DOCUMENT_PERMISSIONS_ENABLED === "true" ? {
|
|
11232
|
+
defaultProtection,
|
|
11233
|
+
cacheTtlMs: resolvePermissionCacheTtlMs(process.env.DOCUMENT_PERMISSION_CACHE_TTL_MS, logger)
|
|
11234
|
+
} : null;
|
|
11235
|
+
const policy = documentPermissionService || ownDocumentPermissions ? AuthorizationPolicy.DOCUMENT_PERMISSIONS : authEnabled ? AuthorizationPolicy.ADMIN_ONLY : AuthorizationPolicy.OPEN;
|
|
10913
11236
|
const authorizationConfig = {
|
|
10914
11237
|
admins,
|
|
10915
11238
|
defaultProtection,
|
|
@@ -10961,6 +11284,7 @@ async function _setupCommonInfrastructure(options) {
|
|
|
10961
11284
|
relationalDb,
|
|
10962
11285
|
analyticsStore,
|
|
10963
11286
|
documentPermissionService,
|
|
11287
|
+
ownDocumentPermissions,
|
|
10964
11288
|
authorizationConfig,
|
|
10965
11289
|
attachments,
|
|
10966
11290
|
attachmentReferenceIndex,
|
|
@@ -10973,10 +11297,12 @@ async function _setupCommonInfrastructure(options) {
|
|
|
10973
11297
|
/**
|
|
10974
11298
|
* Private helper function containing common setup logic for API initialization
|
|
10975
11299
|
*/
|
|
10976
|
-
async function _setupAPI(
|
|
11300
|
+
async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers = [], reactorDriveClient, syncServingGate, httpRoutes, attachmentReadsFollowDocumentPolicy = false, inspection, driveStore) {
|
|
10977
11301
|
const hostModuleBase = {
|
|
10978
11302
|
...createReactorHostModuleBase({
|
|
10979
|
-
client:
|
|
11303
|
+
client: clients.client,
|
|
11304
|
+
read: clients.read,
|
|
11305
|
+
write: clients.write,
|
|
10980
11306
|
readModels,
|
|
10981
11307
|
relationalDb,
|
|
10982
11308
|
analyticsStore,
|
|
@@ -11013,11 +11339,11 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
|
|
|
11013
11339
|
}))).flat());
|
|
11014
11340
|
}
|
|
11015
11341
|
const { httpServer, wsServer } = await startServer(httpAdapter, port, options.https, logger);
|
|
11016
|
-
const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(
|
|
11342
|
+
const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(clients.read));
|
|
11017
11343
|
logger.info(`Authorization service initialized (policy: ${authorizationConfig.policy})`);
|
|
11018
11344
|
assertAttachmentPolicyReadsAllowed(attachmentReadsFollowDocumentPolicy, syncServingGate !== void 0);
|
|
11019
11345
|
const floor = requireAuthFetchMiddleware !== void 0;
|
|
11020
|
-
const attachmentAccess = new AttachmentAccessService(createCanonicalDocumentIdResolver(
|
|
11346
|
+
const attachmentAccess = new AttachmentAccessService(createCanonicalDocumentIdResolver({ read: clients.read }), authorizationService, attachmentReferenceIndex.store, attachmentReferenceProjection, clients.read, attachmentReadsFollowDocumentPolicy ? syncServingGate : void 0, {
|
|
11021
11347
|
refuseAnonymousWrites: authEnabled || floor,
|
|
11022
11348
|
refuseAnonymousReads: floor
|
|
11023
11349
|
});
|
|
@@ -11034,7 +11360,7 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
|
|
|
11034
11360
|
requireAuthFetchMiddleware,
|
|
11035
11361
|
httpServer,
|
|
11036
11362
|
wsServer,
|
|
11037
|
-
|
|
11363
|
+
clients,
|
|
11038
11364
|
relationalDb,
|
|
11039
11365
|
analyticsStore,
|
|
11040
11366
|
syncManager,
|
|
@@ -11062,7 +11388,7 @@ async function _setupAPI(reactorClient, syncManager, reactorProcessorManager, ht
|
|
|
11062
11388
|
});
|
|
11063
11389
|
if (mcpServerEnabled) {
|
|
11064
11390
|
await setupMcpServer({
|
|
11065
|
-
client:
|
|
11391
|
+
client: clients.client,
|
|
11066
11392
|
syncManager,
|
|
11067
11393
|
authorizeRequest: createMcpRequestAuthorizer(authService, authorizationService)
|
|
11068
11394
|
}, httpAdapter);
|
|
@@ -11136,16 +11462,54 @@ function buildApiDispose(args) {
|
|
|
11136
11462
|
}
|
|
11137
11463
|
};
|
|
11138
11464
|
}
|
|
11465
|
+
/**
|
|
11466
|
+
* Builds the host's own permission service: on the reactor store when the
|
|
11467
|
+
* client initializer handed it over, otherwise on the read-model store after
|
|
11468
|
+
* running reactor-api's legacy permission migrations there.
|
|
11469
|
+
*/
|
|
11470
|
+
async function createOwnDocumentPermissionService(settings, permissionsDb, options, dbClosers, logger) {
|
|
11471
|
+
const cacheOptions = {
|
|
11472
|
+
...DEFAULT_PERMISSION_CACHE_OPTIONS,
|
|
11473
|
+
ttlMs: settings.cacheTtlMs
|
|
11474
|
+
};
|
|
11475
|
+
const config = { defaultProtection: settings.defaultProtection };
|
|
11476
|
+
if (permissionsDb) {
|
|
11477
|
+
logger.info(`Document permission service initialized on the reactor store (cache TTL ${settings.cacheTtlMs} ms)`);
|
|
11478
|
+
return new DocumentPermissionService(permissionsDb, config, cacheOptions);
|
|
11479
|
+
}
|
|
11480
|
+
const { db, knex, pglite } = getDbClient(options.dbPath, options.pgliteFactory);
|
|
11481
|
+
dbClosers.push(...makeDbClosers(knex, pglite, logger));
|
|
11482
|
+
await runMigrations(db);
|
|
11483
|
+
logger.info("Document permission migrations completed");
|
|
11484
|
+
logger.info(`Document permission service initialized on the read-model store (cache TTL ${settings.cacheTtlMs} ms)`);
|
|
11485
|
+
return new DocumentPermissionService(db, config, cacheOptions);
|
|
11486
|
+
}
|
|
11487
|
+
/**
|
|
11488
|
+
* The permission cache TTL from `DOCUMENT_PERMISSION_CACHE_TTL_MS`: a
|
|
11489
|
+
* non-negative integer of milliseconds, 0 disabling the cache. Anything else
|
|
11490
|
+
* falls back to the default with a warning.
|
|
11491
|
+
*/
|
|
11492
|
+
function resolvePermissionCacheTtlMs(raw, logger) {
|
|
11493
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_PERMISSION_CACHE_TTL_MS;
|
|
11494
|
+
const parsed = Number(raw);
|
|
11495
|
+
if (!Number.isInteger(parsed) || parsed < 0) {
|
|
11496
|
+
logger.warn(`Ignoring DOCUMENT_PERMISSION_CACHE_TTL_MS=${raw}: expected a non-negative integer; using ${DEFAULT_PERMISSION_CACHE_TTL_MS} ms`);
|
|
11497
|
+
return DEFAULT_PERMISSION_CACHE_TTL_MS;
|
|
11498
|
+
}
|
|
11499
|
+
return parsed;
|
|
11500
|
+
}
|
|
11139
11501
|
async function initializeAndStartAPI(clientInitializer, options, processorApp) {
|
|
11140
|
-
const { port, httpAdapter, httpRoutes, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, relationalDb, analyticsStore, documentPermissionService, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness, attachmentReadsFollowDocumentPolicy } = await _setupCommonInfrastructure(options);
|
|
11502
|
+
const { port, httpAdapter, httpRoutes, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, relationalDb, analyticsStore, documentPermissionService: providedDocumentPermissionService, ownDocumentPermissions, authorizationConfig, attachments, attachmentReferenceIndex, packages, dbClosers, readiness, attachmentReadsFollowDocumentPolicy } = await _setupCommonInfrastructure(options);
|
|
11141
11503
|
const { documentModels, upgradeManifests, processors, subgraphs } = await packages.init();
|
|
11142
11504
|
const { module: reactorClientModule, reactorDriveClient, attachmentReferenceProjection = {
|
|
11143
11505
|
status: "unavailable",
|
|
11144
11506
|
reason: "initializer-did-not-report"
|
|
11145
|
-
} } = await clientInitializer(documentModels, {
|
|
11507
|
+
}, permissionsDb } = await clientInitializer(documentModels, {
|
|
11146
11508
|
attachmentReferenceWriter: attachmentReferenceIndex.store,
|
|
11147
|
-
upgradeManifests
|
|
11509
|
+
upgradeManifests,
|
|
11510
|
+
readModelDb: getDbClient(options.dbPath, options.pgliteFactory).db
|
|
11148
11511
|
});
|
|
11512
|
+
const documentPermissionService = providedDocumentPermissionService ?? (ownDocumentPermissions ? await createOwnDocumentPermissionService(ownDocumentPermissions, permissionsDb, options, dbClosers, options.logger ?? defaultLogger) : void 0);
|
|
11149
11513
|
const reactorClient = reactorClientModule.client;
|
|
11150
11514
|
const syncManager = reactorClientModule.reactorModule?.syncModule?.syncManager;
|
|
11151
11515
|
if (!syncManager) throw new Error("SyncManager not available from InProcessReactorClientModule");
|
|
@@ -11153,13 +11517,20 @@ async function initializeAndStartAPI(clientInitializer, options, processorApp) {
|
|
|
11153
11517
|
if (!reactorProcessorManager) throw new Error("ProcessorManager not available from InProcessReactorClientModule");
|
|
11154
11518
|
const documentModelRegistry = reactorClientModule.reactorModule?.documentModelRegistry;
|
|
11155
11519
|
if (!documentModelRegistry) throw new Error("DocumentModelRegistry not available from InProcessReactorClientModule");
|
|
11520
|
+
const readModels = (reactorClientModule.reactorModule?.readModelCoordinator)?.readModels ?? [];
|
|
11156
11521
|
return {
|
|
11157
|
-
...await _setupAPI(
|
|
11522
|
+
...await _setupAPI({
|
|
11523
|
+
read: reactorClientModule.read,
|
|
11524
|
+
write: reactorClientModule.write,
|
|
11525
|
+
client: reactorClient
|
|
11526
|
+
}, syncManager, reactorProcessorManager, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, authEnabled, authService, port, packages, relationalDb, analyticsStore, documentPermissionService, processors, subgraphs, options, processorApp, readModels, attachments, attachmentReferenceIndex, attachmentReferenceProjection, authorizationConfig, documentModelRegistry, dbClosers, reactorDriveClient, buildSyncServingGate(reactorClientModule.reactorModule, authorizationConfig, options.logger ?? defaultLogger), httpRoutes, attachmentReadsFollowDocumentPolicy, reactorClientModule.reactorModule && options.inspection !== false ? createReactorInspectionSource(reactorClientModule.reactorModule, {
|
|
11158
11527
|
admin: process.env.INSPECTION_ADMIN_ENABLED === "true",
|
|
11159
11528
|
...options.inspection,
|
|
11160
11529
|
attachmentStore: attachmentInspectionStore(attachments)
|
|
11161
11530
|
}) : void 0, reactorClientModule.reactorModule?.reactor),
|
|
11162
11531
|
client: reactorClient,
|
|
11532
|
+
read: reactorClientModule.read,
|
|
11533
|
+
write: reactorClientModule.write,
|
|
11163
11534
|
syncManager,
|
|
11164
11535
|
documentModelRegistry,
|
|
11165
11536
|
readiness,
|
|
@@ -11347,7 +11718,7 @@ var PackageManagementService = class {
|
|
|
11347
11718
|
}
|
|
11348
11719
|
};
|
|
11349
11720
|
//#endregion
|
|
11350
|
-
export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
|
|
11721
|
+
export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, ConsistencyCoordinateInputSchema, ConsistencyTokenInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DEFAULT_PERMISSION_CACHE_OPTIONS, DEFAULT_PERMISSION_CACHE_TTL_MS, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
|
|
11351
11722
|
|
|
11352
11723
|
//# sourceMappingURL=index.mjs.map
|
|
11353
|
-
//# debugId=
|
|
11724
|
+
//# debugId=560dd033-eac1-581d-a504-0117f3526f86
|