Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

7.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { sql } from "kysely";
import { expect } from "vitest";
import { databaseTest } from "../fixtures/local-database";
import { chargeFixture } from "../fixtures/post-charge";
import { postChargeTransaction } from "../../../app/modules/accounting/accounting.service";

databaseTest(
  "an edit started after posting's parent lock waits and then refuses",
  async () => {
    const f = await chargeFixture();
    const poster = await f.connect();
    const writer = await f.connect();
    const posterPid = (
      await sql<{ pid: number }>`SELECT pg_backend_pid() AS pid`.execute(poster)
    ).rows[0]!.pid;
    const writerPid = (
      await sql<{ pid: number }>`SELECT pg_backend_pid() AS pid`.execute(writer)
    ).rows[0]!.pid;
    const headerLocked = Promise.withResolvers<void>();
    const resumePosting = Promise.withResolvers<void>();
    let paused = false;
    const postingDb = poster.withPlugin({
      transformQuery: ({ node }) => node,
      async transformResult({ result }) {
        if (
          !paused &&
          result.rows.some(
            (row) => row.id === f.chargeId && row.status === "Draft"
          )
        ) {
          paused = true;
          headerLocked.resolve();
          await resumePosting.promise;
        }
        return result;
      }
    });
    let posting:
      | Promise<PromiseSettledResult<{ journalId: string | null }>>
      | undefined;
    let edit: Promise<PromiseSettledResult<unknown>> | undefined;
    try {
      await sql`SET statement_timeout = '5s'`.execute(poster);
      await sql`SET statement_timeout = '5s'`.execute(writer);
      posting = postChargeTransaction(postingDb, f.args).then(
        (value) => ({ status: "fulfilled" as const, value }),
        (reason) => ({ status: "rejected" as const, reason })
      );
      await Promise.race([
        headerLocked.promise,
        posting.then((result) => {
          if (result.status === "rejected") throw result.reason;
          throw new Error(
            "Posting completed without acquiring the header lock"
          );
        })
      ]);
      edit = writer
        .updateTable("chargeLine")
        .set({
          description: "Too late"
        })
        .where("id", "=", f.lineId)
        .where("companyId", "=", f.companyId)
        .execute()
        .then(
          (value) => ({ status: "fulfilled" as const, value }),
          (reason) => ({ status: "rejected" as const, reason })
        );
      // Observe the actual lock wait before allowing posting to read its lines.
      let blocked = false;
      for (let attempt = 0; attempt < 100; attempt++) {
        const observed = await sql<{
          blocked: boolean;
        }>`SELECT ${posterPid} = ANY(pg_blocking_pids(${writerPid})) AS blocked`.execute(
          f.db
        );
        if (observed.rows[0]?.blocked) {
          blocked = true;
          break;
        }
        await new Promise((resolve) => setTimeout(resolve, 10));
      }
      expect(blocked).toBeTruthy();
      resumePosting.resolve();
      const result = await posting;
      expect(result.status).toEqual("fulfilled");
      const mutation = await edit;
      expect(mutation.status).toEqual("rejected");
      if (mutation.status === "rejected") {
        expect(String(mutation.reason).includes("immutable")).toBeTruthy();
      }
    } finally {
      resumePosting.resolve();
      await posting;
      await edit;
      await writer.destroy();
      await poster.destroy();
      await f.cleanup();
    }
  }
);

databaseTest("concurrent posting retries create one journal", async () => {
  const f = await chargeFixture();
  const left = await f.connect();
  const right = await f.connect();
  try {
    const results = await Promise.all([
      postChargeTransaction(left, f.args),
      postChargeTransaction(right, f.args)
    ]);
    expect(results[0]).toEqual(results[1]);
    expect(
      (
        await f.db
          .selectFrom("journal")
          .select("id")
          .where("companyId", "=", f.companyId)
          .where("sourceType", "=", "Charge")
          .execute()
      ).length
    ).toEqual(1);
  } finally {
    await left.destroy();
    await right.destroy();
    await f.cleanup();
  }
});

databaseTest(
  "concurrent void retries create one reversal journal",
  async () => {
    const f = await chargeFixture();
    const left = await f.connect();
    const right = await f.connect();
    try {
      const posted = await postChargeTransaction(f.db, f.args);
      const args = { ...f.args, type: "void" as const };
      const results = await Promise.all([
        postChargeTransaction(left, args),
        postChargeTransaction(right, args)
      ]);
      expect(results).toEqual([posted, posted]);
      expect(
        (
          await f.db
            .selectFrom("journal")
            .select("id")
            .where("companyId", "=", f.companyId)
            .where("sourceType", "=", "Charge")
            .execute()
        ).length
      ).toEqual(2);
      expect(
        (
          await f.db
            .selectFrom("charge")
            .select("status")
            .where("id", "=", f.chargeId)
            .where("companyId", "=", f.companyId)
            .executeTakeFirstOrThrow()
        ).status
      ).toEqual("Voided");
    } finally {
      await left.destroy();
      await right.destroy();
      await f.cleanup();
    }
  }
);

databaseTest("a line mutation holds the parent lock until commit", async () => {
  const f = await chargeFixture();
  const writer = await f.connect();
  const poster = await f.connect();
  let releaseWriter!: () => void;
  let reportWriterReady!: () => void;
  const writerReady = new Promise<void>((resolve) => {
    reportWriterReady = resolve;
  });
  const writerRelease = new Promise<void>((resolve) => {
    releaseWriter = resolve;
  });
  let heldMutation: Promise<void> | undefined;
  try {
    heldMutation = writer.transaction().execute(async (trx) => {
      await trx
        .updateTable("chargeLine")
        .set({
          description: "Committed before posting"
        })
        .where("id", "=", f.lineId)
        .where("companyId", "=", f.companyId)
        .execute();
      reportWriterReady();
      await writerRelease;
    });
    await writerReady;
    await sql`SET lock_timeout = '250ms'`.execute(poster);
    await expect(
      (() => postChargeTransaction(poster, f.args))()
    ).rejects.toThrow("lock timeout");
    releaseWriter();
    await heldMutation;
    await sql`SET lock_timeout = '0'`.execute(poster);
    const result = await postChargeTransaction(poster, f.args);
    const descriptions = await f.db
      .selectFrom("journalLine")
      .select("description")
      .where("journalId", "=", result.journalId!)
      .execute();
    expect(
      descriptions.some(
        (line) => line.description === "Committed before posting"
      )
    ).toEqual(true);
  } finally {
    releaseWriter?.();
    await heldMutation?.catch(() => undefined);
    await writer.destroy();
    await poster.destroy();
    await f.cleanup();
  }
});