import { AsyncLocalStorage } from 'async_hooks'; import crypto from 'crypto'; import vm from 'vm'; import fs from 'fs'; import path from 'path'; import syntaxCheck from 'syntax-error'; import R from 'ramda'; import { LRUCache } from 'lru-cache'; import { FileContent, isNativeSupported, SchemaFileRepository } from '@cubejs-backend/shared'; import { NativeInstance, newModelContext, PythonCtx } from '@cubejs-backend/native'; import type { ModelContext } from '@cubejs-backend/native'; import { UserError } from './UserError'; import { ErrorReporter, ErrorReporterOptions, SyntaxErrorInterface } from './ErrorReporter'; import { CubeDefinition, CubeSymbols } from './CubeSymbols'; import { ViewCompilationGate } from './ViewCompilationGate'; import { memoCallSiteOf } from './transpilers/memoCallSite'; import type { CompilerInterface } from './PrepareCompiler'; import type { JinjaTemplateRenderer } from './JinjaTemplateRenderer'; import { CubeDictionary } from './CubeDictionary'; import { CompilerCache } from './CompilerCache'; import type { BaseQuery } from '../adapter/BaseQuery'; const ctxFileStorage = new AsyncLocalStorage(); // Set while the function passed to `memo` runs, including its async continuations const memoFnStorage = new AsyncLocalStorage(); // For memo() keys: objects compare by their keys whatever the property order, and NaN and // Infinity don't encode as null const memoKeyReplacer = (_key: string, value: unknown) => { if (typeof value === 'number' && !Number.isFinite(value)) { return { $memoNumber: String(value) }; } if (value && typeof value === 'object' && !Array.isArray(value)) { return Object.fromEntries(Object.keys(value).sort().map((k) => [k, (value as Record)[k]])); } return value; }; // Shared realm: closures bind the running compile's scope lexically through `with`, so lazy reads // (sql reading COMPILE_CONTEXT) keep resolving it after the compile; the inner function keeps // top-level declarations off the shared global and gets the compile's own global as `this`. const SHARED_SCOPE_GETTER = '__cubejsCompileScope'; const sharedScriptPrefix = (strict: boolean) => `with (${SHARED_SCOPE_GETTER}(${strict})) { (function () {`; const SHARED_SCRIPT_SUFFIX = '\n}).call(globalThis); }'; // Whether the source opens with a 'use strict' directive, after whitespace and comments. // A linear scan: a regex over repeated comments can backtrack exponentially. function hasUseStrictDirective(source: string): boolean { let i = 0; while (i < source.length) { if (/\s/.test(source[i])) { i++; } else if (source.startsWith('//', i)) { const end = source.indexOf('\n', i); if (end === -1) { return false; } i = end + 1; } else if (source.startsWith('/*', i)) { const end = source.indexOf('*/', i + 2); if (end === -1) { return false; } i = end + 2; } else { break; } } return source.startsWith("'use strict'", i) || source.startsWith('"use strict"', i); } // UMD wrappers probe these with `typeof`: read as undefined, not as a ReferenceError const PROBED_GLOBALS = new Set(['module', 'exports', 'define']); type SharedCompileScope = { // The `with` object: claims every name, so model code never reaches the realm global scope: object; // For strict code: claims only names the compile or the realm has, so assigning an undeclared // name throws a ReferenceError as it does at global scope strictScope: object; vars: Record; }; const sharedScopeStorage = new AsyncLocalStorage(); let sharedVmContext: vm.Context | null = null; let sharedRealmGlobal: Record | null = null; const getSharedVmContext = (): vm.Context => { if (!sharedVmContext) { const sandbox = {}; Object.defineProperty(sandbox, SHARED_SCOPE_GETTER, { value: (strict: boolean) => { const compile = sharedScopeStorage.getStore(); if (!compile) { throw new Error('No compile scope stored in context'); } return strict ? compile.strictScope : compile.scope; }, writable: false, enumerable: false, configurable: false, }); const refuse = (key: PropertyKey): never => { // The realm's own TypeError, as model code would catch it throw new sharedRealmGlobal!.TypeError( `Cannot set global '${String(key)}': data models share one realm with CUBEJS_COMPILER_MULTI_TENANT_SHARING` ); }; // What still reaches the real global (`this` of a nested sloppy function) fails loudly: a // value stored there would be every tenant's. sharedVmContext = vm.createContext(new Proxy(sandbox, { set: (_t, key) => refuse(key), defineProperty: (_t, key) => refuse(key), deleteProperty: (_t, key) => refuse(key), })); sharedRealmGlobal = vm.runInContext('globalThis', sharedVmContext); } return sharedVmContext; }; // Names the compile assigns (implicit globals, `globalThis.x`, `this.x`, even `JSON = ...`) land // in `vars`; reads fall back to the realm's built-ins. Unknown names throw a ReferenceError, also // under `typeof` (except PROBED_GLOBALS). const createSharedCompileScope = (globals: Record): SharedCompileScope => { getSharedVmContext(); const realm = sharedRealmGlobal!; const vars: Record = Object.assign(Object.create(null), globals); // Built-ins this compile deleted from its global const deleted = new Set(); const builtIn = (key: PropertyKey) => key !== SHARED_SCOPE_GETTER && !deleted.has(key) && key in realm; const read = (key: PropertyKey) => { if (key in vars) { return vars[key]; } if (builtIn(key)) { return realm[key]; } if (typeof key !== 'string' || PROBED_GLOBALS.has(key)) { return undefined; } throw new realm.ReferenceError(`${key} is not defined`); }; const remove = (key: PropertyKey) => { const removed = Reflect.deleteProperty(vars, key); if (removed && builtIn(key)) { deleted.add(key); } return removed; }; // The compile's `globalThis` and top-level `this`: its own properties are `vars` (the target, so // defining, deleting and reflecting on them behave as on an ordinary object), then the built-ins const realmOwn = (key: PropertyKey) => builtIn(key) && Object.prototype.hasOwnProperty.call(realm, key); const compileGlobal = new Proxy(vars, { get: (t, key) => (key in t || builtIn(key) ? read(key) : undefined), has: (t, key) => key in t || builtIn(key), // Without it, OrdinarySet would copy the built-in's attributes through getOwnPropertyDescriptor set: (t, key, value) => { t[key] = value; deleted.delete(key); return true; }, defineProperty: (t, key, descriptor) => { // Redefining a built-in keeps the attributes the descriptor leaves out, as on a global const base: PropertyDescriptor = !Object.prototype.hasOwnProperty.call(t, key) && realmOwn(key) ? { ...Reflect.getOwnPropertyDescriptor(realm, key), configurable: true } : {}; const accessor = 'get' in descriptor || 'set' in descriptor; const merged = accessor || 'get' in base ? { enumerable: base.enumerable, configurable: base.configurable, ...descriptor } : { ...base, ...descriptor }; deleted.delete(key); return Reflect.defineProperty(t, key, merged); }, deleteProperty: (_t, key) => remove(key), ownKeys: (t) => [...new Set([ ...Reflect.ownKeys(t), ...Reflect.ownKeys(realm).filter((key) => realmOwn(key)), ])], getOwnPropertyDescriptor: (t, key) => { if (Object.prototype.hasOwnProperty.call(t, key) || !realmOwn(key)) { return Reflect.getOwnPropertyDescriptor(t, key); } // A built-in the compile hasn't shadowed: reported configurable, as the target lacks it return { ...Reflect.getOwnPropertyDescriptor(realm, key), configurable: true }; }, }); Object.defineProperty(vars, 'globalThis', { value: compileGlobal, writable: true, configurable: true, enumerable: false }); const scopeTraps: ProxyHandler> = { get: (_t, key) => read(key), set: (t, key, value) => { t[key] = value; deleted.delete(key); return true; }, deleteProperty: (_t, key) => remove(key), }; const scope = new Proxy(vars, { ...scopeTraps, has: (_t, key) => typeof key === 'string' && key !== SHARED_SCOPE_GETTER, }); const strictScope = new Proxy(vars, { ...scopeTraps, has: (t, key) => typeof key === 'string' && (key in t || builtIn(key)), }); // `new Function(...)` / `Function(...)` compile their body in this compile's scope, as they would // at the global scope of a realm of its own. The result is an ordinary function of the realm. const RealmFunction = realm.Function; const compileFunction = function Function(...args: unknown[]) { const body = args.length > 0 ? String(args[args.length - 1]) : ''; const params = args.slice(0, -1).map(String).join(','); // Parse params and body on their own first, so malformed input throws the realm's SyntaxError // instead of closing the wrapper below early. RealmFunction(...args); const factory = RealmFunction('scope', `with (scope) { return function anonymous(${params}\n) {\n${body}\n}; }`); return factory(hasUseStrictDirective(body) ? strictScope : scope); }; compileFunction.prototype = RealmFunction.prototype; Object.setPrototypeOf(compileFunction, RealmFunction.prototype); Object.defineProperty(compileFunction, 'length', { value: 1 }); Object.defineProperty(vars, 'Function', { value: compileFunction, writable: true, configurable: true, enumerable: false }); return { scope, strictScope, vars }; }; const NATIVE_IS_SUPPORTED = isNativeSupported(); // Holds transpileFile()'s promise un-awaited, while require() hands the entry on as a FileContent. const moduleFileCache: Record = {}; const JINJA_SYNTAX = /{%|%}|{{|}}/ig; const JINJA_MACRO_DEFINITION = /{%[-+]?\s*macro\s/; export type DataSchemaCompilerOptions = { compilerCache: CompilerCache; omitErrors?: boolean; extensions?: Record; filesToCompile?: string[]; nativeInstance: NativeInstance; cubeFactory: Function; cubeDictionary: CubeDictionary; cubeOnlySymbols: CubeSymbols; cubeAndViewSymbols: CubeSymbols; cubeCompilers?: CompilerInterface[]; contextCompilers?: CompilerInterface[]; viewGroupCompilers?: CompilerInterface[]; metaCompilers?: CompilerInterface[]; allowJsDuplicatePropsInSchema?: boolean; viewCompilers?: CompilerInterface[]; viewCompilationGate: ViewCompilationGate; cubeNameCompilers?: CompilerInterface[]; preTranspileCubeCompilers?: CompilerInterface[]; jinjaRenderer: JinjaTemplateRenderer; errorReport?: ErrorReporterOptions; compilerId?: string; standalone?: boolean; compileContext?: any; allowNodeRequire?: boolean; compiledScriptCache: LRUCache; compiledYamlCache: LRUCache; compiledJinjaCache: LRUCache; /** * Evaluate data model files in one realm shared by all compiles (prepareCompiler resolves it) */ sharedVmContext?: boolean; }; export type TranspileOptions = { cubeNames?: string[]; cubeSymbols?: Record>; contextSymbols?: Record; transpilerNames?: string[]; compilerId?: string; stage?: 0 | 1 | 2 | 3; jinjaUsed?: boolean; jinjaMacrosFingerprint?: string; }; export type CompileStage = 0 | 1 | 2 | 3; type CompileCubeFilesCompilers = { cubeCompilers?: CompilerInterface[]; contextCompilers?: CompilerInterface[]; viewGroupCompilers?: CompilerInterface[]; metaCompilers?: CompilerInterface[]; }; export type CompileContext = any; export type TranspiledYaml = { content: string; errors?: unknown[]; }; export type FirstPhaseFiles = { jsFiles: FileContent[]; yamlFiles: FileContent[]; jinjaFiles: FileContent[]; }; export abstract class AbstractDataSchemaCompiler { protected readonly repository: SchemaFileRepository; protected readonly cubeCompilers: CompilerInterface[]; protected readonly contextCompilers: CompilerInterface[]; protected readonly viewGroupCompilers: CompilerInterface[]; protected readonly metaCompilers: CompilerInterface[]; protected readonly viewCompilers: CompilerInterface[]; protected readonly preTranspileCubeCompilers: CompilerInterface[]; protected readonly viewCompilationGate: ViewCompilationGate; protected readonly cubeNameCompilers: CompilerInterface[]; protected readonly extensions: Record; protected readonly cubeDictionary: CubeDictionary; protected readonly cubeOnlySymbols: CubeSymbols; protected readonly cubeAndViewSymbols: CubeSymbols; // Actually should be something like // createCube(cubeDefinition: CubeDefinition): CubeDefinitionExtended protected readonly cubeFactory: CallableFunction; protected readonly filesToCompile: string[]; protected readonly omitErrors: boolean; protected readonly allowNodeRequire: boolean; public readonly compilerCache: CompilerCache; protected modelContextInstance: ModelContext | undefined; protected readonly compileContext: CompileContext; protected errorReportOptions: ErrorReporterOptions | undefined; protected errorsReporter: ErrorReporter | undefined; protected readonly standalone: boolean; protected readonly nativeInstance: NativeInstance; protected readonly jinjaRenderer: JinjaTemplateRenderer; protected pythonContext: PythonCtx | null; protected readonly compilerId: string; protected readonly compiledScriptCache: LRUCache; protected readonly compiledYamlCache: LRUCache; protected readonly compiledJinjaCache: LRUCache; protected compileV8ContextCache: vm.Context | null = null; protected readonly sharedVmContext: boolean; // Flag on: per-compile `with` scope evaluated inside the shared realm. protected compileScope: SharedCompileScope | null = null; // FIXME: Is public only because of tests, should be private public compilePromise: any; protected currentQuery: any; public constructor(repository: SchemaFileRepository, options: DataSchemaCompilerOptions) { this.repository = repository; this.cubeCompilers = options.cubeCompilers || []; this.contextCompilers = options.contextCompilers || []; this.viewGroupCompilers = options.viewGroupCompilers || []; this.metaCompilers = options.metaCompilers || []; this.viewCompilers = options.viewCompilers || []; this.preTranspileCubeCompilers = options.preTranspileCubeCompilers || []; this.viewCompilationGate = options.viewCompilationGate; this.cubeNameCompilers = options.cubeNameCompilers || []; this.extensions = options.extensions || {}; this.cubeDictionary = options.cubeDictionary; this.cubeOnlySymbols = options.cubeOnlySymbols; this.cubeAndViewSymbols = options.cubeAndViewSymbols; this.cubeFactory = options.cubeFactory; this.filesToCompile = options.filesToCompile || []; this.omitErrors = options.omitErrors || false; this.allowNodeRequire = options.allowNodeRequire || false; this.compileContext = options.compileContext; this.compilerCache = options.compilerCache; this.errorReportOptions = options.errorReport; this.standalone = options.standalone || false; this.nativeInstance = options.nativeInstance; this.jinjaRenderer = options.jinjaRenderer; this.pythonContext = null; this.compilerId = options.compilerId || 'default'; this.compiledScriptCache = options.compiledScriptCache; this.compiledYamlCache = options.compiledYamlCache; this.compiledJinjaCache = options.compiledJinjaCache; this.sharedVmContext = !!options.sharedVmContext; } public compileObjects(compileServices: CompilerInterface[], objects: unknown[], errorsReport: ErrorReporter) { try { return compileServices .map((compileService) => (() => compileService.compile(objects, errorsReport))) .reduce((p, fn) => p.then(fn), Promise.resolve()) .catch((error) => { errorsReport.error(error); }); } catch (e) { errorsReport.error(e); return Promise.resolve(); } } protected async loadPythonContext(files: FileContent[], nsFileName: string): Promise { const ns = files.find((f) => f.fileName === nsFileName); if (ns) { return this.nativeInstance.loadPythonContext( ns.fileName, ns.content ); } return { __type: 'PythonCtx', filters: {}, variables: {}, functions: {} } as PythonCtx; } protected async doCompile() { const files = await this.repository.dataSchemaFiles(); this.pythonContext = await this.loadPythonContext(files, 'globals.py'); this.jinjaRenderer.initFromPythonContext(this.pythonContext); const originalJsFiles: FileContent[] = []; const jinjaTemplatedFiles: FileContent[] = []; const yamlFiles: FileContent[] = []; (this.filesToCompile?.length ? files.filter(f => this.filesToCompile.includes(f.fileName)) : files).forEach(file => { if (file.fileName.endsWith('.js')) { originalJsFiles.push(file); } else if (file.fileName.endsWith('.jinja') || (file.fileName.endsWith('.yml') || file.fileName.endsWith('.yaml')) && file.content.match(JINJA_SYNTAX)) { jinjaTemplatedFiles.push(file); } else if (file.fileName.endsWith('.yml') || file.fileName.endsWith('.yaml')) { yamlFiles.push(file); } // We don't transpile/compile other files (like .py and so on) }); let toCompile = [...jinjaTemplatedFiles, ...yamlFiles, ...originalJsFiles]; if (jinjaTemplatedFiles.length > 0) { // Preload Jinja templates to the engine this.loadJinjaTemplates(jinjaTemplatedFiles); } const jinjaMacrosFingerprint = AbstractDataSchemaCompiler.computeJinjaMacrosFingerprint(jinjaTemplatedFiles); const errorsReport = new ErrorReporter(null, [], this.errorReportOptions); this.errorsReporter = errorsReport; this.startTranspiler(); const transpilePhaseFirst = async (stage: CompileStage): Promise => { const results = await this.transpileFirstPhase( { jsFiles: originalJsFiles, yamlFiles, jinjaFiles: jinjaTemplatedFiles }, errorsReport, { ...this.prepareTranspileSymbols(), jinjaMacrosFingerprint, stage } ); return results.filter(f => !!f) as FileContent[]; }; const transpilePhase = async (stage: CompileStage): Promise => { if (toCompile.length === 0) { return []; } // After the first phase all files are with JS source code: original or transpiled const results = await this.transpileNextPhase(toCompile, errorsReport, { ...this.prepareTranspileSymbols(), stage }); return results.filter(f => !!f) as FileContent[]; }; let cubes: CubeDefinition[] = []; let exports: Record> = {}; let contexts: Record[] = []; let viewGroups: Record[] = []; let compiledFiles: Record = {}; let asyncModules: CallableFunction[] = []; let transpiledFiles: FileContent[] = []; // Results of `memo` calls. Unlike the objects above it survives between the compile stages: // the model is evaluated once per stage, and `memo` makes it do a costly call (an API request // from an `asyncModule`, say) only once per compile. const memoResults = new Map(); // Stage that last looked up each key MemoKeyTranspiler generated const memoCallSiteStages = new Map(); let memoStage = -1; // Model objects go to the current stage only, while a memoized function runs in the first stage // that asks for its key: objects defined from there would be missing from all later stages. const assertOutsideMemo = (globalName: string) => { const memoCall = memoFnStorage.getStore(); if (memoCall !== undefined) { throw new UserError( `${globalName}() can't be called from the function passed to ${memoCall}: ` + 'return the data from memo() and define model objects outside of it' ); } }; const cleanup = () => { cubes = []; exports = {}; contexts = []; viewGroups = []; compiledFiles = {}; asyncModules = []; }; const compileGlobals = { // `name` is the definition itself when `cube` is omitted view: (name: any, cube?: any) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } if (cube) { assertOutsideMemo('view'); } return !cube ? this.cubeFactory({ ...name, fileName: file.fileName, isView: true }) : cubes.push({ ...cube, name, fileName: file.fileName, isView: true }); }, cube: (name: any, cube?: any) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } if (cube) { assertOutsideMemo('cube'); } return !cube ? this.cubeFactory({ ...name, fileName: file.fileName }) : cubes.push({ ...cube, name, fileName: file.fileName }); }, context: (name: string, context: Record) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } assertOutsideMemo('context'); return contexts.push({ ...context, name, fileName: file.fileName }); }, view_group: (name: string, viewGroup: Record) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } assertOutsideMemo('view_group'); viewGroups.push({ ...viewGroup, name, fileName: file.fileName }); if (this.sharedVmContext) { this.compileScope!.vars[name] = name; } else { this.compileV8ContextCache![name] = name; } return name; }, addExport: (obj: Record) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } exports[file.fileName] = exports[file.fileName] || {}; exports[file.fileName] = Object.assign(exports[file.fileName], obj); }, setExport: (obj: Record) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } exports[file.fileName] = obj; }, asyncModule: (fn: () => unknown) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } assertOutsideMemo('asyncModule'); // We need to run async module code in the context of the original data model file // where it was defined. So we pass the same file to the async context. // @see https://nodejs.org/api/async_context.html#class-asynclocalstorage asyncModules.push(async () => ctxFileStorage.run(file, () => fn())); }, memo: (key: unknown, fn: () => unknown) => { if (typeof key === 'function' && fn === undefined) { // MemoKeyTranspiler gives `memo(fn)` its key: this call didn't go through it throw new Error('memo() expects a key as its first argument: memo(key, fn)'); } if (typeof fn !== 'function') { throw new Error('memo() expects a function as its second argument'); } // Strings are encoded too, or `memo('1', ...)` would share the result of `memo(1, ...)` let cacheKey: string | undefined; try { cacheKey = JSON.stringify(key, memoKeyReplacer); } catch { // BigInt or a cyclic structure } if (typeof cacheKey !== 'string') { throw new Error('memo() expects a string or a JSON-serializable key as its first argument'); } const callSite = memoCallSiteOf(key); // For errors: the key as the code would write it const label = callSite !== undefined ? `memo() at ${callSite}` : `memo(${cacheKey})`; if (memoStage < 0 || !ctxFileStorage.getStore()) { // Called from a member (`sql: () => memo(...)`) evaluated by a compiler or a query, not // from a model file: it may run any number of times, so there's no stage to cache for return memoFnStorage.run(label, fn); } if (callSite !== undefined) { // A top-level call site runs once per stage: twice means it's in a function or a loop, // where the one key would give every call the result of the first one if (memoCallSiteStages.get(cacheKey) === memoStage) { throw new UserError( `memo() at ${callSite} is called more than once per compile stage: as it's in a function or a loop, ` + 'its result may depend on the arguments: pass a key that does, e.g. memo([\'table\', name], fn)' ); } memoCallSiteStages.set(cacheKey, memoStage); } let result = memoResults.get(cacheKey); if (!result) { // A promise is stored as is, so concurrent and later calls share one invocation. // A throw is stored too: every stage has to see the same outcome. try { result = { value: memoFnStorage.run(label, fn) }; } catch (error) { result = { error }; } memoResults.set(cacheKey, result); } if ('error' in result) { throw result.error; } return result.value; }, require: (extensionName: string) => { const file = ctxFileStorage.getStore(); if (!file) { throw new Error('No file stored in context'); } if (this.extensions[extensionName]) { return new (this.extensions[extensionName])(this.cubeFactory, this, cubes); } else { const foundFile = this.resolveModuleFile(file, extensionName, transpiledFiles, errorsReport); if (!foundFile && this.allowNodeRequire) { if (extensionName.startsWith('.')) { extensionName = path.resolve(this.repository.localPath(), extensionName); } // eslint-disable-next-line global-require,import/no-dynamic-require const Extension = require(extensionName); if (Object.getPrototypeOf(Extension).name === 'AbstractExtension') { return new Extension(this.cubeFactory, this, cubes); } return Extension; } this.compileFile( foundFile, errorsReport, compiledFiles, { doSyntaxCheck: true } ); exports[foundFile.fileName] = exports[foundFile.fileName] || {}; return exports[foundFile.fileName]; } }, COMPILE_CONTEXT: this.standalone ? this.standaloneCompileContextProxy() : this.cloneCompileContextWithGetterAlias(this.compileContext || {}), }; if (this.sharedVmContext) { this.compileScope = createSharedCompileScope(compileGlobals); } else { this.compileV8ContextCache = vm.createContext(compileGlobals); } const compilePhaseFirst = async (compilers: CompileCubeFilesCompilers, stage: 0 | 1 | 2 | 3) => { // clear the objects for the next phase cleanup(); memoStage = stage; transpiledFiles = await transpilePhaseFirst(stage); // We render jinja and transpile yaml only once on first phase and then use resulting JS for these files // afterward avoiding costly YAML/Python parsing again. Original JS files are preserved as is for cache hits. const convertedToJsFiles = transpiledFiles.filter(f => !f.fileName.endsWith('.js')); toCompile = [...originalJsFiles, ...convertedToJsFiles]; return this.compileCubeFiles(cubes, contexts, viewGroups, compiledFiles, asyncModules, compilers, transpiledFiles, errorsReport); }; const compilePhase = async (compilers: CompileCubeFilesCompilers, stage: 0 | 1 | 2 | 3) => { // clear the objects for the next phase cleanup(); memoStage = stage; transpiledFiles = await transpilePhase(stage); return this.compileCubeFiles(cubes, contexts, viewGroups, compiledFiles, asyncModules, compilers, transpiledFiles, errorsReport); }; const compileAll = () => compilePhaseFirst({ cubeCompilers: this.cubeNameCompilers }, 0) .then(() => compilePhase({ cubeCompilers: this.preTranspileCubeCompilers.concat([this.viewCompilationGate]) }, 1)) .then(() => (this.viewCompilationGate.shouldCompileViews() ? compilePhase({ cubeCompilers: this.viewCompilers }, 2) : Promise.resolve())) .then(() => compilePhase({ cubeCompilers: this.cubeCompilers, contextCompilers: this.contextCompilers, viewGroupCompilers: this.viewGroupCompilers, metaCompilers: this.metaCompilers, }, 3)) .then(() => { // Free unneeded resources cleanup(); transpiledFiles = []; toCompile = []; // The functions put into the compile context (cube, view, require, ...) close over // this scope, and member functions keep that context alive as long as the compiled // model lives: drop the model files' contents here, or they stay retained with it. originalJsFiles.length = 0; jinjaTemplatedFiles.length = 0; yamlFiles.length = 0; }) // A failed compile mustn't keep the fetched data or the transpiler resources either .finally(() => { this.stopTranspiler(errorsReport); memoStage = -1; memoResults.clear(); memoCallSiteStages.clear(); // These hold the globals.py TemplateContext, where the Python @memo caches live this.pythonContext = null; this.jinjaRenderer.free(); }); // Every continuation of the compile (asyncModule callbacks included) sees its scope return this.compileScope ? sharedScopeStorage.run(this.compileScope, compileAll) : compileAll(); } public compile() { if (!this.compilePromise) { this.compilePromise = this.doCompile().then((res) => { if (!this.omitErrors) { this.throwIfAnyErrors(); } this.modelContextInstance = newModelContext(); // Free unneeded resources this.compileV8ContextCache = null; this.compileScope = null; this.cubeDictionary.free(); this.cubeOnlySymbols.free(); this.cubeAndViewSymbols.free(); this.jinjaRenderer.free(); return res; }); } return this.compilePromise; } protected loadJinjaTemplates(files: FileContent[]): void { if (NATIVE_IS_SUPPORTED !== true) { throw new Error( `Native extension is required to process jinja files. ${NATIVE_IS_SUPPORTED.reason}. Read more: ` + 'https://github.com/cube-js/cube/blob/master/packages/cubejs-backend-native/README.md#supported-architectures-and-platforms' ); } const jinjaEngine = this.jinjaRenderer.getJinjaEngine(); files.forEach((file) => { jinjaEngine.loadTemplate(file.fileName, file.content); }); } /** * Macro files are hidden dependencies of any cube file that imports them — * minijinja resolves `{% import %}` lazily against its template store, so * the per-file Jinja render cache must be invalidated when *any* macro file * changes. Hashing all macro files together rather than tracking per-cube * imports keeps the implementation simple at the cost of over-invalidating * when macro edits happen (which is rare). CUB-2357. */ protected static computeJinjaMacrosFingerprint(files: FileContent[]): string { const macroFiles = files .filter((f) => JINJA_MACRO_DEFINITION.test(f.content)) .sort((a, b) => a.fileName.localeCompare(b.fileName)); if (macroFiles.length === 0) { return ''; } const hash = crypto.createHash('md5'); for (const f of macroFiles) { hash.update(f.fileName); hash.update('\0'); hash.update(f.content); hash.update('\0'); } return hash.digest('hex'); } protected prepareTranspileSymbols() { const joinAliases = (symbols: Record): string[] => { const joins = symbols.cubeObj?.()?.joins; return Array.isArray(joins) ? joins.map(join => join.alias).filter(Boolean) : []; }; const cubeNames: string[] = this.cubeDictionary.cubeNames(); // We need only cubes and all its member names for transpiling. // Cubes doesn't change during transpiling, but are changed during compilation phase, // so we can prepare them once for every phase. // Communication between main and worker threads uses // The structured clone algorithm (@see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) // which doesn't allow passing any function objects, so we need to sanitize the symbols. // Communication with native backend also involves deserialization. const cubeSymbols: Record> = Object.fromEntries( [...Object.entries(this.cubeOnlySymbols.symbols as Record>), ...Object.entries(this.cubeAndViewSymbols.symbols as Record>) ] .map( ([key, value]: [string, Record]) => [key, Object.fromEntries([ ...Object.keys(value).map((k) => [k, true]), // A join alias is a name in the cube's own scope, like its members ...joinAliases(value).map((alias) => [alias, true]), ])], ), ); return { cubeNames, cubeSymbols }; } protected async transpileFile( file: FileContent, errorsReport: ErrorReporter, options: TranspileOptions = { jinjaUsed: false, } ): Promise<(FileContent | undefined)> { if (file.fileName.endsWith('.js')) { return this.transpileJsFile(file, errorsReport, options); } else if (file.fileName.endsWith('.jinja') || (file.fileName.endsWith('.yml') || file.fileName.endsWith('.yaml')) && file.content.match(JINJA_SYNTAX) ) { return this.transpileJinjaFile(file, errorsReport, options); } else if (file.fileName.endsWith('.yml') || file.fileName.endsWith('.yaml')) { return this.transpileYamlFile(file, errorsReport, options); } else { return file; } } protected abstract startTranspiler(): void; /** * Called once per compile, whether it succeeded or failed */ protected abstract stopTranspiler(errorsReport: ErrorReporter): void; protected abstract transpileFirstPhase( files: FirstPhaseFiles, errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)[]>; /** * The same files, now all JS: YAML and Jinja are converted once, by the first phase */ protected abstract transpileNextPhase( files: FileContent[], errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)[]>; protected abstract transpileJsFile( file: FileContent, errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)>; protected abstract transpileYamlContent( file: FileContent, errorsReport: ErrorReporter, options: TranspileOptions ): Promise; protected reportTranspileError(e: any, file: FileContent, errorsReport: ErrorReporter): void { if (e.toString().indexOf('SyntaxError') !== -1) { const err = e as SyntaxErrorInterface; const line = file.content.split('\n')[(err.loc?.start?.line || 1) - 1]; const spaces = Array(err.loc?.start?.column).fill(' ').join('') || ''; errorsReport.error(`Syntax error during parsing: ${err.message}:\n${line}\n${spaces}^`, file.fileName); } else { errorsReport.error(e); } } protected async transpileYamlFile( file: FileContent, errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)> { // The YAML to JS output only depends on the content: YAML is transpiled once, in the // first phase, before any cube symbols are known. So the key is safe to share between apps. const cacheKey = crypto.createHash('md5').update(file.content).digest('hex'); if (this.compiledYamlCache.has(cacheKey)) { const content = this.compiledYamlCache.get(cacheKey)!; return { ...file, content }; } const res = await this.transpileYamlContent(file, errorsReport, options); // A hit doesn't replay errors, so a failed transpilation must not be cached if (!res.errors?.length) { this.compiledYamlCache.set(cacheKey, res.content); } return { ...file, content: res.content }; } protected async transpileJinjaFile( file: FileContent, errorsReport: ErrorReporter, options: TranspileOptions ): Promise<(FileContent | undefined)> { const cacheKey = crypto.createHash('md5') .update(file.content) .update('\0') .update(options.jinjaMacrosFingerprint || '') .digest('hex'); let renderedFileContent: string; if (this.compiledJinjaCache.has(cacheKey)) { renderedFileContent = this.compiledJinjaCache.get(cacheKey)!; } else { const renderedFile = await this.jinjaRenderer.renderTemplate( file, this.standalone ? {} : this.cloneCompileContextWithGetterAlias(this.compileContext), this.pythonContext! ); renderedFileContent = renderedFile.content; this.compiledJinjaCache.set(cacheKey, renderedFileContent); } return this.transpileYamlFile({ ...file, content: renderedFileContent }, errorsReport, { ...options, jinjaUsed: true }); } public get modelContext(): ModelContext { if (!this.modelContextInstance) { throw new Error('Data model is not compiled'); } return this.modelContextInstance; } public withQuery(query: BaseQuery, fn: () => T): T { const oldQuery = this.currentQuery; this.currentQuery = query; try { return fn(); } finally { this.currentQuery = oldQuery; } } public contextQuery() { return this.currentQuery; } protected async compileCubeFiles( cubes: CubeDefinition[], contexts: Record[], viewGroups: Record[], compiledFiles: Record, asyncModules: CallableFunction[], compilers: CompileCubeFilesCompilers, transpiledFiles: FileContent[], errorsReport: ErrorReporter ) { transpiledFiles .forEach((file) => { this.compileFile( file, errorsReport, compiledFiles, ); }); await asyncModules.reduce((a: Promise, b: CallableFunction) => a.then(() => b()), Promise.resolve()); return this.compileObjects(compilers.cubeCompilers || [], cubes, errorsReport) .then(() => this.compileObjects(compilers.contextCompilers || [], contexts, errorsReport)) .then(() => this.compileObjects(compilers.viewGroupCompilers || [], viewGroups, errorsReport)) .then(() => this.compileObjects(compilers.metaCompilers || [], cubes, errorsReport)); } public throwIfAnyErrors() { this.errorsReporter?.throwIfAny(); } protected compileFile( file: FileContent, errorsReport: ErrorReporter, compiledFiles: Record, { doSyntaxCheck } = { doSyntaxCheck: false } ) { if (compiledFiles[file.fileName]) { return; } compiledFiles[file.fileName] = true; // As now all types of files are transpiled to JS, // we just call JS compiler for all of them this.compileJsFile(file, errorsReport, { doSyntaxCheck }); } protected getJsScript(file: FileContent): vm.Script { // The script carries its file name (stack traces), and the cache may be shared between apps const cacheKey = crypto.createHash('md5') .update(file.fileName) .update('\0') .update(file.content) .digest('hex'); if (this.compiledScriptCache.has(cacheKey)) { return this.compiledScriptCache.get(cacheKey)!; } const script = new vm.Script(file.content, { filename: file.fileName }); this.compiledScriptCache.set(cacheKey, script); return script; } protected getSharedJsScript(file: FileContent): vm.Script { // Not the source getJsScript compiles (the wrapper), hence the prefix const cacheKey = `shared:${crypto.createHash('md5') .update(file.fileName) .update('\0') .update(file.content) .digest('hex')}`; if (this.compiledScriptCache.has(cacheKey)) { return this.compiledScriptCache.get(cacheKey)!; } // The prefix is on line 1, so a negative column offset keeps positions in stack traces intact. const prefix = sharedScriptPrefix(hasUseStrictDirective(file.content)); const script = new vm.Script(`${prefix}${file.content}${SHARED_SCRIPT_SUFFIX}`, { filename: file.fileName, columnOffset: -prefix.length, }); this.compiledScriptCache.set(cacheKey, script); return script; } public compileJsFile( file: FileContent, errorsReport: ErrorReporter, { doSyntaxCheck } = { doSyntaxCheck: false } ) { if (doSyntaxCheck) { // There is no need to run syntax check for data model files // because they were checked during transpilation/transformation phase // Only external files (included modules) might need syntax check const err = syntaxCheck(file.content, file.fileName); if (err) { errorsReport.error(err.toString()); } } try { if (this.sharedVmContext) { const script = this.getSharedJsScript(file); const scope = this.compileScope!; ctxFileStorage.run(file, () => { sharedScopeStorage.run(scope, () => { script.runInContext(getSharedVmContext(), { timeout: 15000 }); }); }); return; } const script = this.getJsScript(file); // We use AsyncLocalStorage to store the current file context // so that it can be accessed in the script execution context even within async functions. // @see https://nodejs.org/api/async_context.html#class-asynclocalstorage ctxFileStorage.run(file, () => { script.runInContext(this.compileV8ContextCache!, { timeout: 15000 }); }); } catch (e) { errorsReport.error(e); } } // Alias "securityContext" with "security_context" (snake case version) // to support snake case based data models protected cloneCompileContextWithGetterAlias(compileContext: Record | undefined) { const ctx = compileContext || {}; const clone = R.clone(ctx); clone.security_context = ctx.securityContext; return clone; } protected standaloneCompileContextProxy() { return new Proxy({}, { get: () => { throw new UserError('COMPILE_CONTEXT can\'t be used unless contextToAppId is defined. Please see https://docs.cube.dev/reference/configuration/config#context_to_app_id.'); } }); } protected resolveModuleFile(currentFile: FileContent, modulePath: string, toCompile: FileContent[], errorsReport: ErrorReporter) { const localImport = modulePath.match(/^\.\/(.*)$/); if (!currentFile.isModule && localImport) { const fileName = localImport[1].match(/^.*\.js$/) ? localImport[1] : `${localImport[1]}.js`; const foundFile = toCompile.find((f) => f.fileName === fileName); if (!foundFile) { throw new UserError(`Required import for ${fileName} is not found`); } return foundFile; } const nodeModulesPath = path.resolve('node_modules'); let absPath = currentFile.isModule ? path.resolve('node_modules', path.dirname(currentFile.fileName), modulePath) : path.resolve('node_modules', modulePath); if (!absPath.startsWith(nodeModulesPath)) { if (this.allowNodeRequire) { return null; } throw new UserError(`'${modulePath}' restricted`); } const packagePath = absPath.replace(nodeModulesPath, '').split('/').filter(s => !!s)[0]; if (!packagePath) { if (this.allowNodeRequire) { return null; } throw new UserError(`'${modulePath}' is incorrect`); } if (!this.isWhiteListedPackage(packagePath)) { if (this.allowNodeRequire) { return null; } throw new UserError(`Package '${packagePath}' not found`); } if (fs.existsSync(absPath)) { const stat = fs.lstatSync(absPath); if (stat.isDirectory()) { absPath = path.resolve(absPath, 'index.js'); } } // eslint-disable-next-line prefer-template absPath = path.extname(absPath) !== '.js' ? absPath + '.js' : absPath; if (!fs.existsSync(absPath)) { if (this.allowNodeRequire) { return null; } // eslint-disable-next-line prefer-template throw new UserError(`Path '${absPath.replace(nodeModulesPath + '/', '')}' not found`); } return this.readModuleFile(absPath, errorsReport); } protected readModuleFile(absPath: string, errorsReport: ErrorReporter) { const nodeModulesPath = path.resolve('node_modules'); if (!moduleFileCache[absPath]) { const content = fs.readFileSync(absPath, 'utf-8'); // eslint-disable-next-line prefer-template const fileName = absPath.replace(nodeModulesPath + '/', ''); const transpiled = this.transpileFile( { fileName, content, isModule: true }, errorsReport ); if (!transpiled) { throw new UserError(`'${fileName}' transpiling failed`); } moduleFileCache[absPath] = transpiled; // TODO isolated transpiling } return moduleFileCache[absPath]; } protected isWhiteListedPackage(packagePath: string): boolean { return packagePath.indexOf('-schema') !== -1 && (packagePath.indexOf('-schema') === packagePath.length - '-schema'.length); } }