0.1.5Updated 6 months ago
import State from "@infinity-beyond/modules/state.ts";
import { randomUUID } from "node:crypto";

export const InfinityRequestMetaSchema = {
  total_requests: 'int',
  total_consumptions: 'int',
  aggregate_total: 'int',
}

export class InfinityRequest implements I_InfinityRequest {
  id?: number
  request_id: string
  user_key?: string
  steps: I_InfinityRequestStep[]
  timestamp_start: Date
  timestamp_end?: Date
  duration?: number

  private saved: boolean = false;

  constructor() {
    this.request_id = randomUUID();
    this.steps = [];
    this.timestamp_start = new Date();
  }

  finish_without_saving() {
    this.timestamp_end = new Date();
    this.duration = this.timestamp_end.valueOf() - this.timestamp_start.valueOf();
  }

  finish() {
    this.finish_without_saving();

    if(this.saved) throw new Error('Request already saved!');

    this.saved = true;

    State.PostgresClient.query(`
      INSERT INTO _requests
        ("request_id", "timestamp_start", "timestamp_end", "duration", "steps")
      VALUES
        ($1, $2, $3, $4, $5);
      -- UPDATE {requests_meta_table} SET value = value + 1 WHERE key='total_requests';`,
      [ this.request_id, this.timestamp_start, this.timestamp_end, this.duration, this.steps ]
    );
    // TODO: Actually add requests_meta_table and uncomment SQL
  }

  static get requests_table() {
    return `_requests`;
  }

  static async Setup() {
    const requests_table = this.requests_table;

    await State.PostgresClient.CreateTable<I_InfinityRequest>(this.requests_table, {
      id: "SERIAL PRIMARY KEY",
      request_id: "VARCHAR(36) NOT NULL",
      user_key: "VARCHAR(36)",
      steps: "jsonb NOT NULL",
      timestamp_start: "timestamptz NOT NULL",
      timestamp_end: "timestamptz NOT NULL DEFAULT NOW()",
      duration: "int NOT NULL"
    }, {
      async onCreate() {
        await State.PostgresClient.query(`
          CREATE INDEX ${requests_table}_request_id_idx ON ${requests_table} using hash(request_id);
          CREATE INDEX ${requests_table}_timestamp_start_idx ON ${requests_table} (timestamp_start);
          CREATE INDEX ${requests_table}_user_key_idx ON ${requests_table} using hash(user_key);
        `);
      }
    });
  }
}

if(!State.IS_BUILDING) await InfinityRequest.Setup();