0.1.4Updated 6 months ago
import { PostgresClient } from "@infinity-beyond/modules/data_store/postgres.ts";
import type { TaskProcessor } from "@infinity-beyond/modules/delegation/task_processor.ts";
import type { Infinity } from "@infinity-beyond/modules/infinity.ts";

import "https://deno.land/std@0.216.0/dotenv/load.ts";

const SIGNATURE = Deno.env.get('SIGNATURE');
if(!SIGNATURE) throw new Error('Signature value not found!\nPlease add the same secure `SIGNATURE` value to the environments of both the host and workers.');

interface State {
  Environment: 'HOST' | 'PROCESSOR',
  IS_PROCESSOR: boolean
  IS_BUILDING: boolean

  SIGNATURE: string
  PROCESSOR?: TaskProcessor
  PostgresClient: PostgresClient
  HOSTS: Infinity[]
}

const HOSTS: Infinity[] = [];
const pushHost = HOSTS.push.bind(HOSTS);

HOSTS.push = (host: Infinity) => {
  if(PROCESSOR) throw new Error('A host and processor should not run in the same instance!');
  pushHost(host);
  return HOSTS.length;
}

let PROCESSOR: TaskProcessor | undefined = undefined;

const State: State = {
  Environment: "HOST",
  HOSTS,

  IS_BUILDING: Deno.args.includes("build"),

  PostgresClient: new PostgresClient(Deno.env.get('POSTGRES_URL')!),

  get IS_PROCESSOR() {
    return this.Environment == 'PROCESSOR';
  },

  get SIGNATURE() {
    return SIGNATURE;
  },

  set PROCESSOR(processor: TaskProcessor) {
    if(HOSTS.length) throw new Error('A host and processor should not run in the same instance!');
    PROCESSOR = processor;
  },

  get PROCESSOR(): TaskProcessor | undefined {
    return PROCESSOR;
  }
}

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

export default State;