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

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 (61) 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 +1 -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/GraphQLSchemaContributor.d.ts +1 -4
  24. package/dist/src/content/GraphQLSchemaContributor.d.ts.map +1 -1
  25. package/dist/src/content/GraphQlSchemaFactory.d.ts +10 -5
  26. package/dist/src/content/GraphQlSchemaFactory.d.ts.map +1 -1
  27. package/dist/src/content/GraphQlSchemaFactory.js +26 -39
  28. package/dist/src/content/GraphQlSchemaFactory.js.map +1 -1
  29. package/dist/src/content/Identity.d.ts +4 -0
  30. package/dist/src/content/Identity.d.ts.map +1 -0
  31. package/dist/src/content/Identity.js +3 -0
  32. package/dist/src/content/Identity.js.map +1 -0
  33. package/dist/src/content/index.d.ts +1 -0
  34. package/dist/src/content/index.d.ts.map +1 -1
  35. package/dist/src/content/index.js +1 -0
  36. package/dist/src/content/index.js.map +1 -1
  37. package/dist/src/project/ProjectContainer.d.ts +12 -5
  38. package/dist/src/project/ProjectContainer.d.ts.map +1 -1
  39. package/dist/src/project/ProjectContainer.js +12 -6
  40. package/dist/src/project/ProjectContainer.js.map +1 -1
  41. package/dist/src/tsconfig.tsbuildinfo +1 -1
  42. package/dist/src/utils/serverStartup.d.ts +3 -0
  43. package/dist/src/utils/serverStartup.d.ts.map +1 -1
  44. package/dist/tests/cases/unit/contentApiSpecificCache.tst.d.ts +2 -0
  45. package/dist/tests/cases/unit/contentApiSpecificCache.tst.d.ts.map +1 -0
  46. package/dist/tests/cases/unit/contentApiSpecificCache.tst.js +132 -0
  47. package/dist/tests/cases/unit/contentApiSpecificCache.tst.js.map +1 -0
  48. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  49. package/package.json +16 -16
  50. package/src/MasterContainer.ts +2 -2
  51. package/src/application/application.ts +15 -10
  52. package/src/config/configSchema.ts +3 -0
  53. package/src/config/configTemplate.ts +3 -0
  54. package/src/content/ContentApiControllerFactory.ts +7 -3
  55. package/src/content/ContentApiSpecificCache.ts +51 -0
  56. package/src/content/GraphQLSchemaContributor.ts +1 -6
  57. package/src/content/GraphQlSchemaFactory.ts +40 -54
  58. package/src/content/Identity.ts +3 -0
  59. package/src/content/index.ts +1 -0
  60. package/src/project/ProjectContainer.ts +33 -8
  61. 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.7",
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.7",
17
+ "@contember/database": "^1.3.0-alpha.7",
18
+ "@contember/database-migrations": "^1.3.0-alpha.7",
19
+ "@contember/dic": "^1.3.0-alpha.7",
20
+ "@contember/engine-common": "^1.3.0-alpha.7",
21
+ "@contember/engine-content-api": "^1.3.0-alpha.7",
22
+ "@contember/engine-system-api": "^1.3.0-alpha.7",
23
+ "@contember/engine-tenant-api": "^1.3.0-alpha.7",
24
+ "@contember/graphql-utils": "^1.3.0-alpha.7",
25
+ "@contember/logger": "^1.3.0-alpha.7",
26
+ "@contember/schema": "^1.3.0-alpha.7",
27
+ "@contember/schema-migrations": "^1.3.0-alpha.7",
28
+ "@contember/schema-utils": "^1.3.0-alpha.7",
29
+ "@contember/typesafe": "^1.3.0-alpha.7",
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,12 @@ 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
+ )
77
81
 
78
82
  const handler = await (async () => {
79
83
  const existingHandler = handlerCache.get(graphQlSchema)
@@ -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
+ }
@@ -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'
@@ -7,13 +7,20 @@ import {
7
7
  StageCreator,
8
8
  SystemMigrationsRunner,
9
9
  } from '@contember/engine-system-api'
10
- import { GraphQlSchemaBuilderFactory, PermissionsByIdentityFactory } from '@contember/engine-content-api'
10
+ import { GraphQlSchemaBuilderFactory, PermissionFactory } from '@contember/engine-content-api'
11
11
  import { Logger } from '@contember/logger'
12
12
  import { ProjectConfig } from './config'
13
- import { ContentSchemaResolver, GraphQlSchemaFactory } from '../content'
13
+ import {
14
+ ContentSchemaResolver,
15
+ GraphQLSchemaContributor,
16
+ GraphQlSchemaFactory,
17
+ GraphQLSchemaFactoryResult,
18
+ } from '../content'
14
19
  import { Providers } from '../providers'
15
20
  import { Plugin } from '../plugin/Plugin'
16
- import { GraphQLSchemaContributor } from '../content/GraphQLSchemaContributor'
21
+ import { ServerConfig } from '../config/config'
22
+ import { ContentApiSpecificCache } from '../content/ContentApiSpecificCache'
23
+ import { Schema } from '@contember/schema'
17
24
 
18
25
  export interface ProjectContainer {
19
26
  systemDatabaseContextFactory: DatabaseContextFactory
@@ -31,11 +38,19 @@ export class ProjectContainerFactoryFactory {
31
38
  private readonly debug: boolean,
32
39
  private readonly plugins: Plugin[],
33
40
  private readonly providers: Providers,
41
+ private readonly serverConfig: ServerConfig,
34
42
  ) {
35
43
  }
36
44
 
37
45
  create(schemaVersionBuilder: SchemaVersionBuilder, logger: Logger): ProjectContainerFactory {
38
- return new ProjectContainerFactory(this.debug, this.plugins, schemaVersionBuilder, this.providers, logger)
46
+ return new ProjectContainerFactory(
47
+ this.debug,
48
+ this.plugins,
49
+ schemaVersionBuilder,
50
+ this.providers,
51
+ logger,
52
+ this.serverConfig,
53
+ )
39
54
  }
40
55
  }
41
56
 
@@ -50,6 +65,7 @@ export class ProjectContainerFactory {
50
65
  private readonly schemaVersionBuilder: SchemaVersionBuilder,
51
66
  private readonly providers: Providers,
52
67
  private readonly logger: Logger,
68
+ private readonly serverConfig: ServerConfig,
53
69
  ) {}
54
70
 
55
71
  public createContainer(args: ProjectContainerFactoryArgs): ProjectContainer {
@@ -94,13 +110,22 @@ export class ProjectContainerFactory {
94
110
  })
95
111
  .addService('graphQlSchemaBuilderFactory', () =>
96
112
  new GraphQlSchemaBuilderFactory())
97
- .addService('permissionsByIdentityFactory', ({}) =>
98
- new PermissionsByIdentityFactory())
99
- .addService('graphQlSchemaFactory', ({ project, permissionsByIdentityFactory, graphQlSchemaBuilderFactory, providers }) => {
113
+ .addService('permissionFactory', ({}) =>
114
+ new PermissionFactory())
115
+ .addService('graphqlSchemaCache', () =>
116
+ new ContentApiSpecificCache<Schema, GraphQLSchemaFactoryResult>({
117
+ ttlSeconds: this.serverConfig.contentApi.schemaCacheTtlSeconds,
118
+ }))
119
+ .addService('graphQlSchemaFactory', ({ project, permissionFactory, graphQlSchemaBuilderFactory, providers, graphqlSchemaCache }) => {
100
120
  const contributors = this.plugins
101
121
  .map(it => (it.getSchemaContributor ? it.getSchemaContributor({ project, providers }) : null))
102
122
  .filter((it): it is GraphQLSchemaContributor => !!it)
103
- return new GraphQlSchemaFactory(graphQlSchemaBuilderFactory, permissionsByIdentityFactory, contributors)
123
+ return new GraphQlSchemaFactory(
124
+ graphqlSchemaCache,
125
+ graphQlSchemaBuilderFactory,
126
+ permissionFactory,
127
+ contributors,
128
+ )
104
129
  })
105
130
  .addService('contentSchemaResolver', ({ schemaVersionBuilder }) =>
106
131
  new ContentSchemaResolver(schemaVersionBuilder))
@@ -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
+ })()