Verifier Recipe

Verify a Business Result in a Database

Query an authoritative database and prove that a business condition is true—not merely that the database is reachable.

Canonical BRS contractIndependently executableBRS-Core ready
Business question

Did the business process produce the result we expected?

A successful database connection only proves that the database is reachable. This verifier asks the authoritative system a business question and validates the returned result.

Configuration

Environment: DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_QUERY, MIN_EXPECTED_RESULT

The read-only query must return one numeric column aliased as result. Requires mysql2 and Node.js 24 or later.

Recipe structure

The top-level executable entry file sits beside a same-named directory that owns the canonical implementation and its dependency manifest. Run npm install once in that directory and retain the generated package-lock.json:

verifiers/
├── verify-database-business-result.js
└── verify-database-business-result/
    ├── package.json
    └── verify-database-business-result.js

The canonical contract stays at the boundary.

The implementation exports the canonical verifier object: id, label, schedule.interval, schedule.timeout, and asynchronous verify() returning structured summary and steps. The top-level file exports that exact object unchanged, adds validated standalone execution, and is what BRS-Core discovers.

Top-level executable entry file

verifiers/verify-database-business-result.js

#!/usr/bin/env node
'use strict';

const verifier = require('./verify-database-business-result/verify-database-business-result');

module.exports = verifier;

if (require.main === module) {
    void runStandalone(verifier);
}

async function runStandalone(standaloneVerifier) {
    let timeoutHandle;

    try {
        const timeout = standaloneVerifier.schedule?.timeout ?? 30;

        if (!Number.isInteger(timeout) || timeout <= 0) {
            throw new Error('schedule.timeout must be a positive integer');
        }

        const timeoutPromise = new Promise((_, reject) => {
            timeoutHandle = setTimeout(() => {
                const error = new Error(
                    `Standalone verifier execution timed out after ${timeout} seconds.`
                );
                error.code = 'BRS_TIMEOUT';
                reject(error);
            }, timeout * 1000);
        });
        const result = await Promise.race([
            Promise.resolve().then(() => standaloneVerifier.verify()),
            timeoutPromise
        ]);

        validateResult(result);
        await writeStream(
            process.stdout,
            `${JSON.stringify(result, null, 2)}\n`
        );
        process.exit(result.steps.some((step) => !step.success) ? 1 : 0);
    } catch (error) {
        const summary = error?.code === 'BRS_TIMEOUT'
            ? error.message
            : error?.code === 'BRS_INVALID_RESULT'
                ? 'Standalone verifier returned a malformed result.'
                : 'Standalone verifier execution failed unexpectedly.';

        await Promise.all([
            writeStream(
                process.stdout,
                `${JSON.stringify({ summary, steps: [] }, null, 2)}\n`
            ),
            writeStream(process.stderr, `${sanitize(error?.message)}\n`)
        ]);
        process.exit(1);
    } finally {
        clearTimeout(timeoutHandle);
    }
}

function validateResult(result) {
    const names = new Set();
    const valid = result &&
        typeof result === 'object' &&
        !Array.isArray(result) &&
        typeof result.summary === 'string' &&
        result.summary.trim() !== '' &&
        Array.isArray(result.steps) &&
        result.steps.length > 0 &&
        result.steps.every((step) => {
            const uniqueName = step &&
                /^[a-z][a-z0-9_]*$/.test(step.name) &&
                !names.has(step.name);

            if (uniqueName) names.add(step.name);

            return uniqueName &&
                typeof step.label === 'string' &&
                step.label.trim() !== '' &&
                typeof step.success === 'boolean' &&
                Number.isFinite(step.durationSeconds) &&
                step.durationSeconds >= 0 &&
                typeof step.message === 'string' &&
                step.message.trim() !== '' &&
                typeof step.checkedAt === 'string' &&
                Number.isFinite(Date.parse(step.checkedAt));
        }) &&
        (result.observations === undefined ||
            Array.isArray(result.observations));

    if (!valid) {
        const error = new Error('verifier result is malformed');
        error.code = 'BRS_INVALID_RESULT';
        throw error;
    }
}

function writeStream(stream, value) {
    return new Promise((resolve, reject) => {
        stream.write(value, (error) => error ? reject(error) : resolve());
    });
}

function sanitize(value) {
    return String(value || 'Unknown error')
        .split(/\r?\n/, 1)[0]
        .replace(/[\u0000-\u001f\u007f]/g, ' ')
        .slice(0, 500);
}

Verifier implementation

verifiers/verify-database-business-result/verify-database-business-result.js

'use strict';

const mysql = require('mysql2/promise');
const path = require('node:path');

module.exports = {
    id: 'database_business_result',
    label: 'Database Business Result',
    schedule: {
        interval: 300,
        timeout: 30
    },

    async verify() {
        loadLocalEnvironment();

        const startedAt = Date.now();
        const steps = [];
        let connection;

        try {
            const minimum = finiteNumber('MIN_EXPECTED_RESULT', 1);

            connection = await mysql.createConnection({
                host: required('DB_HOST'),
                user: required('DB_USER'),
                password: required('DB_PASSWORD'),
                database: required('DB_NAME')
            });

            const [rows] = await connection.execute(
                required('DB_QUERY')
            );
            const actual = Number(rows[0]?.result);

            if (!Number.isFinite(actual) || actual < minimum) {
                throw new Error(
                    'Business result did not meet the expected minimum.'
                );
            }

            steps.push(step(
                'verify_business_result',
                'Verify Business Result',
                true,
                startedAt,
                'The database business result met the expected minimum.'
            ));
        } catch (error) {
            logFailure('verify_business_result', error);
            steps.push(step(
                'verify_business_result',
                'Verify Business Result',
                false,
                startedAt,
                'The expected database business result was not verified.'
            ));
        } finally {
            if (connection) await connection.end();
        }

        return {
            summary: steps[0].success
                ? 'The database business condition is true.'
                : 'The database business condition is not true.',
            steps
        };
    }
};

function loadLocalEnvironment() {
    try {
        process.loadEnvFile(path.join(__dirname, '.env'));
    } catch (error) {
        if (!error || error.code !== 'ENOENT') throw error;
    }
}

function required(name) {
    const value = String(process.env[name] || '').trim();

    if (!value) throw new Error(`${name} is required`);
    return value;
}

function finiteNumber(name, fallback) {
    const raw = String(process.env[name] || '').trim();
    const number = raw === '' ? fallback : Number(raw);

    if (!Number.isFinite(number)) {
        throw new Error(`${name} must be a finite number`);
    }

    return number;
}

function logFailure(name, error) {
    const detail = sanitize(error instanceof Error ? error.message : error);

    console.error(
        `verifier=database_business_result step=${name} error="${detail}"`
    );
}

function sanitize(value) {
    return String(value || 'Unknown error')
        .split(/\r?\n/, 1)[0]
        .replace(/[\u0000-\u001f\u007f]/g, ' ')
        .replace(/\\/g, '\\\\')
        .replace(/"/g, '\\"')
        .slice(0, 500);
}

function step(name, label, success, startedAt, message) {
    return {
        name,
        label,
        success,
        durationSeconds: Number(
            ((Date.now() - startedAt) / 1000).toFixed(3)
        ),
        message,
        checkedAt: new Date().toISOString()
    };
}

Dependency manifest

verifiers/verify-database-business-result/package.json

{
  "name": "brs-verifier-database-business-result",
  "version": "1.0.0",
  "private": true,
  "type": "commonjs",
  "scripts": {
    "verify": "node ../verify-database-business-result.js"
  },
  "dependencies": {
    "mysql2": "3.23.2"
  },
  "engines": {
    "node": ">=24"
  }
}

Run it directly

cd verify-database-business-result
npm install
npm run verify

A passing run writes validated structured JSON to standard output and exits 0. A business failure includes a failed step and exits 1. A timeout, malformed result, or unexpected execution error writes a runner-generated JSON result and exits 1.

Run it continuously with BRS-Core

This verifier does not require BRS-Core to execute. Direct execution is part of the verifier contract and makes development, troubleshooting, CI/CD use, and manual diagnostics straightforward.

BRS-Core can run this verifier alongside your other approved verifiers continuously as part of 24/7 business capability monitoring. Because every recipe presents the same canonical contract, Core can discover and schedule these verifiers together, run them independently, enforce their timeouts, record their results, and expose their signals to the monitoring environment.