@contember/engine-http 1.2.0-alpha.1 → 1.2.0-alpha.12
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.
- package/dist/src/common/TimerMiddleware.d.ts.map +1 -1
- package/dist/src/common/TimerMiddleware.js +24 -7
- package/dist/src/common/TimerMiddleware.js.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/content/ContentApiMiddlewareFactory.js +13 -9
- package/dist/src/content/ContentApiMiddlewareFactory.js.map +1 -1
- package/dist/src/content/ContentGraphQLContextFactory.d.ts +2 -2
- package/dist/src/content/ContentGraphQLContextFactory.d.ts.map +1 -1
- package/dist/src/content/ContentGraphQLContextFactory.js +2 -5
- package/dist/src/content/ContentGraphQLContextFactory.js.map +1 -1
- package/dist/src/content/ContentSchemaResolver.d.ts +2 -3
- package/dist/src/content/ContentSchemaResolver.d.ts.map +1 -1
- package/dist/src/content/GraphQlSchemaFactory.d.ts.map +1 -1
- package/dist/src/content/GraphQlSchemaFactory.js +1 -2
- package/dist/src/content/GraphQlSchemaFactory.js.map +1 -1
- package/dist/src/content/ProjectMembershipFetcher.d.ts +3 -2
- package/dist/src/content/ProjectMembershipFetcher.d.ts.map +1 -1
- package/dist/src/content/ProjectMembershipFetcher.js +1 -1
- package/dist/src/content/ProjectMembershipFetcher.js.map +1 -1
- package/dist/src/content/ProjectMembershipResolver.d.ts +4 -3
- package/dist/src/content/ProjectMembershipResolver.d.ts.map +1 -1
- package/dist/src/content/ProjectMembershipResolver.js +23 -6
- package/dist/src/content/ProjectMembershipResolver.js.map +1 -1
- package/dist/src/graphql/execution.js +2 -2
- package/dist/src/graphql/execution.js.map +1 -1
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +1 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/koa/types.d.ts +1 -0
- package/dist/src/koa/types.d.ts.map +1 -1
- package/dist/src/system/SystemApiMiddlewareFactory.d.ts.map +1 -1
- package/dist/src/system/SystemApiMiddlewareFactory.js +2 -2
- package/dist/src/system/SystemApiMiddlewareFactory.js.map +1 -1
- package/dist/src/system/SystemGraphQLContextFactory.d.ts +2 -2
- package/dist/src/system/SystemGraphQLContextFactory.d.ts.map +1 -1
- package/dist/src/transfer/Command.d.ts +23 -0
- package/dist/src/transfer/Command.d.ts.map +1 -0
- package/dist/src/transfer/Command.js +53 -0
- package/dist/src/transfer/Command.js.map +1 -0
- package/dist/src/transfer/CommandStream.d.ts +6 -0
- package/dist/src/transfer/CommandStream.d.ts.map +1 -0
- package/dist/src/transfer/CommandStream.js +90 -0
- package/dist/src/transfer/CommandStream.js.map +1 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.d.ts +8 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.d.ts.map +1 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.js +108 -0
- package/dist/src/transfer/ContentSchemaTransferMappingFactory.js.map +1 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts +15 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.d.ts.map +1 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.js +73 -0
- package/dist/src/transfer/ExportApiMiddlewareFactory.js.map +1 -0
- package/dist/src/transfer/ExportExecutor.d.ts +26 -0
- package/dist/src/transfer/ExportExecutor.d.ts.map +1 -0
- package/dist/src/transfer/ExportExecutor.js +135 -0
- package/dist/src/transfer/ExportExecutor.js.map +1 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.d.ts +15 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.d.ts.map +1 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.js +47 -0
- package/dist/src/transfer/ImportApiMiddlewareFactory.js.map +1 -0
- package/dist/src/transfer/ImportExecutor.d.ts +33 -0
- package/dist/src/transfer/ImportExecutor.d.ts.map +1 -0
- package/dist/src/transfer/ImportExecutor.js +295 -0
- package/dist/src/transfer/ImportExecutor.js.map +1 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.d.ts +8 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.d.ts.map +1 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.js +167 -0
- package/dist/src/transfer/SystemSchemaTransferMappingFactory.js.map +1 -0
- package/dist/src/transfer/TransferMapping.d.ts +38 -0
- package/dist/src/transfer/TransferMapping.d.ts.map +1 -0
- package/dist/src/transfer/TransferMapping.js +3 -0
- package/dist/src/transfer/TransferMapping.js.map +1 -0
- package/dist/src/transfer/index.d.ts +7 -0
- package/dist/src/transfer/index.d.ts.map +1 -0
- package/dist/src/transfer/index.js +23 -0
- package/dist/src/transfer/index.js.map +1 -0
- package/dist/src/tsconfig.tsbuildinfo +1 -1
- package/dist/src/utils/CryptoWrapper.d.ts +1 -0
- package/dist/src/utils/CryptoWrapper.d.ts.map +1 -1
- package/dist/tests/cases/unit/projectMembershipResolver.test.js +20 -6
- package/dist/tests/cases/unit/projectMembershipResolver.test.js.map +1 -1
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/package.json +14 -15
- package/src/common/TimerMiddleware.ts +30 -9
- package/src/content/ContentApiMiddlewareFactory.ts +2 -1
- package/src/content/ContentGraphQLContextFactory.ts +4 -7
- package/src/content/ContentSchemaResolver.ts +1 -1
- package/src/content/GraphQlSchemaFactory.ts +1 -2
- package/src/content/ProjectMembershipFetcher.ts +4 -4
- package/src/content/ProjectMembershipResolver.ts +36 -12
- package/src/graphql/execution.ts +2 -2
- package/src/index.ts +1 -0
- package/src/koa/types.ts +1 -1
- package/src/system/SystemApiMiddlewareFactory.ts +1 -2
- package/src/system/SystemGraphQLContextFactory.ts +2 -2
- package/src/transfer/Command.ts +42 -0
- package/src/transfer/CommandStream.ts +72 -0
- package/src/transfer/ContentSchemaTransferMappingFactory.ts +117 -0
- package/src/transfer/ExportApiMiddlewareFactory.ts +93 -0
- package/src/transfer/ExportExecutor.ts +139 -0
- package/src/transfer/ImportApiMiddlewareFactory.ts +59 -0
- package/src/transfer/ImportExecutor.ts +361 -0
- package/src/transfer/SystemSchemaTransferMappingFactory.ts +178 -0
- package/src/transfer/TransferMapping.ts +24 -0
- package/src/transfer/index.ts +8 -0
- package/tests/cases/unit/projectMembershipResolver.test.ts +23 -10
|
@@ -0,0 +1,93 @@
|
|
|
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 { toBuffer } from './CommandStream'
|
|
6
|
+
import { ExportExecutor, ExportRequest } from './ExportExecutor'
|
|
7
|
+
import { ParseError } from '@contember/typesafe'
|
|
8
|
+
import { Logger } from '@contember/engine-common'
|
|
9
|
+
import { ProjectContainer } from '../ProjectContainer'
|
|
10
|
+
|
|
11
|
+
type ExportApiMiddlewareState =
|
|
12
|
+
& TimerMiddlewareState
|
|
13
|
+
& KoaRequestState
|
|
14
|
+
& ProjectInfoMiddlewareState
|
|
15
|
+
& { authResult: AuthResult }
|
|
16
|
+
|
|
17
|
+
export class ExportApiMiddlewareFactory {
|
|
18
|
+
constructor(
|
|
19
|
+
private readonly projectGroupResolver: ProjectGroupResolver,
|
|
20
|
+
private readonly exportExecutor: ExportExecutor,
|
|
21
|
+
) {
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
create(): KoaMiddleware<ExportApiMiddlewareState> {
|
|
25
|
+
return async koaContext => {
|
|
26
|
+
const { request, response, state: { timer } } = koaContext
|
|
27
|
+
|
|
28
|
+
const groupContainer = await this.projectGroupResolver.resolveContainer({ request })
|
|
29
|
+
koaContext.state.projectGroup = groupContainer.slug
|
|
30
|
+
|
|
31
|
+
const authResult = await groupContainer.authenticator.authenticate({ request, timer })
|
|
32
|
+
koaContext.state.authResult = authResult
|
|
33
|
+
|
|
34
|
+
let exportRequest: ExportRequest
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
exportRequest = ExportRequest(request.body)
|
|
38
|
+
|
|
39
|
+
} catch (e) {
|
|
40
|
+
if (e instanceof ParseError) {
|
|
41
|
+
response.status = 400
|
|
42
|
+
response.headers['Content-Type'] = 'application/json'
|
|
43
|
+
response.body = { ok: false, error: `Invalid request body: ${e.message}` }
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
} else {
|
|
47
|
+
throw e
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// eslint-disable-next-line no-console
|
|
52
|
+
const logger = new Logger(console.log)
|
|
53
|
+
const projectContainers: Record<string, ProjectContainer> = {}
|
|
54
|
+
|
|
55
|
+
for (const project of exportRequest.projects) {
|
|
56
|
+
const projectContainer = await groupContainer.projectContainerResolver.getProjectContainer(project.slug, { alias: true, logger })
|
|
57
|
+
|
|
58
|
+
if (projectContainer === undefined) {
|
|
59
|
+
throw new HttpError(`Project ${project.slug} NOT found`, 400)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const systemContext = projectContainer.systemDatabaseContextFactory.create()
|
|
63
|
+
const schema = await projectContainer.contentSchemaResolver.getSchema(systemContext, project.slug)
|
|
64
|
+
const memberships = await timer('MembershipFetch', () => groupContainer.projectMembershipResolver.resolveMemberships({
|
|
65
|
+
request: { get: () => '' },
|
|
66
|
+
acl: schema.acl,
|
|
67
|
+
projectSlug: project.slug,
|
|
68
|
+
identity: {
|
|
69
|
+
identityId: authResult.identityId,
|
|
70
|
+
roles: authResult.roles,
|
|
71
|
+
},
|
|
72
|
+
}))
|
|
73
|
+
|
|
74
|
+
const projectRoles = memberships.map(it => it.role)
|
|
75
|
+
|
|
76
|
+
if (!projectRoles.some(role => schema.acl.roles[role]?.content?.export)) {
|
|
77
|
+
throw new HttpError(`Not allowed`, 403)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (project.system && !projectRoles.some(role => schema.acl.roles[role]?.system?.export)) {
|
|
81
|
+
throw new HttpError(`Not allowed`, 403)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
projectContainers[project.slug] = projectContainer
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
koaContext.compress = true
|
|
88
|
+
response.status = 200
|
|
89
|
+
response.res.setHeader('Content-Type', 'application/x-ndjson') // https://github.com/ndjson/ndjson-spec
|
|
90
|
+
response.body = Readable.from(toBuffer(this.exportExecutor.export(exportRequest, projectContainers)))
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
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.intersection(
|
|
15
|
+
Typesafe.object({
|
|
16
|
+
slug: Typesafe.string,
|
|
17
|
+
system: Typesafe.boolean,
|
|
18
|
+
}),
|
|
19
|
+
Typesafe.partial({
|
|
20
|
+
targetSlug: Typesafe.string,
|
|
21
|
+
}),
|
|
22
|
+
)),
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
export class ExportExecutor {
|
|
26
|
+
constructor(
|
|
27
|
+
private readonly contentSchemaTransferMappingFactory: ContentSchemaTransferMappingFactory,
|
|
28
|
+
private readonly systemSchemaTransferMappingFactory: SystemSchemaTransferMappingFactory,
|
|
29
|
+
) {
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async* export(request: ExportRequest, projectContainers: Record<string, ProjectContainer>): AsyncIterable<Command> {
|
|
33
|
+
for (const project of request.projects) {
|
|
34
|
+
const projectContainer = projectContainers[project.slug]
|
|
35
|
+
const systemContext = projectContainer.systemDatabaseContextFactory.create()
|
|
36
|
+
|
|
37
|
+
if (project.system) {
|
|
38
|
+
const systemMapping = this.systemSchemaTransferMappingFactory.build()
|
|
39
|
+
yield ['importSystemSchemaBegin', { project: project.targetSlug ?? project.slug, tables: Object.keys(systemMapping.tables) }]
|
|
40
|
+
yield* this.exportSchema(systemContext.client, systemMapping)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
for (const stage of await systemContext.queryHandler.fetch(new StagesQuery())) {
|
|
44
|
+
const contentSchema = await projectContainer.contentSchemaResolver.getSchema(systemContext, stage.slug)
|
|
45
|
+
const contentMapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema)
|
|
46
|
+
const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {})
|
|
47
|
+
|
|
48
|
+
yield [
|
|
49
|
+
'importContentSchemaBegin', {
|
|
50
|
+
project: project.targetSlug ?? project.slug,
|
|
51
|
+
stage: stage.slug,
|
|
52
|
+
schemaVersion: contentSchema.version,
|
|
53
|
+
tables: Object.keys(contentMapping.tables),
|
|
54
|
+
},
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
yield* this.exportSchema(contentDatabaseClient, contentMapping)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private async* exportSchema(db: Client, mapping: TransferMapping): AsyncIterable<Command> {
|
|
63
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
64
|
+
const that = this
|
|
65
|
+
yield* asyncIterableTransaction(db, async function* (db) {
|
|
66
|
+
await db.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE')
|
|
67
|
+
for (const table of Object.values(mapping.tables)) {
|
|
68
|
+
yield* that.exportSequences(db, table)
|
|
69
|
+
yield* that.exportTable(db, table)
|
|
70
|
+
}
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private async* exportSequences(db: Client<Connection.TransactionLike>, table: TransferTableMapping): AsyncIterable<Command> {
|
|
75
|
+
for (const column of Object.values(table.columns)) {
|
|
76
|
+
if (column.type === Model.ColumnType.Int && column.sequence) {
|
|
77
|
+
const seqNameResult = await db.query<{ name: string }>(
|
|
78
|
+
'SELECT pg_get_serial_sequence(?, ?) AS name',
|
|
79
|
+
[`${db.schema}.${table.name}`, column.name],
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
const seqNameQuoted = seqNameResult.rows[0].name.split('.').map(it => wrapIdentifier(it)).join('.')
|
|
83
|
+
const seqValueResult = await db.query<{ last_value: number|string }>(`SELECT last_value FROM ${seqNameQuoted}`)
|
|
84
|
+
const seqValue = seqValueResult.rows[0].last_value
|
|
85
|
+
yield ['importSequence', { table: table.name, column: column.name, value: Number(seqValue) }]
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private async* exportTable(db: Client<Connection.TransactionLike>, table: TransferTableMapping): AsyncIterable<Command> {
|
|
91
|
+
const DB_FETCH_BATCH_SIZE = 100
|
|
92
|
+
const query = (table.createSelect ?? this.buildQuery)(db, table)
|
|
93
|
+
let empty = true
|
|
94
|
+
|
|
95
|
+
for await (const row of this.cursorQuery(db, DB_FETCH_BATCH_SIZE, query.sql, query.parameters)) {
|
|
96
|
+
if (empty) {
|
|
97
|
+
yield ['insertBegin', { table: table.name, columns: Object.keys(table.columns) }]
|
|
98
|
+
empty = false
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
yield ['insertRow', Object.values(row)]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (!empty) {
|
|
105
|
+
yield ['insertEnd']
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
private buildQuery(db: Client<Connection.TransactionLike>, table: TransferTableMapping) {
|
|
110
|
+
let builder = db.selectBuilder().from(table.name)
|
|
111
|
+
|
|
112
|
+
for (const column of Object.values(table.columns)) {
|
|
113
|
+
if (column.type === Model.ColumnType.Json || column.type === Model.ColumnType.Date || column.type === Model.ColumnType.DateTime) {
|
|
114
|
+
builder = builder.select(expr => expr.raw(`${wrapIdentifier(column.name)}::text`))
|
|
115
|
+
|
|
116
|
+
} else {
|
|
117
|
+
builder = builder.select(column.name)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const namespaceContext = new Compiler.Context(db.schema, new Set())
|
|
122
|
+
return builder.createQuery(namespaceContext)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private async* cursorQuery(db: Client<Connection.TransactionLike>, batchSize: number, sql: string, parameters: readonly any[] = []) {
|
|
126
|
+
await db.query(`DECLARE contember_cursor NO SCROLL CURSOR FOR ${sql}`, parameters)
|
|
127
|
+
|
|
128
|
+
const fetchSql = `FETCH ${Number(batchSize)} FROM contember_cursor`
|
|
129
|
+
let resultPromise: Promise<Connection.Result> | null = db.query(fetchSql)
|
|
130
|
+
|
|
131
|
+
while (resultPromise !== null) {
|
|
132
|
+
const result: Connection.Result = await resultPromise
|
|
133
|
+
resultPromise = result.rowCount < batchSize ? null : db.query(fetchSql) // pipeline
|
|
134
|
+
yield* result.rows
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
await db.query(`CLOSE contember_cursor`)
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { KoaMiddleware, KoaRequestState } from '../koa'
|
|
2
|
+
import { AuthResult, HttpError, TimerMiddlewareState } from '../common'
|
|
3
|
+
import { ProjectGroupResolver, ProjectInfoMiddlewareState } from '../project-common'
|
|
4
|
+
import { fromBuffer } from './CommandStream'
|
|
5
|
+
import { ImportError, ImportExecutor } from './ImportExecutor'
|
|
6
|
+
import { createGunzip } from 'zlib'
|
|
7
|
+
|
|
8
|
+
type ImportApiMiddlewareState =
|
|
9
|
+
& TimerMiddlewareState
|
|
10
|
+
& KoaRequestState
|
|
11
|
+
& ProjectInfoMiddlewareState
|
|
12
|
+
& { authResult: AuthResult }
|
|
13
|
+
|
|
14
|
+
export class ImportApiMiddlewareFactory {
|
|
15
|
+
constructor(
|
|
16
|
+
private readonly projectGroupResolver: ProjectGroupResolver,
|
|
17
|
+
private readonly importExecutor: ImportExecutor,
|
|
18
|
+
) {
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
create(): KoaMiddleware<ImportApiMiddlewareState> {
|
|
22
|
+
return async koaContext => {
|
|
23
|
+
const { request, response, state: { timer } } = koaContext
|
|
24
|
+
|
|
25
|
+
const groupContainer = await this.projectGroupResolver.resolveContainer({ request })
|
|
26
|
+
koaContext.state.projectGroup = groupContainer.slug
|
|
27
|
+
|
|
28
|
+
const authResult = await groupContainer.authenticator.authenticate({ request, timer })
|
|
29
|
+
koaContext.state.authResult = authResult
|
|
30
|
+
|
|
31
|
+
if (request.headers['content-type'] !== 'application/x-ndjson') {
|
|
32
|
+
throw new HttpError(`Unsupported content type`, 400)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (request.headers['content-encoding'] !== undefined && request.headers['content-encoding'] !== 'gzip') {
|
|
36
|
+
throw new HttpError(`Unsupported content encoding`, 415)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
response.headers['Content-Type'] = 'application/json'
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const isGzip = request.headers['content-encoding'] === 'gzip'
|
|
43
|
+
const commands = fromBuffer(isGzip ? request.req.pipe(createGunzip()) : request.req)
|
|
44
|
+
await this.importExecutor.import(groupContainer, authResult, commands)
|
|
45
|
+
response.status = 200
|
|
46
|
+
response.body = { ok: true }
|
|
47
|
+
|
|
48
|
+
} catch (e) {
|
|
49
|
+
if (e instanceof ImportError) {
|
|
50
|
+
response.status = 400
|
|
51
|
+
response.body = { ok: false, error: e.message }
|
|
52
|
+
|
|
53
|
+
} else {
|
|
54
|
+
throw e
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import { Client, Connection, ConstraintHelper, wrapIdentifier } from '@contember/database'
|
|
2
|
+
import { Model, Schema } from '@contember/schema'
|
|
3
|
+
import * as Typesafe from '@contember/typesafe'
|
|
4
|
+
import { ParseError } from '@contember/typesafe'
|
|
5
|
+
import { Command, CommandArgsMap, CommandName } from './Command'
|
|
6
|
+
import { DatabaseContext, StageBySlugQuery } from '@contember/engine-system-api'
|
|
7
|
+
import { ProjectGroupContainer } from '../ProjectGroupContainer'
|
|
8
|
+
import { DbColumnSchema, TransferMapping, TransferTableMapping } from './TransferMapping'
|
|
9
|
+
import { Logger } from '@contember/engine-common'
|
|
10
|
+
import { ContentSchemaTransferMappingFactory } from './ContentSchemaTransferMappingFactory'
|
|
11
|
+
import { SystemSchemaTransferMappingFactory } from './SystemSchemaTransferMappingFactory'
|
|
12
|
+
import { AuthResult, HttpError } from '../common/index'
|
|
13
|
+
|
|
14
|
+
type Cell = boolean | number | string | null
|
|
15
|
+
type Row = readonly Cell[]
|
|
16
|
+
|
|
17
|
+
type InsertContext = {
|
|
18
|
+
tableName: string
|
|
19
|
+
insertStartFragment: string
|
|
20
|
+
rowFragment: string
|
|
21
|
+
rowParser: Typesafe.Type<Row>
|
|
22
|
+
rows: Array<Row>
|
|
23
|
+
insertedRowCount: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class ImportError extends Error {
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type CommandProcessor<T extends CommandName> = (it: CommandIterator<T>) => Promise<CommandIterator | null>
|
|
30
|
+
type CommandProcessorMap<T extends CommandName> = { [N in CommandName]?: N extends T ? CommandProcessor<N> : undefined }
|
|
31
|
+
|
|
32
|
+
class CommandIterator<T extends CommandName = CommandName> {
|
|
33
|
+
private constructor(
|
|
34
|
+
public readonly commandName: T,
|
|
35
|
+
public readonly commandArgs: CommandArgsMap[T],
|
|
36
|
+
private readonly commandIterator: AsyncIterator<Command>,
|
|
37
|
+
) {
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
public static async create(commands: AsyncIterable<Command>): Promise<CommandIterator | null> {
|
|
41
|
+
const commandIterator = commands[Symbol.asyncIterator]()
|
|
42
|
+
const result = await commandIterator.next()
|
|
43
|
+
|
|
44
|
+
if (result.done) {
|
|
45
|
+
return null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const [name, ...args] = result.value
|
|
49
|
+
return new CommandIterator(name, args, commandIterator)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async next(): Promise<CommandIterator | null> {
|
|
53
|
+
const result = await this.commandIterator.next()
|
|
54
|
+
|
|
55
|
+
if (result.done) {
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const [name, ...args] = result.value
|
|
60
|
+
return new CommandIterator(name, args, this.commandIterator)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class ImportExecutor {
|
|
65
|
+
constructor(
|
|
66
|
+
private readonly contentSchemaTransferMappingFactory: ContentSchemaTransferMappingFactory,
|
|
67
|
+
private readonly systemSchemaTransferMappingFactory: SystemSchemaTransferMappingFactory,
|
|
68
|
+
private readonly logger: Logger,
|
|
69
|
+
) {
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async import(groupContainer: ProjectGroupContainer, authResult: AuthResult, commands: AsyncIterable<Command>) {
|
|
73
|
+
const it = await CommandIterator.create(commands)
|
|
74
|
+
|
|
75
|
+
const final = await this.match(it, {
|
|
76
|
+
importContentSchemaBegin: it => this.importContentSchemaBegin(groupContainer, authResult, it),
|
|
77
|
+
importSystemSchemaBegin: it => this.importSystemSchemaBegin(groupContainer, authResult, it),
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
if (final !== null) {
|
|
81
|
+
throw new ImportError(`Unexpected ${final.commandName}`)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private async match<T extends CommandName>(it: CommandIterator<T> | null, processors: CommandProcessorMap<T>) {
|
|
86
|
+
let next: CommandIterator | null = it
|
|
87
|
+
|
|
88
|
+
while (next !== null) {
|
|
89
|
+
const processor = processors[next.commandName]
|
|
90
|
+
|
|
91
|
+
if (processor) {
|
|
92
|
+
next = await processor(next as any)
|
|
93
|
+
|
|
94
|
+
} else {
|
|
95
|
+
break
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return next
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private async importContentSchemaBegin(groupContainer: ProjectGroupContainer, authResult: AuthResult, it: CommandIterator<'importContentSchemaBegin'>) {
|
|
103
|
+
const [options] = it.commandArgs
|
|
104
|
+
const projectContainer = await this.createProjectContainer(groupContainer, options.project)
|
|
105
|
+
const systemDatabaseContext = projectContainer.systemDatabaseContextFactory.create()
|
|
106
|
+
const stage = await this.fetchStageBySlug(systemDatabaseContext, options.project, options.stage)
|
|
107
|
+
|
|
108
|
+
const contentSchema = await projectContainer.contentSchemaResolver.getSchema(systemDatabaseContext, stage.slug)
|
|
109
|
+
|
|
110
|
+
if (contentSchema.version !== options.schemaVersion) {
|
|
111
|
+
throw new ImportError(`Incompatible schema version (import version ${options.schemaVersion} does not match server version ${contentSchema.version})`)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
await this.requireImportAccess(groupContainer, contentSchema, authResult, options.project, 'content')
|
|
115
|
+
const contentDatabaseClient = projectContainer.connection.createClient(stage.schema, {})
|
|
116
|
+
const mapping = this.contentSchemaTransferMappingFactory.createContentSchemaMapping(contentSchema)
|
|
117
|
+
|
|
118
|
+
return await contentDatabaseClient.transaction(async db => {
|
|
119
|
+
await this.disableTriggers(db, options.tables)
|
|
120
|
+
await this.lockTables(db, options.tables)
|
|
121
|
+
await this.truncateTables(db, options.tables)
|
|
122
|
+
|
|
123
|
+
const constraintHelper = new ConstraintHelper(db)
|
|
124
|
+
await constraintHelper.setFkConstraintsDeferred()
|
|
125
|
+
|
|
126
|
+
const result = await this.match(await it.next(), {
|
|
127
|
+
importSequence: it => this.importSequence(db, mapping, it),
|
|
128
|
+
insertBegin: it => this.insertBegin(db, mapping, it),
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
await constraintHelper.setFkConstraintsImmediate()
|
|
132
|
+
await this.enableTriggers(db, options.tables)
|
|
133
|
+
|
|
134
|
+
return result
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private async importSystemSchemaBegin(groupContainer: ProjectGroupContainer, authResult: AuthResult, it: CommandIterator<'importSystemSchemaBegin'>) {
|
|
139
|
+
const [options] = it.commandArgs
|
|
140
|
+
const projectContainer = await this.createProjectContainer(groupContainer, options.project)
|
|
141
|
+
const schema = await groupContainer.projectSchemaResolver.getSchema(options.project)
|
|
142
|
+
|
|
143
|
+
if (schema === undefined) {
|
|
144
|
+
throw new ImportError(`Project ${options.project} does not have schema`)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await this.requireImportAccess(groupContainer, schema, authResult, options.project, 'system')
|
|
148
|
+
const systemDatabaseContext = projectContainer.systemDatabaseContextFactory.create()
|
|
149
|
+
const mapping = this.systemSchemaTransferMappingFactory.build()
|
|
150
|
+
|
|
151
|
+
return await systemDatabaseContext.client.transaction(async db => {
|
|
152
|
+
await this.truncateTables(db, options.tables)
|
|
153
|
+
|
|
154
|
+
const constraintHelper = new ConstraintHelper(db)
|
|
155
|
+
await constraintHelper.setFkConstraintsDeferred()
|
|
156
|
+
|
|
157
|
+
return await this.match(await it.next(), {
|
|
158
|
+
insertBegin: it => this.insertBegin(db, mapping, it),
|
|
159
|
+
})
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private async importSequence(db: Client<Connection.TransactionLike>, mapping: TransferMapping, it: CommandIterator<'importSequence'>): Promise<CommandIterator | null> {
|
|
164
|
+
const [options] = it.commandArgs
|
|
165
|
+
|
|
166
|
+
await db.query(
|
|
167
|
+
'SELECT setval(pg_get_serial_sequence(?, ?), ?)',
|
|
168
|
+
[`${db.schema}.${options.table}`, options.column, options.value],
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
return it.next()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private async insertBegin(db: Client<Connection.TransactionLike>, mapping: TransferMapping, it: CommandIterator<'insertBegin'>): Promise<CommandIterator | null> {
|
|
175
|
+
const [options] = it.commandArgs
|
|
176
|
+
const insertContext = await this.buildInsertContext(db, mapping, db.schema, options.table, options.columns)
|
|
177
|
+
let insertRowsPromise: Promise<Connection.Result> | null = null
|
|
178
|
+
|
|
179
|
+
const result = await this.match(await it.next(), {
|
|
180
|
+
insertRow: async it => {
|
|
181
|
+
const [values] = it.commandArgs
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
insertContext.rows.push(insertContext.rowParser(values))
|
|
185
|
+
|
|
186
|
+
} catch (e) {
|
|
187
|
+
if (e instanceof ParseError) {
|
|
188
|
+
throw new ImportError(`Invalid row ${JSON.stringify(values)} for table ${options.table}: ${e.message}`)
|
|
189
|
+
|
|
190
|
+
} else {
|
|
191
|
+
throw e
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (insertContext.rows.length === 1000) {
|
|
196
|
+
await insertRowsPromise
|
|
197
|
+
insertRowsPromise = this.insertRows(db, insertContext)
|
|
198
|
+
insertContext.insertedRowCount += insertContext.rows.length
|
|
199
|
+
insertContext.rows = []
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return await it.next()
|
|
203
|
+
},
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
if (insertContext.rows.length > 0) {
|
|
207
|
+
await insertRowsPromise
|
|
208
|
+
await this.insertRows(db, insertContext)
|
|
209
|
+
insertContext.insertedRowCount += insertContext.rows.length
|
|
210
|
+
insertContext.rows = []
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (result === null || result.commandName !== 'insertEnd') {
|
|
214
|
+
throw new ImportError(`Missing insertEnd command`)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return await result.next()
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private async createProjectContainer(groupContainer: ProjectGroupContainer, projectSlug: string) {
|
|
221
|
+
const projectContainerResolver = groupContainer.projectContainerResolver
|
|
222
|
+
const projectContainer = await projectContainerResolver.getProjectContainer(projectSlug, { alias: true, logger: this.logger })
|
|
223
|
+
|
|
224
|
+
if (projectContainer === undefined) {
|
|
225
|
+
throw new ImportError(`Project ${projectSlug} does not exists.`)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return projectContainer
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private async requireImportAccess(groupContainer: ProjectGroupContainer, schema: Schema, authResult: AuthResult, projectSlug: string, kind: 'content' | 'system') {
|
|
232
|
+
const memberships = await groupContainer.projectMembershipResolver.resolveMemberships({
|
|
233
|
+
request: { get: () => '' },
|
|
234
|
+
acl: schema.acl,
|
|
235
|
+
projectSlug: projectSlug,
|
|
236
|
+
identity: {
|
|
237
|
+
identityId: authResult.identityId,
|
|
238
|
+
roles: authResult.roles,
|
|
239
|
+
},
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
const projectRoles = memberships.map(it => it.role)
|
|
243
|
+
|
|
244
|
+
if (!projectRoles.some(role => schema.acl.roles[role]?.[kind]?.import)) {
|
|
245
|
+
throw new HttpError(`You are not allowed to import ${kind} in ${projectSlug}`, 403)
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private async fetchStageBySlug(systemDatabaseContext: DatabaseContext, projectSlug: string, stageSlug: string) {
|
|
250
|
+
const stage = await systemDatabaseContext.queryHandler.fetch(new StageBySlugQuery(stageSlug))
|
|
251
|
+
|
|
252
|
+
if (stage === null) {
|
|
253
|
+
throw new ImportError(`Project ${projectSlug} does not have stage ${stageSlug}.`)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return stage
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private async disableTriggers(db: Client, tableNames: readonly string[]) {
|
|
260
|
+
for (const tableName of tableNames) {
|
|
261
|
+
const tableNameQuoted = `${wrapIdentifier(db.schema)}.${wrapIdentifier(tableName)}`
|
|
262
|
+
await db.query(`ALTER TABLE ${tableNameQuoted} DISABLE TRIGGER USER`)
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private async enableTriggers(db: Client, tableNames: readonly string[]) {
|
|
267
|
+
for (const tableName of tableNames) {
|
|
268
|
+
const tableNameQuoted = `${wrapIdentifier(db.schema)}.${wrapIdentifier(tableName)}`
|
|
269
|
+
await db.query(`ALTER TABLE ${tableNameQuoted} ENABLE TRIGGER USER`)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private async lockTables(db: Client, tableNames: readonly string[]) {
|
|
274
|
+
const tableNamesQuoted = tableNames.map(it => `${wrapIdentifier(db.schema)}.${wrapIdentifier(it)}`)
|
|
275
|
+
await db.query(`LOCK ${tableNamesQuoted.join(', ')} IN EXCLUSIVE MODE`)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private async truncateTables(db: Client, tableNames: readonly string[]) {
|
|
279
|
+
const tableNamesQuoted = tableNames.map(it => `${wrapIdentifier(db.schema)}.${wrapIdentifier(it)}`)
|
|
280
|
+
await db.query(`TRUNCATE ${tableNamesQuoted.join(', ')}`)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private async insertRows(db: Client, context: InsertContext) {
|
|
284
|
+
const rowsFragment = context.rows.map(_ => context.rowFragment).join(',\n')
|
|
285
|
+
const sql = context.insertStartFragment + rowsFragment
|
|
286
|
+
const parameters: Cell[] = []
|
|
287
|
+
|
|
288
|
+
for (const row of context.rows) {
|
|
289
|
+
for (const cell of row) {
|
|
290
|
+
parameters.push(cell)
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return await db.query(sql, parameters)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private async buildInsertContext(db: Client, mapping: TransferMapping, schema: string, tableName: string, columnNames: readonly string[]): Promise<InsertContext> {
|
|
298
|
+
const tableMapping = mapping.tables[tableName]
|
|
299
|
+
const columns = []
|
|
300
|
+
|
|
301
|
+
if (tableMapping === undefined) {
|
|
302
|
+
throw new ImportError(`Unknown table ${tableName}`)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
for (const columnName of columnNames) {
|
|
306
|
+
const column = tableMapping.columns[columnName]
|
|
307
|
+
|
|
308
|
+
if (column === undefined) {
|
|
309
|
+
throw new ImportError(`Unknown column ${tableName}.${columnName}`)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
columns.push(column)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const insertStartFragment = (tableMapping.createInsertStartFragment ?? this.createInsertStartFragment)(schema, tableName, columnNames)
|
|
316
|
+
const rowFragment = '(' + columns.map(_ => '?').join(', ') + ')'
|
|
317
|
+
const rowParser = await this.buildRowParser(db, tableMapping, columns)
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
tableName,
|
|
321
|
+
insertStartFragment,
|
|
322
|
+
rowFragment,
|
|
323
|
+
rowParser,
|
|
324
|
+
rows: [],
|
|
325
|
+
insertedRowCount: 0,
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private createInsertStartFragment(schema: string, tableName: string, columnNames: readonly string[]): string {
|
|
330
|
+
const tableQuoted = `${wrapIdentifier(schema)}.${wrapIdentifier(tableName)}`
|
|
331
|
+
const columnsQuoted = '(' + columnNames.map(it => wrapIdentifier(it)).join(', ') + ')'
|
|
332
|
+
return `INSERT INTO ${tableQuoted} ${columnsQuoted} VALUES\n`
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private async buildRowParser(db: Client, tableMapping: TransferTableMapping, columns: DbColumnSchema[]): Promise<Typesafe.Type<readonly Cell[]>> {
|
|
336
|
+
const baseType = Typesafe.tuple(...columns.map(it => {
|
|
337
|
+
const base = this.buildColumnRuntimeType(it.type)
|
|
338
|
+
return it.nullable ? Typesafe.nullable(base) : base
|
|
339
|
+
}))
|
|
340
|
+
|
|
341
|
+
if (tableMapping.createRowParser === undefined) {
|
|
342
|
+
return baseType
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return await tableMapping.createRowParser(db, columns.map(it => it.name), baseType)
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private buildColumnRuntimeType(columnType: Model.ColumnType): Typesafe.Type<Exclude<Cell, null>> {
|
|
349
|
+
switch (columnType) {
|
|
350
|
+
case Model.ColumnType.Uuid: return Typesafe.string // TODO
|
|
351
|
+
case Model.ColumnType.String: return Typesafe.string
|
|
352
|
+
case Model.ColumnType.Int: return Typesafe.number // TODO
|
|
353
|
+
case Model.ColumnType.Double: return Typesafe.number
|
|
354
|
+
case Model.ColumnType.Bool: return Typesafe.boolean
|
|
355
|
+
case Model.ColumnType.Enum: return Typesafe.string // TODO
|
|
356
|
+
case Model.ColumnType.DateTime: return Typesafe.string // TODO
|
|
357
|
+
case Model.ColumnType.Date: return Typesafe.string // TODO
|
|
358
|
+
case Model.ColumnType.Json: return Typesafe.string
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|