import fs from 'node:fs/promises' import { Worker } from 'node:worker_threads' import { config } from 'dotenv-defaults' import autocannon from 'autocannon' config() if (!process.env.FRONTEND_PATH) throw new Error('You need to set "process.env.FRONTEND_PATH"') const frontendPath = process.env.FRONTEND_PATH // 1. check if a UI is present (env variable and http check) const result = await fetch(new URL('manifest.json', frontendPath)) if (!result.ok) throw new Error(`Cannot find UI at "${frontendPath}"`) const configPath = './config/config.yaml' const oldConfigPath = './config/config-old.yaml' if (!process.env.UI_MIDDLEWARE_PATH) { // 2. create configuration file, store old config try { await fs.stat(configPath) await fs.copyFile(configPath, oldConfigPath) } catch (e) {} fs.writeFile(configPath, ` baseUrls: - ${frontendPath} `) // 3. start the ui-middleware const worker = new Worker('./src/index.js', { env: { LOG_LEVEL: 'warn' } }) worker.on('error', err => console.error(err)) process.env.UI_MIDDLEWARE_PATH = `http://localhost:${process.env.PORT}/` } const uiMWPath = process.env.UI_MIDDLEWARE_PATH // 4. collect manifests from the ui-container (or already do that in 1.) const manifests = await result.json() // 5.1 setup autocannon with cold cache console.log('Setup finished, start autocannon...') await new Promise(resolve => setTimeout(resolve, 50)) const coldCacheResult = await autocannon({ url: uiMWPath, connections: 1, duration: 60, requests: Object.values(manifests).map(({ file }) => ({ path: new URL(file, uiMWPath).href })), workers: 5 }) // 6.1 handle result await new Promise(resolve => setTimeout(resolve, 50)) console.log('Autocannon results with cold cache:') console.log(autocannon.printResult(coldCacheResult)) // 5.2 setup autocannon options with all files console.log('Setup finished, start autocannon with warm cache...') await new Promise(resolve => setTimeout(resolve, 50)) const warmCacheResult = await autocannon({ url: uiMWPath, connections: 1, duration: 60, requests: Object.values(manifests).map(({ file }) => ({ path: new URL(file, uiMWPath).href })), workers: 5 }) // 6.2 handle result await new Promise(resolve => setTimeout(resolve, 50)) console.log('Autocannon results with warm cache:') console.log(autocannon.printResult(warmCacheResult)) // 7. restore old config try { await fs.stat(oldConfigPath) await fs.copyFile(oldConfigPath, configPath) await fs.rm(oldConfigPath) } catch (e) {} // force exit, because the server is still running process.exit(0)