import State from "@infinity-beyond/modules/state.ts";
import { randomUUID } from "node:crypto";
export interface I_InfinityRequestStep {
timestamp: number
step_name: string
}
export interface I_InfinityRequest {
id?: number
request_id: string
user_key: string
steps: I_InfinityRequestStep[]
timestamp_start: Date
timestamp_end: Date
duration: number
}
export interface InfinityRequest extends I_InfinityRequest {}
export class InfinityRequest {
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)`,
[ this.request_id, this.timestamp_start, this.timestamp_end, this.duration, this.steps ]
);
}
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);
`);
}
});
}
}
await InfinityRequest.Setup();