All files / src/connection statement-timeout.ts

90.47% Statements 19/21
87.5% Branches 7/8
66.66% Functions 4/6
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77    132x                                                   90x 81x       9x                   2x     2x 2x 2x   2x 2x                 7x 7x 7x 7x 3x 3x   4x 4x         11x      
import type { Client } from './connection-types.ts';
 
const SET = 'SELECT set_config($1, $2, true)';
 
/**
 * Per-query `statement_timeout`: applied with `set_config(..., true)`, so the value is transaction-local
 * and never reaches a pooled connection. The timeout value is a validated integer and is bound.
 */
export class StatementTimeout {
  /**
   * Runs `work` with `statement_timeout` set to `milliseconds`.
   *
   * Outside a transaction the work runs in its own `BEGIN … COMMIT` on the client. Inside one the previous
   * value is restored afterwards, so later statements of the transaction keep their timeout.
   *
   * @param client - Connection the work runs on.
   * @param inTransaction - Whether `client` already holds a transaction.
   * @param milliseconds - Timeout; `0` disables it.
   * @param work - The query to run.
   * @returns The result of `work`.
   * @throws Error when `milliseconds` is not a non-negative integer.
   */
  async run<T>(
    client: Pick<Client, 'query'>,
    inTransaction: boolean,
    milliseconds: number,
    work: () => Promise<T>,
  ): Promise<T> {
    if (!Number.isSafeInteger(milliseconds) || milliseconds < 0) {
      throw new Error(
        `statementTimeout must be a non-negative integer, got ${String(milliseconds)}`,
      );
    }
    return inTransaction
      ? this.#inTransaction(client, milliseconds, work)
      : this.#alone(client, milliseconds, work);
  }
 
  async #inTransaction<T>(
    client: Pick<Client, 'query'>,
    milliseconds: number,
    work: () => Promise<T>,
  ): Promise<T> {
    const previous = await client.query({
      text: "SELECT current_setting('statement_timeout') AS value",
    });
    await StatementTimeout.#set(client, String(milliseconds));
    try {
      return await work();
    } finally {
      const value = (previous.rows[0] as { value: string } | undefined)?.value ?? '0';
      await StatementTimeout.#set(client, value).catch(() => undefined);
    }
  }
 
  async #alone<T>(
    client: Pick<Client, 'query'>,
    milliseconds: number,
    work: () => Promise<T>,
  ): Promise<T> {
    await client.query({ text: 'BEGIN' });
    try {
      await StatementTimeout.#set(client, String(milliseconds));
      const result = await work();
      await client.query({ text: 'COMMIT' });
      return result;
    } catch (error) {
      await client.query({ text: 'ROLLBACK' }).catch(() => undefined);
      throw error;
    }
  }
 
  static #set(client: Pick<Client, 'query'>, value: string): Promise<unknown> {
    return client.query({ text: SET, values: ['statement_timeout', value] });
  }
}