import path from 'path'; import workerpool from 'workerpool'; import { FileContent, getEnv, SchemaFileRepository } from '@cubejs-backend/shared'; import { AbstractDataSchemaCompiler, DataSchemaCompilerOptions, FirstPhaseFiles, TranspiledYaml, TranspileOptions, } from './AbstractDataSchemaCompiler'; import type { ErrorReporter } from './ErrorReporter'; import { CubeCheckDuplicatePropTranspiler, CubePropContextTranspiler, IIFETranspiler, ImportExportTranspiler, MemoKeyTranspiler, ValidationTranspiler, } from './transpilers'; import type { TranspilerInterface } from './transpilers/transpiler.interface'; export type PlainDataSchemaCompilerOptions = DataSchemaCompilerOptions & { /** * Replaces the default list. Only the class names are read: the worker threads look their * transpilers up by them. */ transpilers?: TranspilerInterface[]; }; /** * Transpiles the data model with Babel, in a pool of worker threads */ export class PlainDataSchemaCompiler extends AbstractDataSchemaCompiler { protected workerPool: workerpool.Pool | null = null; protected readonly transpilerNames: string[]; public constructor(repository: SchemaFileRepository, options: PlainDataSchemaCompilerOptions) { // The worker threads hold the instances and look them up by class name const transpilers: { name: string }[] = [ ValidationTranspiler, ImportExportTranspiler, CubePropContextTranspiler, MemoKeyTranspiler, IIFETranspiler, ]; if (!options.allowJsDuplicatePropsInSchema) { transpilers.push(CubeCheckDuplicatePropTranspiler); } super(repository, options); this.transpilerNames = options.transpilers ? options.transpilers.map(t => t.constructor.name) : transpilers.map(t => t.name); } protected startTranspiler(): void { const wc = getEnv('transpilationWorkerThreadsCount'); this.workerPool = workerpool.pool( path.join(__dirname, 'transpilers/transpiler_worker'), wc > 0 ? { maxWorkers: wc } : undefined, ); } protected stopTranspiler(): void { if (this.workerPool) { this.workerPool.terminate(); this.workerPool = null; } } protected async transpileFirstPhase( { jsFiles, yamlFiles, jinjaFiles }: FirstPhaseFiles, errorsReport: ErrorReporter, { cubeNames, cubeSymbols, jinjaMacrosFingerprint }: TranspileOptions ): Promise<(FileContent | undefined)[]> { const { transpilerNames } = this; return Promise.all( [...jinjaFiles, ...yamlFiles, ...jsFiles] .map(f => this.transpileFile(f, errorsReport, { cubeNames, cubeSymbols, transpilerNames, jinjaMacrosFingerprint })) ); } protected async transpileNextPhase( files: FileContent[], errorsReport: ErrorReporter, { cubeNames, cubeSymbols }: TranspileOptions ): Promise<(FileContent | undefined)[]> { return this.transpileJsFilesWorkerBulk(files, errorsReport, { cubeNames, cubeSymbols, transpilerNames: this.transpilerNames }); } /** * Files go to the workers in chunks because every message carries all cube symbols, and * cloning them for each file costs files x members. */ protected async transpileJsFilesWorkerBulk( files: FileContent[], errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)[]> { const { cubeNames, cubeSymbols, transpilerNames } = options; if (!files.length) { return []; } // More chunks than workers, so one chunk of large files doesn't hold up the rest const chunkCount = Math.min(files.length, (this.workerPool!.maxWorkers || 1) * 4); const chunkSize = Math.ceil(files.length / chunkCount); const chunks: FileContent[][] = []; for (let i = 0; i < files.length; i += chunkSize) { chunks.push(files.slice(i, i + chunkSize)); } const results = await Promise.all(chunks.map(async (chunk) => { let res: ({ content: string; errors: any[]; warnings: any[] } | null)[]; try { res = await this.workerPool!.exec('transpileJsBulk', [{ files: chunk.map(({ fileName, content }) => ({ fileName, content })), transpilers: transpilerNames, cubeNames, cubeSymbols, }]); } catch { // The whole chunk failed (the worker died, say): the per-file path reports it file by file res = chunk.map(() => null); } return Promise.all(chunk.map(async (file, i) => { const fileRes = res[i]; if (!fileRes) { return this.transpileJsFile(file, errorsReport, options); } errorsReport.addErrors(fileRes.errors, file.fileName); errorsReport.addWarnings(fileRes.warnings); return { ...file, content: fileRes.content }; })); })); return results.flat(); } protected async transpileJsFile( file: FileContent, errorsReport: ErrorReporter, { cubeNames, cubeSymbols, transpilerNames }: TranspileOptions ): Promise<(FileContent | undefined)> { try { const data = { fileName: file.fileName, content: file.content, transpilers: transpilerNames, cubeNames, cubeSymbols, }; const res = await this.workerPool!.exec('transpileJs', [data]); errorsReport.addErrors(res.errors, file.fileName); errorsReport.addWarnings(res.warnings); return { ...file, content: res.content }; } catch (e: any) { this.reportTranspileError(e, file, errorsReport); } return undefined; } protected async transpileYamlContent( file: FileContent, errorsReport: ErrorReporter, { cubeNames, cubeSymbols, jinjaUsed }: TranspileOptions ): Promise { const data = { fileName: file.fileName, content: file.content, transpilers: [], jinjaUsed: jinjaUsed || false, cubeNames, cubeSymbols, }; const res = await this.workerPool!.exec('transpileYaml', [data]); errorsReport.addErrors(res.errors, file.fileName); errorsReport.addWarnings(res.warnings); return { content: res.content, errors: res.errors }; } }