@contember/engine-http 2.1.0-alpha.3 → 2.1.0-alpha.30

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 (149) hide show
  1. package/dist/development/index.cjs +0 -4
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +0 -4
  4. package/dist/development/index.js.map +1 -1
  5. package/dist/development/src/MasterContainer.cjs +27 -29
  6. package/dist/development/src/MasterContainer.cjs.map +1 -1
  7. package/dist/development/src/MasterContainer.js +27 -29
  8. package/dist/development/src/MasterContainer.js.map +1 -1
  9. package/dist/development/src/application/application.cjs +31 -13
  10. package/dist/development/src/application/application.cjs.map +1 -1
  11. package/dist/development/src/application/application.js +31 -13
  12. package/dist/development/src/application/application.js.map +1 -1
  13. package/dist/development/src/config/configSchema.cjs +5 -1
  14. package/dist/development/src/config/configSchema.cjs.map +1 -1
  15. package/dist/development/src/config/configSchema.js +5 -1
  16. package/dist/development/src/config/configSchema.js.map +1 -1
  17. package/dist/development/src/config/configTemplate.cjs +5 -1
  18. package/dist/development/src/config/configTemplate.cjs.map +1 -1
  19. package/dist/development/src/config/configTemplate.js +5 -1
  20. package/dist/development/src/config/configTemplate.js.map +1 -1
  21. package/dist/development/src/content/ContentApiControllerFactory.cjs +29 -12
  22. package/dist/development/src/content/ContentApiControllerFactory.cjs.map +1 -1
  23. package/dist/development/src/content/ContentApiControllerFactory.js +29 -12
  24. package/dist/development/src/content/ContentApiControllerFactory.js.map +1 -1
  25. package/dist/development/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
  26. package/dist/development/src/content/ContentQueryHandlerFactory.js.map +1 -1
  27. package/dist/development/src/content/ProjectMembershipResolver.cjs +2 -2
  28. package/dist/development/src/content/ProjectMembershipResolver.cjs.map +1 -1
  29. package/dist/development/src/content/ProjectMembershipResolver.js +2 -2
  30. package/dist/development/src/content/ProjectMembershipResolver.js.map +1 -1
  31. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +1 -1
  32. package/dist/development/src/projectGroup/ProjectGroupContainer.js +1 -1
  33. package/dist/development/src/system/ContentQueryExecutor.cjs +6 -2
  34. package/dist/development/src/system/ContentQueryExecutor.cjs.map +1 -1
  35. package/dist/development/src/system/ContentQueryExecutor.js +6 -2
  36. package/dist/development/src/system/ContentQueryExecutor.js.map +1 -1
  37. package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs +13 -7
  38. package/dist/development/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
  39. package/dist/development/src/tenant/TenantApiMiddlewareFactory.js +13 -7
  40. package/dist/development/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
  41. package/dist/development/src/utils/remoteAddress.cjs +58 -0
  42. package/dist/development/src/utils/remoteAddress.cjs.map +1 -0
  43. package/dist/development/src/utils/remoteAddress.js +58 -0
  44. package/dist/development/src/utils/remoteAddress.js.map +1 -0
  45. package/dist/production/index.cjs +0 -4
  46. package/dist/production/index.cjs.map +1 -1
  47. package/dist/production/index.js +0 -4
  48. package/dist/production/index.js.map +1 -1
  49. package/dist/production/src/MasterContainer.cjs +27 -29
  50. package/dist/production/src/MasterContainer.cjs.map +1 -1
  51. package/dist/production/src/MasterContainer.js +27 -29
  52. package/dist/production/src/MasterContainer.js.map +1 -1
  53. package/dist/production/src/application/application.cjs +31 -13
  54. package/dist/production/src/application/application.cjs.map +1 -1
  55. package/dist/production/src/application/application.js +31 -13
  56. package/dist/production/src/application/application.js.map +1 -1
  57. package/dist/production/src/config/configSchema.cjs +5 -1
  58. package/dist/production/src/config/configSchema.cjs.map +1 -1
  59. package/dist/production/src/config/configSchema.js +5 -1
  60. package/dist/production/src/config/configSchema.js.map +1 -1
  61. package/dist/production/src/config/configTemplate.cjs +5 -1
  62. package/dist/production/src/config/configTemplate.cjs.map +1 -1
  63. package/dist/production/src/config/configTemplate.js +5 -1
  64. package/dist/production/src/config/configTemplate.js.map +1 -1
  65. package/dist/production/src/content/ContentApiControllerFactory.cjs +29 -12
  66. package/dist/production/src/content/ContentApiControllerFactory.cjs.map +1 -1
  67. package/dist/production/src/content/ContentApiControllerFactory.js +29 -12
  68. package/dist/production/src/content/ContentApiControllerFactory.js.map +1 -1
  69. package/dist/production/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
  70. package/dist/production/src/content/ContentQueryHandlerFactory.js.map +1 -1
  71. package/dist/production/src/content/ProjectMembershipResolver.cjs +2 -2
  72. package/dist/production/src/content/ProjectMembershipResolver.cjs.map +1 -1
  73. package/dist/production/src/content/ProjectMembershipResolver.js +2 -2
  74. package/dist/production/src/content/ProjectMembershipResolver.js.map +1 -1
  75. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +1 -1
  76. package/dist/production/src/projectGroup/ProjectGroupContainer.js +1 -1
  77. package/dist/production/src/system/ContentQueryExecutor.cjs +6 -2
  78. package/dist/production/src/system/ContentQueryExecutor.cjs.map +1 -1
  79. package/dist/production/src/system/ContentQueryExecutor.js +6 -2
  80. package/dist/production/src/system/ContentQueryExecutor.js.map +1 -1
  81. package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs +13 -7
  82. package/dist/production/src/tenant/TenantApiMiddlewareFactory.cjs.map +1 -1
  83. package/dist/production/src/tenant/TenantApiMiddlewareFactory.js +13 -7
  84. package/dist/production/src/tenant/TenantApiMiddlewareFactory.js.map +1 -1
  85. package/dist/production/src/utils/remoteAddress.cjs +58 -0
  86. package/dist/production/src/utils/remoteAddress.cjs.map +1 -0
  87. package/dist/production/src/utils/remoteAddress.js +58 -0
  88. package/dist/production/src/utils/remoteAddress.js.map +1 -0
  89. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  90. package/dist/types/MasterContainer.d.ts +22 -22
  91. package/dist/types/MasterContainer.d.ts.map +1 -1
  92. package/dist/types/application/application.d.ts +1 -0
  93. package/dist/types/application/application.d.ts.map +1 -1
  94. package/dist/types/config/configSchema.d.ts +18 -0
  95. package/dist/types/config/configSchema.d.ts.map +1 -1
  96. package/dist/types/config/configTemplate.d.ts.map +1 -1
  97. package/dist/types/content/ContentApiControllerFactory.d.ts +4 -4
  98. package/dist/types/content/ContentApiControllerFactory.d.ts.map +1 -1
  99. package/dist/types/content/ContentGraphqlContext.d.ts +9 -0
  100. package/dist/types/content/ContentGraphqlContext.d.ts.map +1 -0
  101. package/dist/types/content/ContentQueryHandlerFactory.d.ts +2 -2
  102. package/dist/types/content/ContentQueryHandlerFactory.d.ts.map +1 -1
  103. package/dist/types/content/index.d.ts +0 -1
  104. package/dist/types/content/index.d.ts.map +1 -1
  105. package/dist/types/system/ContentQueryExecutor.d.ts +1 -1
  106. package/dist/types/system/ContentQueryExecutor.d.ts.map +1 -1
  107. package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts +0 -6
  108. package/dist/types/tenant/TenantApiMiddlewareFactory.d.ts.map +1 -1
  109. package/dist/types/tenant/index.d.ts +0 -1
  110. package/dist/types/tenant/index.d.ts.map +1 -1
  111. package/dist/types/tsconfig.tsbuildinfo +1 -1
  112. package/dist/types/utils/remoteAddress.d.ts +3 -0
  113. package/dist/types/utils/remoteAddress.d.ts.map +1 -0
  114. package/package.json +16 -15
  115. package/src/MasterContainer.ts +33 -36
  116. package/src/application/application.ts +32 -13
  117. package/src/config/configSchema.ts +4 -0
  118. package/src/config/configTemplate.ts +4 -0
  119. package/src/content/ContentApiControllerFactory.ts +37 -15
  120. package/src/content/ContentGraphqlContext.ts +7 -0
  121. package/src/content/ContentQueryHandlerFactory.ts +4 -4
  122. package/src/content/ProjectMembershipResolver.ts +2 -2
  123. package/src/content/index.ts +0 -1
  124. package/src/system/ContentQueryExecutor.ts +8 -4
  125. package/src/tenant/TenantApiMiddlewareFactory.ts +15 -10
  126. package/src/tenant/index.ts +0 -1
  127. package/src/utils/remoteAddress.ts +70 -0
  128. package/dist/development/src/content/ContentGraphQLContextFactory.cjs +0 -39
  129. package/dist/development/src/content/ContentGraphQLContextFactory.cjs.map +0 -1
  130. package/dist/development/src/content/ContentGraphQLContextFactory.js +0 -39
  131. package/dist/development/src/content/ContentGraphQLContextFactory.js.map +0 -1
  132. package/dist/development/src/tenant/TenantGraphQLContextFactory.cjs +0 -19
  133. package/dist/development/src/tenant/TenantGraphQLContextFactory.cjs.map +0 -1
  134. package/dist/development/src/tenant/TenantGraphQLContextFactory.js +0 -19
  135. package/dist/development/src/tenant/TenantGraphQLContextFactory.js.map +0 -1
  136. package/dist/production/src/content/ContentGraphQLContextFactory.cjs +0 -39
  137. package/dist/production/src/content/ContentGraphQLContextFactory.cjs.map +0 -1
  138. package/dist/production/src/content/ContentGraphQLContextFactory.js +0 -39
  139. package/dist/production/src/content/ContentGraphQLContextFactory.js.map +0 -1
  140. package/dist/production/src/tenant/TenantGraphQLContextFactory.cjs +0 -19
  141. package/dist/production/src/tenant/TenantGraphQLContextFactory.cjs.map +0 -1
  142. package/dist/production/src/tenant/TenantGraphQLContextFactory.js +0 -19
  143. package/dist/production/src/tenant/TenantGraphQLContextFactory.js.map +0 -1
  144. package/dist/types/content/ContentGraphQLContextFactory.d.ts +0 -38
  145. package/dist/types/content/ContentGraphQLContextFactory.d.ts.map +0 -1
  146. package/dist/types/tenant/TenantGraphQLContextFactory.d.ts +0 -12
  147. package/dist/types/tenant/TenantGraphQLContextFactory.d.ts.map +0 -1
  148. package/src/content/ContentGraphQLContextFactory.ts +0 -70
  149. package/src/tenant/TenantGraphQLContextFactory.ts +0 -24
@@ -0,0 +1,3 @@
1
+ import { IncomingMessage } from 'node:http';
2
+ export declare function getClientIP(req: IncomingMessage, trustedProxies?: string[]): string;
3
+ //# sourceMappingURL=remoteAddress.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remoteAddress.d.ts","sourceRoot":"","sources":["../../../src/utils/remoteAddress.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AA2C3C,wBAAgB,WAAW,CAAC,GAAG,EAAE,eAAe,EAAE,cAAc,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,CA0BnF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contember/engine-http",
3
- "version": "2.1.0-alpha.3",
3
+ "version": "2.1.0-alpha.30",
4
4
  "license": "Apache-2.0",
5
5
  "main": "./dist/production/index.js",
6
6
  "typings": "./dist/types/index.d.ts",
@@ -26,25 +26,26 @@
26
26
  }
27
27
  },
28
28
  "dependencies": {
29
- "@contember/config-loader": "2.1.0-alpha.3",
30
- "@contember/database": "2.1.0-alpha.3",
31
- "@contember/database-migrations": "2.1.0-alpha.3",
32
- "@contember/dic": "2.1.0-alpha.3",
33
- "@contember/engine-common": "2.1.0-alpha.3",
34
- "@contember/engine-content-api": "2.1.0-alpha.3",
35
- "@contember/engine-system-api": "2.1.0-alpha.3",
36
- "@contember/engine-tenant-api": "2.1.0-alpha.3",
37
- "@contember/graphql-utils": "2.1.0-alpha.3",
38
- "@contember/logger": "2.1.0-alpha.3",
39
- "@contember/schema": "2.1.0-alpha.3",
40
- "@contember/schema-migrations": "2.1.0-alpha.3",
41
- "@contember/schema-utils": "2.1.0-alpha.3",
42
- "@contember/typesafe": "2.1.0-alpha.3",
29
+ "@contember/config-loader": "2.1.0-alpha.30",
30
+ "@contember/database": "2.1.0-alpha.30",
31
+ "@contember/database-migrations": "2.1.0-alpha.30",
32
+ "@contember/dic": "2.1.0-alpha.30",
33
+ "@contember/engine-common": "2.1.0-alpha.30",
34
+ "@contember/engine-content-api": "2.1.0-alpha.30",
35
+ "@contember/engine-system-api": "2.1.0-alpha.30",
36
+ "@contember/engine-tenant-api": "2.1.0-alpha.30",
37
+ "@contember/graphql-utils": "2.1.0-alpha.30",
38
+ "@contember/logger": "2.1.0-alpha.30",
39
+ "@contember/schema": "2.1.0-alpha.30",
40
+ "@contember/schema-migrations": "2.1.0-alpha.30",
41
+ "@contember/schema-utils": "2.1.0-alpha.30",
42
+ "@contember/typesafe": "2.1.0-alpha.30",
43
43
  "@graphql-tools/merge": "^9.0.8",
44
44
  "@graphql-tools/schema": "^10.0.7",
45
45
  "@koa/cors": "^5.0.0",
46
46
  "@sentry/node": "^7.119.2",
47
47
  "bcryptjs": "^2.4.3",
48
+ "ipaddr.js": "^2.2.0",
48
49
  "koa": "^2.15.3",
49
50
  "koa-bodyparser": "^4.4.1",
50
51
  "koa-compress": "^5.1.1",
@@ -1,25 +1,40 @@
1
+ import { Builder } from '@contember/dic'
1
2
  import { SystemContainerFactory } from '@contember/engine-system-api'
2
3
  import { TenantContainerFactory } from '@contember/engine-tenant-api'
3
- import { Builder } from '@contember/dic'
4
- import { ServerConfig } from './config/config'
5
4
  import { ModificationHandlerFactory } from '@contember/schema-migrations'
6
5
  import { Initializer } from './bootstrap'
6
+ import { ServerConfig } from './config/config'
7
7
 
8
- import { ProjectContainerFactoryFactory } from './project'
8
+ import { DatabaseMetadataResolver } from '@contember/database'
9
+ import { ExecutionContainerFactory, GraphQlSchemaBuilderFactory, PermissionFactory } from '@contember/engine-content-api'
10
+ import { Logger } from '@contember/logger'
11
+ import { Schema } from '@contember/schema'
12
+ import Koa from 'koa'
13
+ import { createSecretKey } from 'node:crypto'
14
+ import { Application } from './application'
15
+ import { HttpResponse } from './common'
9
16
  import { ProjectConfigResolver } from './config/projectConfigResolver'
10
17
  import { TenantConfigResolver } from './config/tenantConfigResolver'
11
- import { ProjectGroupContainerFactory } from './projectGroup/ProjectGroupContainer'
12
- import { ProjectGroupResolver } from './projectGroup/ProjectGroupResolver'
13
- import { Logger } from '@contember/logger'
14
- import { ExecutionContainerFactory, GraphQlSchemaBuilderFactory, PermissionFactory } from '@contember/engine-content-api'
15
- import { createProviders, Providers } from './providers'
16
- import { TenantApiMiddlewareFactory, TenantGraphQLContextFactory, TenantGraphQLHandlerFactory } from './tenant'
17
- import { SystemApiMiddlewareFactory, SystemGraphQLContextFactory, SystemGraphQLHandlerFactory } from './system'
18
18
  import {
19
- ContentApiControllerFactory, ContentGraphQLContextFactory, ContentQueryHandlerFactory, GraphQLSchemaContributor, GraphQlSchemaFactory,
19
+ ContentApiControllerFactory,
20
+ ContentQueryHandlerFactory, GraphQLSchemaContributor, GraphQlSchemaFactory,
20
21
  GraphQLSchemaFactoryResult, NotModifiedChecker,
21
22
  } from './content'
23
+ import { ContentApiSpecificCache } from './content/ContentApiSpecificCache'
24
+ import { homepageController } from './misc'
25
+ import { Plugin } from './plugin/Plugin'
26
+ import { ProjectContainerFactoryFactory } from './project'
22
27
  import { ProjectContextResolver } from './project-common'
28
+ import { ProjectGroupContainerFactory } from './projectGroup/ProjectGroupContainer'
29
+ import { ProjectGroupContainerResolver } from './projectGroup/ProjectGroupContainerResolver'
30
+ import { ProjectGroupResolver } from './projectGroup/ProjectGroupResolver'
31
+ import { createColllectHttpMetricsMiddleware, createShowMetricsMiddleware } from './prometheus'
32
+ import { ProjectGroupContainerMetricsHook } from './prometheus/ProjectGroupContainerMetricsHook'
33
+ import { PrometheusRegistryFactory } from './prometheus/PrometheusRegistryFactory'
34
+ import { createProviders, Providers } from './providers'
35
+ import { SystemApiMiddlewareFactory, SystemGraphQLContextFactory, SystemGraphQLHandlerFactory } from './system'
36
+ import { ContentQueryExecutorImpl } from './system/ContentQueryExecutor'
37
+ import { TenantApiMiddlewareFactory, TenantGraphQLHandlerFactory } from './tenant'
23
38
  import {
24
39
  ContentSchemaTransferMappingFactory,
25
40
  ExportApiControllerFactory,
@@ -28,22 +43,8 @@ import {
28
43
  ImportExecutor,
29
44
  SystemSchemaTransferMappingFactory,
30
45
  } from './transfer'
31
- import { homepageController } from './misc'
32
- import { Plugin } from './plugin/Plugin'
33
- import { Application } from './application'
34
- import { ApplicationWorkerManager } from './workers'
35
- import { HttpResponse } from './common'
36
- import { ContentQueryExecutorImpl } from './system/ContentQueryExecutor'
37
- import { DatabaseMetadataResolver } from '@contember/database'
38
- import Koa from 'koa'
39
- import { ProjectGroupContainerResolver } from './projectGroup/ProjectGroupContainerResolver'
40
- import { PrometheusRegistryFactory } from './prometheus/PrometheusRegistryFactory'
41
- import { ProjectGroupContainerMetricsHook } from './prometheus/ProjectGroupContainerMetricsHook'
42
- import { createColllectHttpMetricsMiddleware, createShowMetricsMiddleware } from './prometheus'
43
- import { createSecretKey } from 'node:crypto'
44
46
  import { CryptoWrapper } from './utils/CryptoWrapper'
45
- import { ContentApiSpecificCache } from './content/ContentApiSpecificCache'
46
- import { Schema } from '@contember/schema'
47
+ import { ApplicationWorkerManager } from './workers'
47
48
 
48
49
  export type ProcessType =
49
50
  | 'singleNode'
@@ -113,8 +114,8 @@ export class MasterContainerFactory {
113
114
  new TenantContainerFactory(providers))
114
115
  .addService('modificationHandlerFactory', () =>
115
116
  new ModificationHandlerFactory(ModificationHandlerFactory.defaultFactoryMap))
116
- .addService('executionContainerFactory', ({ providers }) =>
117
- new ExecutionContainerFactory(providers))
117
+ .addService('executionContainerFactory', ({ providers, serverConfig }) =>
118
+ new ExecutionContainerFactory(providers, serverConfig.contentApi?.whereOptimizer))
118
119
  .addService('graphQlSchemaBuilderFactory', () =>
119
120
  new GraphQlSchemaBuilderFactory())
120
121
  .addService('contentQueryExecutor', ({ executionContainerFactory, graphQlSchemaBuilderFactory }) =>
@@ -178,18 +179,14 @@ export class MasterContainerFactory {
178
179
  })
179
180
  .addService('notModifiedChecker', () =>
180
181
  new NotModifiedChecker())
181
- .addService('contentGraphqlContextFactory', ({ providers, executionContainerFactory }) =>
182
- new ContentGraphQLContextFactory(providers, executionContainerFactory))
183
182
  .addService('contentQueryHandlerFactory', ({ debugMode }) =>
184
183
  new ContentQueryHandlerFactory(debugMode))
185
184
  .addService('projectContextResolver', () =>
186
185
  new ProjectContextResolver())
187
- .addService('contentApiMiddlewareFactory', ({ projectContextResolver, notModifiedChecker, contentGraphqlContextFactory, contentQueryHandlerFactory, graphQlSchemaFactory }) =>
188
- new ContentApiControllerFactory(notModifiedChecker, contentGraphqlContextFactory, contentQueryHandlerFactory, projectContextResolver, graphQlSchemaFactory))
189
- .addService('tenantGraphQLContextFactory', () =>
190
- new TenantGraphQLContextFactory())
191
- .addService('tenantApiMiddlewareFactory', ({ debugMode, projectGroupResolver, tenantGraphQLContextFactory }) =>
192
- new TenantApiMiddlewareFactory(debugMode, projectGroupResolver, tenantGraphQLContextFactory))
186
+ .addService('contentApiMiddlewareFactory', ({ projectContextResolver, notModifiedChecker, executionContainerFactory, contentQueryHandlerFactory, graphQlSchemaFactory }) =>
187
+ new ContentApiControllerFactory(notModifiedChecker, executionContainerFactory, contentQueryHandlerFactory, projectContextResolver, graphQlSchemaFactory))
188
+ .addService('tenantApiMiddlewareFactory', () =>
189
+ new TenantApiMiddlewareFactory())
193
190
  .addService('systemGraphQLContextFactory', () =>
194
191
  new SystemGraphQLContextFactory())
195
192
  .addService('systemApiMiddlewareFactory', ({ debugMode, systemGraphQLContextFactory, projectContextResolver }) =>
@@ -14,6 +14,9 @@ import stream, { Duplex, Readable } from 'node:stream'
14
14
  import { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'
15
15
  import { ProjectGroupContainer } from '../projectGroup/ProjectGroupContainer'
16
16
  import { URL } from 'node:url'
17
+ import { cpuUsage, memoryUsage } from 'node:process'
18
+ import { performance } from 'node:perf_hooks'
19
+ import { getClientIP } from '../utils/remoteAddress'
17
20
 
18
21
  type Route<C> = { match: RequestMatcher; controller: C; module: string }
19
22
  export class Application {
@@ -116,13 +119,14 @@ export class Application {
116
119
  let webSocketContext: WebSocketContext | null = null
117
120
  let requestLogger = this.logger
118
121
  const { timer, send: sendTimer } = this.createTimer()
122
+ const clientIp = getClientIP(req)
119
123
  try {
120
124
  const url = new URL(req.url ?? '/', `http://${req.headers.host}`)
121
125
  const matchedRequest = this.matchRequest(this.websocketRoutes, url)
122
126
  if (!matchedRequest) {
123
127
  throw new HttpErrorResponse(404, 'Route not found')
124
128
  }
125
- requestLogger = this.createRequestLogger(req, undefined, matchedRequest.module)
129
+ requestLogger = this.createRequestLogger(req, undefined, matchedRequest.module, clientIp)
126
130
 
127
131
  const groupContainer = await this.projectGroupResolver.resolveContainer({ request: req })
128
132
 
@@ -139,7 +143,7 @@ export class Application {
139
143
  const ws = await new Promise<WebSocket>(resolve => wss.handleUpgrade(req, socket, head, (ws, request) => {
140
144
  resolve(ws)
141
145
  }))
142
- const wsEstablished = new Date().getTime()
146
+ const wsEstablished = performance.now()
143
147
  webSocketContext = {
144
148
  ws,
145
149
  abortSignal,
@@ -147,6 +151,7 @@ export class Application {
147
151
  timer,
148
152
  url,
149
153
  request: req,
154
+ clientIp,
150
155
  authResult,
151
156
  params: matchedRequest.params,
152
157
  projectGroup: groupContainer,
@@ -155,14 +160,14 @@ export class Application {
155
160
  requestLogger.debug('Websocket connection established')
156
161
  ws.on('error', e => {
157
162
  requestLogger.error(e, {
158
- websocketOpenMs: new Date().getTime() - wsEstablished,
163
+ websocketOpenMs: performance.now() - wsEstablished,
159
164
  })
160
165
  })
161
166
 
162
167
  return new Promise<void>(resolve => {
163
168
  ws.on('close', () => {
164
169
  requestLogger.debug('Websocket connection closed', {
165
- websocketOpenMs: new Date().getTime() - wsEstablished,
170
+ websocketOpenMs: performance.now() - wsEstablished,
166
171
  })
167
172
  resolve()
168
173
  })
@@ -193,7 +198,8 @@ export class Application {
193
198
  }
194
199
  }
195
200
  let httpContext: HttpContext | null = null
196
- let requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module)
201
+ const clientIp = getClientIP(ctx.req)
202
+ let requestLogger = this.createRequestLogger(ctx.req, ctx.request.body, matchedRequest?.module, clientIp)
197
203
  const { timer, send: sendTimer } = this.createTimer()
198
204
 
199
205
  try {
@@ -221,12 +227,12 @@ export class Application {
221
227
  user: authResult?.identityId,
222
228
  })
223
229
 
224
-
225
230
  const response = await requestLogger.scope(async logger => {
226
231
  httpContext = {
227
232
  koa: ctx,
228
233
  body: ctx.request.body,
229
234
  url: ctx.request.URL,
235
+ clientIp,
230
236
  logger,
231
237
  timer,
232
238
  request: ctx.req,
@@ -266,6 +272,7 @@ export class Application {
266
272
  const response = await this.logger.scope(async logger => {
267
273
  return await matchedRequest.controller({
268
274
  koa: ctx,
275
+ clientIp: getClientIP(ctx.req),
269
276
  body: ctx.request.body,
270
277
  url: ctx.request.URL,
271
278
  logger,
@@ -317,12 +324,13 @@ export class Application {
317
324
  )
318
325
  }
319
326
 
320
- private createRequestLogger(request: IncomingMessage, body: any, module?: string): Logger {
327
+ private createRequestLogger(request: IncomingMessage, body: any, module?: string, remoteAddress?: string): Logger {
321
328
  return this.logger.child({
322
329
  method: request.method,
323
330
  uri: request.url,
324
331
  requestId: Math.random().toString().substring(2),
325
332
  module,
333
+ remoteAddress,
326
334
  [LoggerRequestBody]: body,
327
335
  }, {
328
336
  handler: FingerCrossedLoggerHandler.factory(),
@@ -331,10 +339,12 @@ export class Application {
331
339
 
332
340
  private createTimer() {
333
341
  const times: EventTime[] = []
334
- const globalStart = new Date().getTime()
342
+ const globalStart = performance.now()
343
+ const cpuUsageStart = cpuUsage()
344
+ const memoryUsageStart = memoryUsage()
335
345
  const timer: Timer = (name: string, cb) => {
336
- const start = new Date().getTime()
337
- const time: EventTime = { label: name, start: start - globalStart }
346
+ const start = performance.now()
347
+ const time: EventTime = { label: name, start: Math.round(start - globalStart) }
338
348
  times.push(time)
339
349
  const res = cb()
340
350
 
@@ -344,7 +354,7 @@ export class Application {
344
354
  await res
345
355
  } catch {
346
356
  } finally {
347
- time.duration = new Date().getTime() - start
357
+ time.duration = Math.round(performance.now() - start)
348
358
  }
349
359
  })()
350
360
  }
@@ -357,16 +367,24 @@ export class Application {
357
367
  }
358
368
 
359
369
  const emit = () => {
360
- const total = new Date().getTime() - globalStart
370
+ const total = performance.now() - globalStart
361
371
  const timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'
362
372
  const shouldSuppress = this.suppressAccessLog === true || !ctx.req.url || (this.suppressAccessLog !== false && this.suppressAccessLog.test(ctx.req.url))
363
373
 
374
+ const cpuUsageEnd = cpuUsage()
375
+ const memoryUsageEnd = memoryUsage()
376
+
377
+ const cpuUsageDiffMs = (cpuUsageEnd.user - cpuUsageStart.user) / 1000
378
+ const memoryUsageDiff = memoryUsageEnd.heapUsed - memoryUsageStart.heapUsed
364
379
  const level = shouldSuppress ? 'debug' : 'info'
365
380
  ctx.logger.log(level, !ctx.response ? 'Connection established' : ctx.response.statusCode < 400 ? `Request successful` : 'Request failed', {
366
381
  status: ctx.response?.statusCode,
367
382
  timeLabel: timeLabel,
368
- totalTimeMs: total,
383
+ totalTimeMs: Math.round(total),
369
384
  events: times,
385
+ cpuUsageDiffMs,
386
+ memoryUsageDiff,
387
+ responseBodySize: ctx.body && typeof ctx.body === 'string' ? ctx.body.length : undefined,
370
388
  })
371
389
  }
372
390
 
@@ -413,6 +431,7 @@ export type BaseRequestContext = {
413
431
  request: IncomingMessage
414
432
  url: URL
415
433
  params: Params
434
+ clientIp: string
416
435
  }
417
436
 
418
437
  export type ApplicationContext =
@@ -117,6 +117,10 @@ export const serverConfigSchema = Typesafe.partial({
117
117
  }),
118
118
  contentApi: Typesafe.partial({
119
119
  schemaCacheTtlSeconds: Typesafe.integer,
120
+ whereOptimizer: Typesafe.partial({
121
+ disable: Typesafe.boolean,
122
+ maxCrossOptimizationInput: Typesafe.number,
123
+ }),
120
124
  }),
121
125
  logging: Typesafe.union(
122
126
  (val): { sentry?: { dsn: string } } => Typesafe.valueAt(val, ['sentry', 'dsn']) === undefined ? {} : Typesafe.fail([]),
@@ -87,6 +87,10 @@ export const configTemplate: any = {
87
87
  },
88
88
  contentApi: {
89
89
  schemaCacheTtlSeconds: '%?env.CONTEMBER_CONTENT_API_SCHEMA_CACHE_TTL_SECONDS::number%',
90
+ whereOptimizer: {
91
+ disable: '%?env.CONTEMBER_CONTENT_API_WHERE_OPTIMIZER_DISABLE::bool%',
92
+ maxCrossOptimizationInput: '%?env.CONTEMBER_CONTENT_API_MAX_CROSS_OPTIMIZATION_INPUT::number%',
93
+ },
90
94
  },
91
95
  projectGroup: {
92
96
  domainMapping: '%?env.CONTEMBER_PROJECT_GROUP_DOMAIN_MAPPING%',
@@ -1,20 +1,20 @@
1
- import { HttpController } from '../application'
2
- import { ProjectContextResolver } from '../project-common'
3
- import { HttpErrorResponse, HttpResponse } from '../common'
1
+ import { createAclVariables, ExecutionContainerFactory } from '@contember/engine-content-api'
4
2
  import { StageBySlugQuery } from '@contember/engine-system-api'
5
- import { NotModifiedChecker } from './NotModifiedChecker'
6
- import { ContentGraphQLContextFactory } from './ContentGraphQLContextFactory'
7
- import { ContentQueryHandler, ContentQueryHandlerFactory } from './ContentQueryHandlerFactory'
8
3
  import { GraphQLSchema } from 'graphql'
4
+ import { HttpController } from '../application'
5
+ import { HttpErrorResponse, HttpResponse } from '../common'
9
6
  import { GraphQLKoaState } from '../graphql'
7
+ import { ProjectContextResolver } from '../project-common'
8
+ import { ContentQueryHandler, ContentQueryHandlerFactory } from './ContentQueryHandlerFactory'
10
9
  import { GraphQlSchemaFactory } from './GraphQlSchemaFactory'
10
+ import { NotModifiedChecker } from './NotModifiedChecker'
11
11
 
12
12
  const debugHeader = 'x-contember-debug'
13
13
 
14
14
  export class ContentApiControllerFactory {
15
15
  constructor(
16
16
  private readonly notModifiedChecker: NotModifiedChecker,
17
- private readonly contentGraphqlContextFactory: ContentGraphQLContextFactory,
17
+ private readonly executionContainerFactory: ExecutionContainerFactory,
18
18
  private readonly handlerFactory: ContentQueryHandlerFactory,
19
19
  private readonly projectContextResolver: ProjectContextResolver,
20
20
  private readonly graphQlSchemaFactory: GraphQlSchemaFactory,
@@ -24,7 +24,7 @@ export class ContentApiControllerFactory {
24
24
  create(): HttpController {
25
25
  const handlerCache = new WeakMap<GraphQLSchema, ContentQueryHandler>()
26
26
  return async context => {
27
- const { params, timer, projectGroup, authResult, request, koa } = context
27
+ const { params, timer, projectGroup, authResult, request, koa, clientIp } = context
28
28
  if (!authResult) {
29
29
  return new HttpErrorResponse(401, 'Authentication required')
30
30
  }
@@ -113,20 +113,42 @@ export class ContentApiControllerFactory {
113
113
  const connection = operation === 'query' ? projectContainer.readConnection : projectContainer.connection
114
114
  const contentDatabase = connection.createClient(stage.schema, { module: 'content' })
115
115
 
116
- return this.contentGraphqlContextFactory.create({
116
+
117
+ const identityVariables = createAclVariables(schema.acl, memberships)
118
+ let identityId = authResult.identityId
119
+ if (
120
+ authResult.assumedIdentityId &&
121
+ memberships.some(it => schema.acl.roles[it.role].system?.assumeIdentity)
122
+ ) {
123
+ identityId = authResult.assumedIdentityId
124
+ }
125
+
126
+ const executionContainer = this.executionContainerFactory.create({
117
127
  db: contentDatabase,
118
- authResult,
119
- memberships,
120
- permissions,
121
- schemaDatabaseMetadata,
128
+ identityVariables,
129
+ identityId,
122
130
  schema,
123
131
  schemaMeta: { id: schemaWithMeta.meta.id },
124
- timer,
125
- requestDebug,
132
+ schemaDatabaseMetadata,
133
+ permissions,
126
134
  systemSchema: projectContainer.systemDatabaseContextFactory.schemaName,
127
135
  stage,
128
136
  project,
137
+ userInfo: {
138
+ ipAddress: clientIp,
139
+ userAgent: koa.request.headers['user-agent'] ?? null,
140
+ },
129
141
  })
142
+
143
+ return {
144
+ db: contentDatabase,
145
+ identityVariables,
146
+ identityId,
147
+ executionContainer,
148
+ timer,
149
+ requestDebug,
150
+ project,
151
+ }
130
152
  },
131
153
  }))
132
154
  logger.debug('Content query finished')
@@ -0,0 +1,7 @@
1
+ import { Context } from '@contember/engine-content-api'
2
+
3
+ export type ContentGraphqlContext = Context & {
4
+ identityId: string
5
+ requestDebug: boolean
6
+ project: { slug: string }
7
+ }
@@ -1,17 +1,17 @@
1
1
  import { GraphQLSchema } from 'graphql'
2
2
  import { createDbQueriesListener, createGraphQLQueryHandler, GraphQLListener, GraphQLQueryHandler } from '../graphql'
3
- import { ExtendedGraphqlContext } from './ContentGraphQLContextFactory'
3
+ import { ContentGraphqlContext } from './ContentGraphqlContext'
4
4
 
5
- export type ContentQueryHandler = GraphQLQueryHandler<ExtendedGraphqlContext>
5
+ export type ContentQueryHandler = GraphQLQueryHandler<ContentGraphqlContext>
6
6
 
7
7
  export class ContentQueryHandlerFactory {
8
8
  constructor(private readonly debug: boolean) {}
9
9
 
10
10
  public create(graphQlSchema: GraphQLSchema): ContentQueryHandler {
11
- const listeners: GraphQLListener<ExtendedGraphqlContext>[] = []
11
+ const listeners: GraphQLListener<ContentGraphqlContext>[] = []
12
12
  listeners.push(createDbQueriesListener(context => context.db, this.debug))
13
13
 
14
- return createGraphQLQueryHandler<ExtendedGraphqlContext>({
14
+ return createGraphQLQueryHandler<ContentGraphqlContext>({
15
15
  schema: graphQlSchema,
16
16
  listeners,
17
17
  })
@@ -53,7 +53,7 @@ export class ProjectMembershipResolver {
53
53
  throwNotAllowed()
54
54
  }
55
55
 
56
- const parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity)
56
+ const parsedMemberships = membershipResolver.resolve(acl, assumedMemberships, identity, true)
57
57
  if (parsedMemberships.errors.length > 0) {
58
58
  throw new HttpErrorResponse(
59
59
  400,
@@ -73,7 +73,7 @@ export class ProjectMembershipResolver {
73
73
  return {
74
74
  effective: [
75
75
  // intentionally ignoring validation errors of stored memberships
76
- ...membershipResolver.resolve(acl, explicitMemberships, identity).memberships,
76
+ ...membershipResolver.resolve(acl, explicitMemberships, identity, false).memberships,
77
77
  ...implicitRolesToAssign.map(it => ({ role: it, variables: [] })),
78
78
  ],
79
79
  fetched: explicitMemberships,
@@ -1,5 +1,4 @@
1
1
  export * from './ContentApiControllerFactory'
2
- export * from './ContentGraphQLContextFactory'
3
2
  export * from './ContentQueryHandlerFactory'
4
3
  export * from './GraphQLSchemaContributor'
5
4
  export * from './ContentSchemaResolver'
@@ -1,15 +1,15 @@
1
+ import { Authorizator, ExecutionContainerFactory, GraphQlSchemaBuilderFactory } from '@contember/engine-content-api'
1
2
  import {
2
3
  ContentQueryExecutor,
3
4
  ContentQueryExecutorContext,
4
5
  ContentQueryExecutorQuery,
5
6
  ContentQueryExecutorResult,
6
7
  } from '@contember/engine-system-api'
7
- import { Authorizator, ExecutionContainerFactory, GraphQlSchemaBuilderFactory } from '@contember/engine-content-api'
8
+ import { logger } from '@contember/logger'
8
9
  import { AllowAllPermissionFactory } from '@contember/schema-utils'
9
10
  import { graphql, GraphQLError } from 'graphql'
10
- import { ExtendedGraphqlContext } from '../content'
11
+ import { ContentGraphqlContext } from '../content/ContentGraphqlContext'
11
12
  import { extractOriginalError } from '../graphql'
12
- import { logger } from '@contember/logger'
13
13
 
14
14
  export class ContentQueryExecutorImpl implements ContentQueryExecutor {
15
15
  constructor(
@@ -37,9 +37,13 @@ export class ContentQueryExecutorImpl implements ContentQueryExecutor {
37
37
  systemSchema: project.systemSchema,
38
38
  stage,
39
39
  project: project,
40
+ userInfo: {
41
+ ipAddress: null,
42
+ userAgent: null,
43
+ },
40
44
  })
41
45
 
42
- const ctx: ExtendedGraphqlContext = {
46
+ const ctx: ContentGraphqlContext = {
43
47
  project,
44
48
  db: db.client.forSchema(stage.schema),
45
49
  identityVariables: {},
@@ -1,20 +1,13 @@
1
1
  import { HttpController } from '../application'
2
2
  import { HttpErrorResponse } from '../common'
3
- import { TenantGraphQLContextFactory } from './TenantGraphQLContextFactory'
4
- import { ProjectGroupResolver } from '../projectGroup/ProjectGroupResolver'
5
3
  import { GraphQLKoaState } from '../graphql'
6
4
 
7
5
  export class TenantApiMiddlewareFactory {
8
- constructor(
9
- private readonly debug: boolean,
10
- private readonly projectGroupResolver: ProjectGroupResolver,
11
- private readonly tenantGraphQLContextFactory: TenantGraphQLContextFactory,
12
- ) {
13
- }
6
+
14
7
 
15
8
  create(): HttpController {
16
9
  return async ctx => {
17
- const { timer, projectGroup, authResult, logger, koa } = ctx
10
+ const { timer, projectGroup, authResult, logger, koa, clientIp } = ctx
18
11
  if (!authResult) {
19
12
  return new HttpErrorResponse(401, 'Authentication required')
20
13
  }
@@ -28,8 +21,20 @@ export class TenantApiMiddlewareFactory {
28
21
  (koa.state as GraphQLKoaState).graphql = {
29
22
  operationName: operation,
30
23
  }
24
+ const resolverContextFactory = tenantContainer.resolverContextFactory
25
+ const db = tenantContainer.databaseContext
26
+ const context = resolverContextFactory.create(
27
+ authResult,
28
+ { ip: clientIp, userAgent: koa.request.headers['user-agent'] },
29
+ db,
30
+ logger,
31
+ )
32
+
33
+ return {
34
+ ...context,
35
+ identityId: authResult.identityId,
36
+ }
31
37
 
32
- return this.tenantGraphQLContextFactory.create({ authResult, tenantContainer, logger })
33
38
  },
34
39
  }))
35
40
  logger.debug('Tenant query finished')
@@ -1,3 +1,2 @@
1
1
  export * from './TenantApiMiddlewareFactory'
2
2
  export * from './TenantGraphQLHandlerFactory'
3
- export * from './TenantGraphQLContextFactory'
@@ -0,0 +1,70 @@
1
+ import { IncomingMessage } from 'node:http'
2
+ import ipaddr from 'ipaddr.js'
3
+
4
+
5
+ function isPrivate(ip: string): boolean {
6
+ let addr: ipaddr.IPv4 | ipaddr.IPv6
7
+ try {
8
+ addr = ipaddr.parse(ip)
9
+ } catch {
10
+ return false
11
+ }
12
+
13
+ const r = addr.range()
14
+ if (r === 'ipv4Mapped') {
15
+ return (addr as ipaddr.IPv6).toIPv4Address().range() === 'private'
16
+ }
17
+
18
+ return r === 'private' // IPv4 RFC1918
19
+ || r === 'uniqueLocal' // IPv6 fc00::/7
20
+ || r === 'linkLocal' // IPv6 fe80::/10
21
+ }
22
+
23
+
24
+ function isInCIDR(ip: string, cidrs: string[]): boolean {
25
+ if (!cidrs || cidrs.length === 0) {
26
+ return false
27
+ }
28
+
29
+ let addr: ipaddr.IPv4 | ipaddr.IPv6
30
+ try {
31
+ addr = ipaddr.parse(ip)
32
+ } catch {
33
+ return false
34
+ }
35
+ return cidrs.some(c => {
36
+ try {
37
+ return addr.match(ipaddr.parseCIDR(c))
38
+ } catch {
39
+ return false
40
+ }
41
+ })
42
+ }
43
+
44
+ export function getClientIP(req: IncomingMessage, trustedProxies?: string[]): string {
45
+ const remote = req.socket.remoteAddress || ''
46
+
47
+ if (!isPrivate(remote) && !isInCIDR(remote, trustedProxies || [])) {
48
+ return remote
49
+ }
50
+
51
+ const xffHeader = req.headers['x-forwarded-for']
52
+ let xffList: string[] = []
53
+
54
+ if (Array.isArray(xffHeader)) {
55
+ xffHeader.forEach(h =>
56
+ xffList.push(...h.split(',').map(ip => ip.trim()).filter(Boolean)),
57
+ )
58
+ } else if (typeof xffHeader === 'string') {
59
+ xffList = xffHeader.split(',').map(ip => ip.trim()).filter(Boolean)
60
+ }
61
+
62
+ for (let i = xffList.length - 1; i >= 0; i--) {
63
+ const ip = xffList[i]
64
+ if (!isPrivate(ip) && !isInCIDR(ip, trustedProxies || [])) {
65
+ return ip
66
+ }
67
+ }
68
+
69
+ return remote
70
+ }