Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@
.claude/worktrees
.claude/settings.local.json
*.DS_Store

# Local environment files may contain credentials. Commit explicit templates only.
.env
.env.*
!.env*.example

# Generated Gitea development data, including database and private keys.
/peopleportal/gitea/

# Local compose files contain development-only credentials; use dev-stack instead.
/docker-compose.yml
/peopleportal/docker-compose.yml

peopleportal/server/.env.development

# Bootstrap script outputs (contain credentials)
Expand Down
381 changes: 381 additions & 0 deletions peopleportal/server/src/clients/AgendaClient/Jobs/index.ts

Large diffs are not rendered by default.

69 changes: 68 additions & 1 deletion peopleportal/server/src/clients/AgendaClient/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,26 @@
import mongoose from "mongoose";
import { Agenda } from "agenda";
import { MongoBackend } from "@agendajs/mongo-backend";
import { DefinedJobs, JobSchedulingData, RecurringJobs } from "./Jobs";
import {
DefinedJobs,
JobSchedulingData,
RecurringJobs,
reconcileApplicationStageUpdateLocks,
recoverQueuedBulkApplicationUpdates,
} from "./Jobs";
import { logger } from "../../utils/logger";

// Agenda exports this channel at runtime but omits it from its root type declarations.
const { InMemoryNotificationChannel } = require("agenda") as {
InMemoryNotificationChannel: new () => Parameters<
Agenda["notifyVia"]
>[0];
};

export class AgendaClient {
private static readonly TAG = "AgendaClient";
private static readonly ATS_RECOVERY_JOB =
"recoverQueuedBulkApplicationUpdates";
private agenda: Agenda | undefined;

constructor() {
Expand All @@ -41,6 +57,7 @@ export class AgendaClient {
mongo: mongoose.connection.db!,
}),
processEvery: dbQueryInterval,
notificationChannel: new InMemoryNotificationChannel(),
});

// Define all jobs
Expand All @@ -50,6 +67,14 @@ export class AgendaClient {
this.agenda!.define(key, job.workerFunction, job.options);
});

this.agenda!.define(AgendaClient.ATS_RECOVERY_JOB, async () => {
await this.reconcileAtsOperations();
});
await this.agenda!.every(
"5 minutes",
AgendaClient.ATS_RECOVERY_JOB,
);

for (const entry of RecurringJobs) {
// Agenda automatically checks for duplicates.
/* Awaited: an unawaited every() swallowed scheduling failures, so a
Expand All @@ -63,10 +88,41 @@ export class AgendaClient {
}

await this.agenda.start();
try {
await this.reconcileAtsOperations();
} catch (error: unknown) {
logger.error(
{ err: error },
"Initial ATS operation reconciliation failed; the recurring recovery job will retry",
);
}
}

// Schedule a job to be run one time.
public async scheduleJobOnce(jobData: JobSchedulingData) {
const payload = jobData.jobPayload;
if (
jobData.jobName === "sendBulkApplicationUpdates" &&
payload !== undefined &&
typeof payload === "object" &&
payload !== null &&
"jobId" in payload &&
typeof payload.jobId === "string"
) {
await this.agenda!
.create(jobData.jobName, payload)
.unique(
{
name: jobData.jobName,
"data.jobId": payload.jobId,
},
{ insertOnly: true },
)
.schedule(jobData.runAt)
.save();
return;
}

await this.agenda!.schedule(
jobData.runAt,
jobData.jobName,
Expand All @@ -78,6 +134,17 @@ export class AgendaClient {
public async cancelJob(jobName: string, jobData: object) {
await this.agenda!.cancel({ name: jobName, data: jobData });
}

private async reconcileAtsOperations(): Promise<void> {
await recoverQueuedBulkApplicationUpdates(async (jobId) => {
await this.scheduleJobOnce({
runAt: new Date(),
jobName: "sendBulkApplicationUpdates",
jobPayload: { jobId },
});
});
await reconcileApplicationStageUpdateLocks();
}
}

export const agendaClient = new AgendaClient();
63 changes: 63 additions & 0 deletions peopleportal/server/src/clients/WebhookClient/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { createHmac } from "crypto";

export interface WebhookEvent {
id: string;
type: string;
occurredAt: string;
data: Record<string, unknown>;
}

export type WebhookDeliveryStatus = "disabled" | "delivered";

const WEBHOOK_URL_ENV = "PEOPLEPORTAL_ATS_WEBHOOK_URL";
const WEBHOOK_SECRET_ENV = "PEOPLEPORTAL_ATS_WEBHOOK_SECRET";
const MIN_SECRET_LENGTH = 32;

export class WebhookClient {
async send(event: WebhookEvent): Promise<WebhookDeliveryStatus> {
const endpoint = process.env[WEBHOOK_URL_ENV]?.trim();
const secret = process.env[WEBHOOK_SECRET_ENV];

if (!endpoint && !secret) return "disabled";
if (!endpoint || !secret) {
throw new Error(
`${WEBHOOK_URL_ENV} and ${WEBHOOK_SECRET_ENV} must be configured together`,
);
}
if (secret.length < MIN_SECRET_LENGTH) {
throw new Error(
`${WEBHOOK_SECRET_ENV} must be at least ${MIN_SECRET_LENGTH} characters long`,
);
}

const url = new URL(endpoint);
const isLocalHttp =
url.protocol === "http:" &&
["localhost", "127.0.0.1", "::1"].includes(url.hostname);
if (url.protocol !== "https:" && !isLocalHttp) {
throw new Error("ATS webhook endpoint must use HTTPS");
}

const body = JSON.stringify(event);
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature = createHmac("sha256", secret)
.update(`${timestamp}.${body}`)
.digest("hex");
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-PeoplePortal-Event": event.type,
"X-PeoplePortal-Delivery": event.id,
"X-PeoplePortal-Signature": `t=${timestamp},v1=${signature}`,
},
body,
signal: AbortSignal.timeout(10_000),
});

if (!response.ok) {
throw new Error(`ATS webhook returned HTTP ${response.status}`);
}
return "delivered";
}
}
Loading