|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const { setTimeout: wait } = require('node:timers/promises') |
| 4 | +const fastify = require('fastify') |
| 5 | + |
| 6 | +// unstable service |
| 7 | + |
| 8 | +async function main () { |
| 9 | + const SLOW_START = process.env.SLOW_START || 2_000 |
| 10 | + const UNSTABLE_MIN = process.env.UNSTABLE_MIN || 1_000 |
| 11 | + const UNSTABLE_MAX = process.env.UNSTABLE_MAX || 10_000 |
| 12 | + const BLOCK_TIME = process.env.BLOCK_TIME || 5_000 |
| 13 | + |
| 14 | + const app = fastify({ logger: true }) |
| 15 | + |
| 16 | + // slow start |
| 17 | + |
| 18 | + await wait(SLOW_START) |
| 19 | + |
| 20 | + app.register(require('@fastify/websocket')) |
| 21 | + app.register(async function (app) { |
| 22 | + app.get('/', { websocket: true }, (socket) => { |
| 23 | + socket.on('message', message => { |
| 24 | + let m = message.toString() |
| 25 | + console.log('incoming message', m) |
| 26 | + m = JSON.parse(m) |
| 27 | + |
| 28 | + socket.send(JSON.stringify({ |
| 29 | + response: m.message |
| 30 | + })) |
| 31 | + }) |
| 32 | + }) |
| 33 | + }) |
| 34 | + |
| 35 | + try { |
| 36 | + const port = process.env.PORT || 3000 |
| 37 | + await app.listen({ port }) |
| 38 | + } catch (err) { |
| 39 | + app.log.error(err) |
| 40 | + process.exit(1) |
| 41 | + } |
| 42 | + |
| 43 | + if (process.env.STABLE) { |
| 44 | + return |
| 45 | + } |
| 46 | + |
| 47 | + function runProblem () { |
| 48 | + const problem = process.env.PROBLEM || (Math.random() < 0.5 ? 'crash' : 'block') |
| 49 | + const unstabilityTimeout = process.env.UNSTABLE_TIMEOUT || Math.round(UNSTABLE_MIN + Math.random() * (UNSTABLE_MAX - UNSTABLE_MIN)) |
| 50 | + |
| 51 | + if (problem === 'crash') { |
| 52 | + console.log(`Restarting (crash and restart) in ${unstabilityTimeout}ms`) |
| 53 | + setTimeout(() => { |
| 54 | + console.log('UNHANDLED EXCEPTION') |
| 55 | + throw new Error('UNHANDLED EXCEPTION') |
| 56 | + }, unstabilityTimeout).unref() |
| 57 | + } else { |
| 58 | + console.log(`Blocking EL in ${unstabilityTimeout}ms for ${BLOCK_TIME}ms`) |
| 59 | + |
| 60 | + setTimeout(() => { |
| 61 | + console.log('Block EL ...') |
| 62 | + const start = performance.now() |
| 63 | + while (performance.now() - start < BLOCK_TIME) { |
| 64 | + // just block |
| 65 | + } |
| 66 | + console.log('Block ends') |
| 67 | + runProblem() |
| 68 | + }, unstabilityTimeout).unref() |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + runProblem() |
| 73 | +} |
| 74 | + |
| 75 | +main() |
0 commit comments