bunsane 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +445 -318
- package/config/cache.config.ts +35 -1
- package/core/App.ts +24 -1064
- package/core/ArcheType.ts +78 -2110
- package/core/BatchLoader.ts +56 -32
- package/core/Entity.ts +85 -1043
- package/core/EntityHookManager.ts +52 -754
- package/core/Logger.ts +10 -0
- package/core/RequestContext.ts +64 -6
- package/core/RequestLoaders.ts +187 -36
- package/core/SchedulerManager.ts +28 -600
- package/core/app/bootstrap.ts +133 -0
- package/core/app/cors.ts +85 -0
- package/core/app/graphqlSetup.ts +56 -0
- package/core/app/healthEndpoints.ts +31 -0
- package/core/app/metricsCollector.ts +27 -0
- package/core/app/preparedStatementWarmup.ts +15 -0
- package/core/app/processHandlers.ts +43 -0
- package/core/app/requestRouter.ts +310 -0
- package/core/app/restRegistry.ts +80 -0
- package/core/app/shutdown.ts +97 -0
- package/core/app/studioRouter.ts +83 -0
- package/core/archetype/customTypes.ts +100 -0
- package/core/archetype/decorators.ts +171 -0
- package/core/archetype/fieldResolvers.ts +666 -0
- package/core/archetype/helpers.ts +29 -0
- package/core/archetype/relationLoader.ts +161 -0
- package/core/archetype/schemaBuilder.ts +141 -0
- package/core/archetype/weaver.ts +218 -0
- package/core/archetype/zodSchemaBuilder.ts +527 -0
- package/core/cache/CacheManager.ts +173 -267
- package/core/cache/CompressionUtils.ts +34 -3
- package/core/cache/MemoryCache.ts +40 -37
- package/core/cache/RedisCache.ts +4 -4
- package/core/cache/health.ts +30 -0
- package/core/cache/invalidation.ts +96 -0
- package/core/cache/strategies/writeInvalidate.ts +111 -0
- package/core/cache/strategies/writeThrough.ts +233 -0
- package/core/components/BaseComponent.ts +16 -8
- package/core/components/ComponentRegistry.ts +28 -0
- package/core/decorators/IndexedField.ts +1 -1
- package/core/entity/cacheStrategies.ts +97 -0
- package/core/entity/componentAccess.ts +364 -0
- package/core/entity/finders.ts +202 -0
- package/core/entity/pendingOps.ts +72 -0
- package/core/entity/saveEntity.ts +377 -0
- package/core/hooks/dispatcher.ts +439 -0
- package/core/hooks/guards.ts +155 -0
- package/core/hooks/registry.ts +247 -0
- package/core/metadata/definitions/Component.ts +1 -1
- package/core/metadata/index.ts +15 -4
- package/core/middleware/AccessLog.ts +8 -1
- package/core/middleware/RateLimit.ts +102 -105
- package/core/middleware/RequestId.ts +2 -9
- package/core/middleware/SecurityHeaders.ts +2 -11
- package/core/middleware/headers.ts +28 -0
- package/core/remote/OutboxWorker.ts +213 -183
- package/core/remote/RemoteManager.ts +401 -400
- package/core/remote/types.ts +153 -151
- package/core/requestScope.ts +34 -0
- package/core/scheduler/cronEvaluator.ts +174 -0
- package/core/scheduler/lifecycleHooks.ts +21 -0
- package/core/scheduler/lockCoordinator.ts +27 -0
- package/core/scheduler/metrics.ts +14 -0
- package/core/scheduler/taskRunner.ts +420 -0
- package/database/DatabaseHelper.ts +128 -101
- package/database/IndexingStrategy.ts +72 -2
- package/database/PreparedStatementCache.ts +20 -5
- package/database/cancellable.ts +35 -0
- package/database/index.ts +15 -3
- package/database/instrumentedDb.ts +141 -0
- package/endpoints/archetypes.ts +2 -8
- package/endpoints/tables.ts +6 -1
- package/gql/index.ts +1 -1
- package/gql/visitors/ResolverGeneratorVisitor.ts +25 -4
- package/package.json +22 -1
- package/query/CTENode.ts +5 -3
- package/query/ComponentInclusionNode.ts +240 -13
- package/query/OrNode.ts +6 -5
- package/query/Query.ts +203 -59
- package/query/QueryContext.ts +6 -0
- package/query/QueryDAG.ts +7 -2
- package/query/membershipSource.ts +66 -0
- package/storage/LocalStorageProvider.ts +8 -3
- package/studio/dist/assets/index-BMZ67Npg.js +254 -0
- package/studio/dist/assets/index-BpbuYz9g.css +1 -0
- package/studio/{index.html → dist/index.html} +3 -2
- package/swagger/generator.ts +11 -1
- package/upload/UploadManager.ts +8 -6
- package/utils/uuid.ts +40 -10
- package/.claude/settings.local.json +0 -47
- package/.prettierrc +0 -4
- package/.serena/memories/architectural-decision-no-dependency-injection.md +0 -76
- package/.serena/memories/architecture.md +0 -154
- package/.serena/memories/cache-interface-refactoring-2026-01-24.md +0 -165
- package/.serena/memories/code_style_and_conventions.md +0 -76
- package/.serena/memories/project_overview.md +0 -43
- package/.serena/memories/schema-dsl-plan.md +0 -107
- package/.serena/memories/suggested_commands.md +0 -80
- package/.serena/memories/typescript-compilation-status.md +0 -54
- package/.serena/project.yml +0 -114
- package/BunSane.jpg +0 -0
- package/CLAUDE.md +0 -198
- package/TODO.md +0 -2
- package/bun.lock +0 -302
- package/bunfig.toml +0 -10
- package/docs/SCALABILITY_PLAN.md +0 -175
- package/studio/bun.lock +0 -482
- package/studio/package.json +0 -39
- package/studio/postcss.config.js +0 -6
- package/studio/src/components/DataTable.tsx +0 -211
- package/studio/src/components/Layout.tsx +0 -13
- package/studio/src/components/PageContainer.tsx +0 -9
- package/studio/src/components/PageHeader.tsx +0 -13
- package/studio/src/components/SearchBar.tsx +0 -57
- package/studio/src/components/Sidebar.tsx +0 -294
- package/studio/src/components/ui/button.tsx +0 -56
- package/studio/src/components/ui/checkbox.tsx +0 -26
- package/studio/src/components/ui/input.tsx +0 -25
- package/studio/src/hooks/useDataTable.ts +0 -131
- package/studio/src/index.css +0 -36
- package/studio/src/lib/api.ts +0 -186
- package/studio/src/lib/utils.ts +0 -13
- package/studio/src/main.tsx +0 -17
- package/studio/src/pages/ArcheType.tsx +0 -239
- package/studio/src/pages/Components.tsx +0 -124
- package/studio/src/pages/EntityInspector.tsx +0 -302
- package/studio/src/pages/QueryRunner.tsx +0 -246
- package/studio/src/pages/Table.tsx +0 -94
- package/studio/src/pages/Welcome.tsx +0 -241
- package/studio/src/routes.tsx +0 -45
- package/studio/src/store/archeTypeSettings.ts +0 -30
- package/studio/src/store/studio.ts +0 -65
- package/studio/src/utils/columnHelpers.tsx +0 -114
- package/studio/studio-instructions.md +0 -81
- package/studio/tailwind.config.js +0 -77
- package/studio/utils.ts +0 -54
- package/studio/vite.config.js +0 -19
- package/tests/benchmark/BENCHMARK_DATABASES_PLAN.md +0 -338
- package/tests/benchmark/bunfig.toml +0 -9
- package/tests/benchmark/fixtures/EcommerceComponents.ts +0 -283
- package/tests/benchmark/fixtures/EcommerceDataGenerators.ts +0 -301
- package/tests/benchmark/fixtures/RelationTracker.ts +0 -159
- package/tests/benchmark/fixtures/index.ts +0 -6
- package/tests/benchmark/index.ts +0 -22
- package/tests/benchmark/noop-preload.ts +0 -3
- package/tests/benchmark/query-lateral-benchmark.test.ts +0 -372
- package/tests/benchmark/runners/BenchmarkLoader.ts +0 -132
- package/tests/benchmark/runners/index.ts +0 -4
- package/tests/benchmark/scenarios/query-benchmarks.test.ts +0 -465
- package/tests/benchmark/scripts/generate-db.ts +0 -344
- package/tests/benchmark/scripts/run-benchmarks.ts +0 -97
- package/tests/e2e/http.test.ts +0 -130
- package/tests/fixtures/archetypes/TestUserArchetype.ts +0 -21
- package/tests/fixtures/components/TestOrder.ts +0 -23
- package/tests/fixtures/components/TestProduct.ts +0 -23
- package/tests/fixtures/components/TestUser.ts +0 -20
- package/tests/fixtures/components/index.ts +0 -6
- package/tests/graphql/SchemaGeneration.test.ts +0 -90
- package/tests/graphql/builders/ResolverBuilder.test.ts +0 -223
- package/tests/graphql/builders/TypeDefBuilder.test.ts +0 -153
- package/tests/helpers/MockRedisClient.ts +0 -113
- package/tests/helpers/MockRedisStreamServer.ts +0 -448
- package/tests/integration/archetype/ArcheType.persistence.test.ts +0 -241
- package/tests/integration/cache/CacheInvalidation.test.ts +0 -259
- package/tests/integration/entity/Entity.persistence.test.ts +0 -333
- package/tests/integration/entity/Entity.saveTimeout.test.ts +0 -110
- package/tests/integration/query/Query.complexAnalysis.test.ts +0 -557
- package/tests/integration/query/Query.edgeCases.test.ts +0 -595
- package/tests/integration/query/Query.exec.test.ts +0 -576
- package/tests/integration/query/Query.explainAnalyze.test.ts +0 -233
- package/tests/integration/query/Query.jsonbArray.test.ts +0 -214
- package/tests/integration/remote/dlq.test.ts +0 -175
- package/tests/integration/remote/event-dispatch.test.ts +0 -114
- package/tests/integration/remote/outbox.test.ts +0 -130
- package/tests/integration/remote/rpc.test.ts +0 -177
- package/tests/pglite-setup.ts +0 -62
- package/tests/setup.ts +0 -164
- package/tests/stress/BenchmarkRunner.ts +0 -203
- package/tests/stress/DataSeeder.ts +0 -190
- package/tests/stress/StressTestReporter.ts +0 -229
- package/tests/stress/cursor-perf-test.ts +0 -171
- package/tests/stress/fixtures/RealisticComponents.ts +0 -235
- package/tests/stress/fixtures/StressTestComponents.ts +0 -58
- package/tests/stress/index.ts +0 -7
- package/tests/stress/scenarios/query-benchmarks.test.ts +0 -285
- package/tests/stress/scenarios/realistic-scenarios.test.ts +0 -1081
- package/tests/stress/scenarios/timeout-investigation.test.ts +0 -522
- package/tests/unit/BatchLoader.test.ts +0 -196
- package/tests/unit/archetype/ArcheType.test.ts +0 -107
- package/tests/unit/cache/CacheManager.test.ts +0 -367
- package/tests/unit/cache/MemoryCache.test.ts +0 -260
- package/tests/unit/cache/RedisCache.test.ts +0 -411
- package/tests/unit/entity/Entity.components.test.ts +0 -317
- package/tests/unit/entity/Entity.drainSideEffects.test.ts +0 -51
- package/tests/unit/entity/Entity.reload.test.ts +0 -63
- package/tests/unit/entity/Entity.requireComponents.test.ts +0 -72
- package/tests/unit/entity/Entity.test.ts +0 -345
- package/tests/unit/gql/depthLimit.test.ts +0 -203
- package/tests/unit/gql/operationMiddleware.test.ts +0 -293
- package/tests/unit/health/Health.test.ts +0 -129
- package/tests/unit/middleware/AccessLog.test.ts +0 -37
- package/tests/unit/middleware/Middleware.test.ts +0 -98
- package/tests/unit/middleware/RequestId.test.ts +0 -54
- package/tests/unit/middleware/SecurityHeaders.test.ts +0 -66
- package/tests/unit/query/FilterBuilder.test.ts +0 -111
- package/tests/unit/query/JsonbArrayBuilder.test.ts +0 -178
- package/tests/unit/query/Query.emptyString.test.ts +0 -69
- package/tests/unit/query/Query.test.ts +0 -310
- package/tests/unit/remote/CircuitBreaker.test.ts +0 -159
- package/tests/unit/remote/RemoteError.test.ts +0 -55
- package/tests/unit/remote/decorators.test.ts +0 -195
- package/tests/unit/remote/metrics.test.ts +0 -115
- package/tests/unit/remote/mockRedisStreamServer.test.ts +0 -104
- package/tests/unit/scheduler/DistributedLock.test.ts +0 -274
- package/tests/unit/scheduler/SchedulerManager.timeBased.test.ts +0 -95
- package/tests/unit/schema/schema-integration.test.ts +0 -426
- package/tests/unit/schema/schema.test.ts +0 -580
- package/tests/unit/storage/S3StorageProvider.test.ts +0 -567
- package/tests/unit/upload/RestUpload.test.ts +0 -267
- package/tests/unit/validateEnv.test.ts +0 -82
- package/tests/utils/entity-tracker.ts +0 -57
- package/tests/utils/index.ts +0 -13
- package/tests/utils/test-context.ts +0 -149
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import ApplicationLifecycle, {
|
|
2
|
+
ApplicationPhase,
|
|
3
|
+
type PhaseChangeEvent,
|
|
4
|
+
} from "../ApplicationLifecycle";
|
|
5
|
+
import { logger as MainLogger } from "../Logger";
|
|
6
|
+
import ServiceRegistry from "../../service/ServiceRegistry";
|
|
7
|
+
import { SchedulerManager } from "../SchedulerManager";
|
|
8
|
+
import { registerScheduledTasks } from "../../scheduler";
|
|
9
|
+
import {
|
|
10
|
+
RemoteManager,
|
|
11
|
+
registerRemoteHandlers,
|
|
12
|
+
setRemoteManager,
|
|
13
|
+
type RemoteManagerConfig,
|
|
14
|
+
} from "../remote";
|
|
15
|
+
import { setupGraphQL } from "./graphqlSetup";
|
|
16
|
+
import { collectRestEndpoints } from "./restRegistry";
|
|
17
|
+
|
|
18
|
+
const logger = MainLogger.child({ scope: "App" });
|
|
19
|
+
|
|
20
|
+
export function createPhaseListener(app: any): (event: PhaseChangeEvent) => Promise<void> {
|
|
21
|
+
return async (event: PhaseChangeEvent) => {
|
|
22
|
+
const phase = event.detail;
|
|
23
|
+
logger.info(`Application phase changed to: ${phase}`);
|
|
24
|
+
for (const plugin of app.plugins) {
|
|
25
|
+
if (plugin.onPhaseChange) {
|
|
26
|
+
await plugin.onPhaseChange(phase, app);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
switch (phase) {
|
|
30
|
+
case ApplicationPhase.DATABASE_READY:
|
|
31
|
+
await runDatabaseReadyPhase(app);
|
|
32
|
+
break;
|
|
33
|
+
case ApplicationPhase.SYSTEM_READY:
|
|
34
|
+
await runSystemReadyPhase(app);
|
|
35
|
+
break;
|
|
36
|
+
case ApplicationPhase.APPLICATION_READY:
|
|
37
|
+
await runApplicationReadyPhase(app);
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function runDatabaseReadyPhase(app: any): Promise<void> {
|
|
44
|
+
try {
|
|
45
|
+
await app.warmUpPreparedStatementCache();
|
|
46
|
+
} catch (error) {
|
|
47
|
+
logger.warn("Failed to warm up prepared statement cache:", error as any);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function runSystemReadyPhase(app: any): Promise<void> {
|
|
52
|
+
try {
|
|
53
|
+
const { CacheManager } = await import('../cache/CacheManager');
|
|
54
|
+
const cacheManager = CacheManager.getInstance();
|
|
55
|
+
const config = cacheManager.getConfig();
|
|
56
|
+
|
|
57
|
+
if (config.enabled) {
|
|
58
|
+
const isHealthy = await cacheManager.getProvider().ping();
|
|
59
|
+
if (isHealthy) {
|
|
60
|
+
logger.info({ scope: 'cache', component: 'App', msg: 'Cache health check passed' });
|
|
61
|
+
} else {
|
|
62
|
+
logger.warn({ scope: 'cache', component: 'App', msg: 'Cache health check failed' });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
} catch (error) {
|
|
66
|
+
logger.warn({ scope: 'cache', component: 'App', msg: 'Cache health check error', error });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
setupGraphQL(app);
|
|
71
|
+
|
|
72
|
+
const services = ServiceRegistry.getServices();
|
|
73
|
+
|
|
74
|
+
const scheduler = SchedulerManager.getInstance();
|
|
75
|
+
scheduler.config.enableLogging = app.config.scheduler.logging;
|
|
76
|
+
|
|
77
|
+
for (const service of services) {
|
|
78
|
+
try {
|
|
79
|
+
registerScheduledTasks(service);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
logger.warn(`Failed to register scheduled tasks for service ${service.constructor.name}`);
|
|
82
|
+
logger.warn(error);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
logger.info(`Registered scheduled tasks for ${services.length} services`);
|
|
86
|
+
|
|
87
|
+
if (app.remoteConfig) {
|
|
88
|
+
try {
|
|
89
|
+
const rmConfig: RemoteManagerConfig = {
|
|
90
|
+
appName: app.remoteConfig.appName || app.name,
|
|
91
|
+
...app.remoteConfig,
|
|
92
|
+
};
|
|
93
|
+
app.remote = new RemoteManager(rmConfig);
|
|
94
|
+
setRemoteManager(app.remote);
|
|
95
|
+
await app.remote.start();
|
|
96
|
+
|
|
97
|
+
for (const service of services) {
|
|
98
|
+
try {
|
|
99
|
+
registerRemoteHandlers(service);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
logger.warn(`Failed to register remote handlers for service ${service.constructor.name}`);
|
|
102
|
+
logger.warn(error);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
logger.info(`RemoteManager initialized for app "${rmConfig.appName}"`);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
logger.error("Failed to start RemoteManager:");
|
|
108
|
+
logger.error(error);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
collectRestEndpoints(app, services);
|
|
113
|
+
|
|
114
|
+
ApplicationLifecycle.setPhase(ApplicationPhase.APPLICATION_READY);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
// SYSTEM_READY failures must not be swallowed silently. Without this,
|
|
117
|
+
// the app stays forever in SYSTEM_READY (isReady=false,
|
|
118
|
+
// /health/ready → 503 forever) and k8s rollout hangs with no
|
|
119
|
+
// observable cause. Surface so readiness probe reports it (C09).
|
|
120
|
+
app.isReady = false;
|
|
121
|
+
logger.fatal({ scope: 'app', component: 'App', err: error }, 'Fatal error during SYSTEM_READY phase — marking app unready');
|
|
122
|
+
if (process.env.NODE_ENV === 'test') {
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
setTimeout(() => process.exit(1), 100).unref?.();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function runApplicationReadyPhase(app: any): Promise<void> {
|
|
130
|
+
if (process.env.NODE_ENV !== "test") {
|
|
131
|
+
app.start();
|
|
132
|
+
}
|
|
133
|
+
}
|
package/core/app/cors.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { CorsConfig } from "../App";
|
|
2
|
+
import { setResponseHeaders } from "../middleware/headers";
|
|
3
|
+
|
|
4
|
+
export function assertValidCorsConfig(cors: CorsConfig): void {
|
|
5
|
+
if (cors.origin === undefined) {
|
|
6
|
+
throw new Error('[CORS] `origin` is required. Pass an explicit string, array, function, or "*" if you truly want to allow everyone.');
|
|
7
|
+
}
|
|
8
|
+
if (cors.credentials && cors.origin === '*') {
|
|
9
|
+
console.warn('[CORS] Warning: credentials=true with origin="*" is invalid per spec. Origin will be reflected from request.');
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function validateOrigin(
|
|
14
|
+
cors: CorsConfig | undefined,
|
|
15
|
+
requestOrigin: string | null | undefined,
|
|
16
|
+
): string | null {
|
|
17
|
+
if (!cors || !requestOrigin) return null;
|
|
18
|
+
|
|
19
|
+
const configOrigin = cors.origin;
|
|
20
|
+
|
|
21
|
+
if (configOrigin === undefined) return null;
|
|
22
|
+
|
|
23
|
+
if (configOrigin === '*') {
|
|
24
|
+
return cors.credentials ? requestOrigin : '*';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (typeof configOrigin === 'string') {
|
|
28
|
+
return requestOrigin === configOrigin ? configOrigin : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (Array.isArray(configOrigin)) {
|
|
32
|
+
return configOrigin.includes(requestOrigin) ? requestOrigin : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (typeof configOrigin === 'function') {
|
|
36
|
+
return configOrigin(requestOrigin) ? requestOrigin : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function getCorsHeaders(
|
|
43
|
+
cors: CorsConfig | undefined,
|
|
44
|
+
req?: Request,
|
|
45
|
+
): Record<string, string> {
|
|
46
|
+
if (!cors) return {};
|
|
47
|
+
|
|
48
|
+
const requestOrigin = req?.headers.get('Origin');
|
|
49
|
+
const allowedOrigin = validateOrigin(cors, requestOrigin);
|
|
50
|
+
|
|
51
|
+
if (requestOrigin && !allowedOrigin) return {};
|
|
52
|
+
|
|
53
|
+
const headers: Record<string, string> = {
|
|
54
|
+
'Access-Control-Allow-Methods': cors.methods?.join(', ') || 'GET, POST, PUT, DELETE, OPTIONS',
|
|
55
|
+
'Access-Control-Allow-Headers': cors.allowedHeaders?.join(', ') || 'Content-Type, Authorization',
|
|
56
|
+
'Vary': 'Origin',
|
|
57
|
+
};
|
|
58
|
+
if (allowedOrigin) {
|
|
59
|
+
headers['Access-Control-Allow-Origin'] = allowedOrigin;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (cors.credentials) {
|
|
63
|
+
headers['Access-Control-Allow-Credentials'] = 'true';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (cors.exposedHeaders?.length) {
|
|
67
|
+
headers['Access-Control-Expose-Headers'] = cors.exposedHeaders.join(', ');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (cors.maxAge !== undefined) {
|
|
71
|
+
headers['Access-Control-Max-Age'] = String(cors.maxAge);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return headers;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function addCorsHeaders(
|
|
78
|
+
response: Response,
|
|
79
|
+
cors: CorsConfig | undefined,
|
|
80
|
+
req?: Request,
|
|
81
|
+
): Response {
|
|
82
|
+
const corsHeaders = getCorsHeaders(cors, req);
|
|
83
|
+
if (Object.keys(corsHeaders).length === 0) return response;
|
|
84
|
+
return setResponseHeaders(response, Object.entries(corsHeaders));
|
|
85
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import ServiceRegistry from "../../service/ServiceRegistry";
|
|
2
|
+
import { type Plugin } from "graphql-yoga";
|
|
3
|
+
import { createYogaInstance } from "../../gql";
|
|
4
|
+
import { createRequestContextPlugin } from "../RequestContext";
|
|
5
|
+
|
|
6
|
+
export function setupGraphQL(app: any): void {
|
|
7
|
+
const schema = ServiceRegistry.getSchema();
|
|
8
|
+
|
|
9
|
+
const wrappedContextFactory = app.contextFactory
|
|
10
|
+
? async (yogaContext: any) => {
|
|
11
|
+
const userContext = await app.contextFactory(yogaContext);
|
|
12
|
+
return {
|
|
13
|
+
...yogaContext,
|
|
14
|
+
...userContext,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
: undefined;
|
|
18
|
+
|
|
19
|
+
const envDepth = process.env.GRAPHQL_MAX_DEPTH;
|
|
20
|
+
if (envDepth) {
|
|
21
|
+
app.graphqlMaxDepth = parseInt(envDepth, 10);
|
|
22
|
+
}
|
|
23
|
+
const envComplexity = process.env.GRAPHQL_MAX_COMPLEXITY;
|
|
24
|
+
if (envComplexity) {
|
|
25
|
+
const parsed = parseInt(envComplexity, 10);
|
|
26
|
+
if (Number.isFinite(parsed) && parsed >= 0) {
|
|
27
|
+
app.graphqlMaxComplexity = parsed;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const yogaOptions = {
|
|
32
|
+
cors: app.config.cors,
|
|
33
|
+
maxDepth: app.graphqlMaxDepth || undefined,
|
|
34
|
+
maxComplexity: app.graphqlMaxComplexity,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const effectivePlugins: Plugin[] = app.requestContextPluginEnabled
|
|
38
|
+
? [createRequestContextPlugin(), ...app.yogaPlugins]
|
|
39
|
+
: [...app.yogaPlugins];
|
|
40
|
+
|
|
41
|
+
if (schema) {
|
|
42
|
+
app.yoga = createYogaInstance(
|
|
43
|
+
schema,
|
|
44
|
+
effectivePlugins,
|
|
45
|
+
wrappedContextFactory,
|
|
46
|
+
yogaOptions,
|
|
47
|
+
);
|
|
48
|
+
} else {
|
|
49
|
+
app.yoga = createYogaInstance(
|
|
50
|
+
undefined,
|
|
51
|
+
effectivePlugins,
|
|
52
|
+
wrappedContextFactory,
|
|
53
|
+
yogaOptions,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { deepHealthCheck, readinessCheck } from "../health";
|
|
2
|
+
|
|
3
|
+
export async function handleHealth(_app: any): Promise<Response> {
|
|
4
|
+
const health = await deepHealthCheck();
|
|
5
|
+
return new Response(JSON.stringify(health.result), {
|
|
6
|
+
status: health.httpStatus,
|
|
7
|
+
headers: { "Content-Type": "application/json" },
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function handleReady(app: any): Promise<Response> {
|
|
12
|
+
const ready = await readinessCheck(app.isReady, app.isShuttingDown);
|
|
13
|
+
return new Response(JSON.stringify(ready.result), {
|
|
14
|
+
status: ready.httpStatus,
|
|
15
|
+
headers: { "Content-Type": "application/json" },
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function handleRemoteHealth(app: any): Promise<Response> {
|
|
20
|
+
if (!app.remote) {
|
|
21
|
+
return new Response(
|
|
22
|
+
JSON.stringify({ healthy: false, error: "Remote subsystem not enabled" }),
|
|
23
|
+
{ status: 503, headers: { "Content-Type": "application/json" } },
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
const health = await app.remote.health();
|
|
27
|
+
return new Response(JSON.stringify(health), {
|
|
28
|
+
status: health.healthy ? 200 : 503,
|
|
29
|
+
headers: { "Content-Type": "application/json" },
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { logger as MainLogger } from "../Logger";
|
|
2
|
+
import { SchedulerManager } from "../SchedulerManager";
|
|
3
|
+
import { preparedStatementCache } from "../../database/PreparedStatementCache";
|
|
4
|
+
import { getDbStats } from "../../database/instrumentedDb";
|
|
5
|
+
|
|
6
|
+
const logger = MainLogger.child({ scope: "App" });
|
|
7
|
+
|
|
8
|
+
export async function collectMetrics(app: any) {
|
|
9
|
+
let cacheStats = null;
|
|
10
|
+
try {
|
|
11
|
+
const { CacheManager } = await import('../cache/CacheManager');
|
|
12
|
+
cacheStats = await CacheManager.getInstance().getStats();
|
|
13
|
+
} catch (err) {
|
|
14
|
+
logger.warn({ err }, 'metrics: cache stats unavailable');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
return {
|
|
18
|
+
timestamp: new Date().toISOString(),
|
|
19
|
+
uptime: process.uptime(),
|
|
20
|
+
process: process.memoryUsage(),
|
|
21
|
+
cache: cacheStats,
|
|
22
|
+
scheduler: SchedulerManager.getInstance().getMetrics(),
|
|
23
|
+
preparedStatements: preparedStatementCache.getStats(),
|
|
24
|
+
db: getDbStats(),
|
|
25
|
+
remote: app.remote ? app.remote.getMetrics() : null,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { logger as MainLogger } from "../Logger";
|
|
2
|
+
|
|
3
|
+
const logger = MainLogger.child({ scope: "App" });
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @deprecated No-op. The framework-level prepared statement cache was
|
|
7
|
+
* removed from the query hot path — Bun SQL auto-prepares parameterized
|
|
8
|
+
* statements per connection (prepare:true default), so server-side plan
|
|
9
|
+
* reuse happens at the driver layer and "warming" a placeholder map bought
|
|
10
|
+
* nothing. Kept so bootstrap's call site and the public App surface remain
|
|
11
|
+
* stable.
|
|
12
|
+
*/
|
|
13
|
+
export async function warmUpPreparedStatementCache(_app: any): Promise<void> {
|
|
14
|
+
logger.trace("Prepared statement warm-up skipped (driver-level auto-prepare in effect)");
|
|
15
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { logger as MainLogger } from "../Logger";
|
|
2
|
+
|
|
3
|
+
const logger = MainLogger.child({ scope: "App" });
|
|
4
|
+
|
|
5
|
+
export function registerProcessHandlers(app: any): void {
|
|
6
|
+
if (app.processHandlersRegistered) return;
|
|
7
|
+
|
|
8
|
+
app.sigTermHandler = () => {
|
|
9
|
+
logger.info({ scope: 'app', component: 'App', msg: 'Received SIGTERM' });
|
|
10
|
+
app.shutdown().finally(() => process.exit(0));
|
|
11
|
+
};
|
|
12
|
+
app.sigIntHandler = () => {
|
|
13
|
+
logger.info({ scope: 'app', component: 'App', msg: 'Received SIGINT' });
|
|
14
|
+
app.shutdown().finally(() => process.exit(0));
|
|
15
|
+
};
|
|
16
|
+
process.once('SIGTERM', app.sigTermHandler);
|
|
17
|
+
process.once('SIGINT', app.sigIntHandler);
|
|
18
|
+
|
|
19
|
+
app.unhandledRejectionHandler = (reason: unknown, _promise: Promise<unknown>) => {
|
|
20
|
+
logger.error({ scope: 'app', component: 'App', reason, msg: 'Unhandled promise rejection' });
|
|
21
|
+
};
|
|
22
|
+
app.uncaughtExceptionHandler = (error: Error) => {
|
|
23
|
+
logger.fatal({ scope: 'app', component: 'App', err: error, msg: 'Uncaught exception — shutting down' });
|
|
24
|
+
app.shutdown().finally(() => process.exit(1));
|
|
25
|
+
};
|
|
26
|
+
process.on('unhandledRejection', app.unhandledRejectionHandler);
|
|
27
|
+
process.on('uncaughtException', app.uncaughtExceptionHandler);
|
|
28
|
+
|
|
29
|
+
app.processHandlersRegistered = true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function unregisterProcessHandlers(app: any): void {
|
|
33
|
+
if (!app.processHandlersRegistered) return;
|
|
34
|
+
if (app.sigTermHandler) process.removeListener('SIGTERM', app.sigTermHandler);
|
|
35
|
+
if (app.sigIntHandler) process.removeListener('SIGINT', app.sigIntHandler);
|
|
36
|
+
if (app.unhandledRejectionHandler) process.removeListener('unhandledRejection', app.unhandledRejectionHandler);
|
|
37
|
+
if (app.uncaughtExceptionHandler) process.removeListener('uncaughtException', app.uncaughtExceptionHandler);
|
|
38
|
+
app.sigTermHandler = null;
|
|
39
|
+
app.sigIntHandler = null;
|
|
40
|
+
app.unhandledRejectionHandler = null;
|
|
41
|
+
app.uncaughtExceptionHandler = null;
|
|
42
|
+
app.processHandlersRegistered = false;
|
|
43
|
+
}
|