0.1.0Updated 7 months ago
import { PostgresClient } from "./data_store/postgres.ts";
import type { TaskProcessor } from "./delegation/task_processor.ts";
import type Host from "./host/host.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
  SIGNATURE: string
  PROCESSOR?: TaskProcessor
  HOSTS: Host[]
  PostgresClient: PostgresClient
}

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

HOSTS.push = (host: Host) => {
  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,

  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;
  }
}

await State.PostgresClient.Setup();

export default State;