Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

2.6 KB
Raw Blame
import { Knex } from "knex";

import { TableName } from "../schemas";
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";

export async function up(knex: Knex): Promise<void> {
  if (!(await knex.schema.hasTable(TableName.EventOutbox))) {
    await knex.schema.createTable(TableName.EventOutbox, (t) => {
      t.bigIncrements("id").primary();
      t.string("consumer").notNullable();
      t.string("eventType").notNullable();
      t.jsonb("payload").notNullable();
      t.string("idempotencyKey");
      t.timestamp("occurredAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
      t.string("status").notNullable().defaultTo("pending");
      t.check(`"status" IN ('pending', 'processing', 'retry', 'delivered', 'failed')`);
      t.integer("attempts").notNullable().defaultTo(0);
      t.timestamp("nextRetryAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());
      t.timestamp("lockedAt", { useTz: true });
      t.uuid("lockToken");
      t.text("lastError");
      t.timestamps(true, true, true);
    });

    // Backs discovery and the claim. `id` before `nextRetryAt` so the claim's ORDER BY needs no sort;
    // `nextRetryAt` is included so rows still in backoff are skipped without hitting the heap.
    await knex.schema.raw(`
      CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_drain_idx"
      ON "${TableName.EventOutbox}" ("consumer", "id", "nextRetryAt")
      WHERE status IN ('pending', 'retry')
    `);

    await knex.schema.raw(`
      CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_processing_idx"
      ON "${TableName.EventOutbox}" ("lockedAt")
      WHERE status = 'processing'
    `);

    // Backs the oldest-pending gauge, which runs on every relay tick; without it that's a seq scan.
    await knex.schema.raw(`
      CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_undelivered_idx"
      ON "${TableName.EventOutbox}" ("consumer", "occurredAt")
      WHERE status IN ('pending', 'retry', 'processing')
    `);

    await knex.schema.raw(`
      CREATE INDEX IF NOT EXISTS "${TableName.EventOutbox}_terminal_idx"
      ON "${TableName.EventOutbox}" ("updatedAt")
      WHERE status IN ('delivered', 'failed')
    `);

    await knex.schema.raw(`
      CREATE UNIQUE INDEX IF NOT EXISTS "${TableName.EventOutbox}_idempotency_idx"
      ON "${TableName.EventOutbox}" ("consumer", "idempotencyKey")
      WHERE "idempotencyKey" IS NOT NULL
    `);
  }

  await createOnUpdateTrigger(knex, TableName.EventOutbox);
}

export async function down(knex: Knex): Promise<void> {
  await dropOnUpdateTrigger(knex, TableName.EventOutbox);
  await knex.schema.dropTableIfExists(TableName.EventOutbox);
}