@contember/engine-http 2.0.9 → 2.0.11

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 (107) hide show
  1. package/dist/development/src/application/application.cjs +100 -18
  2. package/dist/development/src/application/application.cjs.map +1 -1
  3. package/dist/development/src/application/application.js +98 -16
  4. package/dist/development/src/application/application.js.map +1 -1
  5. package/dist/development/src/config/configSchema.cjs +3 -1
  6. package/dist/development/src/config/configSchema.cjs.map +1 -1
  7. package/dist/development/src/config/configSchema.js +3 -1
  8. package/dist/development/src/config/configSchema.js.map +1 -1
  9. package/dist/development/src/config/configTemplate.cjs +1 -0
  10. package/dist/development/src/config/configTemplate.cjs.map +1 -1
  11. package/dist/development/src/config/configTemplate.js +1 -0
  12. package/dist/development/src/config/configTemplate.js.map +1 -1
  13. package/dist/development/src/project/ProjectContainerResolver.cjs +23 -8
  14. package/dist/development/src/project/ProjectContainerResolver.cjs.map +1 -1
  15. package/dist/development/src/project/ProjectContainerResolver.js +23 -8
  16. package/dist/development/src/project/ProjectContainerResolver.js.map +1 -1
  17. package/dist/development/src/project/ProjectContainerStore.cjs +3 -0
  18. package/dist/development/src/project/ProjectContainerStore.cjs.map +1 -1
  19. package/dist/development/src/project/ProjectContainerStore.js +3 -0
  20. package/dist/development/src/project/ProjectContainerStore.js.map +1 -1
  21. package/dist/development/src/projectGroup/ProjectGroupContainerResolver.cjs +1 -3
  22. package/dist/development/src/projectGroup/ProjectGroupContainerResolver.cjs.map +1 -1
  23. package/dist/development/src/projectGroup/ProjectGroupContainerResolver.js +1 -3
  24. package/dist/development/src/projectGroup/ProjectGroupContainerResolver.js.map +1 -1
  25. package/dist/development/src/prometheus/dbMetrics.cjs +1 -1
  26. package/dist/development/src/prometheus/dbMetrics.cjs.map +1 -1
  27. package/dist/development/src/prometheus/dbMetrics.js +1 -1
  28. package/dist/development/src/prometheus/dbMetrics.js.map +1 -1
  29. package/dist/development/src/utils/serverTermination.cjs +5 -1
  30. package/dist/development/src/utils/serverTermination.cjs.map +1 -1
  31. package/dist/development/src/utils/serverTermination.js +5 -1
  32. package/dist/development/src/utils/serverTermination.js.map +1 -1
  33. package/dist/production/src/application/application.cjs +100 -18
  34. package/dist/production/src/application/application.cjs.map +1 -1
  35. package/dist/production/src/application/application.js +98 -16
  36. package/dist/production/src/application/application.js.map +1 -1
  37. package/dist/production/src/config/configSchema.cjs +3 -1
  38. package/dist/production/src/config/configSchema.cjs.map +1 -1
  39. package/dist/production/src/config/configSchema.js +3 -1
  40. package/dist/production/src/config/configSchema.js.map +1 -1
  41. package/dist/production/src/config/configTemplate.cjs +1 -0
  42. package/dist/production/src/config/configTemplate.cjs.map +1 -1
  43. package/dist/production/src/config/configTemplate.js +1 -0
  44. package/dist/production/src/config/configTemplate.js.map +1 -1
  45. package/dist/production/src/project/ProjectContainerResolver.cjs +23 -8
  46. package/dist/production/src/project/ProjectContainerResolver.cjs.map +1 -1
  47. package/dist/production/src/project/ProjectContainerResolver.js +23 -8
  48. package/dist/production/src/project/ProjectContainerResolver.js.map +1 -1
  49. package/dist/production/src/project/ProjectContainerStore.cjs +3 -0
  50. package/dist/production/src/project/ProjectContainerStore.cjs.map +1 -1
  51. package/dist/production/src/project/ProjectContainerStore.js +3 -0
  52. package/dist/production/src/project/ProjectContainerStore.js.map +1 -1
  53. package/dist/production/src/projectGroup/ProjectGroupContainerResolver.cjs +1 -3
  54. package/dist/production/src/projectGroup/ProjectGroupContainerResolver.cjs.map +1 -1
  55. package/dist/production/src/projectGroup/ProjectGroupContainerResolver.js +1 -3
  56. package/dist/production/src/projectGroup/ProjectGroupContainerResolver.js.map +1 -1
  57. package/dist/production/src/prometheus/dbMetrics.cjs +1 -1
  58. package/dist/production/src/prometheus/dbMetrics.cjs.map +1 -1
  59. package/dist/production/src/prometheus/dbMetrics.js +1 -1
  60. package/dist/production/src/prometheus/dbMetrics.js.map +1 -1
  61. package/dist/production/src/utils/serverTermination.cjs +5 -1
  62. package/dist/production/src/utils/serverTermination.cjs.map +1 -1
  63. package/dist/production/src/utils/serverTermination.js +5 -1
  64. package/dist/production/src/utils/serverTermination.js.map +1 -1
  65. package/dist/tests/cases/unit/applicationShutdown.test.d.ts +2 -0
  66. package/dist/tests/cases/unit/applicationShutdown.test.d.ts.map +1 -0
  67. package/dist/tests/cases/unit/dbMetrics.test.d.ts +2 -0
  68. package/dist/tests/cases/unit/dbMetrics.test.d.ts.map +1 -0
  69. package/dist/tests/cases/unit/projectContainerResolver.test.d.ts +2 -0
  70. package/dist/tests/cases/unit/projectContainerResolver.test.d.ts.map +1 -0
  71. package/dist/tests/cases/unit/serverConfig.test.d.ts +2 -0
  72. package/dist/tests/cases/unit/serverConfig.test.d.ts.map +1 -0
  73. package/dist/tests/cases/unit/serverTermination.fixture.d.ts +2 -0
  74. package/dist/tests/cases/unit/serverTermination.fixture.d.ts.map +1 -0
  75. package/dist/tests/cases/unit/serverTermination.test.d.ts +2 -0
  76. package/dist/tests/cases/unit/serverTermination.test.d.ts.map +1 -0
  77. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  78. package/dist/types/MasterContainer.d.ts +1 -0
  79. package/dist/types/MasterContainer.d.ts.map +1 -1
  80. package/dist/types/application/application.d.ts +2 -0
  81. package/dist/types/application/application.d.ts.map +1 -1
  82. package/dist/types/config/configSchema.d.ts +2 -0
  83. package/dist/types/config/configSchema.d.ts.map +1 -1
  84. package/dist/types/config/configTemplate.d.ts.map +1 -1
  85. package/dist/types/project/ProjectContainerResolver.d.ts +7 -1
  86. package/dist/types/project/ProjectContainerResolver.d.ts.map +1 -1
  87. package/dist/types/project/ProjectContainerStore.d.ts +1 -0
  88. package/dist/types/project/ProjectContainerStore.d.ts.map +1 -1
  89. package/dist/types/projectGroup/ProjectGroupContainerResolver.d.ts.map +1 -1
  90. package/dist/types/tsconfig.tsbuildinfo +1 -1
  91. package/dist/types/utils/serverTermination.d.ts +9 -1
  92. package/dist/types/utils/serverTermination.d.ts.map +1 -1
  93. package/package.json +15 -15
  94. package/src/application/application.ts +101 -15
  95. package/src/config/configSchema.ts +2 -0
  96. package/src/config/configTemplate.ts +1 -0
  97. package/src/project/ProjectContainerResolver.ts +27 -9
  98. package/src/project/ProjectContainerStore.ts +4 -0
  99. package/src/projectGroup/ProjectGroupContainerResolver.ts +1 -4
  100. package/src/prometheus/dbMetrics.ts +1 -1
  101. package/src/utils/serverTermination.ts +19 -1
  102. package/tests/cases/unit/applicationShutdown.test.ts +150 -0
  103. package/tests/cases/unit/dbMetrics.test.ts +40 -0
  104. package/tests/cases/unit/projectContainerResolver.test.ts +150 -0
  105. package/tests/cases/unit/serverConfig.test.ts +17 -0
  106. package/tests/cases/unit/serverTermination.fixture.ts +13 -0
  107. package/tests/cases/unit/serverTermination.test.ts +49 -0
@@ -1 +1 @@
1
- {"version":3,"file":"dbMetrics.js","sources":["../../../../../packages/engine-http/src/prometheus/dbMetrics.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../types/prom-client/index.d.ts\" />\nimport prom from 'prom-client'\nimport { Connection, EventManager, PoolStats, poolStatsDescription } from '@contember/database'\nimport { CustomMetric } from './CustomMetric'\n\n\nconst labelNames = ['contember_project' as const, 'contember_module' as const, 'contember_project_group' as const, 'database_instance']\ntype LabelNames = typeof labelNames[number]\ntype Labels = { [K in LabelNames]: string }\ntype DatabaseMetricsEntry = {\n\tconnection: Connection.PoolStatusProvider & Connection.Queryable\n\tlabels: Labels\n}\ntype Unregistrar = () => void\ntype DatabaseMetricsRegistrar = (entry: DatabaseMetricsEntry) => Unregistrar\n\nexport const createDbMetricsRegistrar = (registry: prom.Registry): DatabaseMetricsRegistrar => {\n\tconst dbPoolCollectorInner = createDbPoolMetricsCollector(registry)\n\tconst entries = new Set<DatabaseMetricsEntry>()\n\tconst collector = () => {\n\t\tdbPoolCollectorInner(entries)\n\t}\n\tregistry.registerCollector(collector)\n\tconst sqlMetricsRegistrar = createSqlMetricsRegistrar(registry)\n\treturn entry => {\n\t\tentries.add(entry)\n\t\tconst sqlMetricsUnregistrar = sqlMetricsRegistrar(entry.connection, entry.labels)\n\t\treturn () => {\n\t\t\tentries.delete(entry)\n\t\t\tsqlMetricsUnregistrar()\n\t\t}\n\t}\n}\n\nconst createDbPoolMetricsCollector = (registry: prom.Registry) => {\n\n\tconst descriptionSuffix = 'Dimensions: contember_module (tenant or content; system is not used since it uses the same connection), contember_project_group, contember_project for contember_module=content, database_instance (single, primary, replica).'\n\tconst totalCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_total_count`,\n\t\thelp: `The total number of clients existing within the pool: ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst idleCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_idle_count`,\n\t\thelp: `The number of clients which are not checked out but are currently idle in the pool. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst waitingCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_waiting_count`,\n\t\thelp: `The number of queued requests waiting on a client when all clients are checked out. It can be helpful to monitor this number to see if you need to adjust the size of the pool. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst maxCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_max_count`,\n\t\thelp: `Maximum number of clients the pool should contain. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst connectingCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_connecting_count`,\n\t\thelp: `Current value of clients establishing connection. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst activeCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_active_count`,\n\t\thelp: `Number of connections that are checked out. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst statCounters: {[K in keyof PoolStats]: CustomMetric<LabelNames>} = {} as any\n\tfor (const [key, description] of Object.entries(poolStatsDescription)) {\n\t\tconst customMetric = new CustomMetric<LabelNames>({\n\t\t\tname: `contember_db_pool_${key}`,\n\t\t\thelp: `${description} ${descriptionSuffix}`,\n\t\t\ttype: 'counter',\n\t\t\tlabelNames,\n\t\t})\n\t\tstatCounters[key as keyof PoolStats] = customMetric\n\t\tregistry.registerMetric(customMetric as unknown as prom.Counter<LabelNames>)\n\t}\n\n\treturn (entries: Set<DatabaseMetricsEntry>) => {\n\t\tfor (const counter of Object.values(statCounters)) {\n\t\t\tcounter.reset()\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tconst db = entry.connection\n\t\t\tconst labels = entry.labels\n\t\t\tconst poolInfo = db.getPoolStatus()\n\t\t\tif (!poolInfo) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttotalCount.set(labels, poolInfo.active + poolInfo.idle + poolInfo.connecting)\n\t\t\tidleCount.set(labels, poolInfo.idle)\n\t\t\twaitingCount.set(labels, poolInfo.pending)\n\t\t\tmaxCount.set(labels, poolInfo.max)\n\t\t\tconnectingCount.set(labels, poolInfo.connecting)\n\t\t\tactiveCount.set(labels, poolInfo.active)\n\n\t\t\tfor (const [key, value] of Object.entries(poolInfo.stats)) {\n\t\t\t\tstatCounters[key as keyof PoolStats].add(labels, value)\n\t\t\t}\n\t\t}\n\t}\n}\ntype SqlMetricsRegistrar = (\n\tconnection: Connection.Queryable,\n\tlabels: Labels,\n) => Unregistrar\nconst createSqlMetricsRegistrar = (registry: prom.Registry): SqlMetricsRegistrar => {\n\tconst sqlDuration = new prom.Histogram({\n\t\tname: 'contember_sql_duration_ms',\n\t\thelp: 'Executed SQL queries by contember_module (system, tenant, content or unknown) and contember_project (or \"unknown\" for unknown project)',\n\t\tregisters: [registry],\n\t\tlabelNames,\n\t\tbuckets: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000],\n\t})\n\tconst sqlErrorRate = new prom.Counter({\n\t\tname: 'contember_sql_error_count',\n\t\thelp: 'Failed SQL queries by contember_module (system, tenant, content or unknown) and contember_project (or \"unknown\" for unknown project)',\n\t\tlabelNames,\n\t\tregisters: [registry],\n\t})\n\n\treturn (connection, labels) => {\n\t\tconst queryEndCallback: EventManager.ListenerTypes[EventManager.Event.queryEnd] = ({ meta }, { timing }) => {\n\t\t\tsqlDuration.observe(\n\t\t\t\t{\n\t\t\t\t\t...labels,\n\t\t\t\t\tcontember_module: meta.module || labels.contember_module,\n\t\t\t\t},\n\t\t\t\ttiming ? Math.round(timing.selfDuration / 1000) : 0,\n\t\t\t)\n\t\t}\n\t\tconst queryErrorCallback: EventManager.ListenerTypes[EventManager.Event.queryError] = ({ meta }) => {\n\t\t\tsqlErrorRate.inc({\n\t\t\t\t...labels,\n\t\t\t\tcontember_module: meta.module || labels.contember_module,\n\t\t\t})\n\t\t}\n\t\tconnection.eventManager.on(EventManager.Event.queryEnd, queryEndCallback)\n\t\tconnection.eventManager.on(EventManager.Event.queryError, queryErrorCallback)\n\t\treturn () => {\n\t\t\tconnection.eventManager.removeListener(EventManager.Event.queryEnd, queryEndCallback)\n\t\t\tconnection.eventManager.removeListener(EventManager.Event.queryError, queryErrorCallback)\n\t\t}\n\t}\n}\n"],"names":[],"mappings":";;;AAOA,MAAM,aAAa,CAAC,qBAA8B,oBAA6B,2BAAoC,mBAAmB;AAUzH,MAAA,2BAA2B,CAAC,aAAsD;AACxF,QAAA,uBAAuB,6BAA6B,QAAQ;AAC5D,QAAA,8BAAc,IAA0B;AAC9C,QAAM,YAAY,MAAM;AACvB,yBAAqB,OAAO;AAAA,EAC7B;AACA,WAAS,kBAAkB,SAAS;AAC9B,QAAA,sBAAsB,0BAA0B,QAAQ;AAC9D,SAAO,CAAS,UAAA;AACf,YAAQ,IAAI,KAAK;AACjB,UAAM,wBAAwB,oBAAoB,MAAM,YAAY,MAAM,MAAM;AAChF,WAAO,MAAM;AACZ,cAAQ,OAAO,KAAK;AACE,4BAAA;AAAA,IACvB;AAAA,EACD;AACD;AAEA,MAAM,+BAA+B,CAAC,aAA4B;AAEjE,QAA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AAI;AAAA,MACnD;AAAA,IACD;AACA,UAAM,qBAAgF,CAAC,EAAE,WAAW;AACnG,mBAAa,IAAI;AAAA,QAChB,GAAG;AAAA,QACH,kBAAkB,KAAK,UAAU,OAAO;AAAA,MAAA,CACxC;AAAA,IACF;AACA,eAAW,aAAa,GAAG,aAAa,MAAM,UAAU,gBAAgB;AACxE,eAAW,aAAa,GAAG,aAAa,MAAM,YAAY,kBAAkB;AAC5E,WAAO,MAAM;AACZ,iBAAW,aAAa,eAAe,aAAa,MAAM,UAAU,gBAAgB;AACpF,iBAAW,aAAa,eAAe,aAAa,MAAM,YAAY,kBAAkB;AAAA,IACzF;AAAA,EACD;AACD;"}
1
+ {"version":3,"file":"dbMetrics.js","sources":["../../../../../packages/engine-http/src/prometheus/dbMetrics.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../types/prom-client/index.d.ts\" />\nimport prom from 'prom-client'\nimport { Connection, EventManager, PoolStats, poolStatsDescription } from '@contember/database'\nimport { CustomMetric } from './CustomMetric'\n\n\nconst labelNames = ['contember_project' as const, 'contember_module' as const, 'contember_project_group' as const, 'database_instance']\ntype LabelNames = typeof labelNames[number]\ntype Labels = { [K in LabelNames]: string }\ntype DatabaseMetricsEntry = {\n\tconnection: Connection.PoolStatusProvider & Connection.Queryable\n\tlabels: Labels\n}\ntype Unregistrar = () => void\ntype DatabaseMetricsRegistrar = (entry: DatabaseMetricsEntry) => Unregistrar\n\nexport const createDbMetricsRegistrar = (registry: prom.Registry): DatabaseMetricsRegistrar => {\n\tconst dbPoolCollectorInner = createDbPoolMetricsCollector(registry)\n\tconst entries = new Set<DatabaseMetricsEntry>()\n\tconst collector = () => {\n\t\tdbPoolCollectorInner(entries)\n\t}\n\tregistry.registerCollector(collector)\n\tconst sqlMetricsRegistrar = createSqlMetricsRegistrar(registry)\n\treturn entry => {\n\t\tentries.add(entry)\n\t\tconst sqlMetricsUnregistrar = sqlMetricsRegistrar(entry.connection, entry.labels)\n\t\treturn () => {\n\t\t\tentries.delete(entry)\n\t\t\tsqlMetricsUnregistrar()\n\t\t}\n\t}\n}\n\nconst createDbPoolMetricsCollector = (registry: prom.Registry) => {\n\n\tconst descriptionSuffix = 'Dimensions: contember_module (tenant or content; system is not used since it uses the same connection), contember_project_group, contember_project for contember_module=content, database_instance (single, primary, replica).'\n\tconst totalCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_total_count`,\n\t\thelp: `The total number of clients existing within the pool: ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst idleCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_idle_count`,\n\t\thelp: `The number of clients which are not checked out but are currently idle in the pool. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst waitingCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_waiting_count`,\n\t\thelp: `The number of queued requests waiting on a client when all clients are checked out. It can be helpful to monitor this number to see if you need to adjust the size of the pool. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst maxCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_max_count`,\n\t\thelp: `Maximum number of clients the pool should contain. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst connectingCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_connecting_count`,\n\t\thelp: `Current value of clients establishing connection. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst activeCount = new prom.Gauge({\n\t\tregisters: [registry],\n\t\tname: `contember_db_pool_active_count`,\n\t\thelp: `Number of connections that are checked out. ${descriptionSuffix}`,\n\t\tlabelNames,\n\t})\n\tconst statCounters: {[K in keyof PoolStats]: CustomMetric<LabelNames>} = {} as any\n\tfor (const [key, description] of Object.entries(poolStatsDescription)) {\n\t\tconst customMetric = new CustomMetric<LabelNames>({\n\t\t\tname: `contember_db_pool_${key}`,\n\t\t\thelp: `${description} ${descriptionSuffix}`,\n\t\t\ttype: 'counter',\n\t\t\tlabelNames,\n\t\t})\n\t\tstatCounters[key as keyof PoolStats] = customMetric\n\t\tregistry.registerMetric(customMetric as unknown as prom.Counter<LabelNames>)\n\t}\n\n\treturn (entries: Set<DatabaseMetricsEntry>) => {\n\t\tfor (const counter of Object.values(statCounters)) {\n\t\t\tcounter.reset()\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tconst db = entry.connection\n\t\t\tconst labels = entry.labels\n\t\t\tconst poolInfo = db.getPoolStatus()\n\t\t\tif (!poolInfo) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttotalCount.set(labels, poolInfo.active + poolInfo.idle + poolInfo.connecting)\n\t\t\tidleCount.set(labels, poolInfo.idle)\n\t\t\twaitingCount.set(labels, poolInfo.pending)\n\t\t\tmaxCount.set(labels, poolInfo.max)\n\t\t\tconnectingCount.set(labels, poolInfo.connecting)\n\t\t\tactiveCount.set(labels, poolInfo.active)\n\n\t\t\tfor (const [key, value] of Object.entries(poolInfo.stats)) {\n\t\t\t\tstatCounters[key as keyof PoolStats].add(labels, value)\n\t\t\t}\n\t\t}\n\t}\n}\ntype SqlMetricsRegistrar = (\n\tconnection: Connection.Queryable,\n\tlabels: Labels,\n) => Unregistrar\nconst createSqlMetricsRegistrar = (registry: prom.Registry): SqlMetricsRegistrar => {\n\tconst sqlDuration = new prom.Histogram({\n\t\tname: 'contember_sql_duration_ms',\n\t\thelp: 'Executed SQL queries by contember_module (system, tenant, content or unknown) and contember_project (or \"unknown\" for unknown project)',\n\t\tregisters: [registry],\n\t\tlabelNames,\n\t\tbuckets: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000],\n\t})\n\tconst sqlErrorRate = new prom.Counter({\n\t\tname: 'contember_sql_error_count',\n\t\thelp: 'Failed SQL queries by contember_module (system, tenant, content or unknown) and contember_project (or \"unknown\" for unknown project)',\n\t\tlabelNames,\n\t\tregisters: [registry],\n\t})\n\n\treturn (connection, labels) => {\n\t\tconst queryEndCallback: EventManager.ListenerTypes[EventManager.Event.queryEnd] = ({ meta }, { timing }) => {\n\t\t\tsqlDuration.observe(\n\t\t\t\t{\n\t\t\t\t\t...labels,\n\t\t\t\t\tcontember_module: meta.module || labels.contember_module,\n\t\t\t\t},\n\t\t\t\ttiming ? Math.round(timing.selfDuration / 1000) : 0,\n\t\t\t)\n\t\t}\n\t\tconst queryErrorCallback: EventManager.ListenerTypes[EventManager.Event.queryError] = ({ meta }) => {\n\t\t\tsqlErrorRate.inc({\n\t\t\t\t...labels,\n\t\t\t\tcontember_module: meta.module || labels.contember_module,\n\t\t\t})\n\t\t}\n\t\tconnection.eventManager.on(EventManager.Event.queryEnd, queryEndCallback)\n\t\tconnection.eventManager.on(EventManager.Event.queryError, queryErrorCallback)\n\t\treturn () => {\n\t\t\tconnection.eventManager.removeListener(EventManager.Event.queryEnd, queryEndCallback)\n\t\t\tconnection.eventManager.removeListener(EventManager.Event.queryError, queryErrorCallback)\n\t\t}\n\t}\n}\n"],"names":[],"mappings":";;;AAOA,MAAM,aAAa,CAAC,qBAA8B,oBAA6B,2BAAoC,mBAAmB;AAUzH,MAAA,2BAA2B,CAAC,aAAsD;AACxF,QAAA,uBAAuB,6BAA6B,QAAQ;AAC5D,QAAA,8BAAc,IAA0B;AAC9C,QAAM,YAAY,MAAM;AACvB,yBAAqB,OAAO;AAAA,EAC7B;AACA,WAAS,kBAAkB,SAAS;AAC9B,QAAA,sBAAsB,0BAA0B,QAAQ;AAC9D,SAAO,CAAS,UAAA;AACf,YAAQ,IAAI,KAAK;AACjB,UAAM,wBAAwB,oBAAoB,MAAM,YAAY,MAAM,MAAM;AAChF,WAAO,MAAM;AACZ,cAAQ,OAAO,KAAK;AACE,4BAAA;AAAA,IACvB;AAAA,EACD;AACD;AAEA,MAAM,+BAA+B,CAAC,aAA4B;AAEjE,QAAM,oBAAoB;AACpB,QAAA,aAAa,IAAI,KAAK,MAAM;AAAA,IACjC,WAAW,CAA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G,mBAAa,IAAI;AAAA,QAChB,GAAG;AAAA,QACH,kBAAkB,KAAK,UAAU,OAAO;AAAA,MAAA,CACxC;AAAA,IACF;AACA,eAAW,aAAa,GAAG,aAAa,MAAM,UAAU,gBAAgB;AACxE,eAAW,aAAa,GAAG,aAAa,MAAM,YAAY,kBAAkB;AAC5E,WAAO,MAAM;AACZ,iBAAW,aAAa,eAAe,aAAa,MAAM,UAAU,gBAAgB;AACpF,iBAAW,aAAa,eAAe,aAAa,MAAM,YAAY,kBAAkB;AAAA,IACzF;AAAA,EACD;AACD;"}
@@ -6,9 +6,13 @@ const signals = {
6
6
  SIGINT: 2,
7
7
  SIGTERM: 15
8
8
  };
9
- const listenOnProcessTermination = (jobs, logger) => {
9
+ const listenOnProcessTermination = (jobs, logger, { sigtermDelayMs = 0 } = {}) => {
10
10
  for (const [signal, code] of Object.entries(signals)) {
11
11
  process.on(signal, async () => {
12
+ if (signal === "SIGTERM" && sigtermDelayMs > 0) {
13
+ logger.info(`Process ${process.pid} received a SIGTERM signal, serving for another ${sigtermDelayMs} ms before terminating`);
14
+ await new Promise((resolve) => setTimeout(resolve, sigtermDelayMs));
15
+ }
12
16
  logger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`);
13
17
  await Promise.allSettled(jobs.map((it) => it({ signal, code })));
14
18
  logger.info(cluster.isMaster ? `All terminated, exiting` : "All terminated, exiting a worker");
@@ -1 +1 @@
1
- {"version":3,"file":"serverTermination.cjs","sources":["../../../../../packages/engine-http/src/utils/serverTermination.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport { Logger } from '@contember/logger'\n\nconst signals = {\n\tSIGHUP: 1,\n\tSIGINT: 2,\n\tSIGTERM: 15,\n}\nexport type TerminationJob = (args: { signal: keyof typeof signals; code: number }) => Promise<void>\nexport const listenOnProcessTermination = (jobs: TerminationJob[], logger: Logger) => {\n\tfor (const [signal, code] of Object.entries(signals)) {\n\t\tprocess.on(signal, async () => {\n\t\t\tlogger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`)\n\t\t\tawait Promise.allSettled(jobs.map(it => it({ signal: signal as keyof typeof signals, code })))\n\t\t\tlogger.info(cluster.isMaster ? `All terminated, exiting` : 'All terminated, exiting a worker')\n\t\t\tprocess.exit(128 + code)\n\t\t})\n\t}\n}\n"],"names":[],"mappings":";;;AAGA,MAAM,UAAU;AAAA,EACf,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACV;AAEa,MAAA,6BAA6B,CAAC,MAAwB,WAAmB;AACrF,aAAW,CAAC,QAAQ,IAAI,KAAK,OAAO,QAAQ,OAAO,GAAG;AAC7C,YAAA,GAAG,QAAQ,YAAY;AACvB,aAAA,KAAK,WAAW,QAAQ,GAAG,eAAe,MAAM,sBAAsB,KAAK,MAAM,mBAAmB;AACrG,YAAA,QAAQ,WAAW,KAAK,IAAI,CAAA,OAAM,GAAG,EAAE,QAAwC,KAAA,CAAM,CAAC,CAAC;AAC7F,aAAO,KAAK,QAAQ,WAAW,4BAA4B,kCAAkC;AACrF,cAAA,KAAK,MAAM,IAAI;AAAA,IAAA,CACvB;AAAA,EAAA;AAEH;;"}
1
+ {"version":3,"file":"serverTermination.cjs","sources":["../../../../../packages/engine-http/src/utils/serverTermination.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport { Logger } from '@contember/logger'\n\nconst signals = {\n\tSIGHUP: 1,\n\tSIGINT: 2,\n\tSIGTERM: 15,\n}\nexport type TerminationJob = (args: { signal: keyof typeof signals; code: number }) => Promise<void>\n\nexport interface ProcessTerminationOptions {\n\t/**\n\t * How long the process keeps serving after SIGTERM before the jobs run. An orchestrator stops routing to\n\t * a process only some time after signalling it, so draining at once refuses what is still on its way.\n\t * SIGINT and SIGHUP never wait.\n\t */\n\treadonly sigtermDelayMs?: number\n}\n\nexport const listenOnProcessTermination = (\n\tjobs: TerminationJob[],\n\tlogger: Logger,\n\t{ sigtermDelayMs = 0 }: ProcessTerminationOptions = {},\n) => {\n\tfor (const [signal, code] of Object.entries(signals)) {\n\t\tprocess.on(signal, async () => {\n\t\t\tif (signal === 'SIGTERM' && sigtermDelayMs > 0) {\n\t\t\t\tlogger.info(`Process ${process.pid} received a SIGTERM signal, serving for another ${sigtermDelayMs} ms before terminating`)\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, sigtermDelayMs))\n\t\t\t}\n\t\t\tlogger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`)\n\t\t\tawait Promise.allSettled(jobs.map(it => it({ signal: signal as keyof typeof signals, code })))\n\t\t\tlogger.info(cluster.isMaster ? `All terminated, exiting` : 'All terminated, exiting a worker')\n\t\t\tprocess.exit(128 + code)\n\t\t})\n\t}\n}\n"],"names":[],"mappings":";;;AAGA,MAAM,UAAU;AAAA,EACf,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACV;AAYa,MAAA,6BAA6B,CACzC,MACA,QACA,EAAE,iBAAiB,EAAiC,IAAA,OAChD;AACJ,aAAW,CAAC,QAAQ,IAAI,KAAK,OAAO,QAAQ,OAAO,GAAG;AAC7C,YAAA,GAAG,QAAQ,YAAY;AAC1B,UAAA,WAAW,aAAa,iBAAiB,GAAG;AAC/C,eAAO,KAAK,WAAW,QAAQ,GAAG,mDAAmD,cAAc,wBAAwB;AAC3H,cAAM,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,cAAc,CAAC;AAAA,MAAA;AAE1D,aAAA,KAAK,WAAW,QAAQ,GAAG,eAAe,MAAM,sBAAsB,KAAK,MAAM,mBAAmB;AACrG,YAAA,QAAQ,WAAW,KAAK,IAAI,CAAA,OAAM,GAAG,EAAE,QAAwC,KAAA,CAAM,CAAC,CAAC;AAC7F,aAAO,KAAK,QAAQ,WAAW,4BAA4B,kCAAkC;AACrF,cAAA,KAAK,MAAM,IAAI;AAAA,IAAA,CACvB;AAAA,EAAA;AAEH;;"}
@@ -4,9 +4,13 @@ const signals = {
4
4
  SIGINT: 2,
5
5
  SIGTERM: 15
6
6
  };
7
- const listenOnProcessTermination = (jobs, logger) => {
7
+ const listenOnProcessTermination = (jobs, logger, { sigtermDelayMs = 0 } = {}) => {
8
8
  for (const [signal, code] of Object.entries(signals)) {
9
9
  process.on(signal, async () => {
10
+ if (signal === "SIGTERM" && sigtermDelayMs > 0) {
11
+ logger.info(`Process ${process.pid} received a SIGTERM signal, serving for another ${sigtermDelayMs} ms before terminating`);
12
+ await new Promise((resolve) => setTimeout(resolve, sigtermDelayMs));
13
+ }
10
14
  logger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`);
11
15
  await Promise.allSettled(jobs.map((it) => it({ signal, code })));
12
16
  logger.info(cluster.isMaster ? `All terminated, exiting` : "All terminated, exiting a worker");
@@ -1 +1 @@
1
- {"version":3,"file":"serverTermination.js","sources":["../../../../../packages/engine-http/src/utils/serverTermination.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport { Logger } from '@contember/logger'\n\nconst signals = {\n\tSIGHUP: 1,\n\tSIGINT: 2,\n\tSIGTERM: 15,\n}\nexport type TerminationJob = (args: { signal: keyof typeof signals; code: number }) => Promise<void>\nexport const listenOnProcessTermination = (jobs: TerminationJob[], logger: Logger) => {\n\tfor (const [signal, code] of Object.entries(signals)) {\n\t\tprocess.on(signal, async () => {\n\t\t\tlogger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`)\n\t\t\tawait Promise.allSettled(jobs.map(it => it({ signal: signal as keyof typeof signals, code })))\n\t\t\tlogger.info(cluster.isMaster ? `All terminated, exiting` : 'All terminated, exiting a worker')\n\t\t\tprocess.exit(128 + code)\n\t\t})\n\t}\n}\n"],"names":[],"mappings":";AAGA,MAAM,UAAU;AAAA,EACf,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACV;AAEa,MAAA,6BAA6B,CAAC,MAAwB,WAAmB;AACrF,aAAW,CAAC,QAAQ,IAAI,KAAK,OAAO,QAAQ,OAAO,GAAG;AAC7C,YAAA,GAAG,QAAQ,YAAY;AACvB,aAAA,KAAK,WAAW,QAAQ,GAAG,eAAe,MAAM,sBAAsB,KAAK,MAAM,mBAAmB;AACrG,YAAA,QAAQ,WAAW,KAAK,IAAI,CAAA,OAAM,GAAG,EAAE,QAAwC,KAAA,CAAM,CAAC,CAAC;AAC7F,aAAO,KAAK,QAAQ,WAAW,4BAA4B,kCAAkC;AACrF,cAAA,KAAK,MAAM,IAAI;AAAA,IAAA,CACvB;AAAA,EAAA;AAEH;"}
1
+ {"version":3,"file":"serverTermination.js","sources":["../../../../../packages/engine-http/src/utils/serverTermination.ts"],"sourcesContent":["import cluster from 'node:cluster'\nimport { Logger } from '@contember/logger'\n\nconst signals = {\n\tSIGHUP: 1,\n\tSIGINT: 2,\n\tSIGTERM: 15,\n}\nexport type TerminationJob = (args: { signal: keyof typeof signals; code: number }) => Promise<void>\n\nexport interface ProcessTerminationOptions {\n\t/**\n\t * How long the process keeps serving after SIGTERM before the jobs run. An orchestrator stops routing to\n\t * a process only some time after signalling it, so draining at once refuses what is still on its way.\n\t * SIGINT and SIGHUP never wait.\n\t */\n\treadonly sigtermDelayMs?: number\n}\n\nexport const listenOnProcessTermination = (\n\tjobs: TerminationJob[],\n\tlogger: Logger,\n\t{ sigtermDelayMs = 0 }: ProcessTerminationOptions = {},\n) => {\n\tfor (const [signal, code] of Object.entries(signals)) {\n\t\tprocess.on(signal, async () => {\n\t\t\tif (signal === 'SIGTERM' && sigtermDelayMs > 0) {\n\t\t\t\tlogger.info(`Process ${process.pid} received a SIGTERM signal, serving for another ${sigtermDelayMs} ms before terminating`)\n\t\t\t\tawait new Promise(resolve => setTimeout(resolve, sigtermDelayMs))\n\t\t\t}\n\t\t\tlogger.info(`Process ${process.pid} received a ${signal} signal, executing ${jobs.length} termination jobs`)\n\t\t\tawait Promise.allSettled(jobs.map(it => it({ signal: signal as keyof typeof signals, code })))\n\t\t\tlogger.info(cluster.isMaster ? `All terminated, exiting` : 'All terminated, exiting a worker')\n\t\t\tprocess.exit(128 + code)\n\t\t})\n\t}\n}\n"],"names":[],"mappings":";AAGA,MAAM,UAAU;AAAA,EACf,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AACV;AAYa,MAAA,6BAA6B,CACzC,MACA,QACA,EAAE,iBAAiB,EAAiC,IAAA,OAChD;AACJ,aAAW,CAAC,QAAQ,IAAI,KAAK,OAAO,QAAQ,OAAO,GAAG;AAC7C,YAAA,GAAG,QAAQ,YAAY;AAC1B,UAAA,WAAW,aAAa,iBAAiB,GAAG;AAC/C,eAAO,KAAK,WAAW,QAAQ,GAAG,mDAAmD,cAAc,wBAAwB;AAC3H,cAAM,IAAI,QAAQ,CAAA,YAAW,WAAW,SAAS,cAAc,CAAC;AAAA,MAAA;AAE1D,aAAA,KAAK,WAAW,QAAQ,GAAG,eAAe,MAAM,sBAAsB,KAAK,MAAM,mBAAmB;AACrG,YAAA,QAAQ,WAAW,KAAK,IAAI,CAAA,OAAM,GAAG,EAAE,QAAwC,KAAA,CAAM,CAAC,CAAC;AAC7F,aAAO,KAAK,QAAQ,WAAW,4BAA4B,kCAAkC;AACrF,cAAA,KAAK,MAAM,IAAI;AAAA,IAAA,CACvB;AAAA,EAAA;AAEH;"}
@@ -31,6 +31,7 @@ const http__namespace = /* @__PURE__ */ _interopNamespaceDefault(http);
31
31
  var __defProp = Object.defineProperty;
32
32
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
33
33
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
34
+ const websocketCloseTimeoutMs = 5e3;
34
35
  class Application {
35
36
  constructor(projectGroupResolver, serverConfig, debugMode, version, logger2) {
36
37
  this.projectGroupResolver = projectGroupResolver;
@@ -73,6 +74,15 @@ class Application {
73
74
  async listen() {
74
75
  const koa = new Koa();
75
76
  const wss = new ws.WebSocketServer({ noServer: true });
77
+ let closing = false;
78
+ koa.use(async (ctx, next) => {
79
+ if (closing) {
80
+ ctx.status = 503;
81
+ ctx.set("Connection", "close");
82
+ return;
83
+ }
84
+ await next();
85
+ });
76
86
  for (const middleware of this.middlewares) {
77
87
  koa.use(middleware);
78
88
  }
@@ -89,10 +99,36 @@ class Application {
89
99
  ctx.response.set("X-Powered-By", `Contember ${versionSimplified}` + (this.debugMode ? "-dev" : ""));
90
100
  await this.handleHttpRequest(ctx);
91
101
  });
92
- const server = http__namespace.createServer(koa.callback());
102
+ const activeHttpRequests = /* @__PURE__ */ new Set();
103
+ const handleHttpRequest = koa.callback();
104
+ const server = http__namespace.createServer((request, response) => {
105
+ if (closing) {
106
+ handleHttpRequest(request, response);
107
+ return;
108
+ }
109
+ let resolveRequest = () => {
110
+ };
111
+ const completed = new Promise((resolve) => {
112
+ resolveRequest = resolve;
113
+ });
114
+ activeHttpRequests.add(completed);
115
+ const complete = () => {
116
+ response.off("finish", complete);
117
+ response.off("close", complete);
118
+ activeHttpRequests.delete(completed);
119
+ resolveRequest();
120
+ };
121
+ response.once("finish", complete);
122
+ response.once("close", complete);
123
+ handleHttpRequest(request, response);
124
+ });
93
125
  const abortController = new AbortController();
94
126
  const wsRequests = [];
95
127
  server.on("upgrade", (req, socket, head) => {
128
+ if (closing) {
129
+ this.sendRawHttpResponse(socket, new HttpResponse.HttpErrorResponse(503, "Server is shutting down"));
130
+ return;
131
+ }
96
132
  wsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head));
97
133
  });
98
134
  await new Promise((resolve) => {
@@ -101,9 +137,24 @@ class Application {
101
137
  return {
102
138
  server,
103
139
  close: async () => {
140
+ closing = true;
104
141
  abortController.abort();
105
- await Promise.all(wsRequests);
106
- await new Promise((resolve) => server.close(resolve));
142
+ await Promise.all([...wsRequests, ...activeHttpRequests]);
143
+ if (process.versions.bun !== void 0) {
144
+ server.closeAllConnections();
145
+ } else {
146
+ server.closeIdleConnections();
147
+ }
148
+ if (server.listening) {
149
+ await new Promise(
150
+ (resolve) => server.close((error) => {
151
+ if (error) {
152
+ this.logger.error(error);
153
+ }
154
+ resolve();
155
+ })
156
+ );
157
+ }
107
158
  }
108
159
  };
109
160
  }
@@ -127,12 +178,25 @@ class Application {
127
178
  requestLogger = requestLogger.child({
128
179
  user: authResult?.identityId
129
180
  });
130
- const ws2 = await new Promise((resolve) => wss.handleUpgrade(req, socket, head, (ws22, request) => {
131
- resolve(ws22);
181
+ if (abortSignal.aborted) {
182
+ throw new HttpResponse.HttpErrorResponse(503, "Server is shutting down");
183
+ }
184
+ const ws$1 = await new Promise((resolve) => wss.handleUpgrade(req, socket, head, (ws2, request) => {
185
+ resolve(ws2);
132
186
  }));
133
187
  const wsEstablished = (/* @__PURE__ */ new Date()).getTime();
188
+ ws$1.on("error", (e) => {
189
+ requestLogger.error(e, {
190
+ websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
191
+ });
192
+ });
193
+ if (abortSignal.aborted) {
194
+ await this.closeWebsocket(ws$1);
195
+ return;
196
+ }
197
+ const pendingWork = [];
134
198
  webSocketContext = {
135
- ws: ws2,
199
+ ws: ws$1,
136
200
  abortSignal,
137
201
  logger: requestLogger,
138
202
  timer,
@@ -140,23 +204,25 @@ class Application {
140
204
  request: req,
141
205
  authResult,
142
206
  params: matchedRequest.params,
143
- projectGroup: groupContainer
207
+ projectGroup: groupContainer,
208
+ waitUntil: (promise) => pendingWork.push(promise)
144
209
  };
145
210
  await matchedRequest.controller(webSocketContext);
211
+ if (abortSignal.aborted && ws$1.readyState === ws.WebSocket.OPEN) {
212
+ ws$1.close(1012);
213
+ }
146
214
  requestLogger.debug("Websocket connection established");
147
- ws2.on("error", (e) => {
148
- requestLogger.error(e, {
149
- websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
150
- });
151
- });
152
- return new Promise((resolve) => {
153
- ws2.on("close", () => {
154
- requestLogger.debug("Websocket connection closed", {
155
- websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
215
+ if (ws$1.readyState !== ws.WebSocket.CLOSED) {
216
+ await new Promise((resolve) => {
217
+ ws$1.on("close", () => {
218
+ requestLogger.debug("Websocket connection closed", {
219
+ websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
220
+ });
221
+ resolve();
156
222
  });
157
- resolve();
158
223
  });
159
- });
224
+ }
225
+ await Promise.allSettled(pendingWork);
160
226
  } catch (e) {
161
227
  if (e instanceof HttpResponse.HttpResponse) {
162
228
  this.sendRawHttpResponse(socket, e);
@@ -275,6 +341,22 @@ class Application {
275
341
  ctx.body = response.body;
276
342
  }
277
343
  }
344
+ async closeWebsocket(ws$1) {
345
+ if (ws$1.readyState === ws.WebSocket.CLOSED) {
346
+ return;
347
+ }
348
+ ws$1.close(1012);
349
+ await new Promise((resolve) => {
350
+ const timeout = setTimeout(() => {
351
+ ws$1.terminate();
352
+ resolve();
353
+ }, websocketCloseTimeoutMs);
354
+ ws$1.once("close", () => {
355
+ clearTimeout(timeout);
356
+ resolve();
357
+ });
358
+ });
359
+ }
278
360
  sendRawHttpResponse(socket, response) {
279
361
  const headers = {
280
362
  "Connection": "close",
@@ -1 +1 @@
1
- {"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { Key, pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common'\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'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\nimport { URL } from 'node:url'\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\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\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) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : 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): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\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\tmatch: createRequestMatcher(mask),\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\tmatch: createRequestMatcher(mask),\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\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())\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 server = http.createServer(koa.callback())\n\t\tconst abortController = new AbortController()\n\n\t\tconst wsRequests: (Promise<void>)[] = []\n\t\tserver.on('upgrade', (req, socket, head) => {\n\t\t\t wsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head))\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\tabortController.abort()\n\t\t\t\tawait Promise.all(wsRequests)\n\t\t\t\tawait new Promise(resolve => server.close(resolve))\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 webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\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\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer })\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\n\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\tresolve(ws)\n\t\t\t}))\n\t\t\tconst wsEstablished = new Date().getTime()\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\trequestLogger.debug('Websocket connection established')\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: new Date().getTime() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\n\t\t\treturn new Promise<void>(resolve => {\n\t\t\t\tws.on('close', () => {\n\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\twebsocketOpenMs: new Date().getTime() - wsEstablished,\n\t\t\t\t\t})\n\t\t\t\t\tresolve()\n\t\t\t\t})\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}\n\t\tlet httpContext: HttpContext | null = null\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module)\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: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\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})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer })\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\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\tlogger,\n\t\t\t\t\ttimer,\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\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\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: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\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\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\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\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\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 sendRawHttpResponse(socket: Duplex, response: HttpResponse) {\n\t\tconst headers: Record<string, string> = {\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\tObject.keys(headers)\n\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t.join('\\r\\n') +\n\t\t\t'\\r\\n\\r\\n' +\n\t\t\t(response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\t[LoggerRequestBody]: body,\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 = new Date().getTime()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = new Date().getTime()\n\t\t\tconst time: EventTime = { label: name, start: start - globalStart }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = new Date().getTime() - start\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\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 = new Date().getTime() - 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 || (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\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: total,\n\t\t\t\t\tevents: times,\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\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\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 }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\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}\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}\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 keys: Key[] = []\n\tconst regexp: RegExp = pathToRegexp(mask, keys)\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","module","WebSocketServer","http","URL","Htt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AAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IAAA;AAEjF,WAAA;AAAA,EACR;AAEA,SAAO,CAAW,YAAA;AACV,WAAA,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEa,MAAA,oBAAoB,OAAO,aAAa;;;"}
1
+ {"version":3,"file":"application.cjs","sources":["../../../../../packages/engine-http/src/application/application.ts"],"sourcesContent":["import { Key, pathToRegexp } from 'path-to-regexp'\nimport { KoaContext, KoaMiddleware } from './types'\nimport { AuthResult, HttpErrorResponse, HttpResponse } from '../common'\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'\nimport corsMiddleware from '@koa/cors'\nimport stream, { Duplex, Readable } from 'node:stream'\nimport { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'\nimport { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'\nimport { URL } from 'node:url'\n\nconst websocketCloseTimeoutMs = 5_000\n\ntype Route<C> = { match: RequestMatcher; controller: C; module: string }\nexport class Application {\n\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\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) {\n\t\tconst suppressAccessLogRaw = serverConfig.http?.suppressAccessLog\n\t\tthis.suppressAccessLog = suppressAccessLogRaw === true ? true : suppressAccessLogRaw ? new RegExp(suppressAccessLogRaw) : 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): void {\n\t\tthis.routes.push({\n\t\t\tmodule,\n\t\t\tcontroller,\n\t\t\tmatch: createRequestMatcher(mask),\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\tmatch: createRequestMatcher(mask),\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\tmatch: createRequestMatcher(mask),\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())\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))\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 webSocketContext: WebSocketContext | null = null\n\t\tlet requestLogger = this.logger\n\t\tconst { timer, send: sendTimer } = this.createTimer()\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\trequestLogger = this.createRequestLogger(req, undefined, matchedRequest.module)\n\n\t\t\tconst groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })\n\n\t\t\trequestLogger = requestLogger.child({\n\t\t\t\tprojectGroup: groupContainer.slug,\n\t\t\t})\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: req, timer })\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\n\t\t\tif (abortSignal.aborted) {\n\t\t\t\tthrow new HttpErrorResponse(503, 'Server is shutting down')\n\t\t\t}\n\t\t\tconst ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, (ws, request) => {\n\t\t\t\tresolve(ws)\n\t\t\t}))\n\t\t\tconst wsEstablished = new Date().getTime()\n\t\t\tws.on('error', e => {\n\t\t\t\trequestLogger.error(e, {\n\t\t\t\t\twebsocketOpenMs: new Date().getTime() - wsEstablished,\n\t\t\t\t})\n\t\t\t})\n\t\t\tif (abortSignal.aborted) {\n\t\t\t\tawait this.closeWebsocket(ws)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst pendingWork: Promise<void>[] = []\n\t\t\twebSocketContext = {\n\t\t\t\tws,\n\t\t\t\tabortSignal,\n\t\t\t\tlogger: requestLogger,\n\t\t\t\ttimer,\n\t\t\t\turl,\n\t\t\t\trequest: req,\n\t\t\t\tauthResult,\n\t\t\t\tparams: matchedRequest.params,\n\t\t\t\tprojectGroup: groupContainer,\n\t\t\t\twaitUntil: promise => pendingWork.push(promise),\n\t\t\t}\n\t\t\tawait matchedRequest.controller(webSocketContext)\n\t\t\tif (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {\n\t\t\t\tws.close(1012)\n\t\t\t}\n\t\t\trequestLogger.debug('Websocket connection established')\n\n\t\t\tif (ws.readyState !== WebSocket.CLOSED) {\n\t\t\t\tawait new Promise<void>(resolve => {\n\t\t\t\t\tws.on('close', () => {\n\t\t\t\t\t\trequestLogger.debug('Websocket connection closed', {\n\t\t\t\t\t\t\twebsocketOpenMs: new Date().getTime() - wsEstablished,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tresolve()\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t}\n\t\t\tawait Promise.allSettled(pendingWork)\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}\n\t\tlet httpContext: HttpContext | null = null\n\t\tlet requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module)\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: ctx.request.body,\n\t\t\t\tquery: ctx.request.query,\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})\n\t\t\tctx.state.projectGroup = groupContainer.slug\n\t\t\tctx.state.project = matchedRequest.params.projectSlug\n\n\t\t\tconst authResult = await groupContainer.authenticator.authenticate({ request: ctx.req, timer })\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\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\tlogger,\n\t\t\t\t\ttimer,\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\trequestLogger.error(e)\n\t\t\t}\n\t\t} finally {\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: (httpContext as HttpContext | null)?.requestDebugMode ?? false,\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\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\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\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\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'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\tObject.keys(headers)\n\t\t\t\t.map(h => `${h}: ${headers[h]}`)\n\t\t\t\t.join('\\r\\n') +\n\t\t\t'\\r\\n\\r\\n' +\n\t\t\t(response.body ?? ''),\n\t\t)\n\t}\n\n\tprivate createRequestLogger(request: IncomingMessage, body: any, module?: string): Logger {\n\t\treturn this.logger.child({\n\t\t\tmethod: request.method,\n\t\t\turi: request.url,\n\t\t\trequestId: Math.random().toString().substring(2),\n\t\t\tmodule,\n\t\t\t[LoggerRequestBody]: body,\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 = new Date().getTime()\n\t\tconst timer: Timer = (name: string, cb) => {\n\t\t\tconst start = new Date().getTime()\n\t\t\tconst time: EventTime = { label: name, start: start - globalStart }\n\t\t\ttimes.push(time)\n\t\t\tconst res = cb()\n\n\t\t\tif (res instanceof Promise) {\n\t\t\t\t(async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait res\n\t\t\t\t\t} catch {\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttime.duration = new Date().getTime() - start\n\t\t\t\t\t}\n\t\t\t\t})()\n\t\t\t}\n\t\t\treturn res\n\t\t}\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 = new Date().getTime() - 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 || (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))\n\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: total,\n\t\t\t\t\tevents: times,\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\n\t\t\t} else {\n\t\t\t\temit()\n\t\t\t}\n\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 }\n\t\t\t}\n\t\t}\n\t\treturn null\n\t}\n}\n\n\ntype EventTime = { label: string; start: number; duration?: number }\n\nexport type Timer = <T>(event: string, cb: () => T) => T\n\nexport type MatchedRequest<C> = { params: Params; controller: C; module: string }\n\nexport type BaseRequestContext = {\n\tlogger: Logger\n\trequest: IncomingMessage\n\turl: URL\n\tparams: Params\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}\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 keys: Key[] = []\n\tconst regexp: RegExp = pathToRegexp(mask, keys)\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","module","WebSocketServer","http","HttpErrorResponse","URL","ws","WebSocket","HttpResponse","FingerCrossedLoggerHandler","Readable","pathToRegexp","match"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAM,0BAA0B;AAGzB,MAAM,YAAY;AAAA,EAUxB,YACkB,sBACA,cACA,WACA,SACAA,SAChB;AALgB,SAAA,uBAAA;AACA,SAAA,eAAA;AACA,SAAA,YAAA;AACA,SAAA,UAAA;AACA,SAAA,SAAAA;AAblB,kBAAA,MAAQ,eAAoC,EAAC;AAE7C,kBAAA,MAAQ,UAAkC,EAAC;AAC3C,kBAAA,MAAQ,kBAAkD,EAAC;AAC3D,kBAAA,MAAQ,mBAAgD,EAAC;AAEjD,kBAAA,MAAA,mBAAA;AASD,UAAA,uBAAuB,aAAa,MAAM;AAC3C,SAAA,oBAAoB,yBAAyB,OAAO,OAAO,uBAAuB,IAAI,OAAO,oBAAoB,IAAI;AAAA,EAAA;AAAA,EAG3H,cAAc,YAAgC;AACxC,SAAA,YAAY,KAAK,UAAU;AAAA,EAAA;AAAA,EAG1B,SAASC,SAAgB,MAAc,YAAkC;AAC/E,SAAK,OAAO,KAAK;AAAA,MAChB,QAAAA;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EAAA;AAAA,EAGK,iBAAiBA,SAAgB,MAAc,YAA0C;AAC/F,SAAK,eAAe,KAAK;AAAA,MACxB,QAAAA;AAAA,MACA;AAAA,MACA,OAAO,qBAAqB,IAAI;AAAA,IAAA,CAChC;AAAA,EAAA;AAAA,EAGK,kBAAkBA,SAAgB,MAAc,YAAuC;AAC7F,S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AAA,IAAI,gBAAgBC,sBAAU;AACjC,cAAM,OAAO,IAAI;AACX,cAAA,cAAc,MAAM,UAAU,MAAM;AAClC,iBAAA,IAAI,QAAQ,CAAW,YAAA;AACxB,iBAAA,YAAY,SAAS,MAAM;AAC/B,sBAAQ,IAAI;AAAA,YAAA,CACZ;AAAA,UAAA,CACD;AAAA,QAAA,CACD;AAED,oBAAY,KAAK,IAAI,EAAE,MAAM,IAAI;AAAA,MAAA,OAE3B;AACD,aAAA;AAAA,MAAA;AAAA,IAGP;AACO,WAAA,EAAE,OAAO,KAAK;AAAA,EAAA;AAAA,EAGd,aAAgB,QAAoB,KAAoC;AAC/E,eAAW,SAAS,QAAQ;AAC3B,YAAM,SAAS,MAAM,MAAM,EAAE,KAAK;AAClC,UAAI,WAAW,MAAM;AACpB,eAAO,EAAE,QAAQ,YAAY,MAAM,YAAY,QAAQ,MAAM,OAAO;AAAA,MAAA;AAAA,IACrE;AAEM,WAAA;AAAA,EAAA;AAET;AA0DA,MAAM,uBAAuB,CAC5B,SACoB;AACpB,QAAM,OAAc,CAAC;AACf,QAAA,SAAiBC,aAAAA,aAAa,MAAM,IAAI;AAExC,QAAA,QAAQ,SAAU,KAA4B;AAC7CC,UAAAA,SAAQ,OAAO,KAAK,GAAG;AAC7B,QAAIA,QAAO;AACHA,aAAAA,OAAM,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,OAAO,OAAO,EAAE,GAAG,KAAK,CAAC,KAAK,CAAC,EAAE,IAAI,GAAG,MAAA,IAAU,EAAE;AAAA,IAAA;AAEjF,WAAA;AAAA,EACR;AAEA,SAAO,CAAW,YAAA;AACV,WAAA,MAAM,QAAQ,IAAI,QAAQ;AAAA,EAClC;AACD;AAEa,MAAA,oBAAoB,OAAO,aAAa;;;"}
@@ -2,7 +2,7 @@ import { pathToRegexp } from "path-to-regexp";
2
2
  import { HttpErrorResponse, HttpResponse } from "../common/HttpResponse.js";
3
3
  import Koa from "koa";
4
4
  import * as http from "node:http";
5
- import { WebSocketServer } from "ws";
5
+ import { WebSocketServer, WebSocket } from "ws";
6
6
  import { FingerCrossedLoggerHandler } from "@contember/logger";
7
7
  import koaCompress from "koa-compress";
8
8
  import bodyParser from "koa-bodyparser";
@@ -12,6 +12,7 @@ import { URL } from "node:url";
12
12
  var __defProp = Object.defineProperty;
13
13
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
14
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
15
+ const websocketCloseTimeoutMs = 5e3;
15
16
  class Application {
16
17
  constructor(projectGroupResolver, serverConfig, debugMode, version, logger) {
17
18
  this.projectGroupResolver = projectGroupResolver;
@@ -54,6 +55,15 @@ class Application {
54
55
  async listen() {
55
56
  const koa = new Koa();
56
57
  const wss = new WebSocketServer({ noServer: true });
58
+ let closing = false;
59
+ koa.use(async (ctx, next) => {
60
+ if (closing) {
61
+ ctx.status = 503;
62
+ ctx.set("Connection", "close");
63
+ return;
64
+ }
65
+ await next();
66
+ });
57
67
  for (const middleware of this.middlewares) {
58
68
  koa.use(middleware);
59
69
  }
@@ -70,10 +80,36 @@ class Application {
70
80
  ctx.response.set("X-Powered-By", `Contember ${versionSimplified}` + (this.debugMode ? "-dev" : ""));
71
81
  await this.handleHttpRequest(ctx);
72
82
  });
73
- const server = http.createServer(koa.callback());
83
+ const activeHttpRequests = /* @__PURE__ */ new Set();
84
+ const handleHttpRequest = koa.callback();
85
+ const server = http.createServer((request, response) => {
86
+ if (closing) {
87
+ handleHttpRequest(request, response);
88
+ return;
89
+ }
90
+ let resolveRequest = () => {
91
+ };
92
+ const completed = new Promise((resolve) => {
93
+ resolveRequest = resolve;
94
+ });
95
+ activeHttpRequests.add(completed);
96
+ const complete = () => {
97
+ response.off("finish", complete);
98
+ response.off("close", complete);
99
+ activeHttpRequests.delete(completed);
100
+ resolveRequest();
101
+ };
102
+ response.once("finish", complete);
103
+ response.once("close", complete);
104
+ handleHttpRequest(request, response);
105
+ });
74
106
  const abortController = new AbortController();
75
107
  const wsRequests = [];
76
108
  server.on("upgrade", (req, socket, head) => {
109
+ if (closing) {
110
+ this.sendRawHttpResponse(socket, new HttpErrorResponse(503, "Server is shutting down"));
111
+ return;
112
+ }
77
113
  wsRequests.push(this.handleWebsocketRequest(wss, abortController.signal, req, socket, head));
78
114
  });
79
115
  await new Promise((resolve) => {
@@ -82,9 +118,24 @@ class Application {
82
118
  return {
83
119
  server,
84
120
  close: async () => {
121
+ closing = true;
85
122
  abortController.abort();
86
- await Promise.all(wsRequests);
87
- await new Promise((resolve) => server.close(resolve));
123
+ await Promise.all([...wsRequests, ...activeHttpRequests]);
124
+ if (process.versions.bun !== void 0) {
125
+ server.closeAllConnections();
126
+ } else {
127
+ server.closeIdleConnections();
128
+ }
129
+ if (server.listening) {
130
+ await new Promise(
131
+ (resolve) => server.close((error) => {
132
+ if (error) {
133
+ this.logger.error(error);
134
+ }
135
+ resolve();
136
+ })
137
+ );
138
+ }
88
139
  }
89
140
  };
90
141
  }
@@ -108,10 +159,23 @@ class Application {
108
159
  requestLogger = requestLogger.child({
109
160
  user: authResult?.identityId
110
161
  });
162
+ if (abortSignal.aborted) {
163
+ throw new HttpErrorResponse(503, "Server is shutting down");
164
+ }
111
165
  const ws = await new Promise((resolve) => wss.handleUpgrade(req, socket, head, (ws2, request) => {
112
166
  resolve(ws2);
113
167
  }));
114
168
  const wsEstablished = (/* @__PURE__ */ new Date()).getTime();
169
+ ws.on("error", (e) => {
170
+ requestLogger.error(e, {
171
+ websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
172
+ });
173
+ });
174
+ if (abortSignal.aborted) {
175
+ await this.closeWebsocket(ws);
176
+ return;
177
+ }
178
+ const pendingWork = [];
115
179
  webSocketContext = {
116
180
  ws,
117
181
  abortSignal,
@@ -121,23 +185,25 @@ class Application {
121
185
  request: req,
122
186
  authResult,
123
187
  params: matchedRequest.params,
124
- projectGroup: groupContainer
188
+ projectGroup: groupContainer,
189
+ waitUntil: (promise) => pendingWork.push(promise)
125
190
  };
126
191
  await matchedRequest.controller(webSocketContext);
192
+ if (abortSignal.aborted && ws.readyState === WebSocket.OPEN) {
193
+ ws.close(1012);
194
+ }
127
195
  requestLogger.debug("Websocket connection established");
128
- ws.on("error", (e) => {
129
- requestLogger.error(e, {
130
- websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
131
- });
132
- });
133
- return new Promise((resolve) => {
134
- ws.on("close", () => {
135
- requestLogger.debug("Websocket connection closed", {
136
- websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
196
+ if (ws.readyState !== WebSocket.CLOSED) {
197
+ await new Promise((resolve) => {
198
+ ws.on("close", () => {
199
+ requestLogger.debug("Websocket connection closed", {
200
+ websocketOpenMs: (/* @__PURE__ */ new Date()).getTime() - wsEstablished
201
+ });
202
+ resolve();
137
203
  });
138
- resolve();
139
204
  });
140
- });
205
+ }
206
+ await Promise.allSettled(pendingWork);
141
207
  } catch (e) {
142
208
  if (e instanceof HttpResponse) {
143
209
  this.sendRawHttpResponse(socket, e);
@@ -256,6 +322,22 @@ class Application {
256
322
  ctx.body = response.body;
257
323
  }
258
324
  }
325
+ async closeWebsocket(ws) {
326
+ if (ws.readyState === WebSocket.CLOSED) {
327
+ return;
328
+ }
329
+ ws.close(1012);
330
+ await new Promise((resolve) => {
331
+ const timeout = setTimeout(() => {
332
+ ws.terminate();
333
+ resolve();
334
+ }, websocketCloseTimeoutMs);
335
+ ws.once("close", () => {
336
+ clearTimeout(timeout);
337
+ resolve();
338
+ });
339
+ });
340
+ }
259
341
  sendRawHttpResponse(socket, response) {
260
342
  const headers = {
261
343
  "Connection": "close",