import assert from 'node:assert' import { randomUUID } from 'node:crypto' import { Given, Then, When } from '@cucumber/cucumber' import { diff } from 'jest-diff' import { match } from '@toa.io/generic' import { load as parse } from 'js-yaml' // events emitted while a receiver isn't composed pile up in its durable queue and are // delivered in a burst the next time it starts, so a scenario asserting on what the // receiver has processed has to start from an empty queue Given( 'the {component} event queues are empty', /** * @param {string} id */ async function (id) { const queues = await request('/queues') const suffix = '..' + id for (const { name } of queues) if (name.endsWith(suffix)) await request(`/queues/%2F/${encodeURIComponent(name)}/contents`, 'DELETE') } ) // a task a scenario before left behind — one that raised is tried again for minutes — is taken by // the next scenario to compose the component, as a task of its own Given( 'the {component} task queue is empty', /** * @param {string} id */ async function (id) { await request( `/queues/%2F/${encodeURIComponent(tasksQueueOf(id))}/contents`, 'DELETE' ).catch(() => { // never composed on this broker, so nothing declared it }) } ) // what comq parks a message in, once it is one nothing will process. One queue takes what // every source parked, and a message names the queue it came from in `x-comq-queue` const PARKED = 'comq.parked' Given('the parked queue is empty', async function () { await request(`/queues/%2F/${PARKED}/contents`, 'DELETE').catch(() => { // nothing has been parked on this broker yet, so comq has not declared it }) }) Then( '{component} parks {int} message(s) on the first delivery', /** * A message read rather than counted: the management API's totals come from the statistics * database and lag it by seconds. `ack_requeue_true` puts back what it reads, so asking * again is free. * * @param {string} id * @param {number} expected */ async function (id, expected) { const suffix = '..' + id const deadline = Date.now() + PARKING let parked = [] do { const messages = await request(`/queues/%2F/${PARKED}/get`, 'POST', { count: 100, ackmode: 'ack_requeue_true', encoding: 'auto' }).catch(() => []) parked = messages.filter( ({ properties }) => properties.headers?.['x-comq-queue']?.endsWith(suffix) === true ) if (parked.length === expected) break await new Promise((resolve) => setTimeout(resolve, 100)) } while (Date.now() < deadline) assert.equal(parked.length, expected, `'${id}' has ${parked.length} parked messages`) for (const message of parked) assert.equal( message.properties.headers?.['x-comq-attempt'], undefined, 'the message was retried before it was parked' ) } ) Then( '{component} consumes {int} task queue(s)', /** * Counted by consumer rather than by name: the broker of a development machine keeps * whatever earlier runs declared, and a queue nothing consumes is one of those. * * @param {string} id * @param {number} expected */ async function (id, expected) { const deadline = Date.now() + COUNTING let consumed = [] do { const queues = await request('/queues') consumed = queues .filter(({ name, consumers }) => isTaskQueueOf(name, id) && consumers > 0) .map(({ name }) => name) if (consumed.length === expected) break await new Promise((resolve) => setTimeout(resolve, 200)) } while (Date.now() < deadline) assert.equal( consumed.length, expected, `'${id}' consumes ${consumed.length} task queue(s): ${consumed.join(', ')}` ) } ) When( 'a task naming {token} is published to {component}', /** * What a caller running ahead of this component sends: a task for an operation it has * and this one does not. * * @param {string} endpoint * @param {string} id */ async function (endpoint, id) { const published = await request('/exchanges/%2F/amq.default/publish', 'POST', { properties: { content_type: 'application/json', delivery_mode: 2, headers: { 'toa.io/endpoint': endpoint } }, routing_key: tasksQueueOf(id), payload: JSON.stringify({ input: null, query: {} }), payload_encoding: 'string' }) assert.equal(published.routed, true, `Nothing is bound to '${tasksQueueOf(id)}'`) } ) Given( 'the requests queue of {component} is declared', /** * As a replica still serving the component would have declared it: a broker nothing has * composed the component on yet holds no such queue, and a request published there is dropped. * * @param {string} id */ async function (id) { await request(`/queues/%2F/${encodeURIComponent(requestsQueueOf(id))}`, 'PUT', { durable: true }) } ) When( 'a request naming {token} is published to {component}', /** * What a caller running ahead of this component sends: a request for an operation it has * and this one does not. It is answered on a queue of this scenario's own. * * @param {string} endpoint * @param {string} id * @this {toa.features.Context} */ async function (endpoint, id) { this.answers = 'features.answers.' + randomUUID() await request(`/queues/%2F/${this.answers}`, 'PUT', { durable: false, arguments: { 'x-expires': ANSWERING * 2 } }) const published = await request('/exchanges/%2F/amq.default/publish', 'POST', { properties: { content_type: 'application/json', correlation_id: randomUUID(), reply_to: this.answers, headers: { 'toa.io/endpoint': endpoint } }, routing_key: requestsQueueOf(id), payload: JSON.stringify({ input: null, query: {} }), payload_encoding: 'string' }) assert.equal(published.routed, true, `Nothing is bound to '${requestsQueueOf(id)}'`) } ) Then( 'the request is answered with the exception:', /** * @param {string} yaml * @this {toa.features.Context} */ async function (yaml) { const expected = parse(yaml) const deadline = Date.now() + ANSWERING let answer do { const messages = await request(`/queues/%2F/${this.answers}/get`, 'POST', { count: 1, ackmode: 'ack_requeue_false', encoding: 'auto' }) answer = messages[0] if (answer !== undefined) break await new Promise((resolve) => setTimeout(resolve, 100)) } while (Date.now() < deadline) assert.notEqual(answer, undefined, 'The request is not answered') const reply = JSON.parse(answer.payload) assert.equal(match(reply.exception, expected), true, diff(expected, reply.exception)) } ) Then( 'the request to {component} is not answered within {int} second(s)', /** * What nothing consumes stays where it was published, and is taken off, so that the next * scenario to compose the component is not given it. * * @param {string} id * @param {number} seconds * @this {toa.features.Context} */ async function (id, seconds) { const deadline = Date.now() + seconds * 1000 do { const messages = await request(`/queues/%2F/${this.answers}/get`, 'POST', { count: 1, ackmode: 'ack_requeue_false', encoding: 'auto' }) assert.equal(messages[0], undefined, 'The request is answered') await new Promise((resolve) => setTimeout(resolve, 100)) } while (Date.now() < deadline) await request( `/queues/%2F/${encodeURIComponent(requestsQueueOf(id))}/contents`, 'DELETE' ) } ) Then( '{component} keeps the task at once, saying it named {token}', /** * @param {string} id * @param {string} endpoint */ async function (id, endpoint) { await kept(id, endpoint) } ) Then( '{component} keeps the task at once, saying {token}', /** * @param {string} id * @param {string} reason what the reason it was kept for names */ async function (id, reason) { await kept(id, reason) } ) Then( 'the queue {string} is consumed', /** * @param {string} name */ async function (name) { await consumers(name, (count) => count > 0, `'${name}' is not consumed`) } ) Then( 'the queue {string} is not consumed', /** * A queue an earlier run declared is left on the broker, so what is asserted is that nothing * consumes it, not that it is absent. * * @param {string} name */ async function (name) { await consumers(name, (count) => count === 0, `'${name}' is consumed`) } ) /** * Waits for the number of consumers of a queue to satisfy `condition`, reading an absent queue as * one nobody consumes. * * @param {string} name * @param {(count: number) => boolean} condition * @param {string} failure */ async function consumers(name, condition, failure) { const deadline = Date.now() + COUNTING let count = 0 do { const queue = await request(`/queues/%2F/${encodeURIComponent(name)}`).catch( () => undefined ) count = queue?.consumers ?? 0 if (condition(count)) return await new Promise((resolve) => setTimeout(resolve, 200)) } while (Date.now() < deadline) assert.fail(`${failure}: ${count} consumer(s)`) } /** @param {string} id */ const tasksQueueOf = (id) => id + '..tasks' /** @param {string} id */ const requestsQueueOf = (id) => id + '..requests' /** * @param {string} name * @param {string} id */ const isTaskQueueOf = (name, id) => name.startsWith(id + '.') && name.endsWith('..tasks') /** how long a message may take to reach the queue it is kept in */ const PARKING = 5000 /** how long an answer may take to arrive */ const ANSWERING = 5000 /** * How long a consumer may take to appear in the statistics the management API reads. A queue * reports its statistics every five seconds and the management database takes them in on an * interval of its own, so a consumer that has just arrived is counted up to ten seconds later — * and a wait of exactly that long loses to it about every other time. */ const COUNTING = 20000 /** * @param {string} path * @param {string} [method] * @returns {Promise} */ async function request(path, method = 'GET', body) { const response = await fetch(MANAGEMENT + path, { method, headers: { authorization: AUTHORIZATION, ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, body: body === undefined ? undefined : JSON.stringify(body) }) if (!response.ok) throw new Error( `RabbitMQ management ${method} ${path} responded with ${response.status}` ) // a declaration and a deletion are answered with nothing const text = await response.text() if (text !== '') return JSON.parse(text) } const MANAGEMENT = 'http://localhost:31011/api' const AUTHORIZATION = 'Basic ' + Buffer.from('developer:secret').toString('base64') /** * A task of `id` in the parked queue, kept on its first delivery for a reason that names `named`. * * @param {string} id * @param {string} named */ async function kept(id, named) { const queue = tasksQueueOf(id) const deadline = Date.now() + PARKING let kept do { const messages = await request(`/queues/%2F/${PARKED}/get`, 'POST', { count: 100, ackmode: 'ack_requeue_true', encoding: 'auto' }).catch(() => []) kept = messages.find( ({ properties }) => properties.headers?.['x-comq-queue'] === queue ) if (kept !== undefined) break await new Promise((resolve) => setTimeout(resolve, 100)) } while (Date.now() < deadline) assert.notEqual(kept, undefined, `Nothing from '${queue}' is in '${PARKED}'`) const headers = kept.properties.headers assert.equal( headers['x-comq-attempt'], undefined, 'the task was tried again before it was kept' ) assert.ok( headers['x-comq-reason']?.includes(named) === true, `the kept task says '${headers['x-comq-reason']}'` ) }