@contember/engine-http 1.2.0-alpha.2 → 1.2.0-alpha.3

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 (74) hide show
  1. package/dist/src/common/TimerMiddleware.d.ts.map +1 -1
  2. package/dist/src/common/TimerMiddleware.js +24 -7
  3. package/dist/src/common/TimerMiddleware.js.map +1 -1
  4. package/dist/src/content/ContentSchemaResolver.d.ts +2 -3
  5. package/dist/src/content/ContentSchemaResolver.d.ts.map +1 -1
  6. package/dist/src/content/GraphQlSchemaFactory.d.ts.map +1 -1
  7. package/dist/src/content/GraphQlSchemaFactory.js +1 -2
  8. package/dist/src/content/GraphQlSchemaFactory.js.map +1 -1
  9. package/dist/src/index.d.ts +1 -0
  10. package/dist/src/index.d.ts.map +1 -1
  11. package/dist/src/index.js +1 -0
  12. package/dist/src/index.js.map +1 -1
  13. package/dist/src/koa/types.d.ts +1 -0
  14. package/dist/src/koa/types.d.ts.map +1 -1
  15. package/dist/src/transfer/Command.d.ts +23 -0
  16. package/dist/src/transfer/Command.d.ts.map +1 -0
  17. package/dist/src/transfer/Command.js +53 -0
  18. package/dist/src/transfer/Command.js.map +1 -0
  19. package/dist/src/transfer/CommandStream.d.ts +6 -0
  20. package/dist/src/transfer/CommandStream.d.ts.map +1 -0
  21. package/dist/src/transfer/CommandStream.js +90 -0
  22. package/dist/src/transfer/CommandStream.js.map +1 -0
  23. package/dist/src/transfer/ContentSchemaTransferMappingFactory.d.ts +8 -0
  24. package/dist/src/transfer/ContentSchemaTransferMappingFactory.d.ts.map +1 -0
  25. package/dist/src/transfer/ContentSchemaTransferMappingFactory.js +104 -0
  26. package/dist/src/transfer/ContentSchemaTransferMappingFactory.js.map +1 -0
  27. package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts +15 -0
  28. package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts.map +1 -0
  29. package/dist/src/transfer/ExportApiMiddlewareFactory.js +59 -0
  30. package/dist/src/transfer/ExportApiMiddlewareFactory.js.map +1 -0
  31. package/dist/src/transfer/ExportExecutor.d.ts +24 -0
  32. package/dist/src/transfer/ExportExecutor.d.ts.map +1 -0
  33. package/dist/src/transfer/ExportExecutor.js +130 -0
  34. package/dist/src/transfer/ExportExecutor.js.map +1 -0
  35. package/dist/src/transfer/ImportApiMiddlewareFactory.d.ts +15 -0
  36. package/dist/src/transfer/ImportApiMiddlewareFactory.d.ts.map +1 -0
  37. package/dist/src/transfer/ImportApiMiddlewareFactory.js +39 -0
  38. package/dist/src/transfer/ImportApiMiddlewareFactory.js.map +1 -0
  39. package/dist/src/transfer/ImportExecutor.d.ts +38 -0
  40. package/dist/src/transfer/ImportExecutor.d.ts.map +1 -0
  41. package/dist/src/transfer/ImportExecutor.js +296 -0
  42. package/dist/src/transfer/ImportExecutor.js.map +1 -0
  43. package/dist/src/transfer/SystemSchemaTransferMappingFactory.d.ts +7 -0
  44. package/dist/src/transfer/SystemSchemaTransferMappingFactory.d.ts.map +1 -0
  45. package/dist/src/transfer/SystemSchemaTransferMappingFactory.js +135 -0
  46. package/dist/src/transfer/SystemSchemaTransferMappingFactory.js.map +1 -0
  47. package/dist/src/transfer/TransferMapping.d.ts +38 -0
  48. package/dist/src/transfer/TransferMapping.d.ts.map +1 -0
  49. package/dist/src/transfer/TransferMapping.js +3 -0
  50. package/dist/src/transfer/TransferMapping.js.map +1 -0
  51. package/dist/src/transfer/index.d.ts +7 -0
  52. package/dist/src/transfer/index.d.ts.map +1 -0
  53. package/dist/src/transfer/index.js +23 -0
  54. package/dist/src/transfer/index.js.map +1 -0
  55. package/dist/src/tsconfig.tsbuildinfo +1 -1
  56. package/dist/src/utils/CryptoWrapper.d.ts +1 -0
  57. package/dist/src/utils/CryptoWrapper.d.ts.map +1 -1
  58. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  59. package/package.json +14 -15
  60. package/src/common/TimerMiddleware.ts +30 -9
  61. package/src/content/ContentSchemaResolver.ts +1 -1
  62. package/src/content/GraphQlSchemaFactory.ts +1 -2
  63. package/src/index.ts +1 -0
  64. package/src/koa/types.ts +1 -1
  65. package/src/transfer/Command.ts +42 -0
  66. package/src/transfer/CommandStream.ts +72 -0
  67. package/src/transfer/ContentSchemaTransferMappingFactory.ts +113 -0
  68. package/src/transfer/ExportApiMiddlewareFactory.ts +76 -0
  69. package/src/transfer/ExportExecutor.ts +132 -0
  70. package/src/transfer/ImportApiMiddlewareFactory.ts +53 -0
  71. package/src/transfer/ImportExecutor.ts +366 -0
  72. package/src/transfer/SystemSchemaTransferMappingFactory.ts +129 -0
  73. package/src/transfer/TransferMapping.ts +24 -0
  74. package/src/transfer/index.ts +8 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contember/engine-http",
3
- "version": "1.2.0-alpha.2",
3
+ "version": "1.2.0-alpha.3",
4
4
  "license": "Apache-2.0",
5
5
  "main": "dist/src/index.js",
6
6
  "typings": "dist/src/index.d.ts",
@@ -9,22 +9,21 @@
9
9
  },
10
10
  "dependencies": {
11
11
  "@apollographql/graphql-playground-html": "^1.6.24",
12
- "@contember/database": "^1.2.0-alpha.2",
13
- "@contember/engine-content-api": "^1.2.0-alpha.2",
14
- "@contember/engine-plugins": "^1.2.0-alpha.2",
15
- "@contember/engine-system-api": "^1.2.0-alpha.2",
16
- "@contember/engine-tenant-api": "^1.2.0-alpha.2",
17
- "@contember/graphql-utils": "^1.2.0-alpha.2",
18
- "@contember/schema": "^1.2.0-alpha.2",
19
- "@contember/schema-utils": "^1.2.0-alpha.2",
20
- "@contember/typesafe": "^1.2.0-alpha.2",
21
- "@graphql-tools/merge": "^6.2.14",
12
+ "@contember/database": "^1.2.0-alpha.3",
13
+ "@contember/engine-content-api": "^1.2.0-alpha.3",
14
+ "@contember/engine-plugins": "^1.2.0-alpha.3",
15
+ "@contember/engine-system-api": "^1.2.0-alpha.3",
16
+ "@contember/engine-tenant-api": "^1.2.0-alpha.3",
17
+ "@contember/graphql-utils": "^1.2.0-alpha.3",
18
+ "@contember/schema": "^1.2.0-alpha.3",
19
+ "@contember/schema-utils": "^1.2.0-alpha.3",
20
+ "@contember/typesafe": "^1.2.0-alpha.3",
22
21
  "@graphql-tools/schema": "^8.3.5",
23
- "@types/lru-cache": "^5.1.0",
22
+ "@types/lru-cache": "^7.10.10",
24
23
  "accepts": "^1.3.7",
25
24
  "bcrypt": "^5.0.1",
26
25
  "koa": "^2.11.0",
27
- "lru-cache": "^6.0.0",
26
+ "lru-cache": "^7.10.1",
28
27
  "path-to-regexp": "^6.2.0",
29
28
  "uuid": "^8.3.1"
30
29
  },
@@ -34,9 +33,9 @@
34
33
  "@types/koa-bodyparser": "^4.2.2",
35
34
  "@types/koa__cors": "^3.0.2",
36
35
  "@types/lru-cache": "^5.1.0",
37
- "@types/node": "^17.0.5",
36
+ "@types/node": "^16",
38
37
  "@types/uuid": "^8.3.0",
39
- "graphql": "^15.4.0"
38
+ "graphql": "^16.5.0"
40
39
  },
41
40
  "peerDependencies": {
42
41
  "graphql": "^14.6.0",
@@ -1,4 +1,5 @@
1
1
  import { KoaMiddleware } from '../koa'
2
+ import { Readable } from 'stream'
2
3
 
3
4
  type EventTime = { label: string; start: number; duration?: number }
4
5
 
@@ -25,17 +26,37 @@ export const createTimerMiddleware = (): KoaMiddleware<TimerMiddlewareState> =>
25
26
  time.duration = new Date().getTime() - start
26
27
  return res as any
27
28
  }
29
+
28
30
  await next()
29
31
 
30
- const eventsDescription = times
31
- .map(it => `${it.label} T+${it.start}ms ${it.duration !== undefined ? it.duration : '[unknown]'}ms`)
32
- .join('; ')
33
- const total = new Date().getTime() - globalStart
34
- const timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'
35
- // eslint-disable-next-line no-console
36
- console.log(
37
- `${ctx.request.method} ${ctx.request.url} [${ctx.response.status}] ${ctx.req.connection.remoteAddress} ${timeLabel} ${total}ms (${eventsDescription})`,
38
- )
32
+ const emit = () => {
33
+ const eventsDescription = times
34
+ .map(it => `${it.label} T+${it.start}ms ${it.duration !== undefined ? it.duration : '[unknown]'}ms`)
35
+ .join('; ')
36
+
37
+ const total = new Date().getTime() - globalStart
38
+ const timeLabel = total > 500 ? 'TIME_SLOW' : 'TIME_OK'
39
+ // eslint-disable-next-line no-console
40
+ console.log(
41
+ `${ctx.request.method} ${ctx.request.url} [${ctx.response.status}] ${ctx.req.connection.remoteAddress} ${timeLabel} ${total}ms (${eventsDescription})`,
42
+ )
43
+ }
44
+
45
+ if (ctx.response.body instanceof Readable) {
46
+ const body = ctx.response.body
47
+ const streamTimer = ctx.state.timer('Stream', () => {
48
+ return new Promise(resolve => {
49
+ body.addListener('close', () => {
50
+ resolve(null)
51
+ })
52
+ })
53
+ })
54
+
55
+ streamTimer.then(emit).catch(emit)
56
+
57
+ } else {
58
+ emit()
59
+ }
39
60
  }
40
61
  return timer
41
62
  }
@@ -11,7 +11,7 @@ export class ContentSchemaResolver {
11
11
  this.schemaCache = {}
12
12
  }
13
13
 
14
- public async getSchema(db: DatabaseContext, stage: string): Promise<Schema> {
14
+ public async getSchema(db: DatabaseContext, stage: string): Promise<VersionedSchema> {
15
15
  const cachedSchema = this.schemaCache[stage]
16
16
  let newSchema = await this.schemaVersionBuilder.buildSchema(db, cachedSchema)
17
17
  if (newSchema !== cachedSchema) {
@@ -9,8 +9,7 @@ import {
9
9
  } from '@contember/engine-content-api'
10
10
  import { Acl, Schema } from '@contember/schema'
11
11
  import { GraphQLSchema } from 'graphql'
12
- import { mergeSchemas } from '@graphql-tools/merge'
13
- import { makeExecutableSchema } from '@graphql-tools/schema'
12
+ import { makeExecutableSchema, mergeSchemas } from '@graphql-tools/schema'
14
13
  import { GraphQLSchemaContributor } from '@contember/engine-plugins'
15
14
  import { JSONType } from '@contember/graphql-utils'
16
15
 
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ export * from './misc'
4
4
  export * from './project-common'
5
5
  export * from './system'
6
6
  export * from './tenant'
7
+ export * from './transfer'
7
8
  export * from './koa'
8
9
  export * from './providers'
9
10
  export * from './ProjectContainer'
package/src/koa/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as Koa from 'koa'
2
2
 
3
- export type KoaContext<State> = Koa.ExtendableContext & { state: State }
3
+ export type KoaContext<State> = Koa.ExtendableContext & { state: State; compress?: boolean }
4
4
  type KoaNext = () => Promise<any>
5
5
  export type KoaMiddleware<State> = (context: KoaContext<State>, next: KoaNext) => any
@@ -0,0 +1,42 @@
1
+ import * as Typesafe from '@contember/typesafe'
2
+
3
+ const tuple = <T extends any[]>(...values: T) => values
4
+
5
+ export const Command = Typesafe.discriminatedTupleUnion({
6
+ importTenantSchemaBegin: tuple(),
7
+ importSystemSchemaBegin: tuple(
8
+ Typesafe.object({
9
+ project: Typesafe.string,
10
+ tables: Typesafe.array(Typesafe.string),
11
+ }),
12
+ ),
13
+ importContentSchemaBegin: tuple(
14
+ Typesafe.object({
15
+ project: Typesafe.string,
16
+ stage: Typesafe.string,
17
+ schemaVersion: Typesafe.string,
18
+ tables: Typesafe.array(Typesafe.string),
19
+ }),
20
+ ),
21
+ importSequence: tuple(
22
+ Typesafe.object({
23
+ table: Typesafe.string,
24
+ column: Typesafe.string,
25
+ value: Typesafe.number,
26
+ }),
27
+ ),
28
+ insertBegin: tuple(
29
+ Typesafe.object({
30
+ table: Typesafe.string,
31
+ columns: Typesafe.array(Typesafe.string),
32
+ }),
33
+ ),
34
+ insertRow: tuple(
35
+ Typesafe.array(Typesafe.anyJson), // values
36
+ ),
37
+ insertEnd: tuple(),
38
+ })
39
+
40
+ export type Command = ReturnType<typeof Command>
41
+ export type CommandName = Command[0]
42
+ export type CommandArgsMap<S extends Command = Command> = { [K in S[0]]: S extends readonly [K, ...infer T] ? T : never }
@@ -0,0 +1,72 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import * as Typesafe from '@contember/typesafe'
3
+ import { Command } from './Command'
4
+ import { ImportError } from './ImportExecutor'
5
+
6
+ export async function* toBuffer(lines: AsyncIterable<any>, bufferSize: number = 16 * 1024): AsyncIterable<Buffer> {
7
+ let chunks = []
8
+ let chunksLength = 0
9
+
10
+ for await (const line of lines) {
11
+ const chunk = Buffer.from(JSON.stringify(line) + '\n')
12
+ chunks.push(chunk)
13
+ chunksLength += chunk.length
14
+
15
+ if (chunksLength >= bufferSize) {
16
+ yield Buffer.concat(chunks)
17
+ chunks = []
18
+ chunksLength = 0
19
+ }
20
+ }
21
+
22
+ if (chunksLength > 0) {
23
+ yield Buffer.concat(chunks)
24
+ }
25
+ }
26
+
27
+ export async function* fromBuffer(stream: AsyncIterable<Buffer>): AsyncIterable<Command> {
28
+ yield* readCommands(readLines(stream))
29
+ }
30
+
31
+ async function* readCommands(lines: AsyncIterable<string>) {
32
+ for await (let line of lines) {
33
+ try {
34
+ yield Command(JSON.parse(line))
35
+
36
+ } catch (e) {
37
+ if (e instanceof SyntaxError) {
38
+ throw new ImportError(`Line ${line} is not valid JSON`)
39
+
40
+ } else if (e instanceof Typesafe.ParseError) {
41
+ throw new ImportError(`Line ${line} is not valid command`)
42
+
43
+ } else {
44
+ throw e
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ async function* readLines(stream: AsyncIterable<Buffer>) {
51
+ let chunks = []
52
+
53
+ for await (let chunk of stream) {
54
+ while (true) {
55
+ const eolIndex = chunk.indexOf('\n')
56
+
57
+ if (eolIndex < 0) {
58
+ chunks.push(chunk)
59
+ break
60
+ }
61
+
62
+ chunks.push(chunk.slice(0, eolIndex))
63
+ chunk = chunk.slice(eolIndex + 1)
64
+ yield Buffer.concat(chunks).toString('utf8')
65
+ chunks = []
66
+ }
67
+ }
68
+
69
+ if (Buffer.concat(chunks).length > 0) {
70
+ throw new ImportError(`Unexpected stream end`)
71
+ }
72
+ }
@@ -0,0 +1,113 @@
1
+ import { VersionedSchema } from '@contember/engine-system-api'
2
+ import { Model } from '@contember/schema'
3
+ import { acceptFieldVisitor } from '@contember/schema-utils'
4
+ import { DbColumnSchema, DbColumnSchemaMap, TransferMapping, TransferTableMapping } from './TransferMapping'
5
+
6
+ export class ContentSchemaTransferMappingFactory {
7
+ createContentSchemaMapping(contentSchema: VersionedSchema): TransferMapping {
8
+ const tables: Record<string, TransferTableMapping> = {}
9
+
10
+ for (const entity of Object.values(contentSchema.model.entities)) {
11
+ tables[entity.tableName] = {
12
+ name: entity.tableName,
13
+ columns: this.buildDbColumnSchemaMap(contentSchema.model, entity),
14
+ }
15
+
16
+ for (const joiningTable of this.collectManyHasManyOwned(contentSchema.model, entity)) {
17
+ tables[joiningTable.name] = joiningTable
18
+ }
19
+ }
20
+
21
+ return { tables }
22
+ }
23
+
24
+ private buildDbColumnSchemaMap(schema: Model.Schema, entity: Model.Entity): DbColumnSchemaMap {
25
+ const columns: DbColumnSchemaMap = {}
26
+
27
+ for (const field of Object.values(entity.fields)) {
28
+ const column = acceptFieldVisitor<DbColumnSchema | null>(schema, entity, field, {
29
+ visitColumn: (entity, column) => {
30
+ if (column.type === Model.ColumnType.Enum) {
31
+ return {
32
+ name: column.columnName,
33
+ type: column.type,
34
+ nullable: column.nullable,
35
+ values: schema.enums[column.columnType],
36
+ }
37
+
38
+ } else if (column.type === Model.ColumnType.Int) {
39
+ return {
40
+ name: column.columnName,
41
+ type: column.type,
42
+ nullable: column.nullable,
43
+ sequence: column.sequence !== undefined,
44
+ }
45
+
46
+ } else {
47
+ return {
48
+ name: column.columnName,
49
+ type: column.type,
50
+ nullable: column.nullable,
51
+ }
52
+ }
53
+ },
54
+ visitOneHasOneOwning: (entity, relation, targetEntity) => ({
55
+ name: relation.joiningColumn.columnName,
56
+ type: targetEntity.fields[targetEntity.primary].type as (Model.ColumnType.Uuid | Model.ColumnType.Int),
57
+ nullable: relation.nullable,
58
+ }),
59
+ visitManyHasOne: (entity, relation, targetEntity) => ({
60
+ name: relation.joiningColumn.columnName,
61
+ type: targetEntity.fields[targetEntity.primary].type as (Model.ColumnType.Uuid | Model.ColumnType.Int),
62
+ nullable: relation.nullable,
63
+ }),
64
+ visitManyHasManyOwning: () => null,
65
+ visitManyHasManyInverse: () => null,
66
+ visitOneHasMany: () => null,
67
+ visitOneHasOneInverse: () => null,
68
+ })
69
+
70
+ if (column !== null) {
71
+ columns[column.name] = column
72
+ }
73
+ }
74
+
75
+ return columns
76
+ }
77
+
78
+ private collectManyHasManyOwned(schema: Model.Schema, entity: Model.Entity): TransferTableMapping[] {
79
+ const joiningTables = []
80
+
81
+ for (const field of Object.values(entity.fields)) {
82
+ const joiningTable = acceptFieldVisitor<TransferTableMapping | null>(schema, entity, field, {
83
+ visitColumn: () => null,
84
+ visitOneHasOneOwning: () => null,
85
+ visitManyHasOne: () => null,
86
+ visitManyHasManyOwning: (entity, relation, targetEntity) => ({
87
+ name: relation.joiningTable.tableName,
88
+ columns: {
89
+ [relation.joiningTable.joiningColumn.columnName]: {
90
+ name: relation.joiningTable.joiningColumn.columnName,
91
+ type: entity.fields[entity.primary].type as (Model.ColumnType.Uuid | Model.ColumnType.Int),
92
+ nullable: false,
93
+ },
94
+ [relation.joiningTable.inverseJoiningColumn.columnName]: {
95
+ name: relation.joiningTable.inverseJoiningColumn.columnName,
96
+ type: targetEntity.fields[targetEntity.primary].type as (Model.ColumnType.Uuid | Model.ColumnType.Int),
97
+ nullable: false,
98
+ },
99
+ },
100
+ }),
101
+ visitManyHasManyInverse: () => null,
102
+ visitOneHasMany: () => null,
103
+ visitOneHasOneInverse: () => null,
104
+ })
105
+
106
+ if (joiningTable !== null) {
107
+ joiningTables.push(joiningTable)
108
+ }
109
+ }
110
+
111
+ return joiningTables
112
+ }
113
+ }
@@ -0,0 +1,76 @@
1
+ import { KoaMiddleware, KoaRequestState } from '../koa'
2
+ import { AuthResult, HttpError, TimerMiddlewareState } from '../common'
3
+ import { ProjectGroupResolver, ProjectInfoMiddlewareState } from '../project-common'
4
+ import { Readable } from 'stream'
5
+ import { TenantRole } from '@contember/engine-tenant-api'
6
+ import { toBuffer } from './CommandStream'
7
+ import { ExportExecutor, ExportRequest } from './ExportExecutor'
8
+ import { ParseError } from '@contember/typesafe'
9
+ import { Logger } from '@contember/engine-common'
10
+ import { ProjectContainer } from '../ProjectContainer'
11
+
12
+ type ExportApiMiddlewareState =
13
+ & TimerMiddlewareState
14
+ & KoaRequestState
15
+ & ProjectInfoMiddlewareState
16
+ & { authResult: AuthResult }
17
+
18
+ export class ExportApiMiddlewareFactory {
19
+ constructor(
20
+ private readonly projectGroupResolver: ProjectGroupResolver,
21
+ private readonly exportExecutor: ExportExecutor,
22
+ ) {
23
+ }
24
+
25
+ create(): KoaMiddleware<ExportApiMiddlewareState> {
26
+ return async koaContext => {
27
+ const { request, response, state: { timer } } = koaContext
28
+
29
+ const groupContainer = await this.projectGroupResolver.resolveContainer({ request })
30
+ koaContext.state.projectGroup = groupContainer.slug
31
+
32
+ const authResult = await groupContainer.authenticator.authenticate({ request, timer })
33
+ koaContext.state.authResult = authResult
34
+
35
+ if (!authResult.roles.includes(TenantRole.SUPER_ADMIN) && !authResult.roles.includes(TenantRole.PROJECT_ADMIN)) {
36
+ throw new HttpError(`Not allowed`, 403)
37
+ }
38
+
39
+ let exportRequest: ExportRequest
40
+
41
+ try {
42
+ exportRequest = ExportRequest(request.body)
43
+
44
+ } catch (e) {
45
+ if (e instanceof ParseError) {
46
+ response.status = 400
47
+ response.headers['Content-Type'] = 'application/json'
48
+ response.body = { ok: false, error: `Invalid request body: ${e.message}` }
49
+ return
50
+
51
+ } else {
52
+ throw e
53
+ }
54
+ }
55
+
56
+ // eslint-disable-next-line no-console
57
+ const logger = new Logger(console.log)
58
+ const projectContainers: Record<string, ProjectContainer> = {}
59
+
60
+ for (const project of exportRequest.projects) {
61
+ const projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(project.slug, { alias: true, logger })
62
+
63
+ if (projectContainer === undefined) {
64
+ throw new HttpError(`Project ${project.slug} NOT found`, 400)
65
+ }
66
+
67
+ projectContainers[project.slug] = projectContainer
68
+ }
69
+
70
+ koaContext.compress = true
71
+ response.status = 200
72
+ response.res.setHeader('Content-Type', 'application/x-ndjson') // https://github.com/ndjson/ndjson-spec
73
+ response.body = Readable.from(toBuffer(this.exportExecutor.export(exportRequest, projectContainers)))
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,132 @@
1
+ import { asyncIterableTransaction, Client, Compiler, Connection, wrapIdentifier } from '@contember/database'
2
+ import { Command } from './Command'
3
+ import { TransferMapping, TransferTableMapping } from './TransferMapping'
4
+ import { Model } from '@contember/schema'
5
+ import { ContentSchemaTransferMappingFactory } from './ContentSchemaTransferMappingFactory'
6
+ import { SystemSchemaTransferMappingFactory } from './SystemSchemaTransferMappingFactory'
7
+ import * as Typesafe from '@contember/typesafe'
8
+ import { StagesQuery } from '@contember/engine-system-api'
9
+ import { ProjectContainer } from '../ProjectContainer'
10
+
11
+ export type ExportRequest = ReturnType<typeof ExportRequest>
12
+ export const ExportRequest = Typesafe.object({
13
+ // tenant: Typesafe.boolean,
14
+ projects: Typesafe.array(Typesafe.object({
15
+ slug: Typesafe.string,
16
+ system: Typesafe.boolean,
17
+ })),
18
+ })
19
+
20
+ export class ExportExecutor {
21
+ constructor(
22
+ private readonly contentSchemaTransferMappingFactory: ContentSchemaTransferMappingFactory,
23
+ private readonly systemSchemaTransferMappingFactory: SystemSchemaTransferMappingFactory,
24
+ ) {
25
+ }
26
+
27
+ async* export(request: ExportRequest, projectContainers: Record<string, ProjectContainer>): AsyncIterable<Command> {
28
+ for (const project of request.projects) {
29
+ const projectContainer = projectContainers[project.slug]
30
+ const systemContext = projectContainer.systemDatabaseContextFactory.create()
31
+
32
+ if (project.system) {
33
+ const systemMapping = this.systemSchemaTransferMappingFactory.build()
34
+ yield ['importSystemSchemaBegin', { project: project.slug, tables: Object.keys(systemMapping.tables) }]
35
+ yield* this.exportSchema(systemContext.client, systemMapping)
36
+ }
37
+
38
+ for (const stage of await systemContext.queryHandler.fetch(new StagesQuery())) {
39
+ const contentSchema = await projectContainer.contentSchemaResolver.getSchema(systemContext, stage.slug)
40
+ const contentMapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema)
41
+ const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {})
42
+
43
+ yield [
44
+ 'importContentSchemaBegin', {
45
+ project: project.slug,
46
+ stage: stage.slug,
47
+ schemaVersion: contentSchema.version,
48
+ tables: Object.keys(contentMapping.tables),
49
+ },
50
+ ]
51
+
52
+ yield* this.exportSchema(contentDatabaseClient, contentMapping)
53
+ }
54
+ }
55
+ }
56
+
57
+ private async* exportSchema(db: Client, mapping: TransferMapping): AsyncIterable<Command> {
58
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
59
+ const that = this
60
+ yield* asyncIterableTransaction(db, async function* (db) {
61
+ await db.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE')
62
+ for (const table of Object.values(mapping.tables)) {
63
+ yield* that.exportSequences(db, table)
64
+ yield* that.exportTable(db, table)
65
+ }
66
+ })
67
+ }
68
+
69
+ private async* exportSequences(db: Client<Connection.TransactionLike>, table: TransferTableMapping): AsyncIterable<Command> {
70
+ for (const column of Object.values(table.columns)) {
71
+ if (column.type === Model.ColumnType.Int && column.sequence) {
72
+ const seqResult = await db.query<{ nextval: number }>(
73
+ 'SELECT nextval(pg_get_serial_sequence(?, ?))',
74
+ [table.name, column.name],
75
+ )
76
+
77
+ const seqValue = seqResult.rows[0].nextval
78
+ yield ['importSequence', { table: table.name, column: column.name, value: seqValue }]
79
+ }
80
+ }
81
+ }
82
+
83
+ private async* exportTable(db: Client<Connection.TransactionLike>, table: TransferTableMapping): AsyncIterable<Command> {
84
+ const DB_FETCH_BATCH_SIZE = 100
85
+ const query = (table.createSelect ?? this.buildQuery)(db, table)
86
+ let empty = true
87
+
88
+ for await (const row of this.cursorQuery(db, DB_FETCH_BATCH_SIZE, query.sql, query.parameters)) {
89
+ if (empty) {
90
+ yield ['insertBegin', { table: table.name, columns: Object.keys(table.columns) }]
91
+ empty = false
92
+ }
93
+
94
+ yield ['insertRow', Object.values(row)]
95
+ }
96
+
97
+ if (!empty) {
98
+ yield ['insertEnd']
99
+ }
100
+ }
101
+
102
+ private buildQuery(db: Client<Connection.TransactionLike>, table: TransferTableMapping) {
103
+ let builder = db.selectBuilder().from(table.name)
104
+
105
+ for (const column of Object.values(table.columns)) {
106
+ if (column.type === Model.ColumnType.Json || column.type === Model.ColumnType.Date || column.type === Model.ColumnType.DateTime) {
107
+ builder = builder.select(expr => expr.raw(`${wrapIdentifier(column.name)}::text`))
108
+
109
+ } else {
110
+ builder = builder.select(column.name)
111
+ }
112
+ }
113
+
114
+ const namespaceContext = new Compiler.Context(db.schema, new Set())
115
+ return builder.createQuery(namespaceContext)
116
+ }
117
+
118
+ private async* cursorQuery(db: Client<Connection.TransactionLike>, batchSize: number, sql: string, parameters: readonly any[] = []) {
119
+ await db.query(`DECLARE contember_cursor NO SCROLL CURSOR FOR ${sql}`, parameters)
120
+
121
+ const fetchSql = `FETCH ${Number(batchSize)} FROM contember_cursor`
122
+ let resultPromise: Promise<Connection.Result> | null = db.query(fetchSql)
123
+
124
+ while (resultPromise !== null) {
125
+ const result: Connection.Result = await resultPromise
126
+ resultPromise = result.rowCount < batchSize ? null : db.query(fetchSql) // pipeline
127
+ yield* result.rows
128
+ }
129
+
130
+ await db.query(`CLOSE contember_cursor`)
131
+ }
132
+ }
@@ -0,0 +1,53 @@
1
+ import { KoaMiddleware, KoaRequestState } from '../koa'
2
+ import { AuthResult, HttpError, TimerMiddlewareState } from '../common'
3
+ import { ProjectGroupResolver, ProjectInfoMiddlewareState } from '../project-common'
4
+ import { TenantRole } from '@contember/engine-tenant-api'
5
+ import { fromBuffer, toBuffer } from './CommandStream'
6
+ import { ImportExecutor } from './ImportExecutor'
7
+ import { createGunzip } from 'zlib'
8
+ import { Readable } from 'stream'
9
+
10
+ type ImportApiMiddlewareState =
11
+ & TimerMiddlewareState
12
+ & KoaRequestState
13
+ & ProjectInfoMiddlewareState
14
+ & { authResult: AuthResult }
15
+
16
+ export class ImportApiMiddlewareFactory {
17
+ constructor(
18
+ private readonly projectGroupResolver: ProjectGroupResolver,
19
+ private readonly importExecutor: ImportExecutor,
20
+ ) {
21
+ }
22
+
23
+ create(): KoaMiddleware<ImportApiMiddlewareState> {
24
+ return async koaContext => {
25
+ const { request, response, state: { timer } } = koaContext
26
+
27
+ const groupContainer = await this.projectGroupResolver.resolveContainer({ request })
28
+ koaContext.state.projectGroup = groupContainer.slug
29
+
30
+ const authResult = await groupContainer.authenticator.authenticate({ request, timer })
31
+ koaContext.state.authResult = authResult
32
+
33
+ if (!authResult.roles.includes(TenantRole.SUPER_ADMIN) && !authResult.roles.includes(TenantRole.PROJECT_ADMIN)) {
34
+ throw new HttpError(`Not allowed`, 403)
35
+ }
36
+
37
+ if (request.headers['content-type'] !== 'application/x-ndjson') {
38
+ throw new HttpError(`Unsupported content type`, 400)
39
+ }
40
+
41
+ if (request.headers['content-encoding'] !== undefined && request.headers['content-encoding'] !== 'gzip') {
42
+ throw new HttpError(`Unsupported content encoding`, 415)
43
+ }
44
+
45
+ const isGzip = request.headers['content-encoding'] === 'gzip'
46
+ const commands = fromBuffer(isGzip ? request.req.pipe(createGunzip()) : request.req)
47
+
48
+ response.status = 200
49
+ response.headers['Content-Type'] = 'application/x-ndjson'
50
+ response.body = Readable.from(toBuffer(this.importExecutor.import(groupContainer, commands), 0))
51
+ }
52
+ }
53
+ }