Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
all-files.js 2.52 KiB
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
})