bunsane 0.3.0 → 0.3.2

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.
Files changed (54) hide show
  1. package/.claude/scheduled_tasks.lock +1 -0
  2. package/CHANGELOG.md +104 -0
  3. package/CLAUDE.md +20 -0
  4. package/config/cache.config.ts +35 -1
  5. package/core/App.ts +24 -1060
  6. package/core/ArcheType.ts +78 -2110
  7. package/core/Entity.ts +136 -41
  8. package/core/RequestContext.ts +85 -36
  9. package/core/RequestLoaders.ts +89 -31
  10. package/core/SchedulerManager.ts +13 -13
  11. package/core/app/bootstrap.ts +133 -0
  12. package/core/app/cors.ts +94 -0
  13. package/core/app/graphqlSetup.ts +56 -0
  14. package/core/app/healthEndpoints.ts +31 -0
  15. package/core/app/metricsCollector.ts +27 -0
  16. package/core/app/preparedStatementWarmup.ts +55 -0
  17. package/core/app/processHandlers.ts +43 -0
  18. package/core/app/requestRouter.ts +309 -0
  19. package/core/app/restRegistry.ts +72 -0
  20. package/core/app/shutdown.ts +97 -0
  21. package/core/app/studioRouter.ts +83 -0
  22. package/core/archetype/customTypes.ts +100 -0
  23. package/core/archetype/decorators.ts +171 -0
  24. package/core/archetype/fieldResolvers.ts +621 -0
  25. package/core/archetype/helpers.ts +29 -0
  26. package/core/archetype/relationLoader.ts +118 -0
  27. package/core/archetype/schemaBuilder.ts +141 -0
  28. package/core/archetype/weaver.ts +218 -0
  29. package/core/archetype/zodSchemaBuilder.ts +527 -0
  30. package/core/cache/CacheManager.ts +144 -9
  31. package/core/components/BaseComponent.ts +12 -2
  32. package/core/middleware/AccessLog.ts +8 -1
  33. package/database/PreparedStatementCache.ts +17 -16
  34. package/database/cancellable.ts +22 -0
  35. package/database/instrumentedDb.ts +141 -0
  36. package/docs/RFC_APP_REFACTOR.md +248 -0
  37. package/docs/RFC_REFACTOR_TARGETS.md +251 -0
  38. package/package.json +1 -1
  39. package/query/ComponentInclusionNode.ts +5 -5
  40. package/query/Query.ts +65 -48
  41. package/service/ServiceRegistry.ts +7 -1
  42. package/service/index.ts +4 -2
  43. package/tests/integration/loaders/RequestLoaders.abort.test.ts +82 -0
  44. package/tests/integration/query/Query.abort.test.ts +66 -0
  45. package/tests/unit/cache/CacheManager.test.ts +152 -1
  46. package/tests/unit/database/cancellable.test.ts +81 -0
  47. package/tests/unit/database/instrumentedDb.test.ts +160 -0
  48. package/tests/unit/entity/Entity.components.test.ts +73 -0
  49. package/tests/unit/entity/Entity.drainSideEffects.test.ts +51 -0
  50. package/tests/unit/entity/Entity.reload.test.ts +63 -0
  51. package/tests/unit/entity/Entity.requireComponents.test.ts +72 -0
  52. package/tests/unit/query/Query.emptyString.test.ts +69 -0
  53. package/tests/unit/query/Query.test.ts +6 -4
  54. package/tests/unit/scheduler/SchedulerManager.timeBased.test.ts +95 -0
@@ -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
+ }
@@ -0,0 +1,94 @@
1
+ import type { CorsConfig } from "../App";
2
+
3
+ export function assertValidCorsConfig(cors: CorsConfig): void {
4
+ if (cors.origin === undefined) {
5
+ throw new Error('[CORS] `origin` is required. Pass an explicit string, array, function, or "*" if you truly want to allow everyone.');
6
+ }
7
+ if (cors.credentials && cors.origin === '*') {
8
+ console.warn('[CORS] Warning: credentials=true with origin="*" is invalid per spec. Origin will be reflected from request.');
9
+ }
10
+ }
11
+
12
+ export function validateOrigin(
13
+ cors: CorsConfig | undefined,
14
+ requestOrigin: string | null | undefined,
15
+ ): string | null {
16
+ if (!cors || !requestOrigin) return null;
17
+
18
+ const configOrigin = cors.origin;
19
+
20
+ if (configOrigin === undefined) return null;
21
+
22
+ if (configOrigin === '*') {
23
+ return cors.credentials ? requestOrigin : '*';
24
+ }
25
+
26
+ if (typeof configOrigin === 'string') {
27
+ return requestOrigin === configOrigin ? configOrigin : null;
28
+ }
29
+
30
+ if (Array.isArray(configOrigin)) {
31
+ return configOrigin.includes(requestOrigin) ? requestOrigin : null;
32
+ }
33
+
34
+ if (typeof configOrigin === 'function') {
35
+ return configOrigin(requestOrigin) ? requestOrigin : null;
36
+ }
37
+
38
+ return null;
39
+ }
40
+
41
+ export function getCorsHeaders(
42
+ cors: CorsConfig | undefined,
43
+ req?: Request,
44
+ ): Record<string, string> {
45
+ if (!cors) return {};
46
+
47
+ const requestOrigin = req?.headers.get('Origin');
48
+ const allowedOrigin = validateOrigin(cors, requestOrigin);
49
+
50
+ if (requestOrigin && !allowedOrigin) return {};
51
+
52
+ const headers: Record<string, string> = {
53
+ 'Access-Control-Allow-Methods': cors.methods?.join(', ') || 'GET, POST, PUT, DELETE, OPTIONS',
54
+ 'Access-Control-Allow-Headers': cors.allowedHeaders?.join(', ') || 'Content-Type, Authorization',
55
+ 'Vary': 'Origin',
56
+ };
57
+ if (allowedOrigin) {
58
+ headers['Access-Control-Allow-Origin'] = allowedOrigin;
59
+ }
60
+
61
+ if (cors.credentials) {
62
+ headers['Access-Control-Allow-Credentials'] = 'true';
63
+ }
64
+
65
+ if (cors.exposedHeaders?.length) {
66
+ headers['Access-Control-Expose-Headers'] = cors.exposedHeaders.join(', ');
67
+ }
68
+
69
+ if (cors.maxAge !== undefined) {
70
+ headers['Access-Control-Max-Age'] = String(cors.maxAge);
71
+ }
72
+
73
+ return headers;
74
+ }
75
+
76
+ export function addCorsHeaders(
77
+ response: Response,
78
+ cors: CorsConfig | undefined,
79
+ req?: Request,
80
+ ): Response {
81
+ const corsHeaders = getCorsHeaders(cors, req);
82
+ if (Object.keys(corsHeaders).length === 0) return response;
83
+
84
+ const newHeaders = new Headers(response.headers);
85
+ for (const [key, value] of Object.entries(corsHeaders)) {
86
+ newHeaders.set(key, value);
87
+ }
88
+
89
+ return new Response(response.body, {
90
+ status: response.status,
91
+ statusText: response.statusText,
92
+ headers: newHeaders,
93
+ });
94
+ }
@@ -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,55 @@
1
+ import { ComponentRegistry } from "../components";
2
+ import { logger as MainLogger } from "../Logger";
3
+ import { preparedStatementCache } from "../../database/PreparedStatementCache";
4
+ import db from "../../database";
5
+
6
+ const logger = MainLogger.child({ scope: "App" });
7
+
8
+ export async function warmUpPreparedStatementCache(_app: any): Promise<void> {
9
+ const components = ComponentRegistry.getComponents();
10
+
11
+ if (components.length === 0) {
12
+ logger.trace("No components registered yet, skipping cache warm-up");
13
+ return;
14
+ }
15
+
16
+ const commonQueries: Array<{ sql: string; key: string }> = [];
17
+
18
+ commonQueries.push({
19
+ sql: "SELECT COUNT(*) as count FROM (SELECT DISTINCT ec.entity_id as id FROM entity_components ec WHERE ec.deleted_at IS NULL) AS subquery",
20
+ key: "count_all_entities",
21
+ });
22
+
23
+ for (let i = 0; i < Math.min(5, components.length); i++) {
24
+ const component = components[i];
25
+ if (component) {
26
+ const { name } = component;
27
+ const typeId = ComponentRegistry.getComponentId(name);
28
+ if (typeId) {
29
+ commonQueries.push({
30
+ sql: `SELECT DISTINCT ec.entity_id as id FROM entity_components ec WHERE ec.type_id = '${typeId}' AND ec.deleted_at IS NULL LIMIT 10`,
31
+ key: `find_${name.toLowerCase()}_sample`,
32
+ });
33
+ }
34
+ }
35
+ }
36
+
37
+ if (components.length >= 2) {
38
+ const typeIds = components
39
+ .slice(0, 3)
40
+ .map((component: { name: string; ctor: any }) =>
41
+ ComponentRegistry.getComponentId(component.name)
42
+ )
43
+ .filter((id: string | undefined) => id)
44
+ .join("','");
45
+
46
+ if (typeIds) {
47
+ commonQueries.push({
48
+ sql: `SELECT DISTINCT ec.entity_id as id FROM entity_components ec WHERE ec.type_id IN ('${typeIds}') AND ec.deleted_at IS NULL LIMIT 10`,
49
+ key: "find_multi_component_sample",
50
+ });
51
+ }
52
+ }
53
+
54
+ await preparedStatementCache.warmUp(commonQueries, db);
55
+ }
@@ -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
+ }