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

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 (188) hide show
  1. package/CLAUDE.md +2 -0
  2. package/dist/development/index.cjs +8 -0
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +9 -1
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/MasterContainer.cjs +28 -14
  7. package/dist/development/src/MasterContainer.cjs.map +1 -1
  8. package/dist/development/src/MasterContainer.js +28 -14
  9. package/dist/development/src/MasterContainer.js.map +1 -1
  10. package/dist/development/src/config/configSchema.cjs +50 -0
  11. package/dist/development/src/config/configSchema.cjs.map +1 -1
  12. package/dist/development/src/config/configSchema.js +50 -0
  13. package/dist/development/src/config/configSchema.js.map +1 -1
  14. package/dist/development/src/config/configTemplate.cjs +8 -0
  15. package/dist/development/src/config/configTemplate.cjs.map +1 -1
  16. package/dist/development/src/config/configTemplate.js +8 -0
  17. package/dist/development/src/config/configTemplate.js.map +1 -1
  18. package/dist/development/src/content/ContentApiControllerFactory.cjs +12 -1
  19. package/dist/development/src/content/ContentApiControllerFactory.cjs.map +1 -1
  20. package/dist/development/src/content/ContentApiControllerFactory.js +12 -1
  21. package/dist/development/src/content/ContentApiControllerFactory.js.map +1 -1
  22. package/dist/development/src/content/ContentApiSpecificCache.cjs +20 -5
  23. package/dist/development/src/content/ContentApiSpecificCache.cjs.map +1 -1
  24. package/dist/development/src/content/ContentApiSpecificCache.js +20 -5
  25. package/dist/development/src/content/ContentApiSpecificCache.js.map +1 -1
  26. package/dist/development/src/content/ContentGraphQLEngine.cjs +17 -0
  27. package/dist/development/src/content/ContentGraphQLEngine.cjs.map +1 -0
  28. package/dist/development/src/content/ContentGraphQLEngine.js +17 -0
  29. package/dist/development/src/content/ContentGraphQLEngine.js.map +1 -0
  30. package/dist/development/src/content/ContentQueryHandlerFactory.cjs +4 -1
  31. package/dist/development/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
  32. package/dist/development/src/content/ContentQueryHandlerFactory.js +5 -2
  33. package/dist/development/src/content/ContentQueryHandlerFactory.js.map +1 -1
  34. package/dist/development/src/content/ContentRequestLog.cjs +97 -0
  35. package/dist/development/src/content/ContentRequestLog.cjs.map +1 -0
  36. package/dist/development/src/content/ContentRequestLog.js +97 -0
  37. package/dist/development/src/content/ContentRequestLog.js.map +1 -0
  38. package/dist/development/src/content/GraphQlSchemaFactory.cjs +121 -45
  39. package/dist/development/src/content/GraphQlSchemaFactory.cjs.map +1 -1
  40. package/dist/development/src/content/GraphQlSchemaFactory.js +122 -46
  41. package/dist/development/src/content/GraphQlSchemaFactory.js.map +1 -1
  42. package/dist/development/src/graphql/execution.cjs +18 -5
  43. package/dist/development/src/graphql/execution.cjs.map +1 -1
  44. package/dist/development/src/graphql/execution.js +19 -6
  45. package/dist/development/src/graphql/execution.js.map +1 -1
  46. package/dist/development/src/project/ProjectContainer.cjs +2 -0
  47. package/dist/development/src/project/ProjectContainer.cjs.map +1 -1
  48. package/dist/development/src/project/ProjectContainer.js +2 -0
  49. package/dist/development/src/project/ProjectContainer.js.map +1 -1
  50. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +2 -0
  51. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
  52. package/dist/development/src/projectGroup/ProjectGroupContainer.js +2 -0
  53. package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
  54. package/dist/development/src/system/ContentQueryExecutor.cjs +23 -6
  55. package/dist/development/src/system/ContentQueryExecutor.cjs.map +1 -1
  56. package/dist/development/src/system/ContentQueryExecutor.js +25 -8
  57. package/dist/development/src/system/ContentQueryExecutor.js.map +1 -1
  58. package/dist/development/src/system/SystemGraphQLHandlerFactory.cjs +1 -1
  59. package/dist/development/src/system/SystemGraphQLHandlerFactory.cjs.map +1 -1
  60. package/dist/development/src/system/SystemGraphQLHandlerFactory.js +2 -2
  61. package/dist/development/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
  62. package/dist/development/src/tenant/TenantGraphQLHandlerFactory.cjs +1 -1
  63. package/dist/development/src/tenant/TenantGraphQLHandlerFactory.cjs.map +1 -1
  64. package/dist/development/src/tenant/TenantGraphQLHandlerFactory.js +2 -2
  65. package/dist/development/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
  66. package/dist/production/index.cjs +8 -0
  67. package/dist/production/index.cjs.map +1 -1
  68. package/dist/production/index.js +9 -1
  69. package/dist/production/index.js.map +1 -1
  70. package/dist/production/src/MasterContainer.cjs +28 -14
  71. package/dist/production/src/MasterContainer.cjs.map +1 -1
  72. package/dist/production/src/MasterContainer.js +28 -14
  73. package/dist/production/src/MasterContainer.js.map +1 -1
  74. package/dist/production/src/config/configSchema.cjs +50 -0
  75. package/dist/production/src/config/configSchema.cjs.map +1 -1
  76. package/dist/production/src/config/configSchema.js +50 -0
  77. package/dist/production/src/config/configSchema.js.map +1 -1
  78. package/dist/production/src/config/configTemplate.cjs +8 -0
  79. package/dist/production/src/config/configTemplate.cjs.map +1 -1
  80. package/dist/production/src/config/configTemplate.js +8 -0
  81. package/dist/production/src/config/configTemplate.js.map +1 -1
  82. package/dist/production/src/content/ContentApiControllerFactory.cjs +12 -1
  83. package/dist/production/src/content/ContentApiControllerFactory.cjs.map +1 -1
  84. package/dist/production/src/content/ContentApiControllerFactory.js +12 -1
  85. package/dist/production/src/content/ContentApiControllerFactory.js.map +1 -1
  86. package/dist/production/src/content/ContentApiSpecificCache.cjs +20 -5
  87. package/dist/production/src/content/ContentApiSpecificCache.cjs.map +1 -1
  88. package/dist/production/src/content/ContentApiSpecificCache.js +20 -5
  89. package/dist/production/src/content/ContentApiSpecificCache.js.map +1 -1
  90. package/dist/production/src/content/ContentGraphQLEngine.cjs +17 -0
  91. package/dist/production/src/content/ContentGraphQLEngine.cjs.map +1 -0
  92. package/dist/production/src/content/ContentGraphQLEngine.js +17 -0
  93. package/dist/production/src/content/ContentGraphQLEngine.js.map +1 -0
  94. package/dist/production/src/content/ContentQueryHandlerFactory.cjs +4 -1
  95. package/dist/production/src/content/ContentQueryHandlerFactory.cjs.map +1 -1
  96. package/dist/production/src/content/ContentQueryHandlerFactory.js +5 -2
  97. package/dist/production/src/content/ContentQueryHandlerFactory.js.map +1 -1
  98. package/dist/production/src/content/ContentRequestLog.cjs +97 -0
  99. package/dist/production/src/content/ContentRequestLog.cjs.map +1 -0
  100. package/dist/production/src/content/ContentRequestLog.js +97 -0
  101. package/dist/production/src/content/ContentRequestLog.js.map +1 -0
  102. package/dist/production/src/content/GraphQlSchemaFactory.cjs +121 -45
  103. package/dist/production/src/content/GraphQlSchemaFactory.cjs.map +1 -1
  104. package/dist/production/src/content/GraphQlSchemaFactory.js +122 -46
  105. package/dist/production/src/content/GraphQlSchemaFactory.js.map +1 -1
  106. package/dist/production/src/graphql/execution.cjs +18 -5
  107. package/dist/production/src/graphql/execution.cjs.map +1 -1
  108. package/dist/production/src/graphql/execution.js +19 -6
  109. package/dist/production/src/graphql/execution.js.map +1 -1
  110. package/dist/production/src/project/ProjectContainer.cjs +2 -0
  111. package/dist/production/src/project/ProjectContainer.cjs.map +1 -1
  112. package/dist/production/src/project/ProjectContainer.js +2 -0
  113. package/dist/production/src/project/ProjectContainer.js.map +1 -1
  114. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +2 -0
  115. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
  116. package/dist/production/src/projectGroup/ProjectGroupContainer.js +2 -0
  117. package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
  118. package/dist/production/src/system/ContentQueryExecutor.cjs +23 -6
  119. package/dist/production/src/system/ContentQueryExecutor.cjs.map +1 -1
  120. package/dist/production/src/system/ContentQueryExecutor.js +25 -8
  121. package/dist/production/src/system/ContentQueryExecutor.js.map +1 -1
  122. package/dist/production/src/system/SystemGraphQLHandlerFactory.cjs +1 -1
  123. package/dist/production/src/system/SystemGraphQLHandlerFactory.cjs.map +1 -1
  124. package/dist/production/src/system/SystemGraphQLHandlerFactory.js +2 -2
  125. package/dist/production/src/system/SystemGraphQLHandlerFactory.js.map +1 -1
  126. package/dist/production/src/tenant/TenantGraphQLHandlerFactory.cjs +1 -1
  127. package/dist/production/src/tenant/TenantGraphQLHandlerFactory.cjs.map +1 -1
  128. package/dist/production/src/tenant/TenantGraphQLHandlerFactory.js +2 -2
  129. package/dist/production/src/tenant/TenantGraphQLHandlerFactory.js.map +1 -1
  130. package/dist/tests/cases/unit/contentGraphqlCompat.test.d.ts +2 -0
  131. package/dist/tests/cases/unit/contentGraphqlCompat.test.d.ts.map +1 -0
  132. package/dist/tests/cases/unit/contentRequestLog.test.d.ts +2 -0
  133. package/dist/tests/cases/unit/contentRequestLog.test.d.ts.map +1 -0
  134. package/dist/tests/contentControllerHarness.d.ts +29 -0
  135. package/dist/tests/contentControllerHarness.d.ts.map +1 -0
  136. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  137. package/dist/types/MasterContainer.d.ts +10 -1
  138. package/dist/types/MasterContainer.d.ts.map +1 -1
  139. package/dist/types/config/configSchema.d.ts +10 -0
  140. package/dist/types/config/configSchema.d.ts.map +1 -1
  141. package/dist/types/config/configTemplate.d.ts.map +1 -1
  142. package/dist/types/content/ContentApiControllerFactory.d.ts +3 -1
  143. package/dist/types/content/ContentApiControllerFactory.d.ts.map +1 -1
  144. package/dist/types/content/ContentApiSpecificCache.d.ts +2 -0
  145. package/dist/types/content/ContentApiSpecificCache.d.ts.map +1 -1
  146. package/dist/types/content/ContentGraphQLEngine.d.ts +18 -0
  147. package/dist/types/content/ContentGraphQLEngine.d.ts.map +1 -0
  148. package/dist/types/content/ContentQueryHandlerFactory.d.ts +3 -2
  149. package/dist/types/content/ContentQueryHandlerFactory.d.ts.map +1 -1
  150. package/dist/types/content/ContentRequestLog.d.ts +49 -0
  151. package/dist/types/content/ContentRequestLog.d.ts.map +1 -0
  152. package/dist/types/content/GraphQlSchemaFactory.d.ts +14 -4
  153. package/dist/types/content/GraphQlSchemaFactory.d.ts.map +1 -1
  154. package/dist/types/content/index.d.ts +2 -0
  155. package/dist/types/content/index.d.ts.map +1 -1
  156. package/dist/types/graphql/execution.d.ts +21 -3
  157. package/dist/types/graphql/execution.d.ts.map +1 -1
  158. package/dist/types/system/ContentQueryExecutor.d.ts +4 -1
  159. package/dist/types/system/ContentQueryExecutor.d.ts.map +1 -1
  160. package/dist/types/system/SystemGraphQLHandlerFactory.d.ts.map +1 -1
  161. package/dist/types/tenant/TenantGraphQLHandlerFactory.d.ts.map +1 -1
  162. package/dist/types/tsconfig.tsbuildinfo +1 -1
  163. package/package.json +21 -18
  164. package/src/MasterContainer.ts +31 -14
  165. package/src/config/configSchema.ts +63 -0
  166. package/src/config/configTemplate.ts +8 -0
  167. package/src/content/ContentApiControllerFactory.ts +15 -2
  168. package/src/content/ContentApiSpecificCache.ts +22 -7
  169. package/src/content/ContentGraphQLEngine.ts +24 -0
  170. package/src/content/ContentQueryHandlerFactory.ts +16 -4
  171. package/src/content/ContentRequestLog.ts +138 -0
  172. package/src/content/GraphQlSchemaFactory.ts +173 -54
  173. package/src/content/index.ts +2 -0
  174. package/src/graphql/execution.ts +35 -7
  175. package/src/project/ProjectContainer.ts +1 -1
  176. package/src/system/ContentQueryExecutor.ts +43 -10
  177. package/src/system/SystemGraphQLHandlerFactory.ts +8 -2
  178. package/src/tenant/TenantGraphQLHandlerFactory.ts +2 -2
  179. package/src/tsconfig.json +1 -0
  180. package/tests/cases/unit/__snapshots__/contentGraphqlCompat.test.ts.snap +14295 -0
  181. package/tests/cases/unit/contentGraphqlCompat.test.ts +372 -0
  182. package/tests/cases/unit/contentRequestLog.test.ts +141 -0
  183. package/tests/cases/unit/forcePrimary.test.ts +93 -284
  184. package/tests/cases/unit/graphQlSchemaFactory.test.ts +227 -35
  185. package/tests/cases/unit/requestMemoryBudget.test.ts +96 -78
  186. package/tests/cases/unit/serverConfig.test.ts +133 -0
  187. package/tests/contentControllerHarness.ts +222 -0
  188. package/tests/tsconfig.json +3 -1
@@ -0,0 +1,372 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { fetch } from 'bun'
3
+ import { once } from 'node:events'
4
+ import Koa from 'koa'
5
+ import {
6
+ getIntrospectionQuery,
7
+ GraphQLError,
8
+ GraphQLInputObjectType,
9
+ GraphQLInt,
10
+ GraphQLList,
11
+ GraphQLNonNull,
12
+ GraphQLObjectType,
13
+ GraphQLScalarType,
14
+ GraphQLSchemaConfig,
15
+ GraphQLString,
16
+ Kind,
17
+ } from 'graphql'
18
+ import { ExecutionContainerFactory, GraphQlSchemaBuilderFactory, PermissionFactory } from '@contember/engine-content-api'
19
+ import { Client, emptyDatabaseMetadata } from '@contember/database'
20
+ import { createConnectionMock } from '@contember/database-tester'
21
+ import { ForbiddenError } from '@contember/graphql-utils'
22
+ import { createLogger, TestLoggerHandler, withLogger } from '@contember/logger'
23
+ import { Schema } from '@contember/schema'
24
+ import { AllowAllPermissionFactory, c, createSchema } from '@contember/schema-definition'
25
+ import { createRequestBodyMiddleware, defaultFormBodyLimit, defaultJsonBodyLimit } from '../../../src/application/requestBody.js'
26
+ import { ContentApiSpecificCache } from '../../../src/content/ContentApiSpecificCache.js'
27
+ import { ContentGraphqlContext } from '../../../src/content/ContentGraphqlContext.js'
28
+ import { ContentGraphQLEngine, ContentGraphQLEngineResolver } from '../../../src/content/ContentGraphQLEngine.js'
29
+ import { ContentQueryHandlerFactory } from '../../../src/content/ContentQueryHandlerFactory.js'
30
+ import { GraphQlSchemaFactory, GraphQLSchemaFactoryResult } from '../../../src/content/GraphQlSchemaFactory.js'
31
+ import { GraphQLSchemaContributor } from '../../../src/content/GraphQLSchemaContributor.js'
32
+ import { ProjectConfig } from '../../../src/project/config.js'
33
+
34
+ // The snapshots were recorded on main's graphql-js content engine; both engines must keep answering with them.
35
+
36
+ const ArticleStatus = c.createEnum('draft', 'published')
37
+
38
+ class Author {
39
+ name = c.stringColumn().notNull()
40
+ articles = c.oneHasMany(Article, 'author')
41
+ }
42
+
43
+ class Article {
44
+ title = c.stringColumn().notNull().unique()
45
+ status = c.enumColumn(ArticleStatus).notNull().default('draft')
46
+ publishedAt = c.dateTimeColumn()
47
+ author = c.manyHasOne(Author, 'articles')
48
+ tags = c.manyHasMany(Tag)
49
+ }
50
+
51
+ class Tag {
52
+ name = c.stringColumn().notNull()
53
+ }
54
+
55
+ const definition = createSchema({ ArticleStatus, Author, Article, Tag })
56
+ const model = definition.model
57
+ const readAll = new AllowAllPermissionFactory().create(model, false)
58
+
59
+ const schema: Schema = {
60
+ ...definition,
61
+ acl: {
62
+ roles: {
63
+ admin: { variables: {}, entities: new AllowAllPermissionFactory().create(model, true) },
64
+ reader: {
65
+ variables: {},
66
+ entities: Object.fromEntries(
67
+ Object.entries(readAll).map(([name, it]) => [name, { predicates: {}, operations: { read: it.operations.read } }]),
68
+ ),
69
+ },
70
+ },
71
+ },
72
+ }
73
+
74
+ const project: ProjectConfig = {
75
+ slug: 'test',
76
+ name: 'test',
77
+ stages: [{ slug: 'live', name: 'live' }],
78
+ db: { host: 'localhost', port: 5432, user: 'test', password: 'test', database: 'test' },
79
+ }
80
+
81
+ const uploadHeader = new GraphQLObjectType({
82
+ name: 'UploadHeader',
83
+ fields: { key: { type: new GraphQLNonNull(GraphQLString) }, value: { type: new GraphQLNonNull(GraphQLString) } },
84
+ })
85
+ const uploadUrl = new GraphQLObjectType({
86
+ name: 'UploadUrl',
87
+ fields: {
88
+ url: { type: new GraphQLNonNull(GraphQLString) },
89
+ headers: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(uploadHeader))) },
90
+ size: { type: GraphQLInt, deprecationReason: 'Use headers' },
91
+ },
92
+ })
93
+ const uploadInput = new GraphQLInputObjectType({
94
+ name: 'UploadInput',
95
+ fields: {
96
+ contentType: { type: GraphQLString },
97
+ size: { type: GraphQLInt, defaultValue: 10, deprecationReason: 'Ignored' },
98
+ },
99
+ })
100
+
101
+ // shaped like the S3 plugin: a graphql-js contribution with deprecated arguments and errors of each kind
102
+ const uploadContributor: GraphQLSchemaContributor = {
103
+ getCacheKey: () => 'upload',
104
+ createSchema: (): GraphQLSchemaConfig => ({
105
+ query: new GraphQLObjectType({ name: 'Query', fields: { uploadDummyQuery: { type: GraphQLString } } }),
106
+ mutation: new GraphQLObjectType({
107
+ name: 'Mutation',
108
+ fields: {
109
+ generateUpload: {
110
+ type: new GraphQLNonNull(uploadUrl),
111
+ args: {
112
+ contentType: { type: GraphQLString, deprecationReason: 'Use input.contentType' },
113
+ input: { type: uploadInput },
114
+ },
115
+ resolve: (parent, args: { contentType?: string; input?: { contentType?: string } }) => {
116
+ const contentType = args.input?.contentType ?? args.contentType
117
+ if (contentType === 'forbidden') {
118
+ throw new ForbiddenError('Not allowed to upload forbidden')
119
+ }
120
+ if (contentType === 'invalid') {
121
+ throw new GraphQLError('Invalid content type', { extensions: { code: 'INVALID_CONTENT_TYPE' } })
122
+ }
123
+ if (contentType === 'crash') {
124
+ throw new Error('Unexpected failure')
125
+ }
126
+ return { url: `https://upload/${contentType}`, headers: [{ key: 'Content-Type', value: contentType ?? '' }], size: 1 }
127
+ },
128
+ },
129
+ },
130
+ }),
131
+ }),
132
+ }
133
+
134
+ // serializes and parses asymmetrically, so applying either twice fails
135
+ const stamp = new GraphQLScalarType<Date, string>({
136
+ name: 'Stamp',
137
+ serialize: value => {
138
+ if (!(value instanceof Date)) {
139
+ throw new TypeError(`Stamp cannot serialize ${typeof value}`)
140
+ }
141
+ return value.toISOString()
142
+ },
143
+ parseValue: value => {
144
+ if (typeof value !== 'string' || Number.isNaN(Date.parse(value))) {
145
+ throw new TypeError('Stamp expects an ISO date string')
146
+ }
147
+ return new Date(value)
148
+ },
149
+ parseLiteral: ast => {
150
+ if (ast.kind !== Kind.STRING || Number.isNaN(Date.parse(ast.value))) {
151
+ throw new TypeError('Stamp expects an ISO date string')
152
+ }
153
+ return new Date(ast.value)
154
+ },
155
+ })
156
+ const reportLine = new GraphQLObjectType({
157
+ name: 'ReportLine',
158
+ fields: {
159
+ label: { type: new GraphQLNonNull(GraphQLString) },
160
+ failing: {
161
+ type: GraphQLString,
162
+ resolve: () => {
163
+ throw new Error('line failed')
164
+ },
165
+ },
166
+ strict: {
167
+ type: new GraphQLNonNull(GraphQLString),
168
+ resolve: () => {
169
+ throw new GraphQLError('strict failed', { extensions: { code: 'STRICT' } })
170
+ },
171
+ },
172
+ },
173
+ })
174
+ const report = new GraphQLObjectType({
175
+ name: 'Report',
176
+ fields: {
177
+ at: { type: new GraphQLNonNull(stamp) },
178
+ lines: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(reportLine))) },
179
+ maybeLines: { type: new GraphQLList(reportLine) },
180
+ nested: { type: reportLine },
181
+ },
182
+ })
183
+ const reportInput = new GraphQLInputObjectType({
184
+ name: 'ReportInput',
185
+ fields: { since: { type: stamp }, limit: { type: GraphQLInt, defaultValue: 2 } },
186
+ })
187
+ const resolveReport = (parent: unknown, args: { since?: unknown; input?: { since?: unknown } }) => {
188
+ const since = args.input?.since ?? args.since
189
+ if (since !== undefined && !(since instanceof Date)) {
190
+ throw new Error('since is not a Date')
191
+ }
192
+ const lines = [{ label: 'a' }, { label: 'b' }]
193
+ return { at: since ?? new Date('2020-01-01'), lines, maybeLines: lines, nested: { label: 'n' } }
194
+ }
195
+
196
+ // output types with nested resolvers, a custom scalar and errors below the root field
197
+ const reportContributor: GraphQLSchemaContributor = {
198
+ getCacheKey: () => 'report',
199
+ createSchema: (): GraphQLSchemaConfig => ({
200
+ query: new GraphQLObjectType({
201
+ name: 'Query',
202
+ fields: { report: { type: report, args: { since: { type: stamp }, input: { type: reportInput } }, resolve: resolveReport } },
203
+ }),
204
+ mutation: new GraphQLObjectType({ name: 'Mutation', fields: { touchReport: { type: report, resolve: resolveReport } } }),
205
+ }),
206
+ }
207
+
208
+ const createSchemaFactory = (engine: ContentGraphQLEngine) =>
209
+ new GraphQlSchemaFactory(
210
+ new ContentApiSpecificCache<Schema, GraphQLSchemaFactoryResult>({}),
211
+ new GraphQlSchemaBuilderFactory(),
212
+ new PermissionFactory(),
213
+ [uploadContributor, reportContributor],
214
+ new ContentGraphQLEngineResolver(engine),
215
+ )
216
+
217
+ const schemaFactories: Record<ContentGraphQLEngine, GraphQlSchemaFactory> = {
218
+ 'graphql-js': createSchemaFactory('graphql-js'),
219
+ 'graphql-json': createSchemaFactory('graphql-json'),
220
+ }
221
+
222
+ const createContext = (role: string): ContentGraphqlContext => {
223
+ const db = new Client(createConnectionMock([]), 'public', {})
224
+ const permissions = new PermissionFactory().createContextual(schema, [role])
225
+ return {
226
+ db,
227
+ identityVariables: {},
228
+ identityId: '00000000-0000-0000-0000-000000000000',
229
+ requestDebug: false,
230
+ project: { slug: project.slug },
231
+ timer: (label, cb) => cb(),
232
+ executionContainer: new ExecutionContainerFactory({ uuid: () => '00000000-0000-0000-0000-000000000000', now: () => new Date('2020-01-01') })
233
+ .create({
234
+ permissions: permissions.root,
235
+ allPermissions: permissions.all,
236
+ schema,
237
+ schemaMeta: { id: 1 },
238
+ db,
239
+ identityVariables: {},
240
+ identityId: '00000000-0000-0000-0000-000000000000',
241
+ systemSchema: 'system',
242
+ stage: { id: '00000000-0000-0000-0000-000000000000', slug: 'live' },
243
+ project: { slug: project.slug },
244
+ schemaDatabaseMetadata: emptyDatabaseMetadata,
245
+ userInfo: { ipAddress: null, userAgent: null },
246
+ }),
247
+ }
248
+ }
249
+
250
+ const request = async (engine: ContentGraphQLEngine, role: string, query: string, variables?: Record<string, unknown>, operationName?: string) => {
251
+ const result = await schemaFactories[engine].create(schema, { projectRoles: [role] }, project)
252
+ const handler = new ContentQueryHandlerFactory(false).create(result.schema)
253
+ const app = new Koa()
254
+ app.use(createRequestBodyMiddleware({ json: defaultJsonBodyLimit, form: defaultFormBodyLimit }))
255
+ app.use(async context => {
256
+ await withLogger(
257
+ createLogger(new TestLoggerHandler()),
258
+ () => handler({ request: context.request, response: context.response, createContext: () => createContext(role) }),
259
+ )
260
+ })
261
+ const server = app.listen(0, '127.0.0.1')
262
+ try {
263
+ await once(server, 'listening')
264
+ const address = server.address()
265
+ if (!address || typeof address === 'string') {
266
+ throw new Error('Expected a TCP listener')
267
+ }
268
+ const response = await fetch(`http://127.0.0.1:${address.port}/`, {
269
+ method: 'POST',
270
+ headers: { 'Content-Type': 'application/json' },
271
+ body: JSON.stringify({ query, variables, operationName }),
272
+ })
273
+ return { status: response.status, text: await response.text() }
274
+ } finally {
275
+ await new Promise<void>((resolve, reject) => {
276
+ server.close(error => error ? reject(error) : resolve())
277
+ server.closeAllConnections()
278
+ })
279
+ }
280
+ }
281
+
282
+ const introspectionQuery = getIntrospectionQuery({
283
+ descriptions: true,
284
+ specifiedByUrl: true,
285
+ directiveIsRepeatable: true,
286
+ schemaDescription: true,
287
+ inputValueDeprecation: true,
288
+ })
289
+
290
+ const cases: Record<string, [query: string, variables?: Record<string, unknown>, operationName?: string]> = {
291
+ 'unknown field with suggestions': ['{ listArticl { id } }'],
292
+ 'unknown field on entity': ['{ listArticle { id nope } }'],
293
+ 'unknown argument': ['{ listArticle(nope: 1) { id } }'],
294
+ 'invalid enum literal': ['{ listArticle(orderBy: [{ title: up }]) { id } }'],
295
+ 'invalid enum value in filter': ['{ listArticle(filter: { status: { eq: archived } }) { id } }'],
296
+ 'variable of wrong type': ['query($a: Int) { listArticle(limit: $a) { id } }', { a: 'x' }],
297
+ 'required variable not provided': ['query($a: Int!) { listArticle(limit: $a) { id } }', {}],
298
+ 'null for a non-null variable': ['query($id: UUID!) { getArticle(by: { id: $id }) { id } }', { id: null }],
299
+ 'invalid UUID variable': ['query($id: UUID!) { getArticle(by: { id: $id }) { id } }', { id: 'nope' }],
300
+ 'invalid UUID literal': ['{ getArticle(by: { id: "nope" }) { id } }'],
301
+ 'invalid DateTime variable': ['query($d: DateTime) { listArticle(filter: { publishedAt: { gte: $d } }) { id } }', { d: 'yesterday' }],
302
+ 'wrong literal type': ['{ getArticle(by: { id: 123 }) { id } }'],
303
+ 'unknown input field': ['{ listArticle(filter: { nope: { eq: 1 } }) { id } }'],
304
+ 'unused variable': ['query($a: Int) { listArticle { id } }'],
305
+ 'undefined variable': ['{ listArticle(limit: $a) { id } }'],
306
+ 'unknown variable type': ['query($a: Nope) { listArticle { id } }'],
307
+ 'selection on a scalar': ['{ listArticle { id { x } } }'],
308
+ 'missing selection': ['{ listArticle }'],
309
+ 'fragment on a scalar': ['{ listArticle { ...F } } fragment F on String { x }'],
310
+ 'unknown fragment': ['{ listArticle { ...F } }'],
311
+ 'unused fragment': ['{ listArticle { id } } fragment F on Article { id }'],
312
+ 'fragment on a wrong type': ['{ listArticle { ...F } } fragment F on Tag { id }'],
313
+ 'fragment cycle': ['{ listArticle { ...F } } fragment F on Article { ...G } fragment G on Article { ...F }'],
314
+ 'duplicate operation name': ['query A { listArticle { id } } query A { listArticle { id } }'],
315
+ 'anonymous operation among named': ['{ listArticle { id } } query A { listArticle { id } }'],
316
+ 'conflicting aliases': ['{ a: listArticle(limit: 1) { id } a: listArticle(limit: 2) { id } }'],
317
+ 'conflicting field names': ['{ listArticle { id: title id } }'],
318
+ 'duplicate argument': ['{ listArticle(limit: 1, limit: 2) { id } }'],
319
+ 'unknown directive': ['{ listArticle @nope { id } }'],
320
+ 'missing required argument': ['{ getArticle { id } }'],
321
+ 'subscription': ['subscription { listArticle { id } }'],
322
+ 'several operations without a name': ['query A { __typename } query B { __typename }'],
323
+ 'unknown operation name': ['query A { __typename }', undefined, 'B'],
324
+ 'skipped field': ['{ listArticle @skip(if: true) { id } _info { description } }'],
325
+ 'typename': ['{ __typename }'],
326
+ 'mutation on a read-only role': ['mutation { createArticle(data: { title: "x" }) { ok } }'],
327
+ 'contribution with aliases, fragments and variables': [
328
+ 'mutation($type: String) { first: generateUpload(input: { contentType: $type }) { ...U } second: generateUpload(contentType: "b") { url } } fragment U on UploadUrl { url headers { key value } size }',
329
+ { type: 'a' },
330
+ ],
331
+ 'contribution argument of wrong type': ['mutation { generateUpload(contentType: 1) { url } }'],
332
+ 'contribution forbidden error': ['mutation { generateUpload(contentType: "forbidden") { url } }'],
333
+ 'contribution error with extensions': ['mutation { generateUpload(contentType: "invalid") { url } }'],
334
+ 'contribution unexpected error': ['mutation { generateUpload(contentType: "crash") { url } }'],
335
+ 'contribution custom scalar output': ['{ report { at } }'],
336
+ 'contribution custom scalar variable': ['query($s: Stamp) { report(since: $s) { at } }', { s: '2021-05-05T00:00:00.000Z' }],
337
+ 'contribution custom scalar in an input variable': ['query($i: ReportInput) { report(input: $i) { at } }', {
338
+ i: { since: '2021-05-05T00:00:00.000Z' },
339
+ }],
340
+ 'contribution custom scalar literal': ['{ report(since: "2021-05-05T00:00:00.000Z") { at } }'],
341
+ 'contribution invalid custom scalar variable': ['query($s: Stamp) { report(since: $s) { at } }', { s: 'nope' }],
342
+ 'contribution nested nullable error': ['{ report { lines { label failing } } }'],
343
+ 'contribution non-null error bubbling to a nullable list item': ['{ report { maybeLines { label strict } } }'],
344
+ 'contribution non-null error bubbling through a non-null list': ['{ report { at lines { label strict } } }'],
345
+ 'contribution several errors': ['{ report { lines { failing } nested { failing } } }'],
346
+ 'contribution error next to other fields': ['{ __typename r: report { nested { label failing } } uploadDummyQuery }'],
347
+ 'contribution under the mutation query field': ['mutation { query { report { at } } }'],
348
+ 'contribution mutation': ['mutation { touchReport { at nested { failing } } }'],
349
+ 'contribution in a query transaction': ['{ transaction { report { at } } }'],
350
+ 'contribution in a mutation transaction': ['mutation { transaction { ok touchReport { at } } }'],
351
+ }
352
+
353
+ /** graphql-js still answers as recorded, and graphql-json answers with the same bytes: key order and errors included. */
354
+ const expectSameResponse = async (role: string, query: string, variables?: Record<string, unknown>, operationName?: string) => {
355
+ const graphqlJs = await request('graphql-js', role, query, variables, operationName)
356
+ const graphqlJson = await request('graphql-json', role, query, variables, operationName)
357
+ expect({ status: graphqlJs.status, body: JSON.parse(graphqlJs.text) }).toMatchSnapshot()
358
+ expect(graphqlJson).toEqual(graphqlJs)
359
+ }
360
+
361
+ describe('content GraphQL responses match graphql-js', () => {
362
+ test('introspection', async () => {
363
+ await expectSameResponse('admin', introspectionQuery)
364
+ })
365
+ for (const role of ['admin', 'reader']) {
366
+ for (const [name, [query, variables, operationName]] of Object.entries(cases)) {
367
+ test(`${role}: ${name}`, async () => {
368
+ await expectSameResponse(role, query, variables, operationName)
369
+ })
370
+ }
371
+ }
372
+ })
@@ -0,0 +1,141 @@
1
+ import { afterEach, expect, test } from 'bun:test'
2
+ import { existsSync } from 'node:fs'
3
+ import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { createLogger, TestLoggerHandler } from '@contember/logger'
7
+ import { ContentRequestLog, ContentRequestLogOptions } from '../../../src/content/ContentRequestLog.js'
8
+ import { createContentControllerHarness } from '../../contentControllerHarness.js'
9
+
10
+ const directories: string[] = []
11
+
12
+ afterEach(async () => {
13
+ await Promise.all(directories.splice(0).map(it => rm(it, { recursive: true, force: true })))
14
+ })
15
+
16
+ const now = Date.parse('2026-01-02T03:04:05Z')
17
+
18
+ const createLog = async (options: Partial<ContentRequestLogOptions> = {}, clock: () => number = () => now) => {
19
+ const directory = await mkdtemp(join(tmpdir(), 'content-request-log-'))
20
+ directories.push(directory)
21
+ const file = join(directory, 'requests.jsonl')
22
+ const loggerHandler = new TestLoggerHandler()
23
+ const log = new ContentRequestLog(
24
+ { projects: ['test'], file, maxRequests: 10, until: '2026-01-03T00:00:00.000Z', ...options },
25
+ createLogger(loggerHandler),
26
+ clock,
27
+ )
28
+ return { log, file, loggerHandler }
29
+ }
30
+
31
+ const readEntries = async (file: string): Promise<unknown[]> => (await readFile(file, 'utf8')).split('\n').filter(Boolean).map(it => JSON.parse(it))
32
+
33
+ const entry = (project: string) => ({
34
+ projectGroup: undefined,
35
+ project,
36
+ stage: 'live',
37
+ roles: ['editor'],
38
+ method: 'POST',
39
+ request: { query: '{ marker }' },
40
+ status: 200,
41
+ })
42
+
43
+ const waitFor = async (condition: () => boolean) => {
44
+ for (let attempt = 0; attempt < 100 && !condition(); attempt++) {
45
+ await new Promise(resolve => setTimeout(resolve, 10))
46
+ }
47
+ expect(condition()).toBe(true)
48
+ }
49
+
50
+ test('the controller records a request of a listed project with its stage, roles, request and status', async () => {
51
+ const { log, file } = await createLog()
52
+ const harness = createContentControllerHarness('graphql-js', { roles: ['editor'], requestLog: log })
53
+ try {
54
+ await harness.request('query Marker { marker }', {}, { note: 'client data' })
55
+ await harness.request('mutation { unknown }')
56
+ } finally {
57
+ await harness.close()
58
+ }
59
+ await log.close()
60
+
61
+ const recorded = { time: '2026-01-02T03:04:05.000Z', projectGroup: null, project: 'test', stage: 'live', roles: ['editor'], method: 'POST' }
62
+ expect(await readEntries(file)).toEqual([
63
+ { ...recorded, query: 'query Marker { marker }', variables: { note: 'client data' }, status: 200 },
64
+ { ...recorded, query: 'mutation { unknown }', status: 400 },
65
+ ])
66
+ })
67
+
68
+ test('a project that is not listed is not recorded', async () => {
69
+ const { log, file } = await createLog({ projects: ['other'] })
70
+ const harness = createContentControllerHarness('graphql-js', { requestLog: log })
71
+ try {
72
+ await harness.request('{ marker }')
73
+ } finally {
74
+ await harness.close()
75
+ }
76
+ await log.close()
77
+
78
+ expect(existsSync(file)).toBe(false)
79
+ })
80
+
81
+ test('recording stops at the cap of each project', async () => {
82
+ const { log, file, loggerHandler } = await createLog({ projects: ['test', 'other'], maxRequests: 2 })
83
+ for (let i = 0; i < 3; i++) {
84
+ log.record(entry('test'))
85
+ }
86
+ log.record(entry('other'))
87
+ await log.close()
88
+
89
+ const projects = (await readEntries(file)).map(it => typeof it === 'object' && it !== null ? Reflect.get(it, 'project') : undefined)
90
+ expect(projects).toEqual(['test', 'test', 'other'])
91
+ expect(log.accepts('test')).toBe(false)
92
+ expect(loggerHandler.messages.map(it => it.message)).toContain('Content API request log reached its cap for a project')
93
+ })
94
+
95
+ test('nothing is recorded after `until`, also by a log created later, as after a restart', async () => {
96
+ let clock = Date.parse('2026-01-02T23:59:59Z')
97
+ const { log, file } = await createLog({}, () => clock)
98
+ log.record(entry('test'))
99
+ clock = Date.parse('2026-01-03T00:00:00Z')
100
+ log.record(entry('test'))
101
+ await log.close()
102
+
103
+ const restarted = new ContentRequestLog(
104
+ { projects: ['test'], file, maxRequests: 10, until: '2026-01-03T00:00:00.000Z' },
105
+ createLogger(new TestLoggerHandler()),
106
+ () => clock,
107
+ )
108
+ restarted.record(entry('test'))
109
+ await restarted.close()
110
+
111
+ expect(await readEntries(file)).toHaveLength(1)
112
+ })
113
+
114
+ test('the log file is readable by its owner only', async () => {
115
+ const { log, file } = await createLog()
116
+ log.record(entry('test'))
117
+ await log.close()
118
+
119
+ expect((await stat(file)).mode & 0o777).toBe(0o600)
120
+ })
121
+
122
+ test('a destination that cannot be written stops the log, and the request still succeeds', async () => {
123
+ const { file, loggerHandler } = await createLog()
124
+ const unwritable = new ContentRequestLog(
125
+ { projects: ['test'], file: join(file, 'missing-directory', 'requests.jsonl'), maxRequests: 10, until: '2026-01-03T00:00:00.000Z' },
126
+ createLogger(loggerHandler),
127
+ () => now,
128
+ )
129
+ const harness = createContentControllerHarness('graphql-js', { requestLog: unwritable })
130
+ try {
131
+ const { koa } = await harness.request('{ marker }')
132
+ expect(koa.status).toBe(200)
133
+ expect(koa.body).toBe('{"data":{"marker":"replica"}}')
134
+ } finally {
135
+ await harness.close()
136
+ }
137
+
138
+ await waitFor(() => !unwritable.accepts('test'))
139
+ expect(loggerHandler.messages.map(it => it.message)).toContainEqual(expect.stringContaining('Content API request log failed and is stopped'))
140
+ await unwritable.close()
141
+ })