apcore-js 0.5.0 → 0.6.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.
Files changed (314) hide show
  1. package/dist/acl.d.ts +27 -0
  2. package/dist/acl.d.ts.map +1 -0
  3. package/dist/acl.js +175 -0
  4. package/dist/acl.js.map +1 -0
  5. package/dist/async-task.d.ts +90 -0
  6. package/dist/async-task.d.ts.map +1 -0
  7. package/dist/async-task.js +215 -0
  8. package/dist/async-task.js.map +1 -0
  9. package/dist/bindings.d.ts +12 -0
  10. package/dist/bindings.d.ts.map +1 -0
  11. package/dist/bindings.js +185 -0
  12. package/dist/bindings.js.map +1 -0
  13. package/dist/cancel.d.ts +14 -0
  14. package/dist/cancel.d.ts.map +1 -0
  15. package/dist/cancel.js +27 -0
  16. package/dist/cancel.js.map +1 -0
  17. package/dist/config.d.ts +9 -0
  18. package/dist/config.d.ts.map +1 -0
  19. package/dist/config.js +23 -0
  20. package/dist/config.js.map +1 -0
  21. package/dist/context.d.ts +50 -0
  22. package/dist/context.d.ts.map +1 -0
  23. package/dist/context.js +87 -0
  24. package/dist/context.js.map +1 -0
  25. package/dist/decorator.d.ts +57 -0
  26. package/dist/decorator.d.ts.map +1 -0
  27. package/dist/decorator.js +74 -0
  28. package/dist/decorator.js.map +1 -0
  29. package/dist/errors.d.ts +215 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +246 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/executor.d.ts +67 -0
  34. package/dist/executor.d.ts.map +1 -0
  35. package/dist/executor.js +372 -0
  36. package/dist/executor.js.map +1 -0
  37. package/dist/extensions.d.ts +58 -0
  38. package/dist/extensions.d.ts.map +1 -0
  39. package/dist/extensions.js +220 -0
  40. package/dist/extensions.js.map +1 -0
  41. package/{src/index.ts → dist/index.d.ts} +3 -62
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +43 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/middleware/adapters.d.ts +18 -0
  46. package/dist/middleware/adapters.d.ts.map +1 -0
  47. package/dist/middleware/adapters.js +25 -0
  48. package/dist/middleware/adapters.js.map +1 -0
  49. package/dist/middleware/base.d.ts +10 -0
  50. package/dist/middleware/base.d.ts.map +1 -0
  51. package/dist/middleware/base.js +15 -0
  52. package/dist/middleware/base.js.map +1 -0
  53. package/{src/middleware/index.ts → dist/middleware/index.d.ts} +1 -0
  54. package/dist/middleware/index.d.ts.map +1 -0
  55. package/dist/middleware/index.js +5 -0
  56. package/dist/middleware/index.js.map +1 -0
  57. package/dist/middleware/logging.d.ts +25 -0
  58. package/dist/middleware/logging.d.ts.map +1 -0
  59. package/dist/middleware/logging.js +64 -0
  60. package/dist/middleware/logging.js.map +1 -0
  61. package/dist/middleware/manager.d.ts +21 -0
  62. package/dist/middleware/manager.d.ts.map +1 -0
  63. package/dist/middleware/manager.js +77 -0
  64. package/dist/middleware/manager.js.map +1 -0
  65. package/dist/module.d.ts +31 -0
  66. package/dist/module.d.ts.map +1 -0
  67. package/dist/module.js +12 -0
  68. package/dist/module.js.map +1 -0
  69. package/dist/observability/context-logger.d.ts +54 -0
  70. package/dist/observability/context-logger.d.ts.map +1 -0
  71. package/dist/observability/context-logger.js +151 -0
  72. package/dist/observability/context-logger.js.map +1 -0
  73. package/{src/observability/index.ts → dist/observability/index.d.ts} +1 -0
  74. package/dist/observability/index.d.ts.map +1 -0
  75. package/dist/observability/index.js +4 -0
  76. package/dist/observability/index.js.map +1 -0
  77. package/dist/observability/metrics.d.ts +30 -0
  78. package/dist/observability/metrics.d.ts.map +1 -0
  79. package/dist/observability/metrics.js +177 -0
  80. package/dist/observability/metrics.js.map +1 -0
  81. package/dist/observability/tracing.d.ts +62 -0
  82. package/dist/observability/tracing.d.ts.map +1 -0
  83. package/dist/observability/tracing.js +184 -0
  84. package/dist/observability/tracing.js.map +1 -0
  85. package/dist/registry/dependencies.d.ts +6 -0
  86. package/dist/registry/dependencies.d.ts.map +1 -0
  87. package/dist/registry/dependencies.js +83 -0
  88. package/dist/registry/dependencies.js.map +1 -0
  89. package/dist/registry/entry-point.d.ts +6 -0
  90. package/dist/registry/entry-point.d.ts.map +1 -0
  91. package/dist/registry/entry-point.js +55 -0
  92. package/dist/registry/entry-point.js.map +1 -0
  93. package/{src/registry/index.ts → dist/registry/index.d.ts} +1 -0
  94. package/dist/registry/index.d.ts.map +1 -0
  95. package/dist/registry/index.js +8 -0
  96. package/dist/registry/index.js.map +1 -0
  97. package/dist/registry/metadata.d.ts +9 -0
  98. package/dist/registry/metadata.d.ts.map +1 -0
  99. package/dist/registry/metadata.js +105 -0
  100. package/dist/registry/metadata.js.map +1 -0
  101. package/dist/registry/registry.d.ts +102 -0
  102. package/dist/registry/registry.d.ts.map +1 -0
  103. package/dist/registry/registry.js +534 -0
  104. package/dist/registry/registry.js.map +1 -0
  105. package/dist/registry/scanner.d.ts +7 -0
  106. package/dist/registry/scanner.d.ts.map +1 -0
  107. package/dist/registry/scanner.js +164 -0
  108. package/dist/registry/scanner.js.map +1 -0
  109. package/dist/registry/schema-export.d.ts +9 -0
  110. package/dist/registry/schema-export.d.ts.map +1 -0
  111. package/dist/registry/schema-export.js +132 -0
  112. package/dist/registry/schema-export.js.map +1 -0
  113. package/dist/registry/types.d.ts +29 -0
  114. package/dist/registry/types.d.ts.map +1 -0
  115. package/dist/registry/types.js +5 -0
  116. package/dist/registry/types.js.map +1 -0
  117. package/dist/registry/validation.d.ts +9 -0
  118. package/dist/registry/validation.d.ts.map +1 -0
  119. package/dist/registry/validation.js +33 -0
  120. package/dist/registry/validation.js.map +1 -0
  121. package/dist/schema/annotations.d.ts +8 -0
  122. package/dist/schema/annotations.d.ts.map +1 -0
  123. package/dist/schema/annotations.js +52 -0
  124. package/dist/schema/annotations.js.map +1 -0
  125. package/dist/schema/exporter.d.ts +13 -0
  126. package/dist/schema/exporter.d.ts.map +1 -0
  127. package/dist/schema/exporter.js +71 -0
  128. package/dist/schema/exporter.js.map +1 -0
  129. package/dist/schema/index.d.ts +9 -0
  130. package/dist/schema/index.d.ts.map +1 -0
  131. package/{src/schema/index.ts → dist/schema/index.js} +1 -7
  132. package/dist/schema/index.js.map +1 -0
  133. package/dist/schema/loader.d.ts +30 -0
  134. package/dist/schema/loader.d.ts.map +1 -0
  135. package/dist/schema/loader.js +260 -0
  136. package/dist/schema/loader.js.map +1 -0
  137. package/dist/schema/ref-resolver.d.ts +19 -0
  138. package/dist/schema/ref-resolver.d.ts.map +1 -0
  139. package/dist/schema/ref-resolver.js +212 -0
  140. package/dist/schema/ref-resolver.js.map +1 -0
  141. package/dist/schema/strict.d.ts +7 -0
  142. package/dist/schema/strict.d.ts.map +1 -0
  143. package/dist/schema/strict.js +127 -0
  144. package/dist/schema/strict.js.map +1 -0
  145. package/dist/schema/types.d.ts +53 -0
  146. package/dist/schema/types.d.ts.map +1 -0
  147. package/dist/schema/types.js +31 -0
  148. package/dist/schema/types.js.map +1 -0
  149. package/dist/schema/validator.d.ts +16 -0
  150. package/dist/schema/validator.d.ts.map +1 -0
  151. package/dist/schema/validator.js +71 -0
  152. package/dist/schema/validator.js.map +1 -0
  153. package/dist/trace-context.d.ts +35 -0
  154. package/dist/trace-context.d.ts.map +1 -0
  155. package/dist/trace-context.js +86 -0
  156. package/dist/trace-context.js.map +1 -0
  157. package/dist/utils/index.d.ts +11 -0
  158. package/dist/utils/index.d.ts.map +1 -0
  159. package/dist/utils/index.js +32 -0
  160. package/dist/utils/index.js.map +1 -0
  161. package/dist/utils/pattern.d.ts +5 -0
  162. package/dist/utils/pattern.d.ts.map +1 -0
  163. package/dist/utils/pattern.js +31 -0
  164. package/dist/utils/pattern.js.map +1 -0
  165. package/package.json +8 -2
  166. package/.claude/settings.local.json +0 -12
  167. package/.github/workflows/ci.yml +0 -39
  168. package/.gitmessage +0 -60
  169. package/.pre-commit-config.yaml +0 -28
  170. package/CHANGELOG.md +0 -214
  171. package/CLAUDE.md +0 -68
  172. package/apcore-logo.svg +0 -79
  173. package/planning/acl-system/overview.md +0 -54
  174. package/planning/acl-system/plan.md +0 -92
  175. package/planning/acl-system/state.json +0 -76
  176. package/planning/acl-system/tasks/acl-core.md +0 -226
  177. package/planning/acl-system/tasks/acl-rule.md +0 -92
  178. package/planning/acl-system/tasks/conditional-rules.md +0 -259
  179. package/planning/acl-system/tasks/pattern-matching.md +0 -152
  180. package/planning/acl-system/tasks/yaml-loading.md +0 -271
  181. package/planning/core-executor/overview.md +0 -53
  182. package/planning/core-executor/plan.md +0 -88
  183. package/planning/core-executor/state.json +0 -76
  184. package/planning/core-executor/tasks/async-support.md +0 -106
  185. package/planning/core-executor/tasks/execution-pipeline.md +0 -113
  186. package/planning/core-executor/tasks/redaction.md +0 -85
  187. package/planning/core-executor/tasks/safety-checks.md +0 -65
  188. package/planning/core-executor/tasks/setup.md +0 -75
  189. package/planning/decorator-bindings/overview.md +0 -62
  190. package/planning/decorator-bindings/plan.md +0 -104
  191. package/planning/decorator-bindings/state.json +0 -87
  192. package/planning/decorator-bindings/tasks/binding-directory.md +0 -79
  193. package/planning/decorator-bindings/tasks/binding-loader.md +0 -148
  194. package/planning/decorator-bindings/tasks/explicit-schemas.md +0 -85
  195. package/planning/decorator-bindings/tasks/function-module.md +0 -127
  196. package/planning/decorator-bindings/tasks/module-factory.md +0 -89
  197. package/planning/decorator-bindings/tasks/schema-modes.md +0 -142
  198. package/planning/middleware-system/overview.md +0 -48
  199. package/planning/middleware-system/plan.md +0 -102
  200. package/planning/middleware-system/state.json +0 -65
  201. package/planning/middleware-system/tasks/adapters.md +0 -170
  202. package/planning/middleware-system/tasks/base.md +0 -115
  203. package/planning/middleware-system/tasks/logging-middleware.md +0 -304
  204. package/planning/middleware-system/tasks/manager.md +0 -313
  205. package/planning/observability/overview.md +0 -53
  206. package/planning/observability/plan.md +0 -119
  207. package/planning/observability/state.json +0 -98
  208. package/planning/observability/tasks/context-logger.md +0 -201
  209. package/planning/observability/tasks/exporters.md +0 -121
  210. package/planning/observability/tasks/metrics-collector.md +0 -162
  211. package/planning/observability/tasks/metrics-middleware.md +0 -141
  212. package/planning/observability/tasks/obs-logging-middleware.md +0 -179
  213. package/planning/observability/tasks/span-model.md +0 -120
  214. package/planning/observability/tasks/tracing-middleware.md +0 -179
  215. package/planning/overview.md +0 -81
  216. package/planning/registry-system/overview.md +0 -57
  217. package/planning/registry-system/plan.md +0 -114
  218. package/planning/registry-system/state.json +0 -109
  219. package/planning/registry-system/tasks/dependencies.md +0 -157
  220. package/planning/registry-system/tasks/entry-point.md +0 -148
  221. package/planning/registry-system/tasks/metadata.md +0 -198
  222. package/planning/registry-system/tasks/registry-core.md +0 -323
  223. package/planning/registry-system/tasks/scanner.md +0 -172
  224. package/planning/registry-system/tasks/schema-export.md +0 -261
  225. package/planning/registry-system/tasks/types.md +0 -124
  226. package/planning/registry-system/tasks/validation.md +0 -177
  227. package/planning/schema-system/overview.md +0 -56
  228. package/planning/schema-system/plan.md +0 -121
  229. package/planning/schema-system/state.json +0 -98
  230. package/planning/schema-system/tasks/exporter.md +0 -153
  231. package/planning/schema-system/tasks/loader.md +0 -106
  232. package/planning/schema-system/tasks/ref-resolver.md +0 -133
  233. package/planning/schema-system/tasks/strict-mode.md +0 -140
  234. package/planning/schema-system/tasks/typebox-generation.md +0 -133
  235. package/planning/schema-system/tasks/types-and-annotations.md +0 -160
  236. package/planning/schema-system/tasks/validator.md +0 -149
  237. package/src/acl.ts +0 -200
  238. package/src/async-task.ts +0 -267
  239. package/src/bindings.ts +0 -207
  240. package/src/cancel.ts +0 -32
  241. package/src/config.ts +0 -24
  242. package/src/context.ts +0 -160
  243. package/src/decorator.ts +0 -110
  244. package/src/errors.ts +0 -429
  245. package/src/executor.ts +0 -493
  246. package/src/extensions.ts +0 -265
  247. package/src/middleware/adapters.ts +0 -54
  248. package/src/middleware/base.ts +0 -33
  249. package/src/middleware/logging.ts +0 -103
  250. package/src/middleware/manager.ts +0 -105
  251. package/src/module.ts +0 -43
  252. package/src/observability/context-logger.ts +0 -203
  253. package/src/observability/metrics.ts +0 -214
  254. package/src/observability/tracing.ts +0 -252
  255. package/src/registry/dependencies.ts +0 -99
  256. package/src/registry/entry-point.ts +0 -64
  257. package/src/registry/metadata.ts +0 -111
  258. package/src/registry/registry.ts +0 -580
  259. package/src/registry/scanner.ts +0 -168
  260. package/src/registry/schema-export.ts +0 -181
  261. package/src/registry/types.ts +0 -32
  262. package/src/registry/validation.ts +0 -38
  263. package/src/schema/annotations.ts +0 -68
  264. package/src/schema/exporter.ts +0 -90
  265. package/src/schema/loader.ts +0 -273
  266. package/src/schema/ref-resolver.ts +0 -244
  267. package/src/schema/strict.ts +0 -136
  268. package/src/schema/types.ts +0 -73
  269. package/src/schema/validator.ts +0 -82
  270. package/src/trace-context.ts +0 -102
  271. package/src/utils/index.ts +0 -5
  272. package/src/utils/pattern.ts +0 -30
  273. package/tests/async-task.test.ts +0 -335
  274. package/tests/helpers.ts +0 -30
  275. package/tests/integration/test-acl-safety.test.ts +0 -269
  276. package/tests/integration/test-binding-executor.test.ts +0 -194
  277. package/tests/integration/test-e2e-flow.test.ts +0 -117
  278. package/tests/integration/test-error-propagation.test.ts +0 -259
  279. package/tests/integration/test-middleware-chain.test.ts +0 -120
  280. package/tests/integration/test-observability-integration.test.ts +0 -438
  281. package/tests/observability/test-context-logger.test.ts +0 -123
  282. package/tests/observability/test-metrics.test.ts +0 -186
  283. package/tests/observability/test-tracing.test.ts +0 -303
  284. package/tests/registry/test-dependencies.test.ts +0 -70
  285. package/tests/registry/test-entry-point.test.ts +0 -133
  286. package/tests/registry/test-metadata.test.ts +0 -265
  287. package/tests/registry/test-registry.test.ts +0 -1397
  288. package/tests/registry/test-scanner.test.ts +0 -257
  289. package/tests/registry/test-schema-export.test.ts +0 -355
  290. package/tests/registry/test-validation.test.ts +0 -75
  291. package/tests/schema/test-annotations.test.ts +0 -137
  292. package/tests/schema/test-exporter.test.ts +0 -172
  293. package/tests/schema/test-loader.test.ts +0 -461
  294. package/tests/schema/test-ref-resolver.test.ts +0 -530
  295. package/tests/schema/test-strict.test.ts +0 -348
  296. package/tests/schema/test-validator.test.ts +0 -64
  297. package/tests/test-acl.test.ts +0 -423
  298. package/tests/test-bindings.test.ts +0 -227
  299. package/tests/test-cancel.test.ts +0 -71
  300. package/tests/test-config.test.ts +0 -76
  301. package/tests/test-context.test.ts +0 -266
  302. package/tests/test-decorator.test.ts +0 -173
  303. package/tests/test-errors.test.ts +0 -647
  304. package/tests/test-executor-stream.test.ts +0 -208
  305. package/tests/test-executor.test.ts +0 -252
  306. package/tests/test-extensions.test.ts +0 -310
  307. package/tests/test-logging-middleware.test.ts +0 -150
  308. package/tests/test-middleware-manager.test.ts +0 -185
  309. package/tests/test-middleware.test.ts +0 -86
  310. package/tests/test-trace-context.test.ts +0 -251
  311. package/tests/utils/test-pattern.test.ts +0 -109
  312. package/tsconfig.build.json +0 -8
  313. package/tsconfig.json +0 -20
  314. package/vitest.config.ts +0 -18
@@ -1,203 +0,0 @@
1
- /**
2
- * Structured logging: ContextLogger and ObsLoggingMiddleware.
3
- */
4
-
5
- import type { Context } from '../context.js';
6
- import { Middleware } from '../middleware/base.js';
7
-
8
- const LEVELS: Record<string, number> = {
9
- trace: 0,
10
- debug: 10,
11
- info: 20,
12
- warn: 30,
13
- error: 40,
14
- fatal: 50,
15
- };
16
-
17
- const REDACTED = '***REDACTED***';
18
-
19
- interface WritableOutput {
20
- write(s: string): void;
21
- }
22
-
23
- export class ContextLogger {
24
- private _name: string;
25
- private _format: string;
26
- private _level: string;
27
- private _levelValue: number;
28
- private _redactSensitive: boolean;
29
- private _output: WritableOutput;
30
- private _traceId: string | null = null;
31
- private _moduleId: string | null = null;
32
- private _callerId: string | null = null;
33
-
34
- constructor(options?: {
35
- name?: string;
36
- format?: string;
37
- level?: string;
38
- redactSensitive?: boolean;
39
- output?: WritableOutput;
40
- }) {
41
- this._name = options?.name ?? 'apcore';
42
- this._format = options?.format ?? 'json';
43
- this._level = options?.level ?? 'info';
44
- this._levelValue = LEVELS[this._level] ?? 20;
45
- this._redactSensitive = options?.redactSensitive ?? true;
46
- this._output = options?.output ?? { write: (s: string) => process.stderr.write(s) };
47
- }
48
-
49
- static fromContext(context: Context, name: string, options?: {
50
- format?: string;
51
- level?: string;
52
- redactSensitive?: boolean;
53
- output?: WritableOutput;
54
- }): ContextLogger {
55
- const logger = new ContextLogger({ name, ...options });
56
- logger._traceId = context.traceId;
57
- logger._moduleId = context.callChain.length > 0 ? context.callChain[context.callChain.length - 1] : null;
58
- logger._callerId = context.callerId;
59
- return logger;
60
- }
61
-
62
- private _emit(levelName: string, message: string, extra?: Record<string, unknown> | null): void {
63
- const levelValue = LEVELS[levelName] ?? 20;
64
- if (levelValue < this._levelValue) return;
65
-
66
- let redactedExtra = extra ?? null;
67
- if (extra != null && this._redactSensitive) {
68
- redactedExtra = {};
69
- for (const [k, v] of Object.entries(extra)) {
70
- (redactedExtra as Record<string, unknown>)[k] = k.startsWith('_secret_') ? REDACTED : v;
71
- }
72
- }
73
-
74
- const now = new Date();
75
- const entry: Record<string, unknown> = {
76
- timestamp: now.toISOString(),
77
- level: levelName,
78
- message,
79
- trace_id: this._traceId,
80
- module_id: this._moduleId,
81
- caller_id: this._callerId,
82
- logger: this._name,
83
- extra: redactedExtra,
84
- };
85
-
86
- if (this._format === 'json') {
87
- this._output.write(JSON.stringify(entry) + '\n');
88
- } else {
89
- const ts = now.toISOString().replace('T', ' ').replace(/\.\d+Z$/, '');
90
- const lvl = levelName.toUpperCase();
91
- const trace = this._traceId ?? 'none';
92
- const mod = this._moduleId ?? 'none';
93
- let extrasStr = '';
94
- if (redactedExtra) {
95
- extrasStr = ' ' + Object.entries(redactedExtra).map(([k, v]) => `${k}=${v}`).join(' ');
96
- }
97
- this._output.write(`${ts} [${lvl}] [trace=${trace}] [module=${mod}] ${message}${extrasStr}\n`);
98
- }
99
- }
100
-
101
- trace(message: string, extra?: Record<string, unknown>): void {
102
- this._emit('trace', message, extra);
103
- }
104
-
105
- debug(message: string, extra?: Record<string, unknown>): void {
106
- this._emit('debug', message, extra);
107
- }
108
-
109
- info(message: string, extra?: Record<string, unknown>): void {
110
- this._emit('info', message, extra);
111
- }
112
-
113
- warn(message: string, extra?: Record<string, unknown>): void {
114
- this._emit('warn', message, extra);
115
- }
116
-
117
- error(message: string, extra?: Record<string, unknown>): void {
118
- this._emit('error', message, extra);
119
- }
120
-
121
- fatal(message: string, extra?: Record<string, unknown>): void {
122
- this._emit('fatal', message, extra);
123
- }
124
- }
125
-
126
- export class ObsLoggingMiddleware extends Middleware {
127
- private _logger: ContextLogger;
128
- private _logInputs: boolean;
129
- private _logOutputs: boolean;
130
-
131
- constructor(options?: {
132
- logger?: ContextLogger;
133
- logInputs?: boolean;
134
- logOutputs?: boolean;
135
- }) {
136
- super();
137
- this._logger = options?.logger ?? new ContextLogger({ name: 'apcore.obs_logging' });
138
- this._logInputs = options?.logInputs ?? true;
139
- this._logOutputs = options?.logOutputs ?? true;
140
- }
141
-
142
- override before(
143
- moduleId: string,
144
- inputs: Record<string, unknown>,
145
- context: Context,
146
- ): null {
147
- const starts = (context.data['_obs_logging_starts'] as number[]) ?? [];
148
- starts.push(performance.now());
149
- context.data['_obs_logging_starts'] = starts;
150
-
151
- const extra: Record<string, unknown> = {
152
- module_id: moduleId,
153
- caller_id: context.callerId,
154
- };
155
- if (this._logInputs) {
156
- extra['inputs'] = context.redactedInputs ?? inputs;
157
- }
158
- this._logger.info('Module call started', extra);
159
- return null;
160
- }
161
-
162
- override after(
163
- moduleId: string,
164
- _inputs: Record<string, unknown>,
165
- output: Record<string, unknown>,
166
- context: Context,
167
- ): null {
168
- const starts = context.data['_obs_logging_starts'] as number[] | undefined;
169
- if (!starts || starts.length === 0) return null;
170
- const startTime = starts.pop()!;
171
- const durationMs = performance.now() - startTime;
172
-
173
- const extra: Record<string, unknown> = {
174
- module_id: moduleId,
175
- duration_ms: durationMs,
176
- };
177
- if (this._logOutputs) {
178
- extra['output'] = output;
179
- }
180
- this._logger.info('Module call completed', extra);
181
- return null;
182
- }
183
-
184
- override onError(
185
- moduleId: string,
186
- _inputs: Record<string, unknown>,
187
- error: Error,
188
- context: Context,
189
- ): null {
190
- const starts = context.data['_obs_logging_starts'] as number[] | undefined;
191
- if (!starts || starts.length === 0) return null;
192
- const startTime = starts.pop()!;
193
- const durationMs = performance.now() - startTime;
194
-
195
- this._logger.error('Module call failed', {
196
- module_id: moduleId,
197
- duration_ms: durationMs,
198
- error_type: error.constructor.name,
199
- error_message: String(error),
200
- });
201
- return null;
202
- }
203
- }
@@ -1,214 +0,0 @@
1
- /**
2
- * In-memory metrics collection with Prometheus export.
3
- */
4
-
5
- import type { Context } from '../context.js';
6
- import { ModuleError } from '../errors.js';
7
- import { Middleware } from '../middleware/base.js';
8
-
9
- const DESCRIPTIONS: Record<string, string> = {
10
- apcore_module_calls_total: 'Total module calls',
11
- apcore_module_errors_total: 'Total module errors',
12
- apcore_module_duration_seconds: 'Module execution duration',
13
- };
14
-
15
- function labelsKey(labels: Record<string, string>): string {
16
- return Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}=${v}`).join(',');
17
- }
18
-
19
- export class MetricsCollector {
20
- static readonly DEFAULT_BUCKETS: number[] = [
21
- 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
22
- ];
23
-
24
- private _buckets: number[];
25
- private _counters: Map<string, number> = new Map();
26
- private _histogramSums: Map<string, number> = new Map();
27
- private _histogramCounts: Map<string, number> = new Map();
28
- private _histogramBuckets: Map<string, number> = new Map();
29
-
30
- constructor(buckets?: number[]) {
31
- this._buckets = buckets ? [...buckets].sort((a, b) => a - b) : [...MetricsCollector.DEFAULT_BUCKETS];
32
- }
33
-
34
- increment(name: string, labels: Record<string, string>, amount: number = 1): void {
35
- const key = `${name}|${labelsKey(labels)}`;
36
- this._counters.set(key, (this._counters.get(key) ?? 0) + amount);
37
- }
38
-
39
- observe(name: string, labels: Record<string, string>, value: number): void {
40
- const lk = labelsKey(labels);
41
- const key = `${name}|${lk}`;
42
-
43
- this._histogramSums.set(key, (this._histogramSums.get(key) ?? 0) + value);
44
- this._histogramCounts.set(key, (this._histogramCounts.get(key) ?? 0) + 1);
45
-
46
- for (const b of this._buckets) {
47
- if (value <= b) {
48
- const bkey = `${name}|${lk}|${b}`;
49
- this._histogramBuckets.set(bkey, (this._histogramBuckets.get(bkey) ?? 0) + 1);
50
- }
51
- }
52
- // +Inf bucket
53
- const infKey = `${name}|${lk}|Inf`;
54
- this._histogramBuckets.set(infKey, (this._histogramBuckets.get(infKey) ?? 0) + 1);
55
- }
56
-
57
- snapshot(): Record<string, unknown> {
58
- return {
59
- counters: Object.fromEntries(this._counters),
60
- histograms: {
61
- sums: Object.fromEntries(this._histogramSums),
62
- counts: Object.fromEntries(this._histogramCounts),
63
- buckets: Object.fromEntries(this._histogramBuckets),
64
- },
65
- };
66
- }
67
-
68
- reset(): void {
69
- this._counters.clear();
70
- this._histogramSums.clear();
71
- this._histogramCounts.clear();
72
- this._histogramBuckets.clear();
73
- }
74
-
75
- exportPrometheus(): string {
76
- const lines: string[] = [];
77
- const counterNames = new Set<string>();
78
- const histNames = new Set<string>();
79
-
80
- // Counters
81
- for (const [compositeKey, value] of [...this._counters.entries()].sort()) {
82
- const [name, lk] = compositeKey.split('|', 2);
83
- if (!counterNames.has(name)) {
84
- const desc = DESCRIPTIONS[name] ?? name;
85
- lines.push(`# HELP ${name} ${desc}`);
86
- lines.push(`# TYPE ${name} counter`);
87
- counterNames.add(name);
88
- }
89
- const labelsStr = formatLabels(parseLabels(lk));
90
- lines.push(`${name}${labelsStr} ${value}`);
91
- }
92
-
93
- // Histograms
94
- const histKeys = [...this._histogramSums.keys()].sort();
95
- for (const compositeKey of histKeys) {
96
- const [name, lk] = compositeKey.split('|', 2);
97
- if (!histNames.has(name)) {
98
- const desc = DESCRIPTIONS[name] ?? name;
99
- lines.push(`# HELP ${name} ${desc}`);
100
- lines.push(`# TYPE ${name} histogram`);
101
- histNames.add(name);
102
- }
103
-
104
- const labelsDict = parseLabels(lk);
105
- const labelsStr = formatLabels(labelsDict);
106
-
107
- for (const b of this._buckets) {
108
- const bkey = `${name}|${lk}|${b}`;
109
- const count = this._histogramBuckets.get(bkey) ?? 0;
110
- const leStr = String(b);
111
- const leLabels = { ...labelsDict, le: leStr };
112
- lines.push(`${name}_bucket${formatLabels(leLabels)} ${count}`);
113
- }
114
-
115
- const infKey = `${name}|${lk}|Inf`;
116
- const infCount = this._histogramBuckets.get(infKey) ?? 0;
117
- const infLabels = { ...labelsDict, le: '+Inf' };
118
- lines.push(`${name}_bucket${formatLabels(infLabels)} ${infCount}`);
119
-
120
- const sumVal = this._histogramSums.get(compositeKey) ?? 0;
121
- const countVal = this._histogramCounts.get(compositeKey) ?? 0;
122
- lines.push(`${name}_sum${labelsStr} ${sumVal}`);
123
- lines.push(`${name}_count${labelsStr} ${countVal}`);
124
- }
125
-
126
- return lines.length > 0 ? lines.join('\n') + '\n' : '';
127
- }
128
-
129
- incrementCalls(moduleId: string, status: string): void {
130
- this.increment('apcore_module_calls_total', { module_id: moduleId, status });
131
- }
132
-
133
- incrementErrors(moduleId: string, errorCode: string): void {
134
- this.increment('apcore_module_errors_total', { module_id: moduleId, error_code: errorCode });
135
- }
136
-
137
- observeDuration(moduleId: string, durationSeconds: number): void {
138
- this.observe('apcore_module_duration_seconds', { module_id: moduleId }, durationSeconds);
139
- }
140
- }
141
-
142
- function parseLabels(lk: string): Record<string, string> {
143
- if (!lk) return {};
144
- const result: Record<string, string> = {};
145
- for (const pair of lk.split(',')) {
146
- const [k, v] = pair.split('=', 2);
147
- if (k) result[k] = v ?? '';
148
- }
149
- return result;
150
- }
151
-
152
- function formatLabels(labels: Record<string, string>): string {
153
- const entries = Object.entries(labels);
154
- if (entries.length === 0) return '';
155
- const sorted = entries.sort(([a], [b]) => {
156
- if (a === 'le') return 1;
157
- if (b === 'le') return -1;
158
- return a.localeCompare(b);
159
- });
160
- const pairs = sorted.map(([k, v]) => `${k}="${v}"`).join(',');
161
- return `{${pairs}}`;
162
- }
163
-
164
- export class MetricsMiddleware extends Middleware {
165
- private _collector: MetricsCollector;
166
-
167
- constructor(collector: MetricsCollector) {
168
- super();
169
- this._collector = collector;
170
- }
171
-
172
- override before(
173
- _moduleId: string,
174
- _inputs: Record<string, unknown>,
175
- context: Context,
176
- ): null {
177
- const starts = (context.data['_metrics_starts'] as number[]) ?? [];
178
- starts.push(performance.now());
179
- context.data['_metrics_starts'] = starts;
180
- return null;
181
- }
182
-
183
- override after(
184
- moduleId: string,
185
- _inputs: Record<string, unknown>,
186
- _output: Record<string, unknown>,
187
- context: Context,
188
- ): null {
189
- const starts = context.data['_metrics_starts'] as number[] | undefined;
190
- if (!starts || starts.length === 0) return null;
191
- const startTime = starts.pop()!;
192
- const durationS = (performance.now() - startTime) / 1000;
193
- this._collector.incrementCalls(moduleId, 'success');
194
- this._collector.observeDuration(moduleId, durationS);
195
- return null;
196
- }
197
-
198
- override onError(
199
- moduleId: string,
200
- _inputs: Record<string, unknown>,
201
- error: Error,
202
- context: Context,
203
- ): null {
204
- const starts = context.data['_metrics_starts'] as number[] | undefined;
205
- if (!starts || starts.length === 0) return null;
206
- const startTime = starts.pop()!;
207
- const durationS = (performance.now() - startTime) / 1000;
208
- const errorCode = error instanceof ModuleError ? error.code : error.constructor.name;
209
- this._collector.incrementCalls(moduleId, 'error');
210
- this._collector.incrementErrors(moduleId, errorCode);
211
- this._collector.observeDuration(moduleId, durationS);
212
- return null;
213
- }
214
- }
@@ -1,252 +0,0 @@
1
- /**
2
- * Tracing system: Span, SpanExporter implementations, and TracingMiddleware.
3
- */
4
-
5
- import { randomBytes } from 'node:crypto';
6
- import type { Context } from '../context.js';
7
- import { Middleware } from '../middleware/base.js';
8
-
9
- export interface Span {
10
- traceId: string;
11
- name: string;
12
- startTime: number;
13
- spanId: string;
14
- parentSpanId: string | null;
15
- attributes: Record<string, unknown>;
16
- endTime: number | null;
17
- status: string;
18
- events: Array<Record<string, unknown>>;
19
- }
20
-
21
- export function createSpan(options: {
22
- traceId: string;
23
- name: string;
24
- startTime: number;
25
- spanId?: string;
26
- parentSpanId?: string | null;
27
- attributes?: Record<string, unknown>;
28
- }): Span {
29
- return {
30
- traceId: options.traceId,
31
- name: options.name,
32
- startTime: options.startTime,
33
- spanId: options.spanId ?? randomBytes(8).toString('hex'),
34
- parentSpanId: options.parentSpanId ?? null,
35
- attributes: options.attributes ?? {},
36
- endTime: null,
37
- status: 'ok',
38
- events: [],
39
- };
40
- }
41
-
42
- export interface SpanExporter {
43
- export(span: Span): void;
44
- }
45
-
46
- export class StdoutExporter implements SpanExporter {
47
- export(span: Span): void {
48
- process.stdout.write(JSON.stringify(span) + '\n');
49
- }
50
- }
51
-
52
- export class InMemoryExporter implements SpanExporter {
53
- private _spans: Span[] = [];
54
- private _maxSpans: number;
55
-
56
- constructor(maxSpans: number = 10_000) {
57
- this._maxSpans = maxSpans;
58
- }
59
-
60
- export(span: Span): void {
61
- if (this._spans.length >= this._maxSpans) {
62
- // Drop oldest half to amortize the cost instead of O(n) shift per insert
63
- this._spans = this._spans.slice(Math.floor(this._maxSpans / 2));
64
- }
65
- this._spans.push(span);
66
- }
67
-
68
- getSpans(): Span[] {
69
- return [...this._spans];
70
- }
71
-
72
- clear(): void {
73
- this._spans = [];
74
- }
75
- }
76
-
77
- export class OTLPExporter implements SpanExporter {
78
- private _endpoint: string;
79
- private _serviceName: string;
80
- private _headers: Record<string, string>;
81
-
82
- constructor(options?: {
83
- endpoint?: string;
84
- serviceName?: string;
85
- headers?: Record<string, string>;
86
- }) {
87
- this._endpoint = options?.endpoint ?? 'http://localhost:4318/v1/traces';
88
- this._serviceName = options?.serviceName ?? 'apcore';
89
- this._headers = options?.headers ?? {};
90
- }
91
-
92
- export(span: Span): void {
93
- const payload = {
94
- resourceSpans: [{
95
- resource: {
96
- attributes: [
97
- { key: 'service.name', value: { stringValue: this._serviceName } },
98
- ],
99
- },
100
- scopeSpans: [{
101
- scope: { name: 'apcore' },
102
- spans: [{
103
- traceId: span.traceId,
104
- spanId: span.spanId,
105
- parentSpanId: span.parentSpanId ?? undefined,
106
- name: span.name,
107
- startTimeUnixNano: String(Math.round(span.startTime * 1_000_000_000)),
108
- endTimeUnixNano: span.endTime ? String(Math.round(span.endTime * 1_000_000_000)) : undefined,
109
- status: { code: span.status === 'ok' ? 1 : 2 },
110
- attributes: Object.entries(span.attributes).map(([key, value]) => ({
111
- key,
112
- value: { stringValue: String(value) },
113
- })),
114
- }],
115
- }],
116
- }],
117
- };
118
-
119
- // Fire-and-forget POST
120
- fetch(this._endpoint, {
121
- method: 'POST',
122
- headers: {
123
- 'Content-Type': 'application/json',
124
- ...this._headers,
125
- },
126
- body: JSON.stringify(payload),
127
- }).catch(() => {
128
- // Silently ignore network errors
129
- });
130
- }
131
- }
132
-
133
- const VALID_STRATEGIES = new Set(['full', 'proportional', 'error_first', 'off']);
134
-
135
- export class TracingMiddleware extends Middleware {
136
- private _exporter: SpanExporter;
137
- private _samplingRate: number;
138
- private _samplingStrategy: string;
139
-
140
- constructor(
141
- exporter: SpanExporter,
142
- samplingRate: number = 1.0,
143
- samplingStrategy: string = 'full',
144
- ) {
145
- super();
146
- if (samplingRate < 0.0 || samplingRate > 1.0) {
147
- throw new Error(`sampling_rate must be between 0.0 and 1.0, got ${samplingRate}`);
148
- }
149
- if (!VALID_STRATEGIES.has(samplingStrategy)) {
150
- throw new Error(`sampling_strategy must be one of ${[...VALID_STRATEGIES].join(', ')}, got '${samplingStrategy}'`);
151
- }
152
- this._exporter = exporter;
153
- this._samplingRate = samplingRate;
154
- this._samplingStrategy = samplingStrategy;
155
- }
156
-
157
- /** Replace the span exporter used by this middleware. */
158
- setExporter(exporter: SpanExporter): void {
159
- if (!exporter || typeof exporter.export !== 'function') {
160
- throw new Error('exporter must implement SpanExporter interface');
161
- }
162
- this._exporter = exporter;
163
- }
164
-
165
- private _shouldSample(context: Context): boolean {
166
- const existing = context.data['_tracing_sampled'];
167
- if (typeof existing === 'boolean') return existing;
168
-
169
- let decision: boolean;
170
- if (this._samplingStrategy === 'full') {
171
- decision = true;
172
- } else if (this._samplingStrategy === 'off') {
173
- decision = false;
174
- } else {
175
- decision = Math.random() < this._samplingRate;
176
- }
177
-
178
- context.data['_tracing_sampled'] = decision;
179
- return decision;
180
- }
181
-
182
- override before(
183
- moduleId: string,
184
- _inputs: Record<string, unknown>,
185
- context: Context,
186
- ): null {
187
- this._shouldSample(context);
188
-
189
- const spansStack = (context.data['_tracing_spans'] as Span[]) ?? [];
190
- context.data['_tracing_spans'] = spansStack;
191
- const parentSpanId = spansStack.length > 0 ? spansStack[spansStack.length - 1].spanId : null;
192
-
193
- const span = createSpan({
194
- traceId: context.traceId,
195
- name: 'apcore.module.execute',
196
- startTime: Date.now() / 1000,
197
- parentSpanId,
198
- attributes: {
199
- moduleId,
200
- method: 'execute',
201
- callerId: context.callerId,
202
- },
203
- });
204
- spansStack.push(span);
205
- return null;
206
- }
207
-
208
- override after(
209
- moduleId: string,
210
- _inputs: Record<string, unknown>,
211
- _output: Record<string, unknown>,
212
- context: Context,
213
- ): null {
214
- const spansStack = (context.data['_tracing_spans'] as Span[]) ?? [];
215
- if (spansStack.length === 0) return null;
216
-
217
- const span = spansStack.pop()!;
218
- span.endTime = Date.now() / 1000;
219
- span.status = 'ok';
220
- span.attributes['duration_ms'] = (span.endTime - span.startTime) * 1000;
221
- span.attributes['success'] = true;
222
-
223
- if (context.data['_tracing_sampled']) {
224
- this._exporter.export(span);
225
- }
226
- return null;
227
- }
228
-
229
- override onError(
230
- moduleId: string,
231
- _inputs: Record<string, unknown>,
232
- error: Error,
233
- context: Context,
234
- ): null {
235
- const spansStack = (context.data['_tracing_spans'] as Span[]) ?? [];
236
- if (spansStack.length === 0) return null;
237
-
238
- const span = spansStack.pop()!;
239
- span.endTime = Date.now() / 1000;
240
- span.status = 'error';
241
- span.attributes['duration_ms'] = (span.endTime - span.startTime) * 1000;
242
- span.attributes['success'] = false;
243
- span.attributes['error_code'] = (error as unknown as Record<string, unknown>)['code'] ?? error.constructor.name;
244
-
245
- const shouldExport =
246
- this._samplingStrategy === 'error_first' || context.data['_tracing_sampled'];
247
- if (shouldExport) {
248
- this._exporter.export(span);
249
- }
250
- return null;
251
- }
252
- }