@contember/engine-http 2.2.0-alpha.18 → 2.2.0-alpha.19

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 (141) hide show
  1. package/dist/development/index.cjs +0 -1
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +1 -2
  4. package/dist/development/src/application/application.cjs +8 -9
  5. package/dist/development/src/application/application.cjs.map +1 -1
  6. package/dist/development/src/application/application.js +8 -9
  7. package/dist/development/src/application/application.js.map +1 -1
  8. package/dist/development/src/application/compression.cjs +99 -0
  9. package/dist/development/src/application/compression.cjs.map +1 -0
  10. package/dist/development/src/application/compression.js +82 -0
  11. package/dist/development/src/application/compression.js.map +1 -0
  12. package/dist/development/src/application/cors.cjs +52 -0
  13. package/dist/development/src/application/cors.cjs.map +1 -0
  14. package/dist/development/src/application/cors.js +52 -0
  15. package/dist/development/src/application/cors.js.map +1 -0
  16. package/dist/development/src/application/requestBody.cjs +242 -0
  17. package/dist/development/src/application/requestBody.cjs.map +1 -0
  18. package/dist/development/src/application/requestBody.js +242 -0
  19. package/dist/development/src/application/requestBody.js.map +1 -0
  20. package/dist/development/src/config/configSchema.cjs +8 -1
  21. package/dist/development/src/config/configSchema.cjs.map +1 -1
  22. package/dist/development/src/config/configSchema.js +8 -1
  23. package/dist/development/src/config/configSchema.js.map +1 -1
  24. package/dist/development/src/graphql/execution.cjs +3 -9
  25. package/dist/development/src/graphql/execution.cjs.map +1 -1
  26. package/dist/development/src/graphql/execution.js +3 -9
  27. package/dist/development/src/graphql/execution.js.map +1 -1
  28. package/dist/development/src/project/ProjectContainer.cjs +1 -1
  29. package/dist/development/src/project/ProjectContainer.js +1 -1
  30. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +1 -1
  31. package/dist/development/src/projectGroup/ProjectGroupContainer.js +1 -1
  32. package/dist/development/src/providers.cjs +2 -2
  33. package/dist/development/src/providers.cjs.map +1 -1
  34. package/dist/development/src/providers.js +2 -2
  35. package/dist/development/src/providers.js.map +1 -1
  36. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
  37. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  38. package/dist/development/src/transfer/ImportExecutor.cjs +18 -3
  39. package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
  40. package/dist/development/src/transfer/ImportExecutor.js +18 -3
  41. package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
  42. package/dist/development/src/utils/sentry.cjs +31 -49
  43. package/dist/development/src/utils/sentry.cjs.map +1 -1
  44. package/dist/development/src/utils/sentry.js +32 -33
  45. package/dist/development/src/utils/sentry.js.map +1 -1
  46. package/dist/development/src/utils/serverStartup.cjs +5 -3
  47. package/dist/development/src/utils/serverStartup.cjs.map +1 -1
  48. package/dist/development/src/utils/serverStartup.js +5 -3
  49. package/dist/development/src/utils/serverStartup.js.map +1 -1
  50. package/dist/production/index.cjs +0 -1
  51. package/dist/production/index.cjs.map +1 -1
  52. package/dist/production/index.js +1 -2
  53. package/dist/production/src/application/application.cjs +8 -9
  54. package/dist/production/src/application/application.cjs.map +1 -1
  55. package/dist/production/src/application/application.js +8 -9
  56. package/dist/production/src/application/application.js.map +1 -1
  57. package/dist/production/src/application/compression.cjs +99 -0
  58. package/dist/production/src/application/compression.cjs.map +1 -0
  59. package/dist/production/src/application/compression.js +82 -0
  60. package/dist/production/src/application/compression.js.map +1 -0
  61. package/dist/production/src/application/cors.cjs +52 -0
  62. package/dist/production/src/application/cors.cjs.map +1 -0
  63. package/dist/production/src/application/cors.js +52 -0
  64. package/dist/production/src/application/cors.js.map +1 -0
  65. package/dist/production/src/application/requestBody.cjs +242 -0
  66. package/dist/production/src/application/requestBody.cjs.map +1 -0
  67. package/dist/production/src/application/requestBody.js +242 -0
  68. package/dist/production/src/application/requestBody.js.map +1 -0
  69. package/dist/production/src/config/configSchema.cjs +8 -1
  70. package/dist/production/src/config/configSchema.cjs.map +1 -1
  71. package/dist/production/src/config/configSchema.js +8 -1
  72. package/dist/production/src/config/configSchema.js.map +1 -1
  73. package/dist/production/src/graphql/execution.cjs +3 -9
  74. package/dist/production/src/graphql/execution.cjs.map +1 -1
  75. package/dist/production/src/graphql/execution.js +3 -9
  76. package/dist/production/src/graphql/execution.js.map +1 -1
  77. package/dist/production/src/project/ProjectContainer.cjs +1 -1
  78. package/dist/production/src/project/ProjectContainer.js +1 -1
  79. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +1 -1
  80. package/dist/production/src/projectGroup/ProjectGroupContainer.js +1 -1
  81. package/dist/production/src/providers.cjs +2 -2
  82. package/dist/production/src/providers.cjs.map +1 -1
  83. package/dist/production/src/providers.js +2 -2
  84. package/dist/production/src/providers.js.map +1 -1
  85. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
  86. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  87. package/dist/production/src/transfer/ImportExecutor.cjs +18 -3
  88. package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
  89. package/dist/production/src/transfer/ImportExecutor.js +18 -3
  90. package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
  91. package/dist/production/src/utils/sentry.cjs +31 -49
  92. package/dist/production/src/utils/sentry.cjs.map +1 -1
  93. package/dist/production/src/utils/sentry.js +32 -33
  94. package/dist/production/src/utils/sentry.js.map +1 -1
  95. package/dist/production/src/utils/serverStartup.cjs +5 -3
  96. package/dist/production/src/utils/serverStartup.cjs.map +1 -1
  97. package/dist/production/src/utils/serverStartup.js +5 -3
  98. package/dist/production/src/utils/serverStartup.js.map +1 -1
  99. package/dist/tests/cases/unit/compression.test.d.ts +2 -0
  100. package/dist/tests/cases/unit/compression.test.d.ts.map +1 -0
  101. package/dist/tests/cases/unit/cors.test.d.ts +2 -0
  102. package/dist/tests/cases/unit/cors.test.d.ts.map +1 -0
  103. package/dist/tests/cases/unit/requestBody.test.d.ts +2 -0
  104. package/dist/tests/cases/unit/requestBody.test.d.ts.map +1 -0
  105. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  106. package/dist/types/MasterContainer.d.ts +1 -1
  107. package/dist/types/application/application.d.ts.map +1 -1
  108. package/dist/types/application/compression.d.ts +19 -0
  109. package/dist/types/application/compression.d.ts.map +1 -0
  110. package/dist/types/application/cors.d.ts +10 -0
  111. package/dist/types/application/cors.d.ts.map +1 -0
  112. package/dist/types/application/requestBody.d.ts +45 -0
  113. package/dist/types/application/requestBody.d.ts.map +1 -0
  114. package/dist/types/config/configSchema.d.ts +3 -3
  115. package/dist/types/config/configSchema.d.ts.map +1 -1
  116. package/dist/types/graphql/execution.d.ts.map +1 -1
  117. package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
  118. package/dist/types/tsconfig.tsbuildinfo +1 -1
  119. package/dist/types/utils/sentry.d.ts +13 -6
  120. package/dist/types/utils/sentry.d.ts.map +1 -1
  121. package/dist/types/utils/serverStartup.d.ts.map +1 -1
  122. package/package.json +18 -24
  123. package/src/application/application.ts +8 -9
  124. package/src/application/compression.ts +118 -0
  125. package/src/application/cors.ts +61 -0
  126. package/src/application/requestBody.ts +295 -0
  127. package/src/config/configSchema.ts +8 -1
  128. package/src/graphql/execution.ts +3 -9
  129. package/src/providers.ts +2 -2
  130. package/src/transfer/ImportExecutor.ts +21 -3
  131. package/src/tsconfig.json +3 -1
  132. package/src/utils/sentry.ts +42 -39
  133. package/src/utils/serverStartup.ts +7 -5
  134. package/tests/cases/unit/compression.test.ts +172 -0
  135. package/tests/cases/unit/cors.test.ts +106 -0
  136. package/tests/cases/unit/requestBody.test.ts +333 -0
  137. package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
  138. package/tests/cases/unit/serverConfig.test.ts +19 -0
  139. package/dist/tests/cases/unit/sentryIntegrations.test.d.ts +0 -2
  140. package/dist/tests/cases/unit/sentryIntegrations.test.d.ts.map +0 -1
  141. package/tests/cases/unit/sentryIntegrations.test.ts +0 -15
@@ -126,7 +126,6 @@ exports.executeTerminationJobs = serverTermination.executeTerminationJobs;
126
126
  exports.listenOnProcessTermination = serverTermination.listenOnProcessTermination;
127
127
  exports.SentryLoggerHandler = sentry.SentryLoggerHandler;
128
128
  exports.createSentryLoggerHandler = sentry.createSentryLoggerHandler;
129
- exports.filterSentryIntegrations = sentry.filterSentryIntegrations;
130
129
  exports.createFastSqlSpanFilter = FilteringSpanProcessor.createFastSqlSpanFilter;
131
130
  exports.createFilteringSpanProcessor = FilteringSpanProcessor.createFilteringSpanProcessor;
132
131
  exports.isIncomingTraceTrusted = incomingTrace.isIncomingTraceTrusted;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../../packages/engine-http/src/index.ts"],"sourcesContent":["import { MasterContainerArgs, MasterContainerFactory } from './MasterContainer.js'\nimport Koa from 'koa'\n\nexport * from './config/config.js'\nexport * from './config/ConfigProcessor.js'\nexport { projectNameToEnvName } from './config/projectConfigResolver.js'\nexport * from './config/tenantConfigResolver.js'\nexport * from './common/index.js'\nexport * from './content/index.js'\nexport * from './plugin/Plugin.js'\nexport * from './misc/index.js'\nexport * from './project-common/index.js'\nexport * from './system/index.js'\nexport * from './tenant/index.js'\nexport * from './transfer/index.js'\nexport * from './application/index.js'\nexport * from './providers.js'\nexport * from './graphql/index.js'\nexport * from './project/config.js'\nexport * from './utils/CryptoWrapper.js'\nexport * from './project/ProjectContainer.js'\nexport * from './project/ProjectContainerResolver.js'\nexport * from './projectGroup/ProjectGroupContainer.js'\nexport * from './projectGroup/ProjectGroupResolver.js'\nexport type { ProjectGroupContainerResolver } from './projectGroup/ProjectGroupContainerResolver.js'\n\nexport * from './testing/index.js'\nexport * from './utils/serverStartup.js'\nexport * from './utils/serverTermination.js'\nexport * from './utils/sentry.js'\nexport * from './telemetry/index.js'\nexport * from './MasterContainer.js'\nexport { serverConfigSchema } from './config/configSchema.js'\n\nexport const createContainer = (args: MasterContainerArgs) => {\n\treturn new MasterContainerFactory().create(args)\n}\n\nexport { Koa }\n"],"names":["MasterContainerFactory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCO,MAAM,kBAAkB,CAAC,SAA8B;AAC7D,SAAO,IAAIA,gBAAAA,uBAAA,EAAyB,OAAO,IAAI;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../../../packages/engine-http/src/index.ts"],"sourcesContent":["import { MasterContainerArgs, MasterContainerFactory } from './MasterContainer.js'\nimport Koa from 'koa'\n\nexport * from './config/config.js'\nexport * from './config/ConfigProcessor.js'\nexport { projectNameToEnvName } from './config/projectConfigResolver.js'\nexport * from './config/tenantConfigResolver.js'\nexport * from './common/index.js'\nexport * from './content/index.js'\nexport * from './plugin/Plugin.js'\nexport * from './misc/index.js'\nexport * from './project-common/index.js'\nexport * from './system/index.js'\nexport * from './tenant/index.js'\nexport * from './transfer/index.js'\nexport * from './application/index.js'\nexport * from './providers.js'\nexport * from './graphql/index.js'\nexport * from './project/config.js'\nexport * from './utils/CryptoWrapper.js'\nexport * from './project/ProjectContainer.js'\nexport * from './project/ProjectContainerResolver.js'\nexport * from './projectGroup/ProjectGroupContainer.js'\nexport * from './projectGroup/ProjectGroupResolver.js'\nexport type { ProjectGroupContainerResolver } from './projectGroup/ProjectGroupContainerResolver.js'\n\nexport * from './testing/index.js'\nexport * from './utils/serverStartup.js'\nexport * from './utils/serverTermination.js'\nexport * from './utils/sentry.js'\nexport * from './telemetry/index.js'\nexport * from './MasterContainer.js'\nexport { serverConfigSchema } from './config/configSchema.js'\n\nexport const createContainer = (args: MasterContainerArgs) => {\n\treturn new MasterContainerFactory().create(args)\n}\n\nexport { Koa }\n"],"names":["MasterContainerFactory"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCO,MAAM,kBAAkB,CAAC,SAA8B;AAC7D,SAAO,IAAIA,gBAAAA,uBAAA,EAAyB,OAAO,IAAI;AAChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -44,7 +44,7 @@ import { ProjectGroupResolver } from "./src/projectGroup/ProjectGroupResolver.js
44
44
  import { TestTransactionService } from "./src/testing/TestTransactions.js";
45
45
  import { createDefaultLogger, getServerVersion, isDebugMode, printStartInfo, resolveServerConfig } from "./src/utils/serverStartup.js";
46
46
  import { createTerminationExecutor, executeTerminationJobs, listenOnProcessTermination } from "./src/utils/serverTermination.js";
47
- import { SentryLoggerHandler, createSentryLoggerHandler, filterSentryIntegrations } from "./src/utils/sentry.js";
47
+ import { SentryLoggerHandler, createSentryLoggerHandler } from "./src/utils/sentry.js";
48
48
  import { createFastSqlSpanFilter, createFilteringSpanProcessor } from "./src/telemetry/FilteringSpanProcessor.js";
49
49
  import { isIncomingTraceTrusted, resolveIncomingSpanContext } from "./src/telemetry/incomingTrace.js";
50
50
  import { ProjectGroupContainerTelemetryHook } from "./src/telemetry/ProjectGroupContainerTelemetryHook.js";
@@ -114,7 +114,6 @@ export {
114
114
  defaultServiceName,
115
115
  executeTerminationJobs,
116
116
  extractOriginalError,
117
- filterSentryIntegrations,
118
117
  forceHttpOkHeader,
119
118
  getServerVersion,
120
119
  homepageController,
@@ -8,9 +8,9 @@ const Koa = require("koa");
8
8
  const http = require("node:http");
9
9
  const ws = require("ws");
10
10
  const logger = require("@contember/logger");
11
- const koaCompress = require("koa-compress");
12
- const bodyParser = require("koa-bodyparser");
13
- const corsMiddleware = require("@koa/cors");
11
+ const compression = require("./compression.cjs");
12
+ const cors = require("./cors.cjs");
13
+ const requestBody = require("./requestBody.cjs");
14
14
  const node_stream = require("node:stream");
15
15
  const node_url = require("node:url");
16
16
  const node_process = require("node:process");
@@ -110,13 +110,12 @@ class Application {
110
110
  for (const middleware of this.middlewares) {
111
111
  koa.use(middleware);
112
112
  }
113
- koa.use(koaCompress({
114
- br: false
113
+ koa.use(compression.createCompressionMiddleware());
114
+ koa.use(requestBody.createRequestBodyMiddleware({
115
+ json: this.serverConfig.http?.requestBodySize ?? requestBody.defaultJsonBodyLimit,
116
+ form: requestBody.defaultFormBodyLimit
115
117
  }));
116
- koa.use(bodyParser({
117
- jsonLimit: this.serverConfig.http?.requestBodySize || "1mb"
118
- }));
119
- koa.use(corsMiddleware({ exposeHeaders: ["X-Contember-Mutation"] }));
118
+ koa.use(cors.createCorsMiddleware({ exposeHeaders: ["X-Contember-Mutation"] }));
120
119
  const versionMatch = this.version?.match(/^(0\.\d+|\d+)/);
121
120
  const versionSimplified = versionMatch?.[1] ?? "unknown";
122
121
  koa.use(async (ctx) => {
@@ -1 +1 @@
1
- {"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\nimport { INVALID_TRACE_ID, noopTracer, Span, SpanContext, Tracer, withSpanContext } from '@contember/telemetry'\nimport { AcceptIncomingTraceMode, resolveIncomingSpanContext } from '../telemetry/incomingTrace.js'\nimport { maskRequestBody, maskRequestUri } from './requestBodyMasking.js'\n\nconst websocketCloseTimeoutMs = 5_000\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type RouteOptions = {\n\t/** The route receives engine credentials (passwords, OTP codes, tokens), so its body and URI are masked in logs. */\n\treadonly carriesCredentials?: boolean\n}\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\tprivate acceptIncomingTrace: AcceptIncomingTraceMode\n\tprivate traceIdResponseHeader: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t\tprivate readonly tracer: Tracer = noopTracer,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t\tthis.acceptIncomingTrace = serverConfig.telemetry?.traces?.acceptIncoming ?? 'trusted-proxies'\n\t\tthis.traceIdResponseHeader = serverConfig.telemetry?.traces?.traceIdResponseHeader ?? false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController, options: RouteOptions = {}): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: options.carriesCredentials ?? false,\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tlet closing = false\n\t\tkoa.use(async (ctx, next) => {\n\t\t\tif (closing) {\n\t\t\t\tctx.status = 503\n\t\t\t\tctx.set('Connection', 'close')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tawait next()\n\t\t})\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst activeHttpRequests = new Set<Promise<void>>()\n\t\tconst handleHttpRequest = koa.callback()\n\t\tconst server = http.createServer((request, response) => {\n\t\t\tif (closing) {\n\t\t\t\thandleHttpRequest(request, response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlet resolveRequest = () => {}\n\t\t\tconst completed = new Promise<void>(resolve => {\n\t\t\t\tresolveRequest = resolve\n\t\t\t})\n\t\t\tactiveHttpRequests.add(completed)\n\t\t\tconst complete = () => {\n\t\t\t\tresponse.off('finish', complete)\n\t\t\t\tresponse.off('close', complete)\n\t\t\t\tactiveHttpRequests.delete(completed)\n\t\t\t\tresolveRequest()\n\t\t\t}\n\t\t\tresponse.once('finish', complete)\n\t\t\tresponse.once('close', complete)\n\t\t\thandleHttpRequest(request, response)\n\t\t})\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\tif (closing) {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(503, 'Server is shutting down'))\n\t\t\t\treturn\n\t\t\t}\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head).finally(() => socket.destroy()))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tclosing = true\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all([...wsRequests, ...activeHttpRequests])\n\t\t\t\tif (process.versions.bun !== undefined) {\n\t\t\t\t\t// Bun does not finish server.close() after a WebSocket upgrade unless all connections are closed first.\n\t\t\t\t\tserver.closeAllConnections()\n\t\t\t\t} else {\n\t\t\t\t\tserver.closeIdleConnections()\n\t\t\t\t}\n\t\t\t\tif (server.listening) {\n\t\t\t\t\tawait new Promise<void>(resolve =>\n\t\t\t\t\t\tserver.close(error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tthis.logger.error(error)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\tconst established = await this.withIncomingTrace(req, async () => {\n\t\t\t\tconst span = this.tracer.startSpan(`WS ${matchedRequest.mask}`, {\n\t\t\t\t\tkind: 'server',\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t'http.request.method': req.method ?? 'GET',\n\t\t\t\t\t\t'url.path': url.pathname,\n\t\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn await this.tracer.withSpan(span, async () => {\n\t\t\t\t\tconst pendingWork: Promise<void>[] = []\n\t\t\t\t\ttry {\n\t\t\t\t\t\trequestLogger = this.createRequestLogger(req, undefined, false, matchedRequest.module, clientIp, span.context)\n\t\t\t\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ projectGroup: groupContainer.slug, project: matchedRequest.params.projectSlug })\n\t\t\t\t\t\tspan.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\t\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\t\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ user: authResult?.identityId })\n\t\t\t\t\t\tif (authResult) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tthrow new HttpErrorResponse(503, 'Server is shutting down')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, ws => resolve(ws)))\n\t\t\t\t\t\tconst establishedAt = performance.now()\n\t\t\t\t\t\tconst closed = new Promise<void>(resolve => ws.once('close', () => resolve()))\n\t\t\t\t\t\tws.on('error', e => {\n\t\t\t\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', 101)\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tawait this.closeWebsocket(ws)\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst context: WebSocketContext = {\n\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\tlogger: requestLogger,\n\t\t\t\t\t\t\ttimer,\n\t\t\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\trequest: req,\n\t\t\t\t\t\t\tclientIp: authResult?.clientIp ?? clientIp,\n\t\t\t\t\t\t\tauthResult,\n\t\t\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t\t\t\twaitUntil: promise => pendingWork.push(promise),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait matchedRequest.controller(context)\n\t\t\t\t\t\tif (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {\n\t\t\t\t\t\t\tws.close(1012)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { closed, pendingWork, establishedAt }\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst response = error instanceof HttpResponse ? error : new HttpErrorResponse(500, 'Internal server error')\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', response.code)\n\t\t\t\t\t\tif (response.code >= 500) {\n\t\t\t\t\t\t\tspan.setStatus('error')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(error instanceof HttpResponse)) {\n\t\t\t\t\t\t\tspan.recordException(error)\n\t\t\t\t\t\t\trequestLogger.error(error)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.sendRawHttpResponse(socket, response)\n\t\t\t\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tspan.end()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (established === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { closed, pendingWork, establishedAt } = established\n\t\t\trequestLogger.debug('Websocket connection established')\n\n\t\t\tawait closed\n\t\t\tawait Promise.allSettled(pendingWork)\n\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t\treturn await this.processHttpRequest(ctx, null)\n\t\t}\n\t\treturn await this.withIncomingTrace(ctx.req, async () => {\n\t\t\tconst span = this.tracer.startSpan(`HTTP ${ctx.request.method} ${matchedRequest.mask}`, {\n\t\t\t\tkind: 'server',\n\t\t\t\tattributes: {\n\t\t\t\t\t'http.request.method': ctx.request.method,\n\t\t\t\t\t'url.path': ctx.request.URL.pathname,\n\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (span.context.traceId === INVALID_TRACE_ID) {\n\t\t\t\treturn await this.processHttpRequest(ctx, matchedRequest, span)\n\t\t\t}\n\t\t\tconst endSpan = () => {\n\t\t\t\tctx.res.off('finish', endSpan)\n\t\t\t\tctx.res.off('close', closeSpan)\n\t\t\t\tspan.end()\n\t\t\t}\n\t\t\tconst closeSpan = () => {\n\t\t\t\tif (!ctx.res.writableFinished) {\n\t\t\t\t\tspan.setStatus('error', 'Response closed before completion')\n\t\t\t\t}\n\t\t\t\tendSpan()\n\t\t\t}\n\t\t\tctx.res.once('finish', endSpan)\n\t\t\tctx.res.once('close', closeSpan)\n\t\t\ttry {\n\t\t\t\treturn await this.tracer.withSpan(span, () => this.processHttpRequest(ctx, matchedRequest, span))\n\t\t\t} catch (error) {\n\t\t\t\tspan.recordException(error)\n\t\t\t\tspan.setStatus('error')\n\t\t\t\tendSpan()\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\tif (ctx.res.writableFinished) {\n\t\t\t\t\tendSpan()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async processHttpRequest(\n\t\tctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>,\n\t\tmatchedRequest: MatchedRequest<HttpController> | null,\n\t\tspan?: Span,\n\t) {\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tconst carriesCredentials = matchedRequest?.carriesCredentials ?? false\n\t\tconst loggedBody = maskRequestBody(ctx.request.body, carriesCredentials)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, loggedBody, carriesCredentials, matchedRequest?.module, clientIp, span?.context)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: loggedBody,\n\t\t\t\tquery: maskRequestBody(ctx.request.query, carriesCredentials),\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t\tproject: matchedRequest.params.projectSlug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\t\t\tspan?.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\tspan?.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t}\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\t\t\tif (authResult) {\n\t\t\t\tspan?.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t}\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tspan?.recordException(e)\n\t\t\t\tspan?.setStatus('error')\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tconst responseStatus = ctx.status\n\t\t\tif (responseStatus >= 500) {\n\t\t\t\tspan?.setStatus('error')\n\t\t\t}\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tconst requestDebugMode = (httpContext as HttpContext | null)?.requestDebugMode ?? false\n\t\t\tspan?.setAttribute('http.response.status_code', ctx.status)\n\t\t\tthis.sendTraceIdHeader(ctx, span, requestDebugMode)\n\t\t\tif (span !== undefined && span.context.traceId !== INVALID_TRACE_ID && ctx.response.body instanceof Readable) {\n\t\t\t\tconst contentLength = ctx.response.get('Content-Length')\n\t\t\t\tctx.body = createTracedReadable(ctx.response.body, this.tracer, span)\n\t\t\t\tif (contentLength !== '') {\n\t\t\t\t\tctx.set('Content-Length', contentLength)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate withIncomingTrace<T>(request: IncomingMessage, cb: () => T): T {\n\t\tconst incoming = resolveIncomingSpanContext(request, { mode: this.acceptIncomingTrace, trustedProxies: this.trustedProxies })\n\t\treturn incoming === undefined ? cb() : withSpanContext(incoming, cb)\n\t}\n\n\tprivate sendTraceIdHeader(ctx: KoaContext<{}>, span: Span | undefined, requestDebugMode: boolean): void {\n\t\tif (span === undefined || ctx.res.headersSent || span.context.traceId === INVALID_TRACE_ID) {\n\t\t\treturn\n\t\t}\n\t\tif (!this.traceIdResponseHeader && !this.debugMode && !requestDebugMode) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('x-contember-trace-id', span.context.traceId)\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tfor (const [name, value] of Object.entries(response.headers ?? {})) {\n\t\t\tctx.set(name, value)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate async closeWebsocket(ws: WebSocket): Promise<void> {\n\t\tif (ws.readyState === WebSocket.CLOSED) {\n\t\t\treturn\n\t\t}\n\t\tws.close(1012) // Service Restart\n\t\tawait new Promise<void>(resolve => {\n\t\t\t// ws only gives up on the close handshake after 30 s, which outlives a typical shutdown grace period\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tws.terminate()\n\t\t\t\tresolve()\n\t\t\t}, websocketCloseTimeoutMs)\n\t\t\tws.once('close', () => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve()\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t...response.headers,\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\t/** `loggedBody` must already be masked (`maskRequestBody`): it reaches logs and error reports. */\n\tprivate createRequestLogger(\n\t\trequest: IncomingMessage,\n\t\tloggedBody: unknown,\n\t\tcarriesCredentials: boolean,\n\t\tmodule?: string,\n\t\tremoteAddress?: string,\n\t\tspanContext?: SpanContext,\n\t): Logger {\n\t\tconst traceAttributes = spanContext === undefined || spanContext.traceId === INVALID_TRACE_ID\n\t\t\t? {}\n\t\t\t: { traceId: spanContext.traceId, spanId: spanContext.spanId }\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: maskRequestUri(request.url, carriesCredentials),\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t...traceAttributes,\n\t\t\t[LoggerRequestBody]: loggedBody,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer = createEventTimer(this.tracer, times, globalStart)\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module, mask: route.mask, carriesCredentials: route.carriesCredentials }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nexport type EventTime = { label: string; start: number; duration?: number }\n\nexport const createEventTimer = (tracer: Tracer, times: EventTime[], globalStart: number): Timer => (name, cb) => {\n\tconst start = performance.now()\n\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\ttimes.push(time)\n\tconst res = tracer.span(name, () => cb())\n\n\tif (res instanceof Promise) {\n\t\t;(async () => {\n\t\t\ttry {\n\t\t\t\tawait res\n\t\t\t} catch {\n\t\t\t} finally {\n\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t}\n\t\t})()\n\t}\n\treturn res\n}\n\nconst createTracedReadable = (body: Readable, tracer: Tracer, span: Span): Readable => {\n\tconst iterator = body[Symbol.asyncIterator]()\n\treturn Readable.from((async function*() {\n\t\tlet completed = false\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst next = await tracer.withSpan(span, () => iterator.next())\n\t\t\t\tif (next.done) {\n\t\t\t\t\tcompleted = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tyield next.value\n\t\t\t}\n\t\t} finally {\n\t\t\tif (!completed && iterator.return !== undefined) {\n\t\t\t\tawait tracer.withSpan(span, () => iterator.return?.())\n\t\t\t}\n\t\t}\n\t})())\n}\n\n/** @deprecated use `tracer` from the request context instead */\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t\ttracer: Tracer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t\twaitUntil(promise: Promise<void>): void\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["logger","noopTracer","module","WebSocketServer","http","HttpErrorResponse","getClientIP","URL","pendingWork","ws","establishedAt","performance","closed","WebSocket","HttpResponse","INVALID_TRACE_ID","maskRequestBody","Readable","resolveIncomingSpanContext","withSpanContext","shouldForceHttpOk","isForceHttpOkRequested","remoteAddress","maskRequestUri","FingerCrossedLoggerHandler","cpuUsage","memoryUsage","pathToRegexp","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,0BAA0B;AAQzB,MAAM,YAAY;AAAA,EAaxB,YACkB,sBACA,cACA,WACA,SACAA,SACA,SAAiBC,sBACjC;AANgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAAD;AACA,SAAA,SAAA;AAlBlB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AACR,kBAAA,MAAQ,gBAAA;AACR,kBAAA,MAAQ,oBAAA;AACR,kBAAA,MAAQ,qBAAA;AACR,kBAAA,MAAQ,uBAAA;AAUP,UAAM,uBAAuB,aAAa,MAAM;AAChD,SAAK,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAC1H,SAAK,iBAAiB,aAAa,MAAM,kBAAkB,CAAA;AAC3D,SAAK,qBAAqB,aAAa,MAAM,wBAAwB;AACrE,SAAK,sBAAsB,aAAa,WAAW,QAAQ,kBAAkB;AAC7E,SAAK,wBAAwB,aAAa,WAAW,QAAQ,yBAAyB;AAAA,EACvF;AAAA,EAEA,cAAc,YAAgC;AAC7C,SAAK,YAAY,KAAK,UAAU;AAAA,EACjC;AAAA,EAEO,SAASE,SAAgB,MAAc,YAA4B,UAAwB,CAAA,GAAU;AAC3G,SAAK,OAAO,KAAK;AAAA,MAChB,QAAAA;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB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K,MAAMA,gBAAAA,YAAY,IAAA,IAAQ,KAAK;AAAA,MACrD;AAAA,IACD,GAAA;AAAA,EACD;AACA,SAAO;AACR;AAEA,MAAM,uBAAuB,CAAC,MAAgB,QAAgB,SAAyB;AACtF,QAAM,WAAW,KAAK,OAAO,aAAa,EAAA;AAC1C,SAAOM,YAAAA,SAAS,MAAM,mBAAkB;AACvC,QAAI,YAAY;AAChB,QAAI;AACH,aAAO,MAAM;AACZ,cAAM,OAAO,MAAM,OAAO,SAAS,MAAM,MAAM,SAAS,MAAM;AAC9D,YAAI,KAAK,MAAM;AACd,sBAAY;AACZ;AAAA,QACD;AACA,cAAM,KAAK;AAAA,MACZ;AAAA,IACD,UAAA;AACC,UAAI,CAAC,aAAa,SAAS,WAAW,QAAW;AAChD,cAAM,OAAO,SAAS,MAAM,MAAM,SAAS,UAAU;AAAA,MACtD;AAAA,IACD;AAAA,EACD,IAAI;AACL;AA0DA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,EAAE,QAAQ,SAASU,aAAAA,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;;;;"}
1
+ {"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport { ServerConfig } from '../config/config.js'\nimport { createCompressionMiddleware } from './compression.js'\nimport { createCorsMiddleware } from './cors.js'\nimport { createRequestBodyMiddleware, defaultFormBodyLimit, defaultJsonBodyLimit } from './requestBody.js'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\nimport { INVALID_TRACE_ID, noopTracer, Span, SpanContext, Tracer, withSpanContext } from '@contember/telemetry'\nimport { AcceptIncomingTraceMode, resolveIncomingSpanContext } from '../telemetry/incomingTrace.js'\nimport { maskRequestBody, maskRequestUri } from './requestBodyMasking.js'\n\nconst websocketCloseTimeoutMs = 5_000\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type RouteOptions = {\n\t/** The route receives engine credentials (passwords, OTP codes, tokens), so its body and URI are masked in logs. */\n\treadonly carriesCredentials?: boolean\n}\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\tprivate acceptIncomingTrace: AcceptIncomingTraceMode\n\tprivate traceIdResponseHeader: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t\tprivate readonly tracer: Tracer = noopTracer,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t\tthis.acceptIncomingTrace = serverConfig.telemetry?.traces?.acceptIncoming ?? 'trusted-proxies'\n\t\tthis.traceIdResponseHeader = serverConfig.telemetry?.traces?.traceIdResponseHeader ?? false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController, options: RouteOptions = {}): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: options.carriesCredentials ?? false,\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tlet closing = false\n\t\tkoa.use(async (ctx, next) => {\n\t\t\tif (closing) {\n\t\t\t\tctx.status = 503\n\t\t\t\tctx.set('Connection', 'close')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tawait next()\n\t\t})\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(createCompressionMiddleware())\n\t\tkoa.use(createRequestBodyMiddleware({\n\t\t\tjson: this.serverConfig.http?.requestBodySize ?? defaultJsonBodyLimit,\n\t\t\tform: defaultFormBodyLimit,\n\t\t}))\n\t\tkoa.use(createCorsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst activeHttpRequests = new Set<Promise<void>>()\n\t\tconst handleHttpRequest = koa.callback()\n\t\tconst server = http.createServer((request, response) => {\n\t\t\tif (closing) {\n\t\t\t\thandleHttpRequest(request, response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlet resolveRequest = () => {}\n\t\t\tconst completed = new Promise<void>(resolve => {\n\t\t\t\tresolveRequest = resolve\n\t\t\t})\n\t\t\tactiveHttpRequests.add(completed)\n\t\t\tconst complete = () => {\n\t\t\t\tresponse.off('finish', complete)\n\t\t\t\tresponse.off('close', complete)\n\t\t\t\tactiveHttpRequests.delete(completed)\n\t\t\t\tresolveRequest()\n\t\t\t}\n\t\t\tresponse.once('finish', complete)\n\t\t\tresponse.once('close', complete)\n\t\t\thandleHttpRequest(request, response)\n\t\t})\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\tif (closing) {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(503, 'Server is shutting down'))\n\t\t\t\treturn\n\t\t\t}\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head).finally(() => socket.destroy()))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tclosing = true\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all([...wsRequests, ...activeHttpRequests])\n\t\t\t\tif (process.versions.bun !== undefined) {\n\t\t\t\t\t// Bun does not finish server.close() after a WebSocket upgrade unless all connections are closed first.\n\t\t\t\t\tserver.closeAllConnections()\n\t\t\t\t} else {\n\t\t\t\t\tserver.closeIdleConnections()\n\t\t\t\t}\n\t\t\t\tif (server.listening) {\n\t\t\t\t\tawait new Promise<void>(resolve =>\n\t\t\t\t\t\tserver.close(error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tthis.logger.error(error)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\tconst established = await this.withIncomingTrace(req, async () => {\n\t\t\t\tconst span = this.tracer.startSpan(`WS ${matchedRequest.mask}`, {\n\t\t\t\t\tkind: 'server',\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t'http.request.method': req.method ?? 'GET',\n\t\t\t\t\t\t'url.path': url.pathname,\n\t\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn await this.tracer.withSpan(span, async () => {\n\t\t\t\t\tconst pendingWork: Promise<void>[] = []\n\t\t\t\t\ttry {\n\t\t\t\t\t\trequestLogger = this.createRequestLogger(req, undefined, false, matchedRequest.module, clientIp, span.context)\n\t\t\t\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ projectGroup: groupContainer.slug, project: matchedRequest.params.projectSlug })\n\t\t\t\t\t\tspan.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\t\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\t\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ user: authResult?.identityId })\n\t\t\t\t\t\tif (authResult) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tthrow new HttpErrorResponse(503, 'Server is shutting down')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, ws => resolve(ws)))\n\t\t\t\t\t\tconst establishedAt = performance.now()\n\t\t\t\t\t\tconst closed = new Promise<void>(resolve => ws.once('close', () => resolve()))\n\t\t\t\t\t\tws.on('error', e => {\n\t\t\t\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', 101)\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tawait this.closeWebsocket(ws)\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst context: WebSocketContext = {\n\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\tlogger: requestLogger,\n\t\t\t\t\t\t\ttimer,\n\t\t\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\trequest: req,\n\t\t\t\t\t\t\tclientIp: authResult?.clientIp ?? clientIp,\n\t\t\t\t\t\t\tauthResult,\n\t\t\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t\t\t\twaitUntil: promise => pendingWork.push(promise),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait matchedRequest.controller(context)\n\t\t\t\t\t\tif (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {\n\t\t\t\t\t\t\tws.close(1012)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { closed, pendingWork, establishedAt }\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst response = error instanceof HttpResponse ? error : new HttpErrorResponse(500, 'Internal server error')\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', response.code)\n\t\t\t\t\t\tif (response.code >= 500) {\n\t\t\t\t\t\t\tspan.setStatus('error')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(error instanceof HttpResponse)) {\n\t\t\t\t\t\t\tspan.recordException(error)\n\t\t\t\t\t\t\trequestLogger.error(error)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.sendRawHttpResponse(socket, response)\n\t\t\t\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tspan.end()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (established === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { closed, pendingWork, establishedAt } = established\n\t\t\trequestLogger.debug('Websocket connection established')\n\n\t\t\tawait closed\n\t\t\tawait Promise.allSettled(pendingWork)\n\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t\treturn await this.processHttpRequest(ctx, null)\n\t\t}\n\t\treturn await this.withIncomingTrace(ctx.req, async () => {\n\t\t\tconst span = this.tracer.startSpan(`HTTP ${ctx.request.method} ${matchedRequest.mask}`, {\n\t\t\t\tkind: 'server',\n\t\t\t\tattributes: {\n\t\t\t\t\t'http.request.method': ctx.request.method,\n\t\t\t\t\t'url.path': ctx.request.URL.pathname,\n\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (span.context.traceId === INVALID_TRACE_ID) {\n\t\t\t\treturn await this.processHttpRequest(ctx, matchedRequest, span)\n\t\t\t}\n\t\t\tconst endSpan = () => {\n\t\t\t\tctx.res.off('finish', endSpan)\n\t\t\t\tctx.res.off('close', closeSpan)\n\t\t\t\tspan.end()\n\t\t\t}\n\t\t\tconst closeSpan = () => {\n\t\t\t\tif (!ctx.res.writableFinished) {\n\t\t\t\t\tspan.setStatus('error', 'Response closed before completion')\n\t\t\t\t}\n\t\t\t\tendSpan()\n\t\t\t}\n\t\t\tctx.res.once('finish', endSpan)\n\t\t\tctx.res.once('close', closeSpan)\n\t\t\ttry {\n\t\t\t\treturn await this.tracer.withSpan(span, () => this.processHttpRequest(ctx, matchedRequest, span))\n\t\t\t} catch (error) {\n\t\t\t\tspan.recordException(error)\n\t\t\t\tspan.setStatus('error')\n\t\t\t\tendSpan()\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\tif (ctx.res.writableFinished) {\n\t\t\t\t\tendSpan()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async processHttpRequest(\n\t\tctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>,\n\t\tmatchedRequest: MatchedRequest<HttpController> | null,\n\t\tspan?: Span,\n\t) {\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tconst carriesCredentials = matchedRequest?.carriesCredentials ?? false\n\t\tconst loggedBody = maskRequestBody(ctx.request.body, carriesCredentials)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, loggedBody, carriesCredentials, matchedRequest?.module, clientIp, span?.context)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: loggedBody,\n\t\t\t\tquery: maskRequestBody(ctx.request.query, carriesCredentials),\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t\tproject: matchedRequest.params.projectSlug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\t\t\tspan?.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\tspan?.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t}\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\t\t\tif (authResult) {\n\t\t\t\tspan?.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t}\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tspan?.recordException(e)\n\t\t\t\tspan?.setStatus('error')\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tconst responseStatus = ctx.status\n\t\t\tif (responseStatus >= 500) {\n\t\t\t\tspan?.setStatus('error')\n\t\t\t}\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tconst requestDebugMode = (httpContext as HttpContext | null)?.requestDebugMode ?? false\n\t\t\tspan?.setAttribute('http.response.status_code', ctx.status)\n\t\t\tthis.sendTraceIdHeader(ctx, span, requestDebugMode)\n\t\t\tif (span !== undefined && span.context.traceId !== INVALID_TRACE_ID && ctx.response.body instanceof Readable) {\n\t\t\t\tconst contentLength = ctx.response.get('Content-Length')\n\t\t\t\tctx.body = createTracedReadable(ctx.response.body, this.tracer, span)\n\t\t\t\tif (contentLength !== '') {\n\t\t\t\t\tctx.set('Content-Length', contentLength)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate withIncomingTrace<T>(request: IncomingMessage, cb: () => T): T {\n\t\tconst incoming = resolveIncomingSpanContext(request, { mode: this.acceptIncomingTrace, trustedProxies: this.trustedProxies })\n\t\treturn incoming === undefined ? cb() : withSpanContext(incoming, cb)\n\t}\n\n\tprivate sendTraceIdHeader(ctx: KoaContext<{}>, span: Span | undefined, requestDebugMode: boolean): void {\n\t\tif (span === undefined || ctx.res.headersSent || span.context.traceId === INVALID_TRACE_ID) {\n\t\t\treturn\n\t\t}\n\t\tif (!this.traceIdResponseHeader && !this.debugMode && !requestDebugMode) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('x-contember-trace-id', span.context.traceId)\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tfor (const [name, value] of Object.entries(response.headers ?? {})) {\n\t\t\tctx.set(name, value)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate async closeWebsocket(ws: WebSocket): Promise<void> {\n\t\tif (ws.readyState === WebSocket.CLOSED) {\n\t\t\treturn\n\t\t}\n\t\tws.close(1012) // Service Restart\n\t\tawait new Promise<void>(resolve => {\n\t\t\t// ws only gives up on the close handshake after 30 s, which outlives a typical shutdown grace period\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tws.terminate()\n\t\t\t\tresolve()\n\t\t\t}, websocketCloseTimeoutMs)\n\t\t\tws.once('close', () => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve()\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t...response.headers,\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\t/** `loggedBody` must already be masked (`maskRequestBody`): it reaches logs and error reports. */\n\tprivate createRequestLogger(\n\t\trequest: IncomingMessage,\n\t\tloggedBody: unknown,\n\t\tcarriesCredentials: boolean,\n\t\tmodule?: string,\n\t\tremoteAddress?: string,\n\t\tspanContext?: SpanContext,\n\t): Logger {\n\t\tconst traceAttributes = spanContext === undefined || spanContext.traceId === INVALID_TRACE_ID\n\t\t\t? {}\n\t\t\t: { traceId: spanContext.traceId, spanId: spanContext.spanId }\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: maskRequestUri(request.url, carriesCredentials),\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t...traceAttributes,\n\t\t\t[LoggerRequestBody]: loggedBody,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer = createEventTimer(this.tracer, times, globalStart)\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module, mask: route.mask, carriesCredentials: route.carriesCredentials }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nexport type EventTime = { label: string; start: number; duration?: number }\n\nexport const createEventTimer = (tracer: Tracer, times: EventTime[], globalStart: number): Timer => (name, cb) => {\n\tconst start = performance.now()\n\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\ttimes.push(time)\n\tconst res = tracer.span(name, () => cb())\n\n\tif (res instanceof Promise) {\n\t\t;(async () => {\n\t\t\ttry {\n\t\t\t\tawait res\n\t\t\t} catch {\n\t\t\t} finally {\n\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t}\n\t\t})()\n\t}\n\treturn res\n}\n\nconst createTracedReadable = (body: Readable, tracer: Tracer, span: Span): Readable => {\n\tconst iterator = body[Symbol.asyncIterator]()\n\treturn Readable.from((async function*() {\n\t\tlet completed = false\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst next = await tracer.withSpan(span, () => iterator.next())\n\t\t\t\tif (next.done) {\n\t\t\t\t\tcompleted = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tyield next.value\n\t\t\t}\n\t\t} finally {\n\t\t\tif (!completed && iterator.return !== undefined) {\n\t\t\t\tawait tracer.withSpan(span, () => iterator.return?.())\n\t\t\t}\n\t\t}\n\t})())\n}\n\n/** @deprecated use `tracer` from the request context instead */\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t\ttracer: Tracer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t\twaitUntil(promise: Promise<void>): void\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["logger","noopTracer","module","WebSocketServer","createCompressionMiddleware","createRequestBodyMiddleware","defaultJsonBodyLimit","defaultFormBodyLimit","createCorsMiddleware","http","HttpErrorResponse","getClientIP","URL","pendingWork","ws","establishedAt","performance","closed","WebSocket","HttpResponse","INVALID_TRACE_ID","maskRequestBody","Readable","resolveIncomingSpanContext","withSpanContext","shouldForceHttpOk","isForceHttpOkRequested","remoteAddress","maskRequestUri","FingerCrossedLoggerHandler","cpuUsage","memoryUsage","pathToRegexp","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,0BAA0B;AAQzB,MAAM,YAAY;AAAA,EAaxB,YACkB,sBACA,cACA,WACA,SACAA,SACA,SAAiBC,sBACjC;AANgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAAD;AACA,SAAA,SAAA;AAlBlB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD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D;AAAA,EACD,IAAI;AACL;AA0DA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,EAAE,QAAQ,SAASU,aAAAA,aAAa,IAAI;AAE1C,QAAM,QAAQ,SAAS,KAA4B;AAClD,UAAMC,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACV,aAAOA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IACxF;AACA,WAAO;AAAA,EACR;AAEA,SAAO,CAAA,YAAW;AACjB,WAAO,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEO,MAAM,2CAA2B,aAAa;;;;"}
@@ -6,9 +6,9 @@ import Koa from "koa";
6
6
  import * as http from "node:http";
7
7
  import { WebSocketServer, WebSocket } from "ws";
8
8
  import { FingerCrossedLoggerHandler } from "@contember/logger";
9
- import koaCompress from "koa-compress";
10
- import bodyParser from "koa-bodyparser";
11
- import corsMiddleware from "@koa/cors";
9
+ import { createCompressionMiddleware } from "./compression.js";
10
+ import { createCorsMiddleware } from "./cors.js";
11
+ import { createRequestBodyMiddleware, defaultJsonBodyLimit, defaultFormBodyLimit } from "./requestBody.js";
12
12
  import { Readable } from "node:stream";
13
13
  import { URL } from "node:url";
14
14
  import { cpuUsage, memoryUsage } from "node:process";
@@ -91,13 +91,12 @@ class Application {
91
91
  for (const middleware of this.middlewares) {
92
92
  koa.use(middleware);
93
93
  }
94
- koa.use(koaCompress({
95
- br: false
94
+ koa.use(createCompressionMiddleware());
95
+ koa.use(createRequestBodyMiddleware({
96
+ json: this.serverConfig.http?.requestBodySize ?? defaultJsonBodyLimit,
97
+ form: defaultFormBodyLimit
96
98
  }));
97
- koa.use(bodyParser({
98
- jsonLimit: this.serverConfig.http?.requestBodySize || "1mb"
99
- }));
100
- koa.use(corsMiddleware({ exposeHeaders: ["X-Contember-Mutation"] }));
99
+ koa.use(createCorsMiddleware({ exposeHeaders: ["X-Contember-Mutation"] }));
101
100
  const versionMatch = this.version?.match(/^(0\.\d+|\d+)/);
102
101
  const versionSimplified = versionMatch?.[1] ?? "unknown";
103
102
  koa.use(async (ctx) => {
@@ -1 +1 @@
1
- {"version":3,"file":"application.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport koaCompress from 'koa-compress'\nimport bodyParser from 'koa-bodyparser'\nimport { ServerConfig } from '../config/config.js'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\nimport { INVALID_TRACE_ID, noopTracer, Span, SpanContext, Tracer, withSpanContext } from '@contember/telemetry'\nimport { AcceptIncomingTraceMode, resolveIncomingSpanContext } from '../telemetry/incomingTrace.js'\nimport { maskRequestBody, maskRequestUri } from './requestBodyMasking.js'\n\nconst websocketCloseTimeoutMs = 5_000\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type RouteOptions = {\n\t/** The route receives engine credentials (passwords, OTP codes, tokens), so its body and URI are masked in logs. */\n\treadonly carriesCredentials?: boolean\n}\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\tprivate acceptIncomingTrace: AcceptIncomingTraceMode\n\tprivate traceIdResponseHeader: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t\tprivate readonly tracer: Tracer = noopTracer,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t\tthis.acceptIncomingTrace = serverConfig.telemetry?.traces?.acceptIncoming ?? 'trusted-proxies'\n\t\tthis.traceIdResponseHeader = serverConfig.telemetry?.traces?.traceIdResponseHeader ?? false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController, options: RouteOptions = {}): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: options.carriesCredentials ?? false,\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tlet closing = false\n\t\tkoa.use(async (ctx, next) => {\n\t\t\tif (closing) {\n\t\t\t\tctx.status = 503\n\t\t\t\tctx.set('Connection', 'close')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tawait next()\n\t\t})\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(koaCompress({\n\t\t\tbr: false,\n\t\t}))\n\t\tkoa.use(bodyParser({\n\t\t\tjsonLimit: this.serverConfig.http?.requestBodySize || '1mb',\n\t\t}))\n\t\tkoa.use(corsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst activeHttpRequests = new Set<Promise<void>>()\n\t\tconst handleHttpRequest = koa.callback()\n\t\tconst server = http.createServer((request, response) => {\n\t\t\tif (closing) {\n\t\t\t\thandleHttpRequest(request, response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlet resolveRequest = () => {}\n\t\t\tconst completed = new Promise<void>(resolve => {\n\t\t\t\tresolveRequest = resolve\n\t\t\t})\n\t\t\tactiveHttpRequests.add(completed)\n\t\t\tconst complete = () => {\n\t\t\t\tresponse.off('finish', complete)\n\t\t\t\tresponse.off('close', complete)\n\t\t\t\tactiveHttpRequests.delete(completed)\n\t\t\t\tresolveRequest()\n\t\t\t}\n\t\t\tresponse.once('finish', complete)\n\t\t\tresponse.once('close', complete)\n\t\t\thandleHttpRequest(request, response)\n\t\t})\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\tif (closing) {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(503, 'Server is shutting down'))\n\t\t\t\treturn\n\t\t\t}\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head).finally(() => socket.destroy()))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tclosing = true\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all([...wsRequests, ...activeHttpRequests])\n\t\t\t\tif (process.versions.bun !== undefined) {\n\t\t\t\t\t// Bun does not finish server.close() after a WebSocket upgrade unless all connections are closed first.\n\t\t\t\t\tserver.closeAllConnections()\n\t\t\t\t} else {\n\t\t\t\t\tserver.closeIdleConnections()\n\t\t\t\t}\n\t\t\t\tif (server.listening) {\n\t\t\t\t\tawait new Promise<void>(resolve =>\n\t\t\t\t\t\tserver.close(error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tthis.logger.error(error)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\tconst established = await this.withIncomingTrace(req, async () => {\n\t\t\t\tconst span = this.tracer.startSpan(`WS ${matchedRequest.mask}`, {\n\t\t\t\t\tkind: 'server',\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t'http.request.method': req.method ?? 'GET',\n\t\t\t\t\t\t'url.path': url.pathname,\n\t\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn await this.tracer.withSpan(span, async () => {\n\t\t\t\t\tconst pendingWork: Promise<void>[] = []\n\t\t\t\t\ttry {\n\t\t\t\t\t\trequestLogger = this.createRequestLogger(req, undefined, false, matchedRequest.module, clientIp, span.context)\n\t\t\t\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ projectGroup: groupContainer.slug, project: matchedRequest.params.projectSlug })\n\t\t\t\t\t\tspan.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\t\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\t\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ user: authResult?.identityId })\n\t\t\t\t\t\tif (authResult) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tthrow new HttpErrorResponse(503, 'Server is shutting down')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, ws => resolve(ws)))\n\t\t\t\t\t\tconst establishedAt = performance.now()\n\t\t\t\t\t\tconst closed = new Promise<void>(resolve => ws.once('close', () => resolve()))\n\t\t\t\t\t\tws.on('error', e => {\n\t\t\t\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', 101)\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tawait this.closeWebsocket(ws)\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst context: WebSocketContext = {\n\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\tlogger: requestLogger,\n\t\t\t\t\t\t\ttimer,\n\t\t\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\trequest: req,\n\t\t\t\t\t\t\tclientIp: authResult?.clientIp ?? clientIp,\n\t\t\t\t\t\t\tauthResult,\n\t\t\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t\t\t\twaitUntil: promise => pendingWork.push(promise),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait matchedRequest.controller(context)\n\t\t\t\t\t\tif (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {\n\t\t\t\t\t\t\tws.close(1012)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { closed, pendingWork, establishedAt }\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst response = error instanceof HttpResponse ? error : new HttpErrorResponse(500, 'Internal server error')\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', response.code)\n\t\t\t\t\t\tif (response.code >= 500) {\n\t\t\t\t\t\t\tspan.setStatus('error')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(error instanceof HttpResponse)) {\n\t\t\t\t\t\t\tspan.recordException(error)\n\t\t\t\t\t\t\trequestLogger.error(error)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.sendRawHttpResponse(socket, response)\n\t\t\t\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tspan.end()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (established === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { closed, pendingWork, establishedAt } = established\n\t\t\trequestLogger.debug('Websocket connection established')\n\n\t\t\tawait closed\n\t\t\tawait Promise.allSettled(pendingWork)\n\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t\treturn await this.processHttpRequest(ctx, null)\n\t\t}\n\t\treturn await this.withIncomingTrace(ctx.req, async () => {\n\t\t\tconst span = this.tracer.startSpan(`HTTP ${ctx.request.method} ${matchedRequest.mask}`, {\n\t\t\t\tkind: 'server',\n\t\t\t\tattributes: {\n\t\t\t\t\t'http.request.method': ctx.request.method,\n\t\t\t\t\t'url.path': ctx.request.URL.pathname,\n\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (span.context.traceId === INVALID_TRACE_ID) {\n\t\t\t\treturn await this.processHttpRequest(ctx, matchedRequest, span)\n\t\t\t}\n\t\t\tconst endSpan = () => {\n\t\t\t\tctx.res.off('finish', endSpan)\n\t\t\t\tctx.res.off('close', closeSpan)\n\t\t\t\tspan.end()\n\t\t\t}\n\t\t\tconst closeSpan = () => {\n\t\t\t\tif (!ctx.res.writableFinished) {\n\t\t\t\t\tspan.setStatus('error', 'Response closed before completion')\n\t\t\t\t}\n\t\t\t\tendSpan()\n\t\t\t}\n\t\t\tctx.res.once('finish', endSpan)\n\t\t\tctx.res.once('close', closeSpan)\n\t\t\ttry {\n\t\t\t\treturn await this.tracer.withSpan(span, () => this.processHttpRequest(ctx, matchedRequest, span))\n\t\t\t} catch (error) {\n\t\t\t\tspan.recordException(error)\n\t\t\t\tspan.setStatus('error')\n\t\t\t\tendSpan()\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\tif (ctx.res.writableFinished) {\n\t\t\t\t\tendSpan()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async processHttpRequest(\n\t\tctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>,\n\t\tmatchedRequest: MatchedRequest<HttpController> | null,\n\t\tspan?: Span,\n\t) {\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tconst carriesCredentials = matchedRequest?.carriesCredentials ?? false\n\t\tconst loggedBody = maskRequestBody(ctx.request.body, carriesCredentials)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, loggedBody, carriesCredentials, matchedRequest?.module, clientIp, span?.context)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: loggedBody,\n\t\t\t\tquery: maskRequestBody(ctx.request.query, carriesCredentials),\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t\tproject: matchedRequest.params.projectSlug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\t\t\tspan?.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\tspan?.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t}\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\t\t\tif (authResult) {\n\t\t\t\tspan?.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t}\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tspan?.recordException(e)\n\t\t\t\tspan?.setStatus('error')\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tconst responseStatus = ctx.status\n\t\t\tif (responseStatus >= 500) {\n\t\t\t\tspan?.setStatus('error')\n\t\t\t}\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tconst requestDebugMode = (httpContext as HttpContext | null)?.requestDebugMode ?? false\n\t\t\tspan?.setAttribute('http.response.status_code', ctx.status)\n\t\t\tthis.sendTraceIdHeader(ctx, span, requestDebugMode)\n\t\t\tif (span !== undefined && span.context.traceId !== INVALID_TRACE_ID && ctx.response.body instanceof Readable) {\n\t\t\t\tconst contentLength = ctx.response.get('Content-Length')\n\t\t\t\tctx.body = createTracedReadable(ctx.response.body, this.tracer, span)\n\t\t\t\tif (contentLength !== '') {\n\t\t\t\t\tctx.set('Content-Length', contentLength)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate withIncomingTrace<T>(request: IncomingMessage, cb: () => T): T {\n\t\tconst incoming = resolveIncomingSpanContext(request, { mode: this.acceptIncomingTrace, trustedProxies: this.trustedProxies })\n\t\treturn incoming === undefined ? cb() : withSpanContext(incoming, cb)\n\t}\n\n\tprivate sendTraceIdHeader(ctx: KoaContext<{}>, span: Span | undefined, requestDebugMode: boolean): void {\n\t\tif (span === undefined || ctx.res.headersSent || span.context.traceId === INVALID_TRACE_ID) {\n\t\t\treturn\n\t\t}\n\t\tif (!this.traceIdResponseHeader && !this.debugMode && !requestDebugMode) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('x-contember-trace-id', span.context.traceId)\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tfor (const [name, value] of Object.entries(response.headers ?? {})) {\n\t\t\tctx.set(name, value)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate async closeWebsocket(ws: WebSocket): Promise<void> {\n\t\tif (ws.readyState === WebSocket.CLOSED) {\n\t\t\treturn\n\t\t}\n\t\tws.close(1012) // Service Restart\n\t\tawait new Promise<void>(resolve => {\n\t\t\t// ws only gives up on the close handshake after 30 s, which outlives a typical shutdown grace period\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tws.terminate()\n\t\t\t\tresolve()\n\t\t\t}, websocketCloseTimeoutMs)\n\t\t\tws.once('close', () => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve()\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t...response.headers,\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\t/** `loggedBody` must already be masked (`maskRequestBody`): it reaches logs and error reports. */\n\tprivate createRequestLogger(\n\t\trequest: IncomingMessage,\n\t\tloggedBody: unknown,\n\t\tcarriesCredentials: boolean,\n\t\tmodule?: string,\n\t\tremoteAddress?: string,\n\t\tspanContext?: SpanContext,\n\t): Logger {\n\t\tconst traceAttributes = spanContext === undefined || spanContext.traceId === INVALID_TRACE_ID\n\t\t\t? {}\n\t\t\t: { traceId: spanContext.traceId, spanId: spanContext.spanId }\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: maskRequestUri(request.url, carriesCredentials),\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t...traceAttributes,\n\t\t\t[LoggerRequestBody]: loggedBody,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer = createEventTimer(this.tracer, times, globalStart)\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module, mask: route.mask, carriesCredentials: route.carriesCredentials }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nexport type EventTime = { label: string; start: number; duration?: number }\n\nexport const createEventTimer = (tracer: Tracer, times: EventTime[], globalStart: number): Timer => (name, cb) => {\n\tconst start = performance.now()\n\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\ttimes.push(time)\n\tconst res = tracer.span(name, () => cb())\n\n\tif (res instanceof Promise) {\n\t\t;(async () => {\n\t\t\ttry {\n\t\t\t\tawait res\n\t\t\t} catch {\n\t\t\t} finally {\n\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t}\n\t\t})()\n\t}\n\treturn res\n}\n\nconst createTracedReadable = (body: Readable, tracer: Tracer, span: Span): Readable => {\n\tconst iterator = body[Symbol.asyncIterator]()\n\treturn Readable.from((async function*() {\n\t\tlet completed = false\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst next = await tracer.withSpan(span, () => iterator.next())\n\t\t\t\tif (next.done) {\n\t\t\t\t\tcompleted = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tyield next.value\n\t\t\t}\n\t\t} finally {\n\t\t\tif (!completed && iterator.return !== undefined) {\n\t\t\t\tawait tracer.withSpan(span, () => iterator.return?.())\n\t\t\t}\n\t\t}\n\t})())\n}\n\n/** @deprecated use `tracer` from the request context instead */\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t\ttracer: Tracer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t\twaitUntil(promise: Promise<void>): void\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["pendingWork","ws","establishedAt","closed","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,0BAA0B;AAQzB,MAAM,YAAY;AAAA,EAaxB,YACkB,sBACA,cACA,WACA,SACA,QACA,SAAiB,YACjC;AANgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AACA,SAAA,SAAA;AAlBlB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;A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.js","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types.js'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common/index.js'\nimport Koa from 'koa'\nimport * as http from 'node:http'\nimport { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { WebSocket, WebSocketServer } from 'ws'\nimport { FingerCrossedLoggerHandler, Logger } from '@contember/logger'\nimport { ServerConfig } from '../config/config.js'\nimport { createCompressionMiddleware } from './compression.js'\nimport { createCorsMiddleware } from './cors.js'\nimport { createRequestBodyMiddleware, defaultFormBodyLimit, defaultJsonBodyLimit } from './requestBody.js'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver.js'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer.js'\nimport { URL } from 'node:url'\nimport { cpuUsage, memoryUsage } from 'node:process'\nimport { performance } from 'node:perf_hooks'\nimport { getClientIP } from '../utils/remoteAddress.js'\nimport { isForceHttpOkRequested, shouldForceHttpOk } from './forceHttpOk.js'\nimport { INVALID_TRACE_ID, noopTracer, Span, SpanContext, Tracer, withSpanContext } from '@contember/telemetry'\nimport { AcceptIncomingTraceMode, resolveIncomingSpanContext } from '../telemetry/incomingTrace.js'\nimport { maskRequestBody, maskRequestUri } from './requestBodyMasking.js'\n\nconst websocketCloseTimeoutMs = 5_000\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type RouteOptions = {\n\t/** The route receives engine credentials (passwords, OTP codes, tokens), so its body and URI are masked in logs. */\n\treadonly carriesCredentials?: boolean\n}\nexport class Application {\n\tprivate middlewares: KoaMiddleware<any>[] = []\n\n\tprivate routes: Route<HttpController>[] = []\n\tprivate internalRoutes: Route<InternalHttpController>[] = []\n\tprivate websocketRoutes: Route<WebSocketController>[] = []\n\n\tprivate suppressAccessLog: boolean | RegExp\n\tprivate trustedProxies: string[]\n\tprivate forceHttpOkEnabled: boolean\n\tprivate acceptIncomingTrace: AcceptIncomingTraceMode\n\tprivate traceIdResponseHeader: boolean\n\n\tconstructor(\n\t\tprivate readonly projectGroupResolver: ProjectGroupResolver,\n\t\tprivate readonly serverConfig: ServerConfig,\n\t\tprivate readonly debugMode: boolean,\n\t\tprivate readonly version: string | undefined,\n\t\tprivate readonly logger: Logger,\n\t\tprivate readonly tracer: Tracer = noopTracer,\n\t) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : false\n\t\tthis.trustedProxies = serverConfig.http?.trustedProxies ?? []\n\t\tthis.forceHttpOkEnabled = serverConfig.http?.responseStatusHeader ?? true\n\t\tthis.acceptIncomingTrace = serverConfig.telemetry?.traces?.acceptIncoming ?? 'trusted-proxies'\n\t\tthis.traceIdResponseHeader = serverConfig.telemetry?.traces?.traceIdResponseHeader ?? false\n\t}\n\n\taddMiddleware(middleware: KoaMiddleware<any>) {\n\t\tthis.middlewares.push(middleware)\n\t}\n\n\tpublic addRoute(module: string, mask: string, controller: HttpController, options: RouteOptions = {}): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: options.carriesCredentials ?? false,\n\t\t})\n\t}\n\n\tpublic addInternalRoute(module: string, mask: string, controller: InternalHttpController): void {\n\t\tthis.internalRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tpublic addWebsocketRoute(module: string, mask: string, controller: WebSocketController): void {\n\t\tthis.websocketRoutes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmask,\n\t\t\tmatch: createRequestMatcher(mask),\n\t\t\tcarriesCredentials: false,\n\t\t})\n\t}\n\n\tasync listen(): Promise<RunningApplication> {\n\t\tconst koa = new Koa()\n\t\tconst wss = new WebSocketServer({ noServer: true })\n\t\tlet closing = false\n\t\tkoa.use(async (ctx, next) => {\n\t\t\tif (closing) {\n\t\t\t\tctx.status = 503\n\t\t\t\tctx.set('Connection', 'close')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tawait next()\n\t\t})\n\t\tfor (const middleware of this.middlewares) {\n\t\t\tkoa.use(middleware)\n\t\t}\n\t\tkoa.use(createCompressionMiddleware())\n\t\tkoa.use(createRequestBodyMiddleware({\n\t\t\tjson: this.serverConfig.http?.requestBodySize ?? defaultJsonBodyLimit,\n\t\t\tform: defaultFormBodyLimit,\n\t\t}))\n\t\tkoa.use(createCorsMiddleware({ exposeHeaders: ['X-Contember-Mutation'] }))\n\t\tconst versionMatch = this.version?.match(/^(0\\.\\d+|\\d+)/)\n\t\tconst versionSimplified = versionMatch?.[1] ?? 'unknown'\n\t\tkoa.use(async ctx => {\n\t\t\tctx.response.set('X-Powered-By', `Contember ${versionSimplified}` + (this.debugMode ? '-dev' : ''))\n\t\t\tawait this.handleHttpRequest(ctx)\n\t\t})\n\n\t\tconst activeHttpRequests = new Set<Promise<void>>()\n\t\tconst handleHttpRequest = koa.callback()\n\t\tconst server = http.createServer((request, response) => {\n\t\t\tif (closing) {\n\t\t\t\thandleHttpRequest(request, response)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlet resolveRequest = () => {}\n\t\t\tconst completed = new Promise<void>(resolve => {\n\t\t\t\tresolveRequest = resolve\n\t\t\t})\n\t\t\tactiveHttpRequests.add(completed)\n\t\t\tconst complete = () => {\n\t\t\t\tresponse.off('finish', complete)\n\t\t\t\tresponse.off('close', complete)\n\t\t\t\tactiveHttpRequests.delete(completed)\n\t\t\t\tresolveRequest()\n\t\t\t}\n\t\t\tresponse.once('finish', complete)\n\t\t\tresponse.once('close', complete)\n\t\t\thandleHttpRequest(request, response)\n\t\t})\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\tif (closing) {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(503, 'Server is shutting down'))\n\t\t\t\treturn\n\t\t\t}\n\t\t\twsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head).finally(() => socket.destroy()))\n\t\t})\n\t\tawait new Promise<void>(resolve => {\n\t\t\tserver.listen(this.serverConfig.port, () => resolve())\n\t\t})\n\n\t\treturn {\n\t\t\tserver,\n\t\t\tclose: async () => {\n\t\t\t\tclosing = true\n\t\t\t\tabortController.abort()\n\t\t\t\tawait Promise.all([...wsRequests, ...activeHttpRequests])\n\t\t\t\tif (process.versions.bun !== undefined) {\n\t\t\t\t\t// Bun does not finish server.close() after a WebSocket upgrade unless all connections are closed first.\n\t\t\t\t\tserver.closeAllConnections()\n\t\t\t\t} else {\n\t\t\t\t\tserver.closeIdleConnections()\n\t\t\t\t}\n\t\t\t\tif (server.listening) {\n\t\t\t\t\tawait new Promise<void>(resolve =>\n\t\t\t\t\t\tserver.close(error => {\n\t\t\t\t\t\t\tif (error) {\n\t\t\t\t\t\t\t\tthis.logger.error(error)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tresolve()\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n\n\tprivate async handleWebsocketRequest(\n\t\twss: WebSocketServer,\n\t\tabortSignal: AbortSignal,\n\t\treq: IncomingMessage,\n\t\tsocket: stream.Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\t\tconst clientIp = getClientIP(req, this.trustedProxies)\n\t\ttry {\n\t\t\tconst url = new URL(req.url ?? '/', `http://${req.headers.host}`)\n\t\t\tconst matchedRequest = this.matchRequest(this.websocketRoutes, url)\n\t\t\tif (!matchedRequest) {\n\t\t\t\tthrow new HttpErrorResponse(404, 'Route not found')\n\t\t\t}\n\t\t\tconst established = await this.withIncomingTrace(req, async () => {\n\t\t\t\tconst span = this.tracer.startSpan(`WS ${matchedRequest.mask}`, {\n\t\t\t\t\tkind: 'server',\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t'http.request.method': req.method ?? 'GET',\n\t\t\t\t\t\t'url.path': url.pathname,\n\t\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn await this.tracer.withSpan(span, async () => {\n\t\t\t\t\tconst pendingWork: Promise<void>[] = []\n\t\t\t\t\ttry {\n\t\t\t\t\t\trequestLogger = this.createRequestLogger(req, undefined, false, matchedRequest.module, clientIp, span.context)\n\t\t\t\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ projectGroup: groupContainer.slug, project: matchedRequest.params.projectSlug })\n\t\t\t\t\t\tspan.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\t\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer, clientIp })\n\t\t\t\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\t\t\t\trequestLogger = requestLogger.child({ user: authResult?.identityId })\n\t\t\t\t\t\tif (authResult) {\n\t\t\t\t\t\t\tspan.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tthrow new HttpErrorResponse(503, 'Server is shutting down')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, ws => resolve(ws)))\n\t\t\t\t\t\tconst establishedAt = performance.now()\n\t\t\t\t\t\tconst closed = new Promise<void>(resolve => ws.once('close', () => resolve()))\n\t\t\t\t\t\tws.on('error', e => {\n\t\t\t\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t})\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', 101)\n\t\t\t\t\t\tif (abortSignal.aborted) {\n\t\t\t\t\t\t\tawait this.closeWebsocket(ws)\n\t\t\t\t\t\t\treturn undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst context: WebSocketContext = {\n\t\t\t\t\t\t\tws,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\tlogger: requestLogger,\n\t\t\t\t\t\t\ttimer,\n\t\t\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\trequest: req,\n\t\t\t\t\t\t\tclientIp: authResult?.clientIp ?? clientIp,\n\t\t\t\t\t\t\tauthResult,\n\t\t\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t\t\t\twaitUntil: promise => pendingWork.push(promise),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait matchedRequest.controller(context)\n\t\t\t\t\t\tif (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {\n\t\t\t\t\t\t\tws.close(1012)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn { closed, pendingWork, establishedAt }\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst response = error instanceof HttpResponse ? error : new HttpErrorResponse(500, 'Internal server error')\n\t\t\t\t\t\tspan.setAttribute('http.response.status_code', response.code)\n\t\t\t\t\t\tif (response.code >= 500) {\n\t\t\t\t\t\t\tspan.setStatus('error')\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!(error instanceof HttpResponse)) {\n\t\t\t\t\t\t\tspan.recordException(error)\n\t\t\t\t\t\t\trequestLogger.error(error)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.sendRawHttpResponse(socket, response)\n\t\t\t\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t\t\t\t\treturn undefined\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tspan.end()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (established === undefined) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { closed, pendingWork, establishedAt } = established\n\t\t\trequestLogger.debug('Websocket connection established')\n\n\t\t\tawait closed\n\t\t\tawait Promise.allSettled(pendingWork)\n\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\twebsocketOpenMs: performance.now() - establishedAt,\n\t\t\t})\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendRawHttpResponse(socket, e)\n\t\t\t} else {\n\t\t\t\tthis.sendRawHttpResponse(socket, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection failed')\n\t\t} finally {\n\t\t\tsendTimer({\n\t\t\t\treq,\n\t\t\t\trequestDebugMode: false,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t}\n\t}\n\n\tprivate async handleHttpRequest(ctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>) {\n\t\tconst matchedRequest = this.matchRequest(this.routes, ctx.request.URL)\n\t\tif (!matchedRequest) {\n\t\t\tconst internalMatchedRequest = this.matchRequest(this.internalRoutes, ctx.request.URL)\n\t\t\tif (internalMatchedRequest) {\n\t\t\t\treturn await this.handleInternalRequest(internalMatchedRequest, ctx)\n\t\t\t}\n\t\t\treturn await this.processHttpRequest(ctx, null)\n\t\t}\n\t\treturn await this.withIncomingTrace(ctx.req, async () => {\n\t\t\tconst span = this.tracer.startSpan(`HTTP ${ctx.request.method} ${matchedRequest.mask}`, {\n\t\t\t\tkind: 'server',\n\t\t\t\tattributes: {\n\t\t\t\t\t'http.request.method': ctx.request.method,\n\t\t\t\t\t'url.path': ctx.request.URL.pathname,\n\t\t\t\t\t'contember.module': matchedRequest.module,\n\t\t\t\t},\n\t\t\t})\n\t\t\tif (span.context.traceId === INVALID_TRACE_ID) {\n\t\t\t\treturn await this.processHttpRequest(ctx, matchedRequest, span)\n\t\t\t}\n\t\t\tconst endSpan = () => {\n\t\t\t\tctx.res.off('finish', endSpan)\n\t\t\t\tctx.res.off('close', closeSpan)\n\t\t\t\tspan.end()\n\t\t\t}\n\t\t\tconst closeSpan = () => {\n\t\t\t\tif (!ctx.res.writableFinished) {\n\t\t\t\t\tspan.setStatus('error', 'Response closed before completion')\n\t\t\t\t}\n\t\t\t\tendSpan()\n\t\t\t}\n\t\t\tctx.res.once('finish', endSpan)\n\t\t\tctx.res.once('close', closeSpan)\n\t\t\ttry {\n\t\t\t\treturn await this.tracer.withSpan(span, () => this.processHttpRequest(ctx, matchedRequest, span))\n\t\t\t} catch (error) {\n\t\t\t\tspan.recordException(error)\n\t\t\t\tspan.setStatus('error')\n\t\t\t\tendSpan()\n\t\t\t\tthrow error\n\t\t\t} finally {\n\t\t\t\tif (ctx.res.writableFinished) {\n\t\t\t\t\tendSpan()\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate async processHttpRequest(\n\t\tctx: KoaContext<{ module?: string; projectGroup?: string; project?: string }>,\n\t\tmatchedRequest: MatchedRequest<HttpController> | null,\n\t\tspan?: Span,\n\t) {\n\t\tlet httpContext: HttpContext | null = null\n\t\tconst clientIp = getClientIP(ctx.req, this.trustedProxies)\n\t\tconst carriesCredentials = matchedRequest?.carriesCredentials ?? false\n\t\tconst loggedBody = maskRequestBody(ctx.request.body, carriesCredentials)\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, loggedBody, carriesCredentials, matchedRequest?.module, clientIp, span?.context)\n\t\tconst { timer, send: sendTimer } = this.createTimer()\n\n\t\ttry {\n\t\t\tif (!matchedRequest) {\n\t\t\t\treturn this.sendHttpResponse(ctx, new HttpErrorResponse(404, 'Route not found'))\n\t\t\t}\n\t\t\trequestLogger.debug('Request processing started', {\n\t\t\t\tbody: loggedBody,\n\t\t\t\tquery: maskRequestBody(ctx.request.query, carriesCredentials),\n\t\t\t})\n\n\t\t\t// todo: solve without koa context (required by prom metrics)\n\t\t\tctx.state.module = matchedRequest.module\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: ctx.req })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t\tproject: matchedRequest.params.projectSlug,\n\t\t\t})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\t\t\tspan?.setAttribute('contember.project_group', groupContainer.slug ?? 'unknown')\n\t\t\tif (matchedRequest.params.projectSlug !== undefined) {\n\t\t\t\tspan?.setAttribute('contember.project', matchedRequest.params.projectSlug)\n\t\t\t}\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer, clientIp })\n\t\t\trequestLogger.debug('User authenticated', { authResult })\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tuser: authResult?.identityId,\n\t\t\t})\n\t\t\tif (authResult) {\n\t\t\t\tspan?.setAttribute('contember.identity_id', authResult.identityId)\n\t\t\t}\n\n\t\t\tconst effectiveClientIp = authResult?.clientIp ?? clientIp\n\n\t\t\tconst response = await requestLogger.scope(async logger => {\n\t\t\t\thttpContext = {\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tclientIp: effectiveClientIp,\n\t\t\t\t\tlogger,\n\t\t\t\t\ttimer,\n\t\t\t\t\ttracer: this.tracer,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\trequestDebugMode: false,\n\t\t\t\t\tauthResult,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\t}\n\t\t\t\treturn await matchedRequest.controller(httpContext)\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tspan?.recordException(e)\n\t\t\t\tspan?.setStatus('error')\n\t\t\t\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\n\t\t\tconst responseStatus = ctx.status\n\t\t\tif (responseStatus >= 500) {\n\t\t\t\tspan?.setStatus('error')\n\t\t\t}\n\t\t\tthis.maybeForceHttpOk(ctx, matchedRequest?.module)\n\t\t\tconst requestDebugMode = (httpContext as HttpContext | null)?.requestDebugMode ?? false\n\t\t\tspan?.setAttribute('http.response.status_code', ctx.status)\n\t\t\tthis.sendTraceIdHeader(ctx, span, requestDebugMode)\n\t\t\tif (span !== undefined && span.context.traceId !== INVALID_TRACE_ID && ctx.response.body instanceof Readable) {\n\t\t\t\tconst contentLength = ctx.response.get('Content-Length')\n\t\t\t\tctx.body = createTracedReadable(ctx.response.body, this.tracer, span)\n\t\t\t\tif (contentLength !== '') {\n\t\t\t\t\tctx.set('Content-Length', contentLength)\n\t\t\t\t}\n\t\t\t}\n\t\t\tsendTimer({\n\t\t\t\treq: ctx.req,\n\t\t\t\tresponse: ctx.res,\n\t\t\t\tbody: ctx.response.body,\n\t\t\t\trequestDebugMode,\n\t\t\t\tlogger: requestLogger,\n\t\t\t})\n\t\t\trequestLogger.debug('Request processing finished')\n\t\t}\n\t}\n\n\tprivate withIncomingTrace<T>(request: IncomingMessage, cb: () => T): T {\n\t\tconst incoming = resolveIncomingSpanContext(request, { mode: this.acceptIncomingTrace, trustedProxies: this.trustedProxies })\n\t\treturn incoming === undefined ? cb() : withSpanContext(incoming, cb)\n\t}\n\n\tprivate sendTraceIdHeader(ctx: KoaContext<{}>, span: Span | undefined, requestDebugMode: boolean): void {\n\t\tif (span === undefined || ctx.res.headersSent || span.context.traceId === INVALID_TRACE_ID) {\n\t\t\treturn\n\t\t}\n\t\tif (!this.traceIdResponseHeader && !this.debugMode && !requestDebugMode) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('x-contember-trace-id', span.context.traceId)\n\t}\n\n\tprivate async handleInternalRequest(matchedRequest: MatchedRequest<InternalHttpController>, ctx: KoaContext<{ module?: string }>) {\n\t\ttry {\n\t\t\tconst response = await this.logger.scope(async logger => {\n\t\t\t\treturn await matchedRequest.controller({\n\t\t\t\t\tkoa: ctx,\n\t\t\t\t\tclientIp: getClientIP(ctx.req, this.trustedProxies),\n\t\t\t\t\tbody: ctx.request.body,\n\t\t\t\t\turl: ctx.request.URL,\n\t\t\t\t\tlogger,\n\t\t\t\t\trequest: ctx.req,\n\t\t\t\t\tresponse: ctx.res,\n\t\t\t\t\tparams: matchedRequest.params,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (response) {\n\t\t\t\tthis.sendHttpResponse(ctx, response)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (e instanceof HttpResponse) {\n\t\t\t\tthis.sendHttpResponse(ctx, e)\n\t\t\t} else {\n\t\t\t\tthis.sendHttpResponse(ctx, new HttpErrorResponse(500, 'Internal server error'))\n\t\t\t\tthis.logger.error(e)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * When the X-Contember-Force-Ok header is present (and the capability is enabled in config),\n\t * coerce the HTTP status of a GraphQL API response (content/tenant/system) to 200, keeping the\n\t * error information in the JSON body. Scoped to those modules so non-JSON / non-GraphQL responses\n\t * are not mislabeled. Default behavior (real status codes) is preserved when the header is absent.\n\t */\n\tprivate maybeForceHttpOk(ctx: KoaContext<{}>, module: string | undefined) {\n\t\tconst coerce = shouldForceHttpOk({\n\t\t\tenabled: this.forceHttpOkEnabled,\n\t\t\tstatus: ctx.status,\n\t\t\tmodule,\n\t\t\thasBody: ctx.body !== undefined && ctx.body !== null,\n\t\t\theaderRequested: isForceHttpOkRequested(ctx.req),\n\t\t})\n\t\tif (!coerce) {\n\t\t\treturn\n\t\t}\n\t\tctx.set('X-Contember-Original-Status', String(ctx.status))\n\t\tctx.status = 200\n\t}\n\n\tprivate sendHttpResponse(ctx: KoaContext<{}>, response: HttpResponse) {\n\t\tif (response.contentType) {\n\t\t\tctx.set('Content-type', response.contentType)\n\t\t}\n\t\tfor (const [name, value] of Object.entries(response.headers ?? {})) {\n\t\t\tctx.set(name, value)\n\t\t}\n\t\tctx.status = response.code\n\t\tif (response.body !== undefined) {\n\t\t\tctx.body = response.body\n\t\t}\n\t}\n\n\tprivate async closeWebsocket(ws: WebSocket): Promise<void> {\n\t\tif (ws.readyState === WebSocket.CLOSED) {\n\t\t\treturn\n\t\t}\n\t\tws.close(1012) // Service Restart\n\t\tawait new Promise<void>(resolve => {\n\t\t\t// ws only gives up on the close handshake after 30 s, which outlives a typical shutdown grace period\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\tws.terminate()\n\t\t\t\tresolve()\n\t\t\t}, websocketCloseTimeoutMs)\n\t\t\tws.once('close', () => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tresolve()\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\n\t\t\t...response.headers,\n\t\t\t'Connection': 'close',\n\t\t\t'Content-Type': response.contentType ?? 'text/plain',\n\t\t\t'Content-Length': String(response.body?.length ?? 0),\n\t\t}\n\n\t\tsocket.once('finish', socket.destroy)\n\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${response.code} ${http.STATUS_CODES[response.code]}\\r\\n`\n\t\t\t\t+ Object.keys(headers)\n\t\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t\t.join('\\r\\n')\n\t\t\t\t+ '\\r\\n\\r\\n'\n\t\t\t\t+ (response.body ?? ''),\n\t\t)\n\t}\n\n\t/** `loggedBody` must already be masked (`maskRequestBody`): it reaches logs and error reports. */\n\tprivate createRequestLogger(\n\t\trequest: IncomingMessage,\n\t\tloggedBody: unknown,\n\t\tcarriesCredentials: boolean,\n\t\tmodule?: string,\n\t\tremoteAddress?: string,\n\t\tspanContext?: SpanContext,\n\t): Logger {\n\t\tconst traceAttributes = spanContext === undefined || spanContext.traceId === INVALID_TRACE_ID\n\t\t\t? {}\n\t\t\t: { traceId: spanContext.traceId, spanId: spanContext.spanId }\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: maskRequestUri(request.url, carriesCredentials),\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\tremoteAddress,\n\t\t\t...traceAttributes,\n\t\t\t[LoggerRequestBody]: loggedBody,\n\t\t}, {\n\t\t\thandler: FingerCrossedLoggerHandler.factory(),\n\t\t})\n\t}\n\n\tprivate createTimer() {\n\t\tconst times: EventTime[] = []\n\t\tconst globalStart = performance.now()\n\t\tconst cpuUsageStart = cpuUsage()\n\t\tconst memoryUsageStart = memoryUsage()\n\t\tconst timer = createEventTimer(this.tracer, times, globalStart)\n\n\t\tconst send = (ctx: { req: IncomingMessage; response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {\n\t\t\tif (ctx.response && !ctx.response.headersSent && (ctx.requestDebugMode || this.debugMode) && times.length) {\n\t\t\t\tctx.response.setHeader('server-timing', times.map(it => `${it.label};desc=\"${it.label} T+${it.start}\";dur=${it.duration ?? -1}`).join(', '))\n\t\t\t}\n\n\t\t\tconst emit = () => {\n\t\t\t\tconst total = performance.now() - globalStart\n\t\t\t\tconst timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'\n\t\t\t\tconst shouldSuppress = this.suppressAccessLog === true || !ctx.req.url\n\t\t\t\t\t|| (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\n\t\t\t\tconst cpuUsageEnd = cpuUsage()\n\t\t\t\tconst memoryUsageEnd = memoryUsage()\n\n\t\t\t\tconst cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000\n\t\t\t\tconst memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed\n\t\t\t\tconst level = shouldSuppress ? 'debug' : 'info'\n\t\t\t\tctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {\n\t\t\t\t\tstatus: ctx.response?.statusCode,\n\t\t\t\t\ttimeLabel: timeLabel,\n\t\t\t\t\ttotalTimeMs: Math.round(total),\n\t\t\t\t\tevents: times,\n\t\t\t\t\tcpuUsageDiffMs,\n\t\t\t\t\tmemoryUsageDiff,\n\t\t\t\t\tresponseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (ctx.body instanceof Readable) {\n\t\t\t\tconst body = ctx.body\n\t\t\t\tconst streamTimer = timer('Stream', () => {\n\t\t\t\t\treturn new Promise(resolve => {\n\t\t\t\t\t\tbody.addListener('close', () => {\n\t\t\t\t\t\t\tresolve(null)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\n\t\t\t\tstreamTimer.then(emit).catch(emit)\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\t\t}\n\t\treturn { timer, send }\n\t}\n\n\tprivate matchRequest<C>(routes: Route<C>[], url: URL): MatchedRequest<C> | null {\n\t\tfor (const route of routes) {\n\t\t\tconst params = route.match({ url })\n\t\t\tif (params !== null) {\n\t\t\t\treturn { params, controller: route.controller, module: route.module, mask: route.mask, carriesCredentials: route.carriesCredentials }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\nexport type EventTime = { label: string; start: number; duration?: number }\n\nexport const createEventTimer = (tracer: Tracer, times: EventTime[], globalStart: number): Timer => (name, cb) => {\n\tconst start = performance.now()\n\tconst time: EventTime = { label: name, start: Math.round(start - globalStart) }\n\ttimes.push(time)\n\tconst res = tracer.span(name, () => cb())\n\n\tif (res instanceof Promise) {\n\t\t;(async () => {\n\t\t\ttry {\n\t\t\t\tawait res\n\t\t\t} catch {\n\t\t\t} finally {\n\t\t\t\ttime.duration = Math.round(performance.now() - start)\n\t\t\t}\n\t\t})()\n\t}\n\treturn res\n}\n\nconst createTracedReadable = (body: Readable, tracer: Tracer, span: Span): Readable => {\n\tconst iterator = body[Symbol.asyncIterator]()\n\treturn Readable.from((async function*() {\n\t\tlet completed = false\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst next = await tracer.withSpan(span, () => iterator.next())\n\t\t\t\tif (next.done) {\n\t\t\t\t\tcompleted = true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tyield next.value\n\t\t\t}\n\t\t} finally {\n\t\t\tif (!completed && iterator.return !== undefined) {\n\t\t\t\tawait tracer.withSpan(span, () => iterator.return?.())\n\t\t\t}\n\t\t}\n\t})())\n}\n\n/** @deprecated use `tracer` from the request context instead */\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string; mask: string; carriesCredentials: boolean }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\n\tclientIp: string\n}\n\nexport type ApplicationContext =\n\t& BaseRequestContext\n\t& {\n\t\tprojectGroup: ProjectGroupContainer\n\t\tauthResult: AuthResult | null\n\t\ttimer: Timer\n\t\ttracer: Tracer\n\t}\n\nexport type BaseHttpRequestContext = {\n\tkoa: KoaContext<{}>\n\tbody: unknown\n\tresponse: ServerResponse\n}\n\nexport type HttpContext =\n\t& ApplicationContext\n\t& BaseHttpRequestContext\n\t& {\n\t\trequestDebugMode: boolean\n\t}\n\nexport type InternalHttpContext =\n\t& BaseRequestContext\n\t& BaseHttpRequestContext\n\nexport type WebSocketContext =\n\t& ApplicationContext\n\t& {\n\t\tws: WebSocket\n\t\tabortSignal: AbortSignal\n\t\twaitUntil(promise: Promise<void>): void\n\t}\n\nexport type HttpControllerResponse = Promise<HttpErrorResponse | undefined | void> | HttpErrorResponse | undefined | void\nexport type HttpController = (context: HttpContext) => HttpControllerResponse\nexport type InternalHttpController = (context: InternalHttpContext) => HttpControllerResponse\n\nexport type WebSocketController = (context: WebSocketContext) => void\n\ntype Params = { [param: string]: string }\n\ntype RequestMatcher = (args: { url: URL }) => Params | null\nconst createRequestMatcher = (\n\tmask: string,\n): RequestMatcher => {\n\tconst { regexp, keys } = pathToRegexp(mask)\n\n\tconst match = function(url: string): Params | null {\n\t\tconst match = regexp.exec(url)\n\t\tif (match) {\n\t\t\treturn match.slice(1).reduce((acc, value, i) => ({ ...acc, [keys[i].name]: value }), {})\n\t\t}\n\t\treturn null\n\t}\n\n\treturn request => {\n\t\treturn match(request.url.pathname)\n\t}\n}\n\nexport const LoggerRequestBody = Symbol('RequestBody')\n\nexport interface RunningApplication {\n\tclose(): Promise<void>\n\treadonly server: Server\n}\n"],"names":["pendingWork","ws","establishedAt","closed","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,0BAA0B;AAQzB,MAAM,YAAY;AAAA,EAaxB,YACkB,sBACA,cACA,WACA,SACA,QACA,SAAiB,YACjC;AANgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAA;AACA,SAAA,SAAA;AAlBlB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEzD,kBAAA,MAAQ,mBAAA;AACR,kBAAA,MAAQ,gBAAA;AACR,kBAAA,MAAQ,oBAAA;AACR,kBAAA,MAAQ,qBAAA;AACR,kBAAA,MAAQ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