import assert from 'node:assert' import { After, Given, Then, When } from '@cucumber/cucumber' import { MongoClient } from 'mongodb' Given( 'the {component} database in {string} is empty', /** * The database a scope names, where the one a step does not name is `toa-dev`. * * @param {string} id * @param {string} database */ async function (id, database) { await using( id, async (collection, outbox, db, inbox) => { await collection.deleteMany({}) await outbox.drop().catch(() => undefined) await inbox.drop().catch(() => undefined) await forget(db, collection) }, database ) } ) Given( 'the {component} database in {string} contains:', /** * @param {string} id * @param {string} database * @param {import('@cucumber/cucumber').DataTable} table */ async function (id, database, table) { const documents = parse(table) await using( id, async (collection, outbox, db, inbox) => { await collection.deleteMany({}) await outbox.drop().catch(() => undefined) await inbox.drop().catch(() => undefined) await forget(db, collection) if (documents.length > 0) await collection.insertMany(documents) }, database ) } ) Then( 'the {component} collection in {string} holds:', /** * @param {string} id * @param {string} database * @param {import('@cucumber/cucumber').DataTable} table */ async function (id, database, table) { await holds(id, table, database) } ) Then( 'the {component} database holds:', /** * What a scenario reads back. Not `database contains`, which is what a scenario writes: it * seeds whatever keyword it is given, so as an outcome it replaces what it was meant to read. * * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table */ async function (id, table) { await holds(id, table) } ) Then( 'the {component} database holds within {int} second(s):', /** * For what arrives on a schedule the scenario does not keep — a redelivery after an outage, * which is as far away as whatever went down takes to come back. * * @param {string} id * @param {number} seconds * @param {import('@cucumber/cucumber').DataTable} table */ async function (id, seconds, table) { const deadline = Date.now() + seconds * 1000 while (Date.now() < deadline) { try { return await holds(id, table) } catch (error) { if (!(error instanceof assert.AssertionError)) throw error } await new Promise((resolve) => setTimeout(resolve, 250)) } await holds(id, table) } ) Then( 'the {component} database holds nothing', /** * What a refusal leaves behind: not a row, live or settled. * * @param {string} id */ async function (id) { await using(id, async (collection) => { const documents = await collection.find().toArray() assert.equal(documents.length, 0, `there is ${JSON.stringify(documents)}`) }) } ) Given( 'the {component} database contains:', /** * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table * @this {toa.features.Context} */ async function (id, table) { await seed(id, parse(table)) } ) Given( 'the {component} database contains, with its timestamps as numbers:', /** * What a release that did not write them as dates left behind. * * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table */ async function (id, table) { await seed(id, parse(table, false)) } ) /** * @param {string} id * @param {object[]} documents */ async function seed(id, documents) { await using(id, async (collection, outbox, db, inbox) => { await collection.deleteMany({}) // dropped, not emptied: the collection is created at boot, and one left behind by an // earlier scenario would read as one this scenario's boot created await outbox.drop().catch(() => undefined) await inbox.drop().catch(() => undefined) await forget(db, collection) if (documents.length > 0) await collection.insertMany(documents) }) } Given( 'the {component} database is empty', /** * @param {string} id */ async function (id) { await using(id, async (collection, outbox, db, inbox) => { await collection.deleteMany({}) await outbox.drop().catch(() => undefined) await inbox.drop().catch(() => undefined) await forget(db, collection) }) } ) Given( 'the {component} outbox contains:', /** * Seeding a row directly is the post-crash state: the entity was written, the event was * not published, and nothing is left to publish it but the pump. */ async function (id, table) { const rows = parse(table).map(({ event, ...rest }) => ({ published: false, ...rest, event: json(event) })) await using(id, async (_, outbox) => { if (rows.length > 0) await outbox.insertMany(rows) }) } ) When('I make the {component} outbox rows due', async function (id) { await using(id, async (_, outbox) => outbox.updateMany({}, { $set: { pending: 0 } })) }) Then('the {component} outbox is empty', async function (id) { await using(id, async (_, outbox) => assert.strictEqual(await outbox.countDocuments({}), 0) ) }) Then('the {component} outbox holds {int} row(s)', async function (id, count) { await using(id, async (_, outbox) => assert.strictEqual(await outbox.countDocuments({}), count) ) }) Then('the {component} outbox holds {int} published row(s)', async function (id, count) { await using(id, async (_, outbox) => assert.strictEqual(await outbox.countDocuments({ published: true }), count) ) }) Then('the {component} outbox holds {int} unpublished row(s)', async function (id, count) { await using(id, async (_, outbox) => assert.strictEqual(await outbox.countDocuments({ published: false }), count) ) }) Then( 'the {component} outbox collection does not exist', /** * The collection is created at boot beside the entity's, so its absence is the assertion * that nothing was set up to publish. */ async function (id) { await using(id, async (_, outbox, db) => { const found = await db.listCollections({ name: outbox.collectionName }).toArray() assert.strictEqual( found.length, 0, `outbox collection '${outbox.collectionName}' exists` ) }) } ) Given( 'the {component} inbox contains:', /** * Seeding a record directly is the state of a call already answered, which is how a duplicate * arriving after the first one finished is tested without making the first one. */ async function (id, table) { const records = parse(table).map(({ reply, ...rest }) => ({ at: new Date(), ...rest, reply: json(reply) })) await using(id, async (_, __, ___, inbox) => { if (records.length > 0) await inbox.insertMany(records) }) } ) Then('the {component} inbox holds {int} record(s)', async function (id, count) { await using(id, async (_, __, ___, inbox) => assert.strictEqual(await inbox.countDocuments({}), count) ) }) Then( 'the {component} inbox holds {int} record(s) within {int} second(s)', /** * For what MongoDB does on its own schedule rather than in answer to a call — a TTL pass. */ async function (id, count, seconds) { const deadline = Date.now() + seconds * 1000 let held while (Date.now() < deadline) { await using( id, async (_, __, ___, inbox) => (held = await inbox.countDocuments({})) ) if (held === count) return await new Promise((resolve) => setTimeout(resolve, 250)) } assert.strictEqual(held, count) } ) Then( 'the {component} inbox record {token} expires {int} seconds after it was made', async function (id, key, seconds) { await using(id, async (_, __, ___, inbox) => { const record = await inbox.findOne({ _id: key }) assert.ok(record !== null, `no inbox record '${key}'`) assert.ok(record.expires instanceof Date, `inbox record '${key}' has no expiry`) assert.strictEqual(record.expires.getTime() - record.at.getTime(), seconds * 1000) }) } ) Given( 'the {component} inbox is indexed with {token} on {token} expiring after {int} seconds', /** an index of the shape an earlier release made, which a boot is to replace */ async function (id, name, field, seconds) { await using(id, async (_, __, ___, inbox) => { await inbox.createIndex({ [field]: 1 }, { name, expireAfterSeconds: seconds }) }) } ) Then('the {component} inbox is indexed with {token} alone', async function (id, name) { await using(id, async (_, __, ___, inbox) => { const names = (await inbox.listIndexes().toArray()).map((index) => index.name) assert.deepStrictEqual( names.filter((n) => n !== '_id_'), [name] ) }) }) Given( 'MongoDB reaps expired documents every second', /** * The TTL pass runs every sixty seconds unless told otherwise; this tells it otherwise for the * scenario, and the hook below puts it back. */ async function () { await ttl(1) reaping = true } ) After(async function () { if (!reaping) return reaping = false await ttl(60) }) let reaping = false async function ttl(seconds) { const client = new MongoClient(URL) await client.connect() try { await client.db('admin').command({ setParameter: 1, ttlMonitorSleepSecs: seconds }) } finally { await client.close() } } Then( 'the {component} inbox collection does not exist', /** * The collection is created at boot beside the entity's, so its absence is the assertion that * nothing was set up to remember a call. */ async function (id) { await using(id, async (_, __, db, inbox) => { const found = await db.listCollections({ name: inbox.collectionName }).toArray() assert.strictEqual( found.length, 0, `inbox collection '${inbox.collectionName}' exists` ) }) } ) Then('the {component} outbox row carries an origin', async function (id) { await using(id, async (_, outbox) => { const [row] = await outbox.find({}).sort({ _id: -1 }).limit(1).toArray() assert.ok(row !== undefined, 'no outbox row') assert.ok( row.event.origin !== undefined && row.event.origin !== null, 'outbox row has no origin: ' + JSON.stringify(row.event) ) }) }) Then( 'the {component} record matches the last reply', /** * The post-image an assignment returns is computed from the pre-image rather than read * back, so this asserts the computation still mirrors the update it stands for. * * @this {toa.features.Context} */ async function (id) { const reply = this.reply await using(id, async (collection) => { const stored = await collection.findOne({ _id: reply.id }) assert.ok(stored !== null, 'record not found') const { _id, ...rest } = stored // the timestamps are stored as dates and answered as the milliseconds the entity carries for (const name of TIMESTAMPS) if (rest[name] instanceof Date) rest[name] = rest[name].getTime() assert.deepStrictEqual({ id: _id, ...rest }, reply) }) } ) Then( 'the {component} collection holds:', /** * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table * @this {toa.features.Context} */ async function (id, table) { await using(id, async (collection) => { for (const document of parse(table)) { const found = await collection.findOne(document) assert.ok( found !== null, `no record matching ${JSON.stringify(document)}, there is ` + JSON.stringify(await collection.find().toArray()) ) } }) } ) Given( 'the {component} migration {word} is recorded', /** * A migration whose row says it is done is one no replica applies, which is what makes a * scenario boot a component that has already migrated. * * @param {string} id * @param {string} migration * @this {toa.features.Context} */ async function (id, migration) { await using(id, async (collection, _, db) => { await db.collection('system_migrations').replaceOne( { _id: `${collection.collectionName}:${migration}` }, { state: 'done', owner: 'features', started: new Date(), heartbeat: new Date(), completed: new Date() }, { upsert: true } ) }) } ) Then( 'the {component} collection has indexes:', /** * The `keys` column is the index specification as the driver reports it, so a changed * declaration is visible here as a changed spec under the same name. * * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table * @this {toa.features.Context} */ async function (id, table) { await using(id, async (collection) => { const indexes = await collection.listIndexes().toArray() for (const { name, keys, unique, sparse } of table.hashes()) { const index = indexes.find((candidate) => candidate.name === name) assert.ok( index !== undefined, `index '${name}' not found, there is ${indexes.map((i) => i.name).join(', ')}` ) if (keys !== undefined) assert.deepStrictEqual(index.key, JSON.parse(keys)) if (unique !== undefined) assert.strictEqual(index.unique === true, unique === 'true') if (sparse !== undefined) assert.strictEqual(index.sparse === true, sparse === 'true') } }) } ) Then( 'the {component} migrations are recorded:', /** * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table * @this {toa.features.Context} */ async function (id, table) { await using(id, async (collection, _, db) => { const rows = await db .collection('system_migrations') .find({ _id: { $regex: `^${collection.collectionName}:` } }) .toArray() for (const { migration, state } of table.hashes()) { const row = rows.find( ({ _id }) => _id === `${collection.collectionName}:${migration}` ) assert.ok( row !== undefined, `migration '${migration}' is not recorded, there is ` + rows.map(({ _id }) => _id).join(', ') ) assert.strictEqual(row.state, state) } }) } ) /** * Migrations are applied once for a database and their rows outlive a scenario, so a component * whose structure a scenario has just reset would keep the one an earlier run gave it — * including one an edited migration file no longer describes. */ async function forget(db, collection) { await db .collection('system_migrations') .deleteMany({ _id: { $regex: `^${collection.collectionName}:` } }) } /** * @param {import('@cucumber/cucumber').DataTable} table * @param {boolean} [moments] whether a timestamp is stored as the date the runtime writes */ function parse(table, moments = true) { const columns = table.raw()[0] const rows = table.rows() const documents = [] for (let r = 0; r < rows.length; r++) { const document = {} for (let c = 0; c < columns.length; c++) { const str = rows[r][c] const int = parseInt(str) document[columns[c]] = int.toString() === str ? int : str === 'null' ? null : ISO.test(str) ? new Date(str) : NESTED.test(str) ? JSON.parse(str) : str } // a table states a timestamp as the entity carries it; the storage holds it as a date if (moments) for (const name of TIMESTAMPS) if (typeof document[name] === 'number') document[name] = new Date(document[name]) documents.push(document) } return documents } const TIMESTAMPS = ['CREATED', 'UPDATED', 'DELETED'] /** what a cell is read as, where `parse` has not read it already: an object comes read */ const json = (cell) => (typeof cell === 'string' ? JSON.parse(cell) : cell) /** an object or an array a property holds is written as JSON */ const NESTED = /^[{[]/ /** a moment written as ISO 8601 is stored as the date it names */ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/ /** * @param {string} id * @param {import('@cucumber/cucumber').DataTable} table * @param {string} [database] */ async function holds(id, table, database = DATABASE) { await using( id, async (collection) => { for (const document of parse(table)) { const found = await collection.findOne(document) assert.ok( found !== null, `no record matching ${JSON.stringify(document)} in '${database}', there is ` + JSON.stringify(await collection.find().toArray()) ) } }, database ) } async function using(id, fn, database = DATABASE) { const client = new MongoClient(URL) await client.connect() const [name, namespace = 'default'] = id.split('.').reverse() const collname = `${namespace}_${name}`.toLowerCase() const db = client.db(database) try { await fn( db.collection(collname), db.collection(collname + '_outbox'), db, db.collection(collname + '_inbox') ) } finally { await client.close() } } const URL = 'mongodb://developer:secret@localhost:31020' /** what a process under `TOA_DEV=1` with no context and no suffix writes to */ const DATABASE = 'toa-dev' Then( 'the {component} collection holds {token} as dates', /** * What `collection holds` cannot say where the value is not known: that the property is * stored as a date in every record, rather than as the number it was given. * * @param {string} id * @param {string} property */ async function (id, property) { await using(id, async (collection) => { const records = await collection.find().toArray() assert.ok(records.length > 0, 'the collection holds no records') for (const record of records) assert.ok( record[property] instanceof Date, `${property} of ${record._id} is ${JSON.stringify(record[property])}, not a date` ) }) } ) Then( 'the {component} collection holds {int} record(s)', /** * What `collection holds` cannot say: that nothing else is there. * * @param {string} id * @param {number} count */ async function (id, count) { await using(id, async (collection) => assert.strictEqual(await collection.countDocuments({}), count) ) } ) Given( 'entry {token} of {component} is written by a transaction left open', /** * A commit in flight: the entry is written as `touch` writes it, ten added and its version * moved, and nobody else sees it until the transaction ends. A transaction that writes the * same entry meanwhile is refused as a write conflict, which the server counts. * * @param {string} entry * @param {string} id */ async function (entry, id) { const client = new MongoClient(URL) await client.connect() const [name, namespace = 'default'] = id.split('.').reverse() const collection = client .db(DATABASE) .collection(`${namespace}_${name}`.toLowerCase()) const session = client.startSession() holding = { client, session, conflicts: await conflicts(client) } session.startTransaction() await collection.updateOne( { _id: entry }, { $inc: { count: 10, VERSION: 1 } }, { session } ) } ) When('a write to the entry held open has been refused', async function () { const deadline = Date.now() + 10_000 while ((await conflicts(holding.client)) === holding.conflicts) { assert.ok(Date.now() < deadline, 'no write to the entry held open has been refused') await new Promise((resolve) => setTimeout(resolve, 50)) } }) When('the transaction holding the entry is {word}', async function (end) { if (end === 'committed') await holding.session.commitTransaction() else if (end === 'aborted') await holding.session.abortTransaction() else throw new Error(`a transaction is committed or aborted, not ${end}`) }) After(async function () { if (holding === undefined) return const { client, session } = holding holding = undefined if (session.inTransaction()) await session.abortTransaction() await session.endSession() await client.close() }) /** @type {{ client: MongoClient, session: import('mongodb').ClientSession, conflicts: number } | undefined} */ let holding /** the write conflicts the server has counted since it started */ async function conflicts(client) { const status = await client.db('admin').command({ serverStatus: 1 }) return status.metrics.operation.writeConflicts }