@powerhousedao/reactor-api 6.2.3-dev.85 → 6.2.3-dev.86
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-DZfYOd9M.mjs → base-document-models-DFRhs9rF.mjs} +234 -3
- package/dist/{base-document-models-DZfYOd9M.mjs.map → base-document-models-DFRhs9rF.mjs.map} +1 -1
- package/dist/{error-info-BaEL50f5.mjs → error-info-Cr6oQACe.mjs} +119 -4
- package/dist/error-info-Cr6oQACe.mjs.map +1 -0
- package/dist/index.d.mts +78 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +272 -19
- package/dist/index.mjs.map +1 -1
- package/dist/{package-subgraph-check-DxZhf2lB.mjs → package-subgraph-check-FpKGnzKA.mjs} +4 -4
- package/dist/{package-subgraph-check-DxZhf2lB.mjs.map → package-subgraph-check-FpKGnzKA.mjs.map} +1 -1
- package/dist/{pglite-node-DGms6Ssa.mjs → pglite-node-CcX2YT-l.mjs} +33 -4
- package/dist/pglite-node-CcX2YT-l.mjs.map +1 -0
- package/dist/src/graphql/subgraph-types.mjs +1 -1
- package/dist/src/pglite/pglite-node.d.mts +43 -2
- package/dist/src/pglite/pglite-node.d.mts.map +1 -1
- package/dist/src/pglite/pglite-node.mjs +5 -5
- package/dist/src/pglite/worker/entry.mjs +51 -4
- package/dist/src/pglite/worker/entry.mjs.map +1 -1
- package/package.json +13 -13
- package/dist/error-info-BaEL50f5.mjs.map +0 -1
- package/dist/pglite-node-DGms6Ssa.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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]="22ec6516-d8cb-517f-b432-21a5543b7ee2")}catch(e){}}();
|
|
3
3
|
import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
|
|
4
4
|
import { A as RequestClientBinder, B as CanonicalDocumentIdResolutionError, C as loadDocumentModels, D as manifestDeclaredSubgraphs, E as loadSubgraphs, F as READABLE_DOCUMENTS_NAMESPACE, G as AuthEvaluationUnsupportedError, H as AuthorizationPolicy, I as ReadableDocumentsProjection, J as MalformedStoredOperationError, K as AuthenticationRequiredError, L as applyReadableFilter, M as createCredentialInvalidator, N as DEFAULT_ROOT_TYPES, O as BaseSubgraph, P as EVERYONE, R as isDocumentListed, T as loadScalars, U as AuthorizedDocumentHandle, V as createCanonicalDocumentIdResolver, W as createAuthorizationService, Y as RefusalNotRecordedError, _ as runDetached, a as PIECE_SOURCE_LIST, b as extractUpgradeManifests, c as piecesFromCdnList, d as buildGraphQlDocument, f as buildGraphQlDriveDocument, g as reportFailure, h as isSubgraphClass, j as AuthService, k as callerSubject, l as piecesFromListModule, m as buildGraphqlOperations, n as scalarExportsOf, p as buildGraphqlOperation, q as ForbiddenError, s as pieceListLocation, t as extractSubgraphs, u as extractDocumentModels, v as PACKAGE_MODULE_FAILED, w as loadProcessors, x as failedLoadHeader, y as debounce, z as readableDocumentsSubquery } from "./subgraph-extraction-BA9WKjn1.mjs";
|
|
5
|
-
import { A as getDocumentModelTypeDefs, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as typeDefinitionNames, I as getDocumentModelSchemaName, L as EMPTY_SCALAR_REGISTRY, M as hasOperationSchemas, N as reservedTypeNames, O as generatedTypesOf, P as reservedTypeNamesTaken, R as sameScalarRegistry, 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 getGeneratedDocumentModelTypes, k as getDocumentModelSubgraphName, 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, z as schema_default$1 } from "./base-document-models-
|
|
5
|
+
import { A as getDocumentModelTypeDefs, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as typeDefinitionNames, I as getDocumentModelSchemaName, L as EMPTY_SCALAR_REGISTRY, M as hasOperationSchemas, N as reservedTypeNames, O as generatedTypesOf, P as reservedTypeNamesTaken, R as sameScalarRegistry, 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 getGeneratedDocumentModelTypes, k as getDocumentModelSubgraphName, 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, z as schema_default$1 } from "./base-document-models-DFRhs9rF.mjs";
|
|
6
6
|
import { n as createApolloFetchHandler } from "./adapter-gateway-apollo-D-EdZ4e-.mjs";
|
|
7
|
-
import {
|
|
8
|
-
import { h as preparePgliteDataDir, m as openCurrentPgliteForVerify } from "./pglite-node-
|
|
7
|
+
import { _ as PGLITE_UTC_PARSERS, a as resolvePgliteMaintenance, r as createDurableNodeFs } from "./error-info-Cr6oQACe.mjs";
|
|
8
|
+
import { h as preparePgliteDataDir, m as openCurrentPgliteForVerify } from "./pglite-node-CcX2YT-l.mjs";
|
|
9
9
|
import nodeModule, { isBuiltin } from "node:module";
|
|
10
10
|
import { AttachmentBuilder, AttachmentNotFound, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
|
|
11
11
|
import { ConsoleLogger, childLogger } from "document-model";
|
|
@@ -13,7 +13,7 @@ import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
|
|
|
13
13
|
import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
|
|
14
14
|
import { gql } from "graphql-tag";
|
|
15
15
|
import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, specifiedScalarTypes, validateSchema, valueFromASTUntyped, visit } from "graphql";
|
|
16
|
-
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";
|
|
16
|
+
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, isMemoryTelemetryOutput, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState, warnOnce } from "@powerhousedao/reactor";
|
|
17
17
|
import { deserializeSignature, readPeerManifest, serializeSignature, setName } from "@powerhousedao/shared/document-model";
|
|
18
18
|
import { createRelationalDb, getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
|
|
19
19
|
import { Kysely, Migrator, sql } from "kysely";
|
|
@@ -25,8 +25,8 @@ import posix from "node:path/posix";
|
|
|
25
25
|
import { Readable } from "node:stream";
|
|
26
26
|
import { pipeline } from "node:stream/promises";
|
|
27
27
|
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
28
|
-
import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
|
|
29
|
-
import { monitorEventLoopDelay } from "node:perf_hooks";
|
|
28
|
+
import nodeFs, { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, watchFile } from "node:fs";
|
|
29
|
+
import { PerformanceObserver, constants, monitorEventLoopDelay } from "node:perf_hooks";
|
|
30
30
|
import { pathToFileURL } from "node:url";
|
|
31
31
|
import { SCALAR_DEFINITION_VERSION, getCatalogScalar } from "document-model/scalars";
|
|
32
32
|
import * as z$1 from "zod";
|
|
@@ -51,7 +51,7 @@ import EventEmitter from "node:events";
|
|
|
51
51
|
import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
|
|
52
52
|
import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
|
|
53
53
|
import { setupMcpServer } from "@powerhousedao/reactor-mcp";
|
|
54
|
-
import { tmpdir } from "node:os";
|
|
54
|
+
import { freemem, tmpdir } from "node:os";
|
|
55
55
|
import { WebSocketServer } from "ws";
|
|
56
56
|
import { isAttachmentHash, readGateAllowsAttachmentRead, scopeGateAllowsAttachmentRead } from "@powerhousedao/reactor-attachments/replication";
|
|
57
57
|
import { PGlite } from "@electric-sql/pglite";
|
|
@@ -59,6 +59,8 @@ import { NodeFS } from "@electric-sql/pglite/nodefs";
|
|
|
59
59
|
import knex from "knex";
|
|
60
60
|
import ClientPgLite from "knex-pglite";
|
|
61
61
|
import { KyselyKnexDialect, PGColdDialect } from "kysely-knex";
|
|
62
|
+
import { getHeapSpaceStatistics, getHeapStatistics, writeHeapSnapshot } from "node:v8";
|
|
63
|
+
import { resolvePhDir as resolvePhDir$1 } from "@powerhousedao/shared/clis";
|
|
62
64
|
//#region src/graphql/gateway/types.ts
|
|
63
65
|
/** No authenticated caller resolved, and REQUIRE_AUTHENTICATED_CALLER wants one. */
|
|
64
66
|
const WS_CLOSE_REASON_AUTHENTICATION_REQUIRED = "authentication-required";
|
|
@@ -1658,7 +1660,7 @@ var HttpScope = class {
|
|
|
1658
1660
|
const method = req.method ?? "GET";
|
|
1659
1661
|
const url = `${ctx.transport.baseUrl}${req.url ?? "/"}`;
|
|
1660
1662
|
const controller = new AbortController();
|
|
1661
|
-
|
|
1663
|
+
res.once("close", () => controller.abort());
|
|
1662
1664
|
let raw;
|
|
1663
1665
|
let init = {
|
|
1664
1666
|
method,
|
|
@@ -7114,6 +7116,8 @@ function createInspectionResolvers(source, sync, gate) {
|
|
|
7114
7116
|
}),
|
|
7115
7117
|
queueState: operator(async () => toWireQueueState(await inspector.getQueueState())),
|
|
7116
7118
|
processors: operator(async () => (await inspector.getProcessors()).map(toWireProcessor)),
|
|
7119
|
+
processorTiming: operator(() => inspector.getProcessorTiming()),
|
|
7120
|
+
memoryTelemetry: operator((args) => inspector.getMemoryTelemetry(args.limit ?? void 0, args.sinceIso ?? void 0)),
|
|
7117
7121
|
catchUpStatus: operator(() => inspector.getCatchUpStatus()),
|
|
7118
7122
|
catchUpPriority: operator(async () => toWireCatchUpPriority(await inspector.getCatchUpPriority())),
|
|
7119
7123
|
storageHealth: operator(() => inspector.getStorageHealth()),
|
|
@@ -7227,6 +7231,19 @@ function catchUpPrioritySettingOf(args) {
|
|
|
7227
7231
|
level
|
|
7228
7232
|
};
|
|
7229
7233
|
}
|
|
7234
|
+
/** The change `args` name; throws BAD_USER_INPUT for an unknown output. */
|
|
7235
|
+
function memoryTelemetryChangeOf(args) {
|
|
7236
|
+
const unknown = args.outputs?.find((o) => !isMemoryTelemetryOutput(o));
|
|
7237
|
+
if (unknown !== void 0) throw badInput(`Memory telemetry has no output ${JSON.stringify(unknown)}`);
|
|
7238
|
+
return {
|
|
7239
|
+
enabled: args.enabled,
|
|
7240
|
+
intervalMs: args.intervalMs ?? void 0,
|
|
7241
|
+
outputs: args.outputs?.filter(isMemoryTelemetryOutput)
|
|
7242
|
+
};
|
|
7243
|
+
}
|
|
7244
|
+
function refused(error) {
|
|
7245
|
+
return new GraphQLError(error instanceof Error ? error.message : String(error), { extensions: { code: "LEVER_REFUSED" } });
|
|
7246
|
+
}
|
|
7230
7247
|
/** How long a mutation waits on its lever before answering that it started. */
|
|
7231
7248
|
const LEVER_ANSWER_WINDOW_MS = 2e3;
|
|
7232
7249
|
/**
|
|
@@ -7248,6 +7265,14 @@ async function pulled(lever, onLateFailure, windowMs) {
|
|
|
7248
7265
|
}
|
|
7249
7266
|
return true;
|
|
7250
7267
|
}
|
|
7268
|
+
/** Passes a lever's refusal to the caller as LEVER_REFUSED. */
|
|
7269
|
+
async function refusable(lever) {
|
|
7270
|
+
try {
|
|
7271
|
+
return await lever();
|
|
7272
|
+
} catch (error) {
|
|
7273
|
+
throw new GraphQLError(error instanceof Error ? error.message : String(error), { extensions: { code: "LEVER_REFUSED" } });
|
|
7274
|
+
}
|
|
7275
|
+
}
|
|
7251
7276
|
/** Inspection levers for listed admins, kept apart from the read-only inspection subgraph. */
|
|
7252
7277
|
var InspectionAdminSubgraph = class extends BaseSubgraph {
|
|
7253
7278
|
name = "inspection-admin";
|
|
@@ -7269,10 +7294,16 @@ var InspectionAdminSubgraph = class extends BaseSubgraph {
|
|
|
7269
7294
|
return run(args);
|
|
7270
7295
|
};
|
|
7271
7296
|
return {
|
|
7272
|
-
Query: {
|
|
7273
|
-
|
|
7274
|
-
|
|
7275
|
-
|
|
7297
|
+
Query: {
|
|
7298
|
+
inspectionAdmin: listed(() => ({
|
|
7299
|
+
processors: true,
|
|
7300
|
+
catchUpPriority: true,
|
|
7301
|
+
memoryTelemetry: true,
|
|
7302
|
+
keyframes: true
|
|
7303
|
+
})),
|
|
7304
|
+
inspectionKeyframeCleanup: listed(() => admin.getKeyframeCleanup()),
|
|
7305
|
+
inspectionKeyframeReclaim: listed(() => admin.getKeyframeReclaim())
|
|
7306
|
+
},
|
|
7276
7307
|
Mutation: {
|
|
7277
7308
|
inspectionRetryProcessor: listed(({ processorId }) => pulled(() => admin.retryProcessor(processorId), (error) => this.leverFailed("Retry", processorId, error), this.answerWindowMs)),
|
|
7278
7309
|
inspectionRerunProcessor: listed(({ processorId, clear, fromOrdinal }) => pulled(() => admin.rerunProcessor(processorId, {
|
|
@@ -7284,10 +7315,32 @@ var InspectionAdminSubgraph = class extends BaseSubgraph {
|
|
|
7284
7315
|
try {
|
|
7285
7316
|
await admin.setCatchUpPriority(setting);
|
|
7286
7317
|
} catch (error) {
|
|
7287
|
-
throw
|
|
7318
|
+
throw refused(error);
|
|
7319
|
+
}
|
|
7320
|
+
return true;
|
|
7321
|
+
}),
|
|
7322
|
+
inspectionSetMemoryTelemetry: listed(async (args) => {
|
|
7323
|
+
const change = memoryTelemetryChangeOf(args);
|
|
7324
|
+
try {
|
|
7325
|
+
await admin.setMemoryTelemetry(change);
|
|
7326
|
+
} catch (error) {
|
|
7327
|
+
throw refused(error);
|
|
7328
|
+
}
|
|
7329
|
+
return true;
|
|
7330
|
+
}),
|
|
7331
|
+
inspectionWriteHeapSnapshot: listed(async ({ force }) => {
|
|
7332
|
+
try {
|
|
7333
|
+
return await admin.writeHeapSnapshot(force ?? false);
|
|
7334
|
+
} catch (error) {
|
|
7335
|
+
throw refused(error);
|
|
7288
7336
|
}
|
|
7337
|
+
}),
|
|
7338
|
+
inspectionStartKeyframeCleanup: listed(({ dryRun }) => refusable(() => admin.startKeyframeCleanup({ dryRun }))),
|
|
7339
|
+
inspectionCancelKeyframeCleanup: listed(async () => {
|
|
7340
|
+
await admin.cancelKeyframeCleanup();
|
|
7289
7341
|
return true;
|
|
7290
|
-
})
|
|
7342
|
+
}),
|
|
7343
|
+
inspectionReclaimKeyframeSpace: listed(() => refusable(() => admin.reclaimKeyframeSpace()))
|
|
7291
7344
|
}
|
|
7292
7345
|
};
|
|
7293
7346
|
}
|
|
@@ -8923,10 +8976,10 @@ const ADMIN_USERS = new Proxy([], {
|
|
|
8923
8976
|
//#endregion
|
|
8924
8977
|
//#region src/graphql/system/version.ts
|
|
8925
8978
|
function getVersion() {
|
|
8926
|
-
return "6.2.3-dev.
|
|
8979
|
+
return "6.2.3-dev.86";
|
|
8927
8980
|
}
|
|
8928
8981
|
function getGitHash() {
|
|
8929
|
-
return "
|
|
8982
|
+
return "dfed991250d14ac9b6160e9ac4f24c2ba704e632";
|
|
8930
8983
|
}
|
|
8931
8984
|
function getGitUrl() {
|
|
8932
8985
|
return buildTreeUrl(getGitHash());
|
|
@@ -12412,7 +12465,207 @@ var PackageManagementService = class {
|
|
|
12412
12465
|
}
|
|
12413
12466
|
};
|
|
12414
12467
|
//#endregion
|
|
12415
|
-
|
|
12468
|
+
//#region src/telemetry/jsonl-sink.ts
|
|
12469
|
+
const MIB = 1048576;
|
|
12470
|
+
/** An ISO time usable in a Windows file name. */
|
|
12471
|
+
function fileTimestamp(date) {
|
|
12472
|
+
return date.toISOString().replace(/[:.]/g, "-");
|
|
12473
|
+
}
|
|
12474
|
+
/** Where telemetry files land: `<phDir>/telemetry`, following `PH_USER_DATA_DIR`. */
|
|
12475
|
+
function telemetryDir(env = process.env) {
|
|
12476
|
+
return path.join(resolvePhDir$1(void 0, env), "telemetry");
|
|
12477
|
+
}
|
|
12478
|
+
/**
|
|
12479
|
+
* Appends one JSON line at a time and rotates at `maxBytes`: the full file moves
|
|
12480
|
+
* to `<stem>.<n>.jsonl`, and the oldest beyond `keep` is deleted. Each append is
|
|
12481
|
+
* synchronous and small, so a hard kill loses nothing written so far.
|
|
12482
|
+
*/
|
|
12483
|
+
var JsonlFile = class {
|
|
12484
|
+
options;
|
|
12485
|
+
path;
|
|
12486
|
+
size = 0;
|
|
12487
|
+
rotation = 0;
|
|
12488
|
+
failed = false;
|
|
12489
|
+
stem;
|
|
12490
|
+
dir;
|
|
12491
|
+
constructor(options) {
|
|
12492
|
+
this.options = options;
|
|
12493
|
+
this.path = options.path;
|
|
12494
|
+
this.dir = path.dirname(options.path);
|
|
12495
|
+
this.stem = path.basename(options.path, ".jsonl");
|
|
12496
|
+
mkdirSync(this.dir, { recursive: true });
|
|
12497
|
+
this.append(`${JSON.stringify(options.header)}\n`);
|
|
12498
|
+
}
|
|
12499
|
+
writeLine(value) {
|
|
12500
|
+
const line = `${JSON.stringify(value)}\n`;
|
|
12501
|
+
if (this.size + line.length > this.options.maxBytes) this.rotate();
|
|
12502
|
+
this.append(line);
|
|
12503
|
+
}
|
|
12504
|
+
append(line) {
|
|
12505
|
+
try {
|
|
12506
|
+
appendFileSync(this.path, line);
|
|
12507
|
+
this.size += line.length;
|
|
12508
|
+
this.failed = false;
|
|
12509
|
+
} catch (error) {
|
|
12510
|
+
if (!this.failed) this.options.logger?.warn("Telemetry file '@Path' cannot be written: @Error", this.path, error);
|
|
12511
|
+
this.failed = true;
|
|
12512
|
+
}
|
|
12513
|
+
}
|
|
12514
|
+
rotate() {
|
|
12515
|
+
this.rotation++;
|
|
12516
|
+
try {
|
|
12517
|
+
renameSync(this.path, path.join(this.dir, `${this.stem}.${this.rotation}.jsonl`));
|
|
12518
|
+
} catch {}
|
|
12519
|
+
this.size = 0;
|
|
12520
|
+
this.prune();
|
|
12521
|
+
this.append(`${JSON.stringify(this.options.header)}\n`);
|
|
12522
|
+
}
|
|
12523
|
+
prune() {
|
|
12524
|
+
const rotated = readdirSync(this.dir).map((name) => ({
|
|
12525
|
+
name,
|
|
12526
|
+
n: new RegExp(`^${escapeRegExp(this.stem)}\\.(\\d+)\\.jsonl$`).exec(name)?.[1]
|
|
12527
|
+
})).filter((file) => file.n !== void 0).sort((a, b) => Number(a.n) - Number(b.n));
|
|
12528
|
+
const excess = rotated.length - (this.options.keep - 1);
|
|
12529
|
+
for (const file of rotated.slice(0, Math.max(excess, 0))) rmSync(path.join(this.dir, file.name), { force: true });
|
|
12530
|
+
}
|
|
12531
|
+
};
|
|
12532
|
+
function escapeRegExp(text) {
|
|
12533
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
12534
|
+
}
|
|
12535
|
+
/** Opens the memory telemetry's JSONL file; the header holds no env values. */
|
|
12536
|
+
function memoryFileSink(config, options = {}) {
|
|
12537
|
+
const now = options.now?.() ?? /* @__PURE__ */ new Date();
|
|
12538
|
+
const file = new JsonlFile({
|
|
12539
|
+
path: config.filePath ?? path.join(options.dir ?? telemetryDir(options.env), `memory-${fileTimestamp(now)}-${process.pid}.jsonl`),
|
|
12540
|
+
maxBytes: config.fileMaxMb * MIB,
|
|
12541
|
+
keep: config.fileKeep,
|
|
12542
|
+
header: {
|
|
12543
|
+
telemetry: "memory",
|
|
12544
|
+
startedAt: now.toISOString(),
|
|
12545
|
+
pid: process.pid,
|
|
12546
|
+
node: process.version,
|
|
12547
|
+
argv: process.argv,
|
|
12548
|
+
config
|
|
12549
|
+
},
|
|
12550
|
+
logger: options.logger
|
|
12551
|
+
});
|
|
12552
|
+
return {
|
|
12553
|
+
path: file.path,
|
|
12554
|
+
write: (sample) => file.writeLine(sample),
|
|
12555
|
+
close: () => void 0
|
|
12556
|
+
};
|
|
12557
|
+
}
|
|
12558
|
+
//#endregion
|
|
12559
|
+
//#region src/telemetry/heap-snapshot.ts
|
|
12560
|
+
const COOLDOWN_MS = 12e4;
|
|
12561
|
+
/** Writing a snapshot needs memory close to the heap's size. */
|
|
12562
|
+
const FREE_MEMORY_FACTOR = 1.5;
|
|
12563
|
+
/**
|
|
12564
|
+
* A guarded writer of main-thread heap snapshots: one at a time, at most one
|
|
12565
|
+
* every two minutes, and refused without room for it unless forced. A snapshot
|
|
12566
|
+
* can hold document state, so it stays on the host. It blocks the event loop
|
|
12567
|
+
* for seconds to minutes; take it at 2-4 GB, not at 10 GB.
|
|
12568
|
+
*/
|
|
12569
|
+
function createHeapSnapshotWriter(options) {
|
|
12570
|
+
const now = options.now ?? (() => Date.now());
|
|
12571
|
+
const freeMemory = options.freeMemory ?? freemem;
|
|
12572
|
+
const heapUsed = options.heapUsed ?? (() => process.memoryUsage().heapUsed);
|
|
12573
|
+
const write = options.write ?? ((file) => writeHeapSnapshot(file));
|
|
12574
|
+
let writing = false;
|
|
12575
|
+
let lastAt;
|
|
12576
|
+
return (force) => {
|
|
12577
|
+
if (writing) return Promise.reject(/* @__PURE__ */ new Error("A heap snapshot is already being written"));
|
|
12578
|
+
if (lastAt !== void 0 && now() - lastAt < COOLDOWN_MS) return Promise.reject(/* @__PURE__ */ new Error("A heap snapshot was written in the last two minutes"));
|
|
12579
|
+
const needed = FREE_MEMORY_FACTOR * heapUsed();
|
|
12580
|
+
if (!force && freeMemory() < needed) return Promise.reject(/* @__PURE__ */ new Error(`Too little free memory for a heap snapshot: ${Math.round(freeMemory() / 1048576)} MB free, ${Math.round(needed / 1048576)} MB needed; force overrides this`));
|
|
12581
|
+
writing = true;
|
|
12582
|
+
try {
|
|
12583
|
+
mkdirSync(options.dir, { recursive: true });
|
|
12584
|
+
const stamp = fileTimestamp(new Date(now()));
|
|
12585
|
+
const file = path.resolve(options.dir, `heap-${stamp}-${process.pid}.heapsnapshot`);
|
|
12586
|
+
const written = write(file);
|
|
12587
|
+
lastAt = now();
|
|
12588
|
+
return Promise.resolve(written);
|
|
12589
|
+
} catch (error) {
|
|
12590
|
+
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
12591
|
+
} finally {
|
|
12592
|
+
writing = false;
|
|
12593
|
+
}
|
|
12594
|
+
};
|
|
12595
|
+
}
|
|
12596
|
+
//#endregion
|
|
12597
|
+
//#region src/telemetry/node-memory-sampler.ts
|
|
12598
|
+
const LOOP_RESOLUTION_MS = 20;
|
|
12599
|
+
const NANOS_PER_MS = 1e6;
|
|
12600
|
+
function spaceBytes(name) {
|
|
12601
|
+
return getHeapSpaceStatistics().find((space) => space.space_name === name)?.space_used_size ?? 0;
|
|
12602
|
+
}
|
|
12603
|
+
/**
|
|
12604
|
+
* Reads the process's memory. `heapUsed` alone saw-tooths, so a GC observer
|
|
12605
|
+
* keeps the used heap right after each major collection, which needs no
|
|
12606
|
+
* `--expose-gc`.
|
|
12607
|
+
*/
|
|
12608
|
+
var NodeMemorySampler = class {
|
|
12609
|
+
observer;
|
|
12610
|
+
loop;
|
|
12611
|
+
postGcHeap = null;
|
|
12612
|
+
postGcAt = null;
|
|
12613
|
+
start() {
|
|
12614
|
+
this.observer = new PerformanceObserver((list) => {
|
|
12615
|
+
for (const entry of list.getEntries()) {
|
|
12616
|
+
const { detail } = entry;
|
|
12617
|
+
if (detail?.kind === constants.NODE_PERFORMANCE_GC_MAJOR) {
|
|
12618
|
+
this.postGcHeap = getHeapStatistics().used_heap_size;
|
|
12619
|
+
this.postGcAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
12620
|
+
}
|
|
12621
|
+
}
|
|
12622
|
+
});
|
|
12623
|
+
this.observer.observe({ entryTypes: ["gc"] });
|
|
12624
|
+
this.loop = monitorEventLoopDelay({ resolution: LOOP_RESOLUTION_MS });
|
|
12625
|
+
this.loop.enable();
|
|
12626
|
+
}
|
|
12627
|
+
stop() {
|
|
12628
|
+
this.observer?.disconnect();
|
|
12629
|
+
this.observer = void 0;
|
|
12630
|
+
this.loop?.disable();
|
|
12631
|
+
this.loop = void 0;
|
|
12632
|
+
}
|
|
12633
|
+
sample() {
|
|
12634
|
+
const memory = process.memoryUsage();
|
|
12635
|
+
const heap = getHeapStatistics();
|
|
12636
|
+
const loop = {
|
|
12637
|
+
p50: (this.loop?.percentile(50) ?? 0) / NANOS_PER_MS,
|
|
12638
|
+
p99: (this.loop?.percentile(99) ?? 0) / NANOS_PER_MS
|
|
12639
|
+
};
|
|
12640
|
+
this.loop?.reset();
|
|
12641
|
+
return {
|
|
12642
|
+
rss: memory.rss,
|
|
12643
|
+
maxRss: process.resourceUsage().maxRSS * 1024,
|
|
12644
|
+
heapUsed: memory.heapUsed,
|
|
12645
|
+
heapTotal: memory.heapTotal,
|
|
12646
|
+
heapLimit: heap.heap_size_limit,
|
|
12647
|
+
external: memory.external,
|
|
12648
|
+
arrayBuffers: memory.arrayBuffers,
|
|
12649
|
+
mallocedMemory: heap.malloced_memory,
|
|
12650
|
+
postGcHeap: this.postGcHeap,
|
|
12651
|
+
postGcAt: this.postGcAt,
|
|
12652
|
+
spaces: {
|
|
12653
|
+
old: spaceBytes("old_space"),
|
|
12654
|
+
lo: spaceBytes("large_object_space"),
|
|
12655
|
+
code: spaceBytes("code_space"),
|
|
12656
|
+
new: spaceBytes("new_space")
|
|
12657
|
+
},
|
|
12658
|
+
contexts: {
|
|
12659
|
+
native: heap.number_of_native_contexts,
|
|
12660
|
+
detached: heap.number_of_detached_contexts
|
|
12661
|
+
},
|
|
12662
|
+
loop,
|
|
12663
|
+
freemem: freemem()
|
|
12664
|
+
};
|
|
12665
|
+
}
|
|
12666
|
+
};
|
|
12667
|
+
//#endregion
|
|
12668
|
+
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, DEFAULT_ROOT_TYPES, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, DriveNodeFieldsFragmentDoc, DriveNodeKind, DriveNodeKindSchema, EVERYONE, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetCreateProtocolVersionsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetDriveDescendantsDocument, GetDriveNodeDocument, GetDriveNodesDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, JsonlFile, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, NodeMemorySampler, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, READABLE_DOCUMENTS_NAMESPACE, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, ReadableDocumentsProjection, 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, applyReadableFilter, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertIndexAccessComplete, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHeapSnapshotWriter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, defineIndexSubgraph, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, fileTimestamp, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isDocumentListed, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, memoryFileSink, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, reactorApiConfigFromEnv, readableDocumentsSubquery, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, setAuthContext, telemetryDir, typeDefinitionNames, verifyWebhook };
|
|
12416
12669
|
|
|
12417
12670
|
//# sourceMappingURL=index.mjs.map
|
|
12418
|
-
//# debugId=
|
|
12671
|
+
//# debugId=22ec6516-d8cb-517f-b432-21a5543b7ee2
|