import os from 'os'; import { FileContent, getEnv, SchemaFileRepository } from '@cubejs-backend/shared'; import { transpileJs, transpileYaml } from '@cubejs-backend/native'; import { AbstractDataSchemaCompiler, CompileStage, DataSchemaCompilerOptions, FirstPhaseFiles, TranspiledYaml, TranspileOptions, } from './AbstractDataSchemaCompiler'; import { CONTEXT_SYMBOLS } from './CubeSymbols'; import type { ErrorReporter, SyntaxErrorInterface } from './ErrorReporter'; const getThreadsCount = () => { const envThreads = getEnv('transpilationWorkerThreadsCount'); if (envThreads > 0) { return envThreads; } const cpuCount = os.cpus()?.length; if (cpuCount) { // there's no practical boost above 5 threads even if you have more cores. return Math.min(Math.max(1, cpuCount - 1), 5); } return 3; // Default (like the workerpool do) }; const splitFilesToChunks = (files: FileContent[], chunksCount: number): FileContent[][] => { let chunks: FileContent[][]; if (files.length < chunksCount * chunksCount) { chunks = [files]; } else { const baseSize = Math.floor(files.length / chunksCount); chunks = []; for (let i = 0; i < chunksCount; i++) { const start = i * baseSize; const end = (i === chunksCount - 1) ? files.length : start + baseSize; chunks.push(files.slice(start, end)); } } return chunks; }; /** * Transpiles the data model with swc, in the native extension. Keep Babel out of this module's * imports: nothing here needs it, and it is a large part of the package's load time. */ export class NativeDataSchemaCompiler extends AbstractDataSchemaCompiler { protected readonly threadsCount: number = getThreadsCount(); protected readonly transpilerNames: string[]; public constructor(repository: SchemaFileRepository, options: DataSchemaCompilerOptions) { // Names of the swc transpilers; the Babel classes they mirror aren't imported, see above const transpilerNames = [ 'ValidationTranspiler', 'ImportExportTranspiler', 'CubePropContextTranspiler', 'MemoKeyTranspiler', 'IIFETranspiler', ]; if (!options.allowJsDuplicatePropsInSchema) { transpilerNames.push('CubeCheckDuplicatePropTranspiler'); } super(repository, options); this.transpilerNames = transpilerNames; } protected startTranspiler(): void { // Nothing to set up: the swc cache is warmed by the first file of every phase } protected stopTranspiler(errorsReport: ErrorReporter): void { // Empty cube symbols replace the ones the native side caches for this compilerId, freeing them const dummyFile = { fileName: 'terminate.js', content: ';', }; this.transpileJsFile( dummyFile, errorsReport, { cubeNames: [], cubeSymbols: {}, transpilerNames: [], contextSymbols: {}, compilerId: this.compilerId, stage: 0 } ).then(() => undefined); } protected async warmUp(errorsReport: ErrorReporter, { cubeNames, cubeSymbols, stage }: TranspileOptions) { // Warming up swc compiler cache const dummyFile = { fileName: 'dummy.js', content: ';', }; await this.transpileJsFile( dummyFile, errorsReport, { cubeNames, cubeSymbols, transpilerNames: this.transpilerNames, contextSymbols: CONTEXT_SYMBOLS, compilerId: this.compilerId, stage } ); } protected async transpileFirstPhase( { jsFiles, yamlFiles, jinjaFiles }: FirstPhaseFiles, errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)[]> { const { cubeNames, cubeSymbols, jinjaMacrosFingerprint } = options; const { compilerId, transpilerNames } = this; let jsFilesTasks: Promise<(FileContent | undefined)[]>[] = []; let yamlFilesTasks: Promise<(FileContent | undefined)[]>[] = []; if (jsFiles.length > 0) { await this.warmUp(errorsReport, options); const jsChunks = splitFilesToChunks(jsFiles, this.threadsCount); jsFilesTasks = jsChunks.map(chunk => this.transpileJsFilesNativeBulk(chunk, errorsReport, { transpilerNames, compilerId })); } if (yamlFiles.length > 0) { const yamlChunks = splitFilesToChunks(yamlFiles, this.threadsCount); yamlFilesTasks = yamlChunks.map(chunk => this.transpileYamlFilesNativeBulk(chunk, errorsReport, { transpilerNames, compilerId })); } const jinjaFilesTasks = jinjaFiles .map(f => this.transpileJinjaFile(f, errorsReport, { cubeNames, cubeSymbols, transpilerNames, jinjaMacrosFingerprint })); return (await Promise.all([...jsFilesTasks, ...yamlFilesTasks, ...jinjaFilesTasks])).flat(); } protected async transpileNextPhase( files: FileContent[], errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)[]> { const { compilerId, transpilerNames } = this; await this.warmUp(errorsReport, options); const jsChunks = splitFilesToChunks(files, this.threadsCount); const jsFilesTasks = jsChunks.map(chunk => this.transpileJsFilesNativeBulk(chunk, errorsReport, { transpilerNames, compilerId })); return (await Promise.all(jsFilesTasks)).flat(); } protected async transpileJsFilesNativeBulk( files: FileContent[], errorsReport: ErrorReporter, { cubeNames, cubeSymbols, contextSymbols, transpilerNames, compilerId, stage }: TranspileOptions ): Promise<(FileContent | undefined)[]> { // for bulk processing this data may be optimized even more by passing transpilerNames, compilerId only once for a bulk // but this requires more complex logic to be implemented in the native side. // And comparing to the file content sizes, a few bytes of JSON data is not a big deal here const reqDataArr = files.map(file => ({ fileName: file.fileName, fileContent: file.content, transpilers: transpilerNames || [], compilerId: compilerId || '', ...(cubeNames && { metaData: { cubeNames, cubeSymbols: cubeSymbols || {}, contextSymbols: contextSymbols || {}, stage: stage || 0 as CompileStage, }, }), })); const res = await transpileJs(reqDataArr); return files.map((file, index) => { errorsReport.inFile(file); if (!res[index]) { // This should not happen in theory but just to be safe errorsReport.error('No transpilation result received for the file.'); return undefined; } errorsReport.addErrors(res[index].errors, file.fileName); errorsReport.addWarnings(res[index].warnings as unknown as SyntaxErrorInterface[]); errorsReport.exitFile(); return { ...file, content: res[index].code }; }); } protected async transpileYamlFilesNativeBulk( files: FileContent[], errorsReport: ErrorReporter, { compilerId, jinjaUsed }: TranspileOptions ): Promise<(FileContent | undefined)[]> { const reqDataArr = files.map(file => ({ fileName: file.fileName, fileContent: file.content, transpilers: [], compilerId: compilerId || '', jinjaUsed: jinjaUsed || false, })); const res = await transpileYaml(reqDataArr); return files.map((file, index) => { errorsReport.inFile(file); if (!res[index]) { // This should not happen in theory but just to be safe errorsReport.error('No transpilation result received for the file.'); return undefined; } errorsReport.addErrors(res[index].errors, file.fileName); errorsReport.addWarnings(res[index].warnings as unknown as SyntaxErrorInterface[]); errorsReport.exitFile(); return { ...file, content: res[index].code }; }); } protected async transpileJsFile( file: FileContent, errorsReport: ErrorReporter, { cubeNames, cubeSymbols, contextSymbols, transpilerNames, compilerId, stage }: TranspileOptions ): Promise<(FileContent | undefined)> { try { const reqData = { fileName: file.fileName, fileContent: file.content, transpilers: transpilerNames || [], compilerId: compilerId || '', ...(cubeNames && { metaData: { cubeNames, cubeSymbols: cubeSymbols || {}, contextSymbols: contextSymbols || {}, stage: stage || 0 as CompileStage, }, }), }; errorsReport.inFile(file); const res = await transpileJs([reqData]); errorsReport.addErrors(res[0].errors, file.fileName); errorsReport.addWarnings(res[0].warnings as unknown as SyntaxErrorInterface[]); errorsReport.exitFile(); return { ...file, content: res[0].code }; } catch (e: any) { this.reportTranspileError(e, file, errorsReport); } return undefined; } protected async transpileYamlContent( file: FileContent, errorsReport: ErrorReporter, { compilerId, jinjaUsed }: TranspileOptions ): Promise { const reqData = { fileName: file.fileName, fileContent: file.content, transpilers: [], compilerId: compilerId || '', jinjaUsed: jinjaUsed || false, }; errorsReport.inFile(file); const res = await transpileYaml([reqData]); errorsReport.addErrors(res[0].errors, file.fileName); errorsReport.addWarnings(res[0].warnings as unknown as SyntaxErrorInterface[]); errorsReport.exitFile(); return { content: res[0].code, errors: res[0].errors }; } }