30 lines · 1012 B
import { env } from "cloudflare:workers";
import { sha256Hex } from "../crypto";

export type PushParams = {
  source: "proxy" | "internal" | "artifacts";
  repoId: string | null;
  artifactsName: string | null;
  ref: string;
  before: string;
  after: string;
  pusherId: string | null;
};

export async function pushEventId(repoKey: string, ref: string, before: string, after: string): Promise<string> {
  return (await sha256Hex(`${repoKey}\n${ref}\n${before}\n${after}`)).slice(0, 48);
}

/** Starts durable push processing. Instance ids are deterministic so duplicate triggers collapse. */
export async function triggerPush(
  params: Omit<PushParams, "artifactsName"> & { artifactsName: string },
): Promise<void> {
  const id = await pushEventId(params.artifactsName, params.ref, params.before, params.after);
  try {
    await env.PUSH_WORKFLOW.create({ id, params });
  } catch (error) {
    if (error instanceof Error && /already exists|duplicate/i.test(error.message)) return;
    throw error;
  }
}