/
bundler.ts
363 lines (330 loc) · 13.1 KB
/
bundler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import * as realFS from 'node:fs';
import { builtinModules } from 'node:module';
import path from 'node:path';
import util from 'node:util';
import * as unionfs from 'unionfs';
import * as memfs from 'memfs';
import { Configuration, webpack } from 'webpack';
import { DefaultLogger, Logger } from '../logger';
import { toMB } from '../utils';
export const defaultWorkflowInterceptorModules = [require.resolve('../workflow-log-interceptor')];
export const allowedBuiltinModules = ['assert', 'url'];
export const disallowedBuiltinModules = builtinModules.filter((module) => !allowedBuiltinModules.includes(module));
export const disallowedModules = [
...disallowedBuiltinModules,
'@temporalio/activity',
'@temporalio/client',
'@temporalio/worker',
'@temporalio/common/lib/internal-non-workflow',
'@temporalio/interceptors-opentelemetry/lib/client',
'@temporalio/interceptors-opentelemetry/lib/worker',
'@temporalio/testing',
'@temporalio/core-bridge',
];
export function moduleMatches(userModule: string, modules: string[]): boolean {
return modules.some((module) => userModule === module || userModule.startsWith(`${module}/`));
}
export interface WorkflowBundleWithSourceMap {
/**
* Source maps are generated inline - this is no longer used
* @deprecated
*/
sourceMap: string;
code: string;
}
/**
* Builds a V8 Isolate by bundling provided Workflows using webpack.
*
* @param workflowsPath all Workflows found in path will be put in the bundle
* @param workflowInterceptorModules list of interceptor modules to register on Workflow creation
*/
export class WorkflowCodeBundler {
private foundProblematicModules = new Set<string>();
public readonly logger: Logger;
public readonly workflowsPath: string;
public readonly workflowInterceptorModules: string[];
protected readonly payloadConverterPath?: string;
protected readonly failureConverterPath?: string;
protected readonly ignoreModules: string[];
protected readonly webpackConfigHook: (config: Configuration) => Configuration;
constructor({
logger,
workflowsPath,
payloadConverterPath,
failureConverterPath,
workflowInterceptorModules,
ignoreModules,
webpackConfigHook,
}: BundleOptions) {
this.logger = logger ?? new DefaultLogger('INFO');
this.workflowsPath = workflowsPath;
this.payloadConverterPath = payloadConverterPath;
this.failureConverterPath = failureConverterPath;
this.workflowInterceptorModules = workflowInterceptorModules ?? [];
this.ignoreModules = ignoreModules ?? [];
this.webpackConfigHook = webpackConfigHook ?? ((config) => config);
}
/**
* @return a {@link WorkflowBundle} containing bundled code, including inlined source map
*/
public async createBundle(): Promise<WorkflowBundleWithSourceMap> {
const vol = new memfs.Volume();
const ufs = new unionfs.Union();
/**
* readdir and exclude sourcemaps and d.ts files
*/
function readdir(...args: Parameters<typeof realFS.readdir>) {
// Help TS a bit because readdir has multiple signatures
const callback: (err: NodeJS.ErrnoException | null, files: string[]) => void = args.pop() as any;
const newArgs: Parameters<typeof realFS.readdir> = [
...args,
(err: Error | null, files: string[]) => {
if (err !== null) {
callback(err, []);
return;
}
callback(
null,
files.filter((f) => /\.[jt]s$/.test(path.extname(f)) && !f.endsWith('.d.ts'))
);
},
] as any;
return realFS.readdir(...newArgs);
}
// Cast because the type definitions are inaccurate
const memoryFs = memfs.createFsFromVolume(vol);
ufs.use(memoryFs as any).use({ ...realFS, readdir: readdir as any });
const distDir = '/dist';
const entrypointPath = this.makeEntrypointPath(ufs, this.workflowsPath);
this.genEntrypoint(vol, entrypointPath);
const bundleFilePath = await this.bundle(ufs, memoryFs, entrypointPath, distDir);
let code = memoryFs.readFileSync(bundleFilePath, 'utf8') as string;
// Replace webpack's module cache with an object injected by the runtime.
// This is the key to reusing a single v8 context.
code = code.replace(
'var __webpack_module_cache__ = {}',
'var __webpack_module_cache__ = globalThis.__webpack_module_cache__'
);
this.logger.info('Workflow bundle created', { size: `${toMB(code.length)}MB` });
// Cast because the type definitions are inaccurate
return {
sourceMap: 'deprecated: this is no longer in use\n',
code,
};
}
protected makeEntrypointPath(fs: typeof unionfs.ufs, workflowsPath: string): string {
const stat = fs.statSync(workflowsPath);
if (stat.isFile()) {
// workflowsPath is a file; make the entrypoint a sibling of that file
const { root, dir, name } = path.parse(workflowsPath);
return path.format({ root, dir, base: `${name}-autogenerated-entrypoint.cjs` });
} else {
// workflowsPath is a directory; make the entrypoint a sibling of that directory
const { root, dir, base } = path.parse(workflowsPath);
return path.format({ root, dir, base: `${base}-autogenerated-entrypoint.cjs` });
}
}
/**
* Creates the main entrypoint for the generated webpack library.
*
* Exports all detected Workflow implementations and some workflow libraries to be used by the Worker.
*/
protected genEntrypoint(vol: typeof memfs.vol, target: string): void {
const interceptorImports = [...new Set(this.workflowInterceptorModules)]
.map((v) => `require(/* webpackMode: "eager" */ ${JSON.stringify(v)})`)
.join(', \n');
const code = `
const api = require('@temporalio/workflow/lib/worker-interface.js');
api.overrideGlobals();
exports.api = api;
exports.importWorkflows = function importWorkflows() {
return require(/* webpackMode: "eager" */ ${JSON.stringify(this.workflowsPath)});
}
exports.importInterceptors = function importInterceptors() {
return [
${interceptorImports}
];
}
`;
try {
vol.mkdirSync(path.dirname(target), { recursive: true });
} catch (err: any) {
if (err.code !== 'EEXIST') throw err;
}
vol.writeFileSync(target, code);
}
/**
* Run webpack
*/
protected async bundle(
inputFilesystem: typeof unionfs.ufs,
outputFilesystem: memfs.IFs,
entry: string,
distDir: string
): Promise<string> {
const captureProblematicModules: Configuration['externals'] = async (data, _callback): Promise<undefined> => {
// Ignore the "node:" prefix if any.
const module: string = data.request?.startsWith('node:')
? data.request.slice('node:'.length)
: data.request ?? '';
if (moduleMatches(module, disallowedModules) && !moduleMatches(module, this.ignoreModules)) {
this.foundProblematicModules.add(module);
}
return undefined;
};
const options: Configuration = {
resolve: {
// https://webpack.js.org/configuration/resolve/#resolvemodules
modules: [path.resolve(__dirname, 'module-overrides'), 'node_modules'],
extensions: ['.ts', '.js'],
extensionAlias: { '.js': ['.ts', '.js'] },
alias: {
__temporal_custom_payload_converter$: this.payloadConverterPath ?? false,
__temporal_custom_failure_converter$: this.failureConverterPath ?? false,
...Object.fromEntries([...this.ignoreModules, ...disallowedModules].map((m) => [m, false])),
},
},
externals: captureProblematicModules,
module: {
rules: [
{
test: /\.js$/,
enforce: 'pre',
use: [require.resolve('source-map-loader')],
},
{
test: /\.ts$/,
exclude: /node_modules/,
use: {
loader: require.resolve('swc-loader'),
options: {
sourceMap: true,
jsc: {
target: 'es2017',
parser: {
syntax: 'typescript',
decorators: true,
},
},
},
},
},
],
},
entry: [entry],
mode: 'development',
devtool: 'inline-source-map',
output: {
path: distDir,
filename: 'workflow-bundle-[fullhash].js',
devtoolModuleFilenameTemplate: '[absolute-resource-path]',
library: '__TEMPORAL__',
},
ignoreWarnings: [/Failed to parse source map/],
};
const compiler = webpack(this.webpackConfigHook(options));
// Cast to any because the type declarations are inaccurate
compiler.inputFileSystem = inputFilesystem as any;
// Don't use ufs due to a strange bug on Windows:
// https://github.com/temporalio/sdk-typescript/pull/554
compiler.outputFileSystem = outputFilesystem as any;
try {
return await new Promise<string>((resolve, reject) => {
compiler.run((err, stats) => {
if (stats !== undefined) {
const hasError = stats.hasErrors();
// To debug webpack build:
// const lines = stats.toString({ preset: 'verbose' }).split('\n');
const lines = stats.toString({ chunks: false, colors: true, errorDetails: true }).split('\n');
for (const line of lines) {
this.logger[hasError ? 'error' : 'info'](line);
}
if (hasError) {
reject(
new Error(
"Webpack finished with errors, if you're unsure what went wrong, visit our troubleshooting page at https://docs.temporal.io/dev-guide/typescript/debugging#webpack-errors"
)
);
}
if (this.foundProblematicModules.size) {
const err = new Error(
`Your Workflow code (or a library used by your Workflow code) is importing the following disallowed modules:\n` +
Array.from(this.foundProblematicModules)
.map((module) => ` - '${module}'\n`)
.join('') +
`These modules can't be used in workflow context as they might break determinism.` +
`HINT: Consider the following options:\n` +
` • Make sure that activity code is not imported from workflow code. Use \`import type\` to import activity function signatures.\n` +
` • Move code that has non-deterministic behaviour to activities.\n` +
` • If you know for sure that a disallowed module will not be used at runtime, add its name to 'WorkerOptions.bundlerOptions.ignoreModules' in order to dismiss this warning.\n` +
`See also: https://typescript.temporal.io/api/interfaces/worker.workeroptions/#bundleroptions and https://docs.temporal.io/typescript/determinism.`
);
reject(err);
}
const outputFilename = Object.keys(stats.compilation.assets)[0];
if (!err) {
resolve(path.join(distDir, outputFilename));
}
}
reject(err);
});
});
} finally {
await util.promisify(compiler.close).bind(compiler)();
}
}
}
/**
* Options for bundling Workflow code using Webpack
*/
export interface BundleOptions {
/**
* Path to look up workflows in, any function exported in this path will be registered as a Workflows when the bundle is loaded by a Worker.
*/
workflowsPath: string;
/**
* List of modules to import Workflow interceptors from.
*
* Modules should export an `interceptors` variable of type {@link WorkflowInterceptorsFactory}.
*/
workflowInterceptorModules?: string[];
/**
* Optional logger for logging Webpack output
*/
logger?: Logger;
/**
* Path to a module with a `payloadConverter` named export.
* `payloadConverter` should be an instance of a class that implements {@link PayloadConverter}.
*/
payloadConverterPath?: string;
/**
* Path to a module with a `failureConverter` named export.
* `failureConverter` should be an instance of a class that implements {@link FailureConverter}.
*/
failureConverterPath?: string;
/**
* List of modules to be excluded from the Workflows bundle.
*
* Use this option when your Workflow code references an import that cannot be used in isolation,
* e.g. a Node.js built-in module. Modules listed here **MUST** not be used at runtime.
*
* > NOTE: This is an advanced option that should be used with care.
*/
ignoreModules?: string[];
/**
* Before Workflow code is bundled with Webpack, `webpackConfigHook` is called with the Webpack
* {@link https://webpack.js.org/configuration/ | configuration} object so you can modify it.
*/
webpackConfigHook?: (config: Configuration) => Configuration;
}
/**
* Create a bundle to pass to {@link WorkerOptions.workflowBundle}. Helpful for reducing Worker startup time in
* production.
*
* When using with {@link Worker.runReplayHistory}, make sure to pass the same interceptors and payload converter used
* when the history was generated.
*/
export async function bundleWorkflowCode(options: BundleOptions): Promise<WorkflowBundleWithSourceMap> {
const bundler = new WorkflowCodeBundler(options);
return await bundler.createBundle();
}