462 lines
13 KiB
TypeScript
Raw Normal View History

import { PassThrough, Transform, Readable, Writable, Stream } from 'stream';
2022-12-12 20:37:41 +01:00
import { extname } from 'path';
2022-11-28 16:54:36 +01:00
import { isEmpty, uniq } from 'lodash/fp';
2022-12-12 20:36:26 +01:00
import { diff as semverDiff } from 'semver';
import type { Schema } from '@strapi/strapi';
import type {
IAsset,
IDestinationProvider,
IEntity,
IMetadata,
ISourceProvider,
ITransferEngine,
ITransferEngineOptions,
2022-12-12 14:24:39 +01:00
TransferProgress,
ITransferResults,
2022-11-11 14:24:30 +01:00
TransferStage,
TransferTransform,
} from '../../types';
import type { Diff } from '../utils/json';
import compareSchemas from '../strategies';
import { filter, map } from '../utils/stream';
2022-12-12 14:24:39 +01:00
2022-12-13 15:11:00 +01:00
export const TRANSFER_STAGES: ReadonlyArray<TransferStage> = Object.freeze([
2022-12-12 14:24:39 +01:00
'entities',
'links',
'assets',
'schemas',
'configuration',
2022-12-12 16:38:19 +01:00
]);
2022-11-11 13:41:01 +01:00
export const DEFAULT_VERSION_STRATEGY = 'ignore';
export const DEFAULT_SCHEMA_STRATEGY = 'strict';
2022-12-12 16:51:23 +01:00
type SchemaMap = Record<string, Schema>;
2022-11-11 13:41:01 +01:00
class TransferEngine<
S extends ISourceProvider = ISourceProvider,
D extends IDestinationProvider = IDestinationProvider
> implements ITransferEngine
{
sourceProvider: ISourceProvider;
2022-11-28 16:54:36 +01:00
destinationProvider: IDestinationProvider;
2022-11-28 16:54:36 +01:00
options: ITransferEngineOptions;
2022-11-28 16:54:36 +01:00
#metadata: { source?: IMetadata; destination?: IMetadata } = {};
2022-11-15 14:30:42 +01:00
progress: {
data: TransferProgress;
stream: PassThrough;
};
2022-11-11 13:41:01 +01:00
constructor(
sourceProvider: ISourceProvider,
destinationProvider: IDestinationProvider,
options: ITransferEngineOptions
) {
2022-11-17 21:19:33 +01:00
if (sourceProvider.type !== 'source') {
throw new Error("SourceProvider does not have type 'source'");
}
if (destinationProvider.type !== 'destination') {
throw new Error("DestinationProvider does not have type 'destination'");
2022-11-17 21:19:33 +01:00
}
this.sourceProvider = sourceProvider;
this.destinationProvider = destinationProvider;
this.options = options;
this.progress = { data: {}, stream: new PassThrough({ objectMode: true }) };
}
#createStageTransformStream<T extends TransferStage>(
key: T,
options: { includeGlobal?: boolean } = {}
): PassThrough | Transform {
const { includeGlobal = true } = options;
2022-12-12 16:51:23 +01:00
const { global: globalTransforms, [key]: stageTransforms } = this.options?.transforms ?? {};
let stream = new PassThrough({ objectMode: true });
const applyTransforms = <U>(transforms: TransferTransform<U>[] = []) => {
for (const transform of transforms) {
if ('filter' in transform) {
stream = stream.pipe(filter(transform.filter));
}
if ('map' in transform) {
stream = stream.pipe(map(transform.map));
}
}
};
if (includeGlobal) {
2022-12-12 16:51:23 +01:00
applyTransforms(globalTransforms);
}
2022-12-12 16:51:23 +01:00
applyTransforms(stageTransforms as TransferTransform<unknown>[]);
return stream;
}
#updateTransferProgress<T = unknown>(
stage: TransferStage,
data: T,
aggregate?: {
size?: (value: T) => number;
key?: (value: T) => string;
}
) {
if (!this.progress.data[stage]) {
this.progress.data[stage] = { count: 0, bytes: 0 };
2022-11-11 13:41:01 +01:00
}
2022-12-12 16:51:23 +01:00
const stageProgress = this.progress.data[stage];
if (!stageProgress) {
return;
}
const size = aggregate?.size?.(data) ?? JSON.stringify(data).length;
const key = aggregate?.key?.(data);
stageProgress.count += 1;
stageProgress.bytes += size;
// Handle aggregate updates if necessary
if (key) {
if (!stageProgress.aggregates) {
stageProgress.aggregates = {};
2022-11-11 16:14:21 +01:00
}
const { aggregates } = stageProgress;
if (!aggregates[key]) {
aggregates[key] = { count: 0, bytes: 0 };
2022-11-11 16:14:21 +01:00
}
aggregates[key].count += 1;
aggregates[key].bytes += size;
2022-11-11 16:14:21 +01:00
}
2022-11-11 13:41:01 +01:00
}
#progressTracker(
stage: TransferStage,
aggregate?: {
size?(value: unknown): number;
key?(value: unknown): string;
}
) {
2022-11-11 13:41:01 +01:00
return new PassThrough({
objectMode: true,
2022-11-15 14:30:42 +01:00
transform: (data, _encoding, callback) => {
this.#updateTransferProgress(stage, data, aggregate);
this.#emitStageUpdate('progress', stage);
2022-11-11 15:25:19 +01:00
callback(null, data);
2022-11-11 13:41:01 +01:00
},
});
}
2022-11-11 13:41:01 +01:00
2022-12-12 14:24:39 +01:00
#emitTransferUpdate(type: 'start' | 'finish' | 'error', payload?: object) {
2022-12-12 16:31:44 +01:00
this.progress.stream.emit(`transfer::${type}`, payload);
2022-12-12 14:24:39 +01:00
}
2022-12-12 15:36:04 +01:00
#emitStageUpdate(type: 'start' | 'finish' | 'progress' | 'skip', transferStage: TransferStage) {
2022-12-12 14:24:39 +01:00
this.progress.stream.emit(`stage::${type}`, {
data: this.progress.data,
2022-11-15 18:23:31 +01:00
stage: transferStage,
2022-11-11 13:41:01 +01:00
});
}
2022-11-11 13:41:01 +01:00
#assertStrapiVersionIntegrity(sourceVersion?: string, destinationVersion?: string) {
const strategy = this.options.versionStrategy || DEFAULT_VERSION_STRATEGY;
if (
!sourceVersion ||
!destinationVersion ||
strategy === 'ignore' ||
2022-11-23 14:08:47 +01:00
destinationVersion === sourceVersion
) {
return;
}
2022-11-23 14:08:47 +01:00
let diff;
try {
diff = semverDiff(sourceVersion, destinationVersion);
} catch (e: unknown) {
throw new Error(
`Strapi versions doesn't match (${strategy} check): ${sourceVersion} does not match with ${destinationVersion}`
);
}
if (!diff) {
return;
}
const validPatch = ['prelease', 'build'];
const validMinor = [...validPatch, 'patch', 'prepatch'];
const validMajor = [...validMinor, 'minor', 'preminor'];
if (strategy === 'patch' && validPatch.includes(diff)) {
return;
}
if (strategy === 'minor' && validMinor.includes(diff)) {
return;
}
if (strategy === 'major' && validMajor.includes(diff)) {
return;
}
throw new Error(
`Strapi versions doesn't match (${strategy} check): ${sourceVersion} does not match with ${destinationVersion}`
);
}
2022-12-12 16:51:23 +01:00
#assertSchemasMatching(sourceSchemas: SchemaMap, destinationSchemas: SchemaMap) {
const strategy = this.options.schemaStrategy || DEFAULT_SCHEMA_STRATEGY;
2022-12-13 16:44:07 +01:00
if (strategy === 'ignore') {
return;
}
const keys = uniq(Object.keys(sourceSchemas).concat(Object.keys(destinationSchemas)));
const diffs: { [key: string]: Diff[] } = {};
keys.forEach((key) => {
const sourceSchema = sourceSchemas[key];
const destinationSchema = destinationSchemas[key];
const schemaDiffs = compareSchemas(sourceSchema, destinationSchema, strategy);
if (schemaDiffs.length) {
diffs[key] = schemaDiffs;
}
});
if (!isEmpty(diffs)) {
throw new Error(
`Import process failed because the project doesn't have a matching data structure
2022-11-28 13:24:34 +01:00
${JSON.stringify(diffs, null, 2)}
`
);
}
}
async #transferStage(options: {
stage: TransferStage;
source?: Readable;
destination?: Writable;
transform?: PassThrough;
tracker?: PassThrough;
}) {
const { stage, source, destination, transform, tracker } = options;
if (!source || !destination) {
this.#emitStageUpdate('skip', stage);
return;
}
this.#emitStageUpdate('start', stage);
await new Promise<void>((resolve, reject) => {
let stream: Stream = source;
if (transform) {
stream = stream.pipe(transform);
}
if (tracker) {
stream = stream.pipe(tracker);
}
stream.pipe(destination).on('error', reject).on('close', resolve);
});
this.#emitStageUpdate('finish', stage);
}
async init(): Promise<void> {
// Resolve providers' resource and store
// them in the engine's internal state
await this.#resolveProviderResource();
// Update the destination provider's source metadata
const { source: sourceMetadata } = this.#metadata;
if (sourceMetadata) {
this.destinationProvider.setMetadata?.('source', sourceMetadata);
}
}
2022-11-15 18:51:43 +01:00
async bootstrap(): Promise<void> {
2022-11-17 20:06:53 +01:00
await Promise.all([this.sourceProvider.bootstrap?.(), this.destinationProvider.bootstrap?.()]);
}
async close(): Promise<void> {
2022-11-17 20:06:53 +01:00
await Promise.all([this.sourceProvider.close?.(), this.destinationProvider.close?.()]);
}
async #resolveProviderResource() {
const sourceMetadata = await this.sourceProvider.getMetadata();
const destinationMetadata = await this.destinationProvider.getMetadata();
if (sourceMetadata) {
this.#metadata.source = sourceMetadata;
}
if (destinationMetadata) {
this.#metadata.destination = destinationMetadata;
}
}
async integrityCheck(): Promise<boolean> {
try {
const sourceMetadata = await this.sourceProvider.getMetadata();
const destinationMetadata = await this.destinationProvider.getMetadata();
if (sourceMetadata && destinationMetadata) {
this.#assertStrapiVersionIntegrity(
sourceMetadata?.strapi?.version,
destinationMetadata?.strapi?.version
);
}
2022-12-12 16:51:23 +01:00
const sourceSchemas = (await this.sourceProvider.getSchemas?.()) as SchemaMap;
const destinationSchemas = (await this.destinationProvider.getSchemas?.()) as SchemaMap;
if (sourceSchemas && destinationSchemas) {
this.#assertSchemasMatching(sourceSchemas, destinationSchemas);
}
return true;
} catch (error) {
return false;
}
}
async transfer(): Promise<ITransferResults<S, D>> {
2022-12-12 16:30:56 +01:00
// reset data between transfers
this.progress.data = {};
2022-12-12 17:06:53 +01:00
this.#emitTransferUpdate('start');
2022-12-12 14:24:39 +01:00
try {
2022-11-15 18:51:43 +01:00
await this.bootstrap();
await this.init();
const isValidTransfer = await this.integrityCheck();
if (!isValidTransfer) {
2022-11-28 13:24:34 +01:00
// TODO: provide the log from the integrity check
throw new Error(
`Unable to transfer the data between ${this.sourceProvider.name} and ${this.destinationProvider.name}.\nPlease refer to the log above for more information.`
);
}
await this.beforeTransfer();
// Run the transfer stages
2022-11-03 10:12:16 +02:00
await this.transferSchemas();
2022-11-08 15:23:14 +01:00
await this.transferEntities();
2022-11-24 16:07:07 +01:00
await this.transferAssets();
await this.transferLinks();
await this.transferConfiguration();
// Gracefully close the providers
await this.close();
2022-12-21 10:23:18 +01:00
this.#emitTransferUpdate('finish');
2022-11-17 14:32:28 +01:00
} catch (e: unknown) {
2022-12-12 17:06:53 +01:00
this.#emitTransferUpdate('error', { error: e });
2022-12-12 14:24:39 +01:00
// Rollback the destination provider if an exception is thrown during the transfer
// Note: This will be configurable in the future
2022-11-17 14:32:28 +01:00
await this.destinationProvider.rollback?.(e as Error);
throw e;
}
return {
source: this.sourceProvider.results,
destination: this.destinationProvider.results,
engine: this.progress.data,
};
}
async beforeTransfer(): Promise<void> {
2022-12-02 17:15:27 +02:00
await this.sourceProvider.beforeTransfer?.();
await this.destinationProvider.beforeTransfer?.();
2022-11-16 15:00:29 +02:00
}
2022-11-03 10:12:16 +02:00
async transferSchemas(): Promise<void> {
const stage: TransferStage = 'schemas';
2022-11-07 11:10:05 +02:00
const source = await this.sourceProvider.streamSchemas?.();
const destination = await this.destinationProvider.getSchemasStream?.();
const transform = this.#createStageTransformStream(stage);
const tracker = this.#progressTracker(stage, { key: (value: Schema) => value.modelType });
2022-11-03 10:12:16 +02:00
await this.#transferStage({ stage, source, destination, transform, tracker });
2022-11-03 10:12:16 +02:00
}
async transferEntities(): Promise<void> {
const stage: TransferStage = 'entities';
const source = await this.sourceProvider.streamEntities?.();
const destination = await this.destinationProvider.getEntitiesStream?.();
const transform = this.#createStageTransformStream(stage);
const tracker = this.#progressTracker(stage, { key: (value: IEntity) => value.type });
await this.#transferStage({ stage, source, destination, transform, tracker });
}
async transferLinks(): Promise<void> {
const stage: TransferStage = 'links';
const source = await this.sourceProvider.streamLinks?.();
const destination = await this.destinationProvider.getLinksStream?.();
const transform = this.#createStageTransformStream(stage);
const tracker = this.#progressTracker(stage);
2022-11-11 13:41:01 +01:00
await this.#transferStage({ stage, source, destination, transform, tracker });
}
2022-11-24 16:07:07 +01:00
async transferAssets(): Promise<void> {
const stage: TransferStage = 'assets';
2022-11-21 18:55:51 +01:00
const source = await this.sourceProvider.streamAssets?.();
const destination = await this.destinationProvider.getAssetsStream?.();
2022-11-21 18:55:51 +01:00
const transform = this.#createStageTransformStream(stage);
const tracker = this.#progressTracker(stage, {
size: (value: IAsset) => value.stats.size,
key: (value: IAsset) => extname(value.filename),
2022-11-21 18:55:51 +01:00
});
await this.#transferStage({ stage, source, destination, transform, tracker });
}
async transferConfiguration(): Promise<void> {
const stage: TransferStage = 'configuration';
2022-11-02 17:26:32 +01:00
const source = await this.sourceProvider.streamConfiguration?.();
const destination = await this.destinationProvider.getConfigurationStream?.();
2022-11-11 13:41:01 +01:00
const transform = this.#createStageTransformStream(stage);
const tracker = this.#progressTracker(stage);
2022-11-02 17:26:32 +01:00
await this.#transferStage({ stage, source, destination, transform, tracker });
}
}
2022-11-15 21:15:16 +01:00
export const createTransferEngine = <
S extends ISourceProvider = ISourceProvider,
D extends IDestinationProvider = IDestinationProvider
>(
sourceProvider: S,
destinationProvider: D,
options: ITransferEngineOptions
): TransferEngine<S, D> => {
return new TransferEngine<S, D>(sourceProvider, destinationProvider, options);
};