import assert from 'node:assert' import { Given, When, Then } from '@cucumber/cucumber' import { diff } from 'jest-diff' import { exceptions, instance } from '@toa.io/core' import { transpose, match, timeout } from '@toa.io/generic' import { load as parse } from 'js-yaml' import { cli } from './.connectors/cli.js' import * as stage from './.workspace/components/index.js' When( 'I debug command {word}', /** * @param {string} name * @param {import('@cucumber/cucumber').DataTable} inputs * @this {toa.features.Context} */ async function (name, inputs) { const handler = await cli(name) const argv = Object.fromEntries(inputs.raw()) this.connector = await handler(argv) } ) When( 'I boot {component} component', /** * @param {string} reference * @this {toa.features.Context} */ async function (reference) { this.connector = /** @type {import('@toa.io/core').Connector} */ await stage.component(reference) } ) When( 'I boot {component} component without waiting', /** * A boot that may be held back by what it depends on, asserted by the steps below. * * @param {string} reference * @this {toa.features.Context} */ function (reference) { const boot = stage.component(reference) this.booting = { settled: false, boot } boot.then( () => (this.booting.settled = true), () => (this.booting.settled = true) ) } ) Then( 'the component is not booted within {int} second(s)', /** * @param {number} seconds * @this {toa.features.Context} */ async function (seconds) { assert.ok(this.booting !== undefined, 'No component is booting') await timeout(seconds * 1000) assert.equal(this.booting.settled, false, 'The component has booted') } ) Then( 'the component boots within {int} second(s)', /** * @param {number} seconds * @this {toa.features.Context} */ async function (seconds) { assert.ok(this.booting !== undefined, 'No component is booting') const expired = timeout(seconds * 1000).then(() => { throw new Error(`The component has not booted within ${seconds} seconds`) }) this.connector = await Promise.race([this.booting.boot, expired]) } ) When( 'I compose {component} component without waiting', /** * A composition that may be held back by what it depends on, asserted by the step below. * * @param {string} reference * @this {toa.features.Context} */ function (reference) { const composition = stage.composition([reference], {}) this.composing = composition.then( () => undefined, () => undefined ) } ) Then( 'the composition does not settle within {int} second(s)', /** * @param {number} seconds * @this {toa.features.Context} */ async function (seconds) { assert.ok(this.composing !== undefined, 'No composition is under way') const settled = await Promise.race([ this.composing.then(() => true), timeout(seconds * 1000).then(() => false) ]) assert.equal(settled, false, 'The composition has settled') } ) When( 'I compose {component} component', /** * @param {string} reference * @this {toa.features.Context} */ async function (reference) { await stage.composition([reference], {}) } ) Given( 'calls within this process go through the broker', /** * A call that names this process is otherwise served without leaving it, so whether the * broker has the process's name is never asked. Reset after the scenario. */ function () { globalThis.TOA_INTEGRATION_BINDINGS_LOOP_DISABLED = true } ) Given( 'calls within this process go through a binding', /** * The loop answers a call to a component composed here before any binding is asked, so a * scenario about what a binding carries takes it out of the way. Reset after the scenario. */ function () { globalThis.TOA_INTEGRATION_BINDINGS_LOOP_DISABLED = true } ) Given( 'I run components:', /** * @param {import('@cucumber/cucumber').DataTable} data * @this {toa.features.Context} */ async function (data) { const references = transpose(data.raw())[0] this.workload = await stage.workload(references, {}) } ) Given( 'I run {token} service with components:', /** * A service staged apart is a process of its own, which is not the one being halted — so a * service whose own clock is what a scenario is about is run inside this one. * * @param {string} service * @param {import('@cucumber/cucumber').DataTable} data * @this {toa.features.Context} */ async function (service, data) { const references = transpose(data.raw())[0] this.workload = await stage.workload(references, {}, [service]) } ) When( 'the process is halted for {int} seconds', /** * Returns once it is down rather than once it is asked, so what follows is asserted of a * halted process and not of one on its way there. * * @param {number} seconds * @this {toa.features.Context} */ async function (seconds) { assert.ok(this.workload !== undefined, 'No process is running') this.workload.stop(seconds) await until(() => !this.workload.running(), 'the process did not halt') } ) Then( 'the process is running again', /** * @this {toa.features.Context} */ async function () { assert.ok(this.workload !== undefined, 'No process is running') await until(() => this.workload.running(), 'the process did not come back') } ) Given( 'I run {component} component', /** * The same components, as a process runs them. What belongs to the process rather than to * the composition — the readiness probe — is there only this way. * * @param {string} reference * @this {toa.features.Context} */ async function (reference) { this.workload = await stage.workload([reference], {}) } ) Then( 'I compose {component} component and it fails with:', /** * @param {string} reference * @this {toa.features.Context} */ async function (reference, errorMessage) { await assert.rejects(stage.composition([reference], {}), { message: errorMessage }) } ) Then( 'I compose {component} component and it fails with a message containing:', /** * The version a message names is a hash of sources a scenario may edit, so what is asserted * is the sentence rather than the whole of it. * * @param {string} reference * @param {string} text * @this {toa.features.Context} */ async function (reference, text) { await assert.rejects(stage.composition([reference], {}), (error) => { assert.ok( error.message.includes(text), `'${error.message}' does not contain '${text}'` ) return true }) } ) When( 'I stage {component} component', /** * @param {string} reference * @this {toa.features.Context} */ async function (reference) { await stage.composition([reference]) } ) When( 'I compose components:', /** * @param {import('@cucumber/cucumber').DataTable} data * @this {toa.features.Context} */ async function (data) { const cells = data.raw() const rows = transpose(cells) const references = rows[0] await stage.composition(references) } ) Then( 'I disconnect', /** * @this {toa.features.Context} */ async function () { if (this.connector) await this.connector.disconnect() if (this.amqp) { await this.amqp.channel.close() await this.amqp.connection.close() } } ) When( 'I invoke {token}', /** * @param {string} endpoint * @this {toa.features.Context} */ async function (endpoint) { await invoke.call(this, endpoint) } ) When( 'I invoke {token} with:', /** * @param {string} endpoint * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, yaml) { const request = parse(yaml) await invoke.call(this, endpoint, request) } ) When( 'I invoke {token} without waiting with:', /** * @param {string} endpoint * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, yaml) { const request = parse(yaml) this.invoking = invoke.call(this, endpoint, request).catch((exception) => { this.exception = exception }) } ) When( 'the invocation made without waiting ends within {int} second(s)', /** * @param {number} seconds * @this {toa.features.Context} */ async function (seconds) { const ended = await Promise.race([ this.invoking.then(() => true), timeout(seconds * 1000).then(() => false) ]) assert.ok(ended, `The invocation has not ended within ${seconds} seconds`) } ) When( 'I call {endpoint} with:', /** * @param {string} endpoint * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, yaml) { const request = parse(yaml) await call.call(this, endpoint, request) } ) When( 'I call {endpoint} on this process with:', /** * An addressed call to the process the scenario runs in, whose name is known only here. * * @param {string} endpoint * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, yaml) { const request = { ...parse(yaml), instance: instance() } await call.call(this, endpoint, request) } ) When( 'I call {endpoint} on this process until it is answered, within {int} seconds, with:', /** * A process that has lost its broker holds its name again once it is back, and a call * made in between is refused; this is the call that finds it back. * * @param {string} endpoint * @param {number} seconds * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, seconds, yaml) { const request = { ...parse(yaml), instance: instance() } const deadline = Date.now() + seconds * 1000 do { await call.call(this, endpoint, request) if (this.exception === undefined) return await new Promise((resolve) => setTimeout(resolve, 500)) } while (Date.now() < deadline) } ) When( 'I call {endpoint} {int} time(s) with:', /** * @param {string} endpoint * @param {number} times * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, times, yaml) { const request = parse(yaml) for (let i = 0; i < times; i++) await call.call(this, endpoint, request) } ) When( 'I call {endpoint} without waiting with:', /** * @param {string} endpoint * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, yaml) { const request = parse(yaml) this.calling = call.call(this, endpoint, request) } ) When( 'the call made without waiting returns', /** * Its reply or its exception, kept where the steps that read either look for them. * * @this {toa.features.Context} */ async function () { await this.calling } ) Then( 'the pending reply is not received yet', /** * @this {toa.features.Context} */ async function () { if (this.exception !== undefined) throw this.exception assert.equal(this.reply, undefined, 'Reply is received') } ) Then( 'the pending reply is received', /** * @this {toa.features.Context} */ async function () { if (this.exception !== undefined) throw this.exception await this.pendingReply } ) When( 'I call {endpoint}', /** * @param {string} endpoint * @this {toa.features.Context} */ async function (endpoint) { await call.call(this, endpoint, {}) } ) Then( 'the reply is received:', /** * @param {string} yaml * @this {toa.features.Context} */ function (yaml) { if (this.exception !== undefined) throw this.exception const expected = parse(yaml) if (Array.isArray(this.reply)) { assert.ok(Array.isArray(expected), 'Expected reply is not an array') assert.equal(this.reply.length, expected.length, diff(expected, this.reply)) } assert.equal(received(this.reply, expected), true, diff(expected, this.reply)) } ) Then( 'the reply holds {token} as nothing but:', /** * What a reply leaves out of a property is told by nothing else: `the reply is received` asks * for what is expected to be among what came. * * @param {string} property * @param {string} yaml * @this {toa.features.Context} */ function (property, yaml) { if (this.exception !== undefined) throw this.exception assert.deepStrictEqual(this.reply[property], parse(yaml)) } ) Then( 'the reply is received within {int} second(s):', /** * What an event does is done after the call that emits it has replied, so the last call * is made again until its reply is the one expected. * * @param {number} seconds * @param {string} yaml * @this {toa.features.Context} */ async function (seconds, yaml) { const expected = parse(yaml) const deadline = Date.now() + seconds * 1000 while (!received(this.reply, expected) && Date.now() < deadline) { await timeout(POLL) await call.call(this, this.called.endpoint, this.called.request) } if (this.exception !== undefined) throw this.exception assert.equal(received(this.reply, expected), true, diff(expected, this.reply)) } ) Then( 'the error is received:', /** * @param {string} yaml * @this {toa.features.Context} */ function (yaml) { if (this.exception !== undefined) { throw this.exception } if (!(this.reply instanceof Error)) { throw new Error('Reply is not an error') } const expected = parse(yaml) const matches = match(this.reply, expected) assert.equal(matches, true, diff(expected, this.reply)) } ) Then( 'the error carries nothing but:', /** * What a caller reads from an error by copying it: its own enumerable properties. * * @param {string} yaml * @this {toa.features.Context} */ function (yaml) { if (this.exception !== undefined) throw this.exception assert.equal(this.reply instanceof Error, true, 'Reply is not an error') assert.deepEqual({ ...this.reply }, parse(yaml)) } ) Then( 'the reply stream is received:', /** * @param {string} yaml * @this {toa.features.Context} */ async function (yaml) { if (this.exception !== undefined) throw this.exception const expected = parse(yaml) const received = [] for await (const chunk of this.reply) { received.push(chunk) } const matches = match(received, expected) assert.equal(matches, true, diff(expected, received)) } ) Then( 'the stream of {int} item(s) is received', /** * @param {number} expected * @this {toa.features.Context} */ async function (expected) { if (this.exception !== undefined) throw this.exception // count items in the stream let received = 0 for await (const _ of this.reply) received++ assert.equal(received, expected, diff(expected, received)) } ) Then( 'the reply is received', /** * @this {toa.features.Context} */ function () { if (this.exception !== undefined) throw this.exception assert.notStrictEqual(this.reply, undefined, 'Reply is not received') } ) Then( 'the following exception is thrown:', /** * @param {string} yaml * @this {toa.features.Context} */ function (yaml) { assert.ok(this.exception !== undefined, 'Exception is not thrown') const expected = parse(yaml) const matches = match(this.exception, expected) assert.equal(matches, true, diff(expected, this.exception)) } ) Then( 'the {label} explained is:', /** * @param {string} endpoint * @param {string} yaml * @this {toa.features.Context} */ async function (endpoint, yaml) { const operation = endpoint.split('.').pop() const remote = await stage.remote(endpoint) const explanation = remote.explain(operation) const expected = parse(yaml) const matches = match(explanation, expected) assert.equal(matches, true, diff(expected, explanation)) } ) /** * A call within the process hands the reply over as it is, while one across a process boundary * gets it encoded — a secret, for one, is `` there. */ function received(reply, expected) { return match(reply, expected) || match(encoded(reply), expected) } /** The reply as a caller across a process boundary receives it. */ function encoded(reply) { return reply !== null && typeof reply === 'object' && !(reply instanceof Error) ? JSON.parse(JSON.stringify(reply)) : reply } /** * @param {string} endpoint * @param {import('@toa.io/core/types').Request} request * @returns {Promise} */ async function invoke(endpoint, request = {}) { const component = /** @type {import('@toa.io/core').Component} */ this.connector const reply = await component.invoke(endpoint, request) if (reply === null) { this.reply = null return } if (reply.exception !== undefined) { throw reply.exception } if (reply.error !== undefined) { throw new Error(`${exceptions.names[reply.error.code]}: ${reply.error.message}`) } this.reply = reply.output } /** * @param {string} endpoint * @param {import('@toa.io/core/types').Request} request * @this {toa.features.Context} * @return {Promise} */ async function call(endpoint, request) { this.called = { endpoint, request } this.exception = undefined this.reply = undefined const [operation, component, namespace = 'default'] = endpoint.split('.').reverse() let remote try { // building the remote is part of making the call: what nothing states cannot be called remote = await stage.remote(`${namespace}.${component}`) this.pendingReply = remote.invoke(operation, request) this.reply = await this.pendingReply } catch (exception) { this.exception = exception } await remote?.disconnect() } /** * @param {() => boolean} condition * @param {string} failure */ async function until(condition, failure) { const deadline = Date.now() + LIMIT while (Date.now() < deadline) { if (condition()) return await timeout(POLL) } assert.fail(failure) } /** A halt is at least thirty seconds, and the teardown and the rebuild are either side of it. */ const LIMIT = 90_000 const POLL = 250