@contember/engine-http 1.3.0-alpha.6 → 1.3.0-alpha.8

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 (71) hide show
  1. package/dist/src/MasterContainer.d.ts +3 -0
  2. package/dist/src/MasterContainer.d.ts.map +1 -1
  3. package/dist/src/MasterContainer.js +1 -1
  4. package/dist/src/MasterContainer.js.map +1 -1
  5. package/dist/src/application/application.d.ts +1 -1
  6. package/dist/src/application/application.d.ts.map +1 -1
  7. package/dist/src/application/application.js +14 -7
  8. package/dist/src/application/application.js.map +1 -1
  9. package/dist/src/config/configSchema.d.ts +3 -0
  10. package/dist/src/config/configSchema.d.ts.map +1 -1
  11. package/dist/src/config/configSchema.js +3 -0
  12. package/dist/src/config/configSchema.js.map +1 -1
  13. package/dist/src/config/configTemplate.d.ts.map +1 -1
  14. package/dist/src/config/configTemplate.js +3 -0
  15. package/dist/src/config/configTemplate.js.map +1 -1
  16. package/dist/src/content/ContentApiControllerFactory.d.ts.map +1 -1
  17. package/dist/src/content/ContentApiControllerFactory.js +3 -1
  18. package/dist/src/content/ContentApiControllerFactory.js.map +1 -1
  19. package/dist/src/content/ContentApiSpecificCache.d.ts +9 -0
  20. package/dist/src/content/ContentApiSpecificCache.d.ts.map +1 -0
  21. package/dist/src/content/ContentApiSpecificCache.js +40 -0
  22. package/dist/src/content/ContentApiSpecificCache.js.map +1 -0
  23. package/dist/src/content/ContentGraphQLContextFactory.d.ts +3 -2
  24. package/dist/src/content/ContentGraphQLContextFactory.d.ts.map +1 -1
  25. package/dist/src/content/ContentGraphQLContextFactory.js +2 -1
  26. package/dist/src/content/ContentGraphQLContextFactory.js.map +1 -1
  27. package/dist/src/content/GraphQLSchemaContributor.d.ts +1 -4
  28. package/dist/src/content/GraphQLSchemaContributor.d.ts.map +1 -1
  29. package/dist/src/content/GraphQlSchemaFactory.d.ts +10 -5
  30. package/dist/src/content/GraphQlSchemaFactory.d.ts.map +1 -1
  31. package/dist/src/content/GraphQlSchemaFactory.js +26 -39
  32. package/dist/src/content/GraphQlSchemaFactory.js.map +1 -1
  33. package/dist/src/content/Identity.d.ts +4 -0
  34. package/dist/src/content/Identity.d.ts.map +1 -0
  35. package/dist/src/content/Identity.js +3 -0
  36. package/dist/src/content/Identity.js.map +1 -0
  37. package/dist/src/content/index.d.ts +1 -0
  38. package/dist/src/content/index.d.ts.map +1 -1
  39. package/dist/src/content/index.js +1 -0
  40. package/dist/src/content/index.js.map +1 -1
  41. package/dist/src/project/ProjectContainer.d.ts +19 -6
  42. package/dist/src/project/ProjectContainer.d.ts.map +1 -1
  43. package/dist/src/project/ProjectContainer.js +18 -9
  44. package/dist/src/project/ProjectContainer.js.map +1 -1
  45. package/dist/src/project/ProjectDatabaseMetadataResolver.d.ts +10 -0
  46. package/dist/src/project/ProjectDatabaseMetadataResolver.d.ts.map +1 -0
  47. package/dist/src/project/ProjectDatabaseMetadataResolver.js +25 -0
  48. package/dist/src/project/ProjectDatabaseMetadataResolver.js.map +1 -0
  49. package/dist/src/tsconfig.tsbuildinfo +1 -1
  50. package/dist/src/utils/serverStartup.d.ts +3 -0
  51. package/dist/src/utils/serverStartup.d.ts.map +1 -1
  52. package/dist/tests/cases/unit/contentApiSpecificCache.tst.d.ts +2 -0
  53. package/dist/tests/cases/unit/contentApiSpecificCache.tst.d.ts.map +1 -0
  54. package/dist/tests/cases/unit/contentApiSpecificCache.tst.js +132 -0
  55. package/dist/tests/cases/unit/contentApiSpecificCache.tst.js.map +1 -0
  56. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  57. package/package.json +16 -16
  58. package/src/MasterContainer.ts +2 -2
  59. package/src/application/application.ts +15 -10
  60. package/src/config/configSchema.ts +3 -0
  61. package/src/config/configTemplate.ts +3 -0
  62. package/src/content/ContentApiControllerFactory.ts +11 -3
  63. package/src/content/ContentApiSpecificCache.ts +51 -0
  64. package/src/content/ContentGraphQLContextFactory.ts +4 -2
  65. package/src/content/GraphQLSchemaContributor.ts +1 -6
  66. package/src/content/GraphQlSchemaFactory.ts +40 -54
  67. package/src/content/Identity.ts +3 -0
  68. package/src/content/index.ts +1 -0
  69. package/src/project/ProjectContainer.ts +43 -10
  70. package/src/project/ProjectDatabaseMetadataResolver.ts +29 -0
  71. package/tests/cases/unit/contentApiSpecificCache.tst.ts +129 -0
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@contember/engine-http",
3
- "version": "1.3.0-alpha.6",
3
+ "version": "1.3.0-alpha.8",
4
4
  "license": "Apache-2.0",
5
5
  "main": "dist/src/index.js",
6
6
  "typings": "dist/src/index.d.ts",
7
7
  "scripts": {
8
- "test": "vitest"
8
+ "test": "vitest && node --expose-gc ./dist/tests/cases/unit/contentApiSpecificCache.tst.js"
9
9
  },
10
10
  "exports": {
11
11
  "typescript": "./src/index.ts",
@@ -13,20 +13,20 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "@apollographql/graphql-playground-html": "^1.6.24",
16
- "@contember/config-loader": "^1.3.0-alpha.6",
17
- "@contember/database": "^1.3.0-alpha.6",
18
- "@contember/database-migrations": "^1.3.0-alpha.6",
19
- "@contember/dic": "^1.3.0-alpha.6",
20
- "@contember/engine-common": "^1.3.0-alpha.6",
21
- "@contember/engine-content-api": "^1.3.0-alpha.6",
22
- "@contember/engine-system-api": "^1.3.0-alpha.6",
23
- "@contember/engine-tenant-api": "^1.3.0-alpha.6",
24
- "@contember/graphql-utils": "^1.3.0-alpha.6",
25
- "@contember/logger": "^1.3.0-alpha.6",
26
- "@contember/schema": "^1.3.0-alpha.6",
27
- "@contember/schema-migrations": "^1.3.0-alpha.6",
28
- "@contember/schema-utils": "^1.3.0-alpha.6",
29
- "@contember/typesafe": "^1.3.0-alpha.6",
16
+ "@contember/config-loader": "^1.3.0-alpha.8",
17
+ "@contember/database": "^1.3.0-alpha.8",
18
+ "@contember/database-migrations": "^1.3.0-alpha.8",
19
+ "@contember/dic": "^1.3.0-alpha.8",
20
+ "@contember/engine-common": "^1.3.0-alpha.8",
21
+ "@contember/engine-content-api": "^1.3.0-alpha.8",
22
+ "@contember/engine-system-api": "^1.3.0-alpha.8",
23
+ "@contember/engine-tenant-api": "^1.3.0-alpha.8",
24
+ "@contember/graphql-utils": "^1.3.0-alpha.8",
25
+ "@contember/logger": "^1.3.0-alpha.8",
26
+ "@contember/schema": "^1.3.0-alpha.8",
27
+ "@contember/schema-migrations": "^1.3.0-alpha.8",
28
+ "@contember/schema-utils": "^1.3.0-alpha.8",
29
+ "@contember/typesafe": "^1.3.0-alpha.8",
30
30
  "@graphql-tools/schema": "^8.3.5",
31
31
  "@graphql-tools/merge": "^8.3.5",
32
32
  "@sentry/node": "^7.1.1",
@@ -95,8 +95,8 @@ export class MasterContainerFactory {
95
95
  new ModificationHandlerFactory(ModificationHandlerFactory.defaultFactoryMap))
96
96
  .addService('systemContainerFactory', ({ providers, modificationHandlerFactory }) =>
97
97
  new SystemContainerFactory(providers, modificationHandlerFactory))
98
- .addService('projectContainerFactoryFactory', ({ debugMode, plugins, providers }) =>
99
- new ProjectContainerFactoryFactory(debugMode, plugins, providers))
98
+ .addService('projectContainerFactoryFactory', ({ debugMode, plugins, providers, serverConfig }) =>
99
+ new ProjectContainerFactoryFactory(debugMode, plugins, providers, serverConfig))
100
100
  .addService('tenantGraphQLHandlerFactory', () =>
101
101
  new TenantGraphQLHandlerFactory())
102
102
  .addService('systemGraphQLHandlerFactory', ({ debugMode }) =>
@@ -272,18 +272,23 @@ export class Application {
272
272
  private createTimer() {
273
273
  const times: EventTime[] = []
274
274
  const globalStart = new Date().getTime()
275
- const timer: Timer = async (name: string, cb) => {
276
- if (!cb) {
277
- times.push({ label: name, start: new Date().getTime() - globalStart })
278
- return
279
- }
280
-
275
+ const timer: Timer = (name: string, cb) => {
281
276
  const start = new Date().getTime()
282
277
  const time: EventTime = { label: name, start: start - globalStart }
283
278
  times.push(time)
284
- const res = await cb()
285
- time.duration = new Date().getTime() - start
286
- return res as any
279
+ const res = cb()
280
+
281
+ if (res instanceof Promise) {
282
+ (async () => {
283
+ try {
284
+ await res
285
+ } catch {
286
+ } finally {
287
+ time.duration = new Date().getTime() - start
288
+ }
289
+ })()
290
+ }
291
+ return res
287
292
  }
288
293
 
289
294
  const send = (ctx: { response?: ServerResponse; body?: unknown; requestDebugMode: boolean; logger: Logger }) => {
@@ -336,7 +341,7 @@ export class Application {
336
341
 
337
342
  type EventTime = { label: string; start: number; duration?: number }
338
343
 
339
- export type Timer = <T>(event: string, cb?: () => T) => Promise<T>
344
+ export type Timer = <T>(event: string, cb: () => T) => T
340
345
 
341
346
  export interface ApplicationContext {
342
347
  logger: Logger
@@ -88,6 +88,9 @@ export const serverConfigSchema = Typesafe.object({
88
88
  http: Typesafe.partial({
89
89
  requestBodySize: Typesafe.string,
90
90
  }),
91
+ contentApi: Typesafe.partial({
92
+ schemaCacheTtlSeconds: Typesafe.integer,
93
+ }),
91
94
  logging: Typesafe.union(
92
95
  (val): { sentry?: { dsn: string } } => Typesafe.valueAt(val, ['sentry', 'dsn']) === undefined ? {} : Typesafe.fail([]),
93
96
  Typesafe.partial({
@@ -73,6 +73,9 @@ export const configTemplate: any = {
73
73
  http: {
74
74
  requestBodySize: '%?env.CONTEMBER_HTTP_REQUEST_BODY_SIZE::string%',
75
75
  },
76
+ contentApi: {
77
+ schemaCacheTtlSeconds: '%?env.CONTEMBER_CONTENT_API_SCHEMA_CACHE_TTL_SECONDS::number%',
78
+ },
76
79
  projectGroup: {
77
80
  domainMapping: '%?env.CONTEMBER_PROJECT_GROUP_DOMAIN_MAPPING%',
78
81
  configHeader: '%?env.CONTEMBER_PROJECT_GROUP_CONFIG_HEADER%',
@@ -58,6 +58,7 @@ export class ContentApiControllerFactory {
58
58
  },
59
59
  }),
60
60
  )
61
+
61
62
  logger.debug('Memberships fetched', { memberships })
62
63
 
63
64
  const debugHeaderValue = request.headers[debugHeader]
@@ -71,9 +72,15 @@ export class ContentApiControllerFactory {
71
72
 
72
73
  const projectRoles = memberships.map(it => it.role)
73
74
 
74
- const [graphQlSchema, permissions] = await timer('GraphQLSchemaCreate', () => projectContainer.graphQlSchemaFactory.create(schema, {
75
- projectRoles: projectRoles,
76
- }))
75
+ const { schema: graphQlSchema, permissions } = await timer(
76
+ 'GraphQLSchemaCreate',
77
+ () => projectContainer.graphQlSchemaFactory.create(schema, {
78
+ projectRoles: projectRoles,
79
+ }),
80
+ )
81
+
82
+
83
+ const schemaDatabaseMetadata = await projectContainer.projectDatabaseMetadataResolver.resolveDatabaseMetadata(systemDatabase, schema, stage.schema)
77
84
 
78
85
  const handler = await (async () => {
79
86
  const existingHandler = handlerCache.get(graphQlSchema)
@@ -100,6 +107,7 @@ export class ContentApiControllerFactory {
100
107
  authResult,
101
108
  memberships,
102
109
  permissions,
110
+ schemaDatabaseMetadata,
103
111
  schema,
104
112
  timer,
105
113
  koaContext: koa,
@@ -0,0 +1,51 @@
1
+ import { clearTimeout } from 'node:timers'
2
+
3
+ type Entry<V> = {
4
+ timer?: ReturnType<typeof setTimeout>
5
+ value: V
6
+ }
7
+
8
+ export class ContentApiSpecificCache<ObjectKey extends object, Value> {
9
+ private cache = new WeakMap<ObjectKey, Map<string, Entry<Value>>>()
10
+
11
+ constructor(
12
+ private options: {
13
+ ttlSeconds?: number
14
+ },
15
+ ) {
16
+ }
17
+
18
+ public fetch(objectKey: ObjectKey, scalarKey: string, createValue: () => Value): Value {
19
+ let cacheMap = this.cache.get(objectKey)
20
+
21
+ if (!cacheMap) {
22
+ cacheMap = new Map()
23
+ this.cache.set(objectKey, cacheMap)
24
+ }
25
+
26
+ const cacheValue = cacheMap.get(scalarKey)
27
+
28
+ let timer: ReturnType<typeof setTimeout> | undefined = undefined
29
+ if (this.options.ttlSeconds) {
30
+ // wrap to WeakRef so the Map can be garbage-collected, when ObjectKey is garbage collected
31
+ const cacheMapRef = new WeakRef(cacheMap)
32
+ timer = setTimeout(() => {
33
+ cacheMapRef.deref()?.delete(scalarKey)
34
+ }, this.options.ttlSeconds * 1000)
35
+ }
36
+
37
+ if (cacheValue) {
38
+ clearTimeout(cacheValue.timer)
39
+ cacheValue.timer = timer
40
+ return cacheValue.value
41
+ }
42
+
43
+ const value = createValue()
44
+ cacheMap.set(scalarKey, {
45
+ timer,
46
+ value,
47
+ })
48
+
49
+ return value
50
+ }
51
+ }
@@ -6,7 +6,7 @@ import { AuthResult } from '../common'
6
6
  import { KoaContext, Timer } from '../application'
7
7
  import { Providers } from '../providers'
8
8
  import { GraphQLKoaState } from '../graphql'
9
- import { ParsedMembership } from '@contember/schema-utils'
9
+ import { ParsedMembership, SchemaDatabaseMetadata } from '@contember/schema-utils'
10
10
  import { Stage } from '@contember/engine-system-api'
11
11
  import { ProjectConfig } from '../project/config'
12
12
 
@@ -23,9 +23,10 @@ export class ContentGraphQLContextFactory {
23
23
  ) {
24
24
  }
25
25
 
26
- create({ db, schema, authResult, memberships, permissions, timer, koaContext, requestDebug, systemSchema, stage, project }: {
26
+ create({ db, schema, schemaDatabaseMetadata, authResult, memberships, permissions, timer, koaContext, requestDebug, systemSchema, stage, project }: {
27
27
  db: Client
28
28
  schema: Schema & { id: number }
29
+ schemaDatabaseMetadata: SchemaDatabaseMetadata
29
30
  permissions: Acl.Permissions
30
31
  authResult: AuthResult
31
32
  memberships: readonly ParsedMembership[]
@@ -50,6 +51,7 @@ export class ContentGraphQLContextFactory {
50
51
  identityVariables,
51
52
  identityId,
52
53
  schema,
54
+ schemaDatabaseMetadata,
53
55
  permissions,
54
56
  systemSchema,
55
57
  stage,
@@ -1,14 +1,9 @@
1
1
  import { Schema } from '@contember/schema'
2
2
  import { GraphQLSchema } from 'graphql'
3
-
4
- export interface Identity {
5
- projectRoles: string[]
6
- }
3
+ import { Identity } from './Identity'
7
4
 
8
5
  export type GraphQLSchemaContributorContext = { schema: Schema; identity: Identity }
9
6
 
10
7
  export interface GraphQLSchemaContributor {
11
8
  createSchema(context: GraphQLSchemaContributorContext): undefined | GraphQLSchema
12
-
13
- getCacheKey(context: GraphQLSchemaContributorContext): string
14
9
  }
@@ -1,82 +1,68 @@
1
1
  import {
2
+ Authorizator,
2
3
  EntityRulesResolver,
3
4
  GraphQlSchemaBuilderFactory,
4
- Identity,
5
5
  IntrospectionSchemaDefinitionFactory,
6
6
  IntrospectionSchemaFactory,
7
- PermissionsByIdentityFactory,
8
- Authorizator,
7
+ PermissionFactory,
9
8
  } from '@contember/engine-content-api'
10
9
  import { Acl, Schema } from '@contember/schema'
11
10
  import { GraphQLSchema } from 'graphql'
12
11
  import { makeExecutableSchema, mergeSchemas } from '@graphql-tools/schema'
13
12
  import { GraphQLSchemaContributor } from './GraphQLSchemaContributor'
14
13
  import { JSONType } from '@contember/graphql-utils'
14
+ import { Identity } from './Identity'
15
+ import { ContentApiSpecificCache } from './ContentApiSpecificCache'
15
16
 
16
- type Context = { schema: Schema; identity: Identity }
17
-
18
- type CacheEntry = {
19
- graphQlSchema: GraphQLSchema
17
+ export interface GraphQLSchemaFactoryResult {
20
18
  permissions: Acl.Permissions
21
- contributorsCacheKey: string
22
- verifier: (identity: Identity) => boolean
19
+ schema: GraphQLSchema
23
20
  }
24
21
 
25
22
  export class GraphQlSchemaFactory {
26
- private cache = new WeakMap<Schema, CacheEntry[]>()
27
23
 
28
24
  constructor(
25
+ private readonly cache: ContentApiSpecificCache<Schema, GraphQLSchemaFactoryResult>,
29
26
  private readonly graphqlSchemaBuilderFactory: GraphQlSchemaBuilderFactory,
30
- private readonly permissionFactory: PermissionsByIdentityFactory,
27
+ private readonly permissionFactory: PermissionFactory,
31
28
  private readonly schemaContributors: GraphQLSchemaContributor[],
32
29
  ) {}
33
30
 
34
- public create(schema: Schema, identity: Identity): [GraphQLSchema, Acl.Permissions] {
35
- let cacheEntries = this.cache.get(schema)
36
- const contributorsCacheKey = this.getContributorsCacheKey({ schema, identity })
37
- if (cacheEntries !== undefined) {
38
- const entry = cacheEntries.find(it => it.contributorsCacheKey === contributorsCacheKey && it.verifier(identity))
39
- if (entry !== undefined) {
40
- return [entry.graphQlSchema, entry.permissions]
41
- }
42
- } else {
43
- cacheEntries = []
44
- this.cache.set(schema, cacheEntries)
45
- }
46
- const { permissions, verifier } = this.permissionFactory.createPermissions(schema, identity)
31
+ public create(schema: Schema, identity: Identity): GraphQLSchemaFactoryResult {
32
+ const rolesKey = [...identity.projectRoles].sort().join('\xff')
47
33
 
48
- const authorizator = new Authorizator(permissions, schema.acl.customPrimary ?? false)
49
- const dataSchemaBuilder = this.graphqlSchemaBuilderFactory.create(schema.model, authorizator)
50
- const contentSchemaFactory = new IntrospectionSchemaDefinitionFactory(
51
- new IntrospectionSchemaFactory(
52
- schema.model,
53
- new EntityRulesResolver(schema.validation, schema.model),
54
- authorizator,
55
- ),
56
- )
57
- const dataSchema: GraphQLSchema = dataSchemaBuilder.build()
58
- const contentSchema = makeExecutableSchema({
59
- ...contentSchemaFactory.create(),
60
- resolverValidationOptions: {
61
- requireResolversForResolveType: 'ignore',
62
- },
63
- })
34
+ return this.cache.fetch(schema, rolesKey, () => {
35
+ const permissions = this.permissionFactory.create(schema, identity.projectRoles)
64
36
 
65
- const otherSchemas = this.schemaContributors
66
- .map(it => it.createSchema({ schema, identity }))
67
- .filter((it): it is GraphQLSchema => it !== undefined)
68
- const graphQlSchema = mergeSchemas({
69
- schemas: [dataSchema, contentSchema, ...otherSchemas],
70
- resolvers: {
71
- Json: JSONType,
72
- },
73
- })
74
- cacheEntries.push({ graphQlSchema, verifier, permissions, contributorsCacheKey })
37
+ const authorizator = new Authorizator(permissions, schema.acl.customPrimary ?? false)
38
+ const dataSchemaBuilder = this.graphqlSchemaBuilderFactory.create(schema.model, authorizator)
39
+ const contentSchemaFactory = new IntrospectionSchemaDefinitionFactory(
40
+ new IntrospectionSchemaFactory(
41
+ schema.model,
42
+ new EntityRulesResolver(schema.validation, schema.model),
43
+ authorizator,
44
+ ),
45
+ )
46
+ const dataSchema: GraphQLSchema = dataSchemaBuilder.build()
47
+ const contentSchema = makeExecutableSchema({
48
+ ...contentSchemaFactory.create(),
49
+ resolverValidationOptions: {
50
+ requireResolversForResolveType: 'ignore',
51
+ },
52
+ })
75
53
 
76
- return [graphQlSchema, permissions]
77
- }
54
+ const otherSchemas = this.schemaContributors
55
+ .map(it => it.createSchema({ schema, identity }))
56
+ .filter((it): it is GraphQLSchema => it !== undefined)
57
+ const graphQlSchema = mergeSchemas({
58
+ schemas: [dataSchema, contentSchema, ...otherSchemas],
59
+ resolvers: {
60
+ Json: JSONType,
61
+ },
62
+ })
63
+
64
+ return { schema: graphQlSchema, permissions }
65
+ })
78
66
 
79
- private getContributorsCacheKey(ctx: Context): string {
80
- return JSON.stringify(this.schemaContributors.map(it => it.getCacheKey(ctx)))
81
67
  }
82
68
  }
@@ -0,0 +1,3 @@
1
+ export interface Identity {
2
+ projectRoles: string[]
3
+ }
@@ -4,6 +4,7 @@ export * from './ContentQueryHandlerFactory'
4
4
  export * from './GraphQLSchemaContributor'
5
5
  export * from './ContentSchemaResolver'
6
6
  export * from './GraphQlSchemaFactory'
7
+ export * from './Identity'
7
8
  export * from './NotModifiedChecker'
8
9
  export * from './ProjectMembershipFetcher'
9
10
  export * from './ProjectMembershipResolver'
@@ -3,17 +3,26 @@ import { Connection } from '@contember/database'
3
3
  import {
4
4
  DatabaseContextFactory,
5
5
  ProjectInitializer,
6
+ SchemaDatabaseMetadataResolver,
6
7
  SchemaVersionBuilder,
7
8
  StageCreator,
8
9
  SystemMigrationsRunner,
9
10
  } from '@contember/engine-system-api'
10
- import { GraphQlSchemaBuilderFactory, PermissionsByIdentityFactory } from '@contember/engine-content-api'
11
+ import { GraphQlSchemaBuilderFactory, PermissionFactory } from '@contember/engine-content-api'
11
12
  import { Logger } from '@contember/logger'
12
13
  import { ProjectConfig } from './config'
13
- import { ContentSchemaResolver, GraphQlSchemaFactory } from '../content'
14
+ import {
15
+ ContentSchemaResolver,
16
+ GraphQLSchemaContributor,
17
+ GraphQlSchemaFactory,
18
+ GraphQLSchemaFactoryResult,
19
+ } from '../content'
14
20
  import { Providers } from '../providers'
15
21
  import { Plugin } from '../plugin/Plugin'
16
- import { GraphQLSchemaContributor } from '../content/GraphQLSchemaContributor'
22
+ import { ServerConfig } from '../config/config'
23
+ import { ContentApiSpecificCache } from '../content/ContentApiSpecificCache'
24
+ import { Schema } from '@contember/schema'
25
+ import { ProjectDatabaseMetadataResolver } from './ProjectDatabaseMetadataResolver'
17
26
 
18
27
  export interface ProjectContainer {
19
28
  systemDatabaseContextFactory: DatabaseContextFactory
@@ -24,6 +33,7 @@ export interface ProjectContainer {
24
33
  graphQlSchemaFactory: GraphQlSchemaFactory
25
34
  contentSchemaResolver: ContentSchemaResolver
26
35
  projectInitializer: ProjectInitializer
36
+ projectDatabaseMetadataResolver: ProjectDatabaseMetadataResolver
27
37
  }
28
38
 
29
39
  export class ProjectContainerFactoryFactory {
@@ -31,11 +41,19 @@ export class ProjectContainerFactoryFactory {
31
41
  private readonly debug: boolean,
32
42
  private readonly plugins: Plugin[],
33
43
  private readonly providers: Providers,
44
+ private readonly serverConfig: ServerConfig,
34
45
  ) {
35
46
  }
36
47
 
37
48
  create(schemaVersionBuilder: SchemaVersionBuilder, logger: Logger): ProjectContainerFactory {
38
- return new ProjectContainerFactory(this.debug, this.plugins, schemaVersionBuilder, this.providers, logger)
49
+ return new ProjectContainerFactory(
50
+ this.debug,
51
+ this.plugins,
52
+ schemaVersionBuilder,
53
+ this.providers,
54
+ logger,
55
+ this.serverConfig,
56
+ )
39
57
  }
40
58
  }
41
59
 
@@ -50,6 +68,7 @@ export class ProjectContainerFactory {
50
68
  private readonly schemaVersionBuilder: SchemaVersionBuilder,
51
69
  private readonly providers: Providers,
52
70
  private readonly logger: Logger,
71
+ private readonly serverConfig: ServerConfig,
53
72
  ) {}
54
73
 
55
74
  public createContainer(args: ProjectContainerFactoryArgs): ProjectContainer {
@@ -64,6 +83,7 @@ export class ProjectContainerFactory {
64
83
  'graphQlSchemaFactory',
65
84
  'projectInitializer',
66
85
  'logger',
86
+ 'projectDatabaseMetadataResolver',
67
87
  )
68
88
  }
69
89
 
@@ -94,13 +114,22 @@ export class ProjectContainerFactory {
94
114
  })
95
115
  .addService('graphQlSchemaBuilderFactory', () =>
96
116
  new GraphQlSchemaBuilderFactory())
97
- .addService('permissionsByIdentityFactory', ({}) =>
98
- new PermissionsByIdentityFactory())
99
- .addService('graphQlSchemaFactory', ({ project, permissionsByIdentityFactory, graphQlSchemaBuilderFactory, providers }) => {
117
+ .addService('permissionFactory', ({}) =>
118
+ new PermissionFactory())
119
+ .addService('graphqlSchemaCache', () =>
120
+ new ContentApiSpecificCache<Schema, GraphQLSchemaFactoryResult>({
121
+ ttlSeconds: this.serverConfig.contentApi.schemaCacheTtlSeconds,
122
+ }))
123
+ .addService('graphQlSchemaFactory', ({ project, permissionFactory, graphQlSchemaBuilderFactory, providers, graphqlSchemaCache }) => {
100
124
  const contributors = this.plugins
101
125
  .map(it => (it.getSchemaContributor ? it.getSchemaContributor({ project, providers }) : null))
102
126
  .filter((it): it is GraphQLSchemaContributor => !!it)
103
- return new GraphQlSchemaFactory(graphQlSchemaBuilderFactory, permissionsByIdentityFactory, contributors)
127
+ return new GraphQlSchemaFactory(
128
+ graphqlSchemaCache,
129
+ graphQlSchemaBuilderFactory,
130
+ permissionFactory,
131
+ contributors,
132
+ )
104
133
  })
105
134
  .addService('contentSchemaResolver', ({ schemaVersionBuilder }) =>
106
135
  new ContentSchemaResolver(schemaVersionBuilder))
@@ -110,9 +139,13 @@ export class ProjectContainerFactory {
110
139
  new DatabaseContextFactory(systemSchemaName, connection, providers))
111
140
  .addService('systemMigrationGroups', () =>
112
141
  Object.fromEntries(this.plugins.flatMap(it => it.getSystemMigrations ? [[it.name, it.getSystemMigrations()]] : [])))
113
- .addService('systemMigrationsRunner', ({ systemDatabaseContextFactory, project, systemSchemaName, systemMigrationGroups }) =>
114
- new SystemMigrationsRunner(systemDatabaseContextFactory, project, systemSchemaName, this.schemaVersionBuilder, systemMigrationGroups))
142
+ .addService('databaseMetadataResolver', () =>
143
+ new SchemaDatabaseMetadataResolver())
144
+ .addService('systemMigrationsRunner', ({ systemDatabaseContextFactory, project, systemSchemaName, systemMigrationGroups, databaseMetadataResolver }) =>
145
+ new SystemMigrationsRunner(systemDatabaseContextFactory, project, systemSchemaName, this.schemaVersionBuilder, systemMigrationGroups, databaseMetadataResolver))
115
146
  .addService('projectInitializer', ({ systemMigrationsRunner, systemDatabaseContextFactory, project }) =>
116
147
  new ProjectInitializer(new StageCreator(), systemMigrationsRunner, systemDatabaseContextFactory, project))
148
+ .addService('projectDatabaseMetadataResolver', ({ databaseMetadataResolver }) =>
149
+ new ProjectDatabaseMetadataResolver(databaseMetadataResolver))
117
150
  }
118
151
  }
@@ -0,0 +1,29 @@
1
+ import { DatabaseContext, SchemaDatabaseMetadataResolver } from '@contember/engine-system-api'
2
+ import { Schema } from '@contember/schema'
3
+ import { SchemaDatabaseMetadata } from '@contember/schema-utils'
4
+
5
+ export class ProjectDatabaseMetadataResolver {
6
+
7
+ private cache: WeakMap<Schema, Map<string, SchemaDatabaseMetadata>> = new WeakMap()
8
+
9
+ constructor(
10
+ private resolver: SchemaDatabaseMetadataResolver,
11
+ ) {
12
+ }
13
+
14
+ async resolveDatabaseMetadata(db: DatabaseContext, schema: Schema, stageSchema: string): Promise<SchemaDatabaseMetadata> {
15
+ let schemaCache = this.cache.get(schema)
16
+ if (!schemaCache) {
17
+ schemaCache = new Map()
18
+ this.cache.set(schema, schemaCache)
19
+ }
20
+ const cachedMeta = schemaCache.get(stageSchema)
21
+ if (cachedMeta) {
22
+ return cachedMeta
23
+ }
24
+ const metadata = await this.resolver.resolveMetadata(db, stageSchema)
25
+ schemaCache.set(stageSchema, metadata)
26
+
27
+ return metadata
28
+ }
29
+ }
@@ -0,0 +1,129 @@
1
+ import * as assert from 'node:assert'
2
+ import { ContentApiSpecificCache } from '../../../src/content/ContentApiSpecificCache'
3
+
4
+ /**
5
+ * Probably not possible to pass --expose-gc through vitest (--expose-gc cannot be in NODE_OPTIONS)
6
+ */
7
+ (async () => {
8
+ if (!global.gc) {
9
+ throw new Error('Pass --expose-gc')
10
+ }
11
+
12
+ (() => {
13
+ const value = {}
14
+ const objectKey = {}
15
+ const cache = new ContentApiSpecificCache({})
16
+ assert.ok(cache.fetch(objectKey, '', () => value) === value)
17
+ // eslint-disable-next-line no-console
18
+ console.log('create value OK')
19
+ })()
20
+
21
+ await (() => {
22
+ const value = {}
23
+ const objectKey = {}
24
+ const cache = new ContentApiSpecificCache({})
25
+ assert.ok(cache.fetch(objectKey, '', () => value) === value)
26
+
27
+ assert.ok(cache.fetch(objectKey, '', () => {
28
+ throw new Error('should not happen')
29
+ }) === value)
30
+ // eslint-disable-next-line no-console
31
+ console.log('repeated fetch OK')
32
+ })()
33
+
34
+ await (async () => {
35
+ let value = { a: 1 }
36
+ const valueRef = new WeakRef(value)
37
+
38
+ let objectKey = {}
39
+ const cache = new ContentApiSpecificCache({})
40
+
41
+ ;(() => {
42
+ assert.ok(cache.fetch(objectKey, '', () => value) === value)
43
+ })()
44
+
45
+ value = { a: 2 }
46
+ objectKey = {} // weakmap should gc value
47
+
48
+ await new Promise(resolve => setImmediate(resolve))
49
+
50
+ global.gc?.()
51
+
52
+ assert.ok(valueRef.deref() === undefined)
53
+
54
+ const value2 = {}
55
+ assert.ok(cache.fetch(objectKey, '', () => value2) === value2)
56
+ // eslint-disable-next-line no-console
57
+ console.log('weakmap clear OK')
58
+ })()
59
+
60
+ await (async () => {
61
+ let value = { a: 1 }
62
+ const valueRef = new WeakRef(value)
63
+ const objectKey = {}
64
+ const cache = new ContentApiSpecificCache({
65
+ ttlSeconds: 1,
66
+ })
67
+ assert.ok(cache.fetch(objectKey, '', () => value) === value)
68
+
69
+ await new Promise(resolve => setTimeout(resolve, 100))
70
+ global.gc?.()
71
+ assert.ok(valueRef.deref() !== undefined)
72
+
73
+
74
+ cache.fetch(objectKey, '', () => {
75
+ throw new Error('should not happen')
76
+ })
77
+
78
+ // eslint-disable-next-line no-console
79
+ console.log('ttl not expired OK')
80
+ })()
81
+
82
+
83
+ await (async () => {
84
+ let value = { a: 1 }
85
+ const valueRef = new WeakRef(value)
86
+ const objectKey = {}
87
+ const cache = new ContentApiSpecificCache({
88
+ ttlSeconds: 0.200,
89
+ })
90
+ assert.ok(cache.fetch(objectKey, '', () => value) === value)
91
+
92
+ for (let i = 0; i < 10; i++) {
93
+ await new Promise(resolve => setTimeout(resolve, 100))
94
+ global.gc?.()
95
+ assert.ok(valueRef.deref() !== undefined)
96
+ cache.fetch(objectKey, '', () => {
97
+ throw new Error('should not happen')
98
+ })
99
+ }
100
+
101
+ // eslint-disable-next-line no-console
102
+ console.log('ttl renew OK')
103
+ })()
104
+
105
+ await (async () => {
106
+ let value = { a: 1 }
107
+ const valueRef = new WeakRef(value)
108
+ const objectKey = {}
109
+ const cache = new ContentApiSpecificCache({
110
+ ttlSeconds: 0.100,
111
+ })
112
+ assert.ok(cache.fetch(objectKey, '', () => value) === value)
113
+
114
+ value = { a: 2 }
115
+ await new Promise(resolve => setTimeout(resolve, 500))
116
+ global.gc?.()
117
+
118
+ assert.ok(valueRef.deref() === undefined)
119
+
120
+ const value2 = {}
121
+ assert.ok(cache.fetch(objectKey, '', () => value2) === value2)
122
+
123
+ // eslint-disable-next-line no-console
124
+ console.log('ttl expired OK')
125
+ })()
126
+
127
+ // eslint-disable-next-line no-console
128
+ console.log('content api cache test DONE')
129
+ })()