summaryrefslogtreecommitdiff
path: root/hooks/server
diff options
context:
space:
mode:
Diffstat (limited to 'hooks/server')
-rw-r--r--hooks/server/ci.ts55
-rw-r--r--hooks/server/health.ts16
-rw-r--r--hooks/server/job/activity.ts100
-rw-r--r--hooks/server/job/mod.ts2
-rw-r--r--hooks/server/job/queuer.ts78
-rw-r--r--hooks/server/mod.ts40
6 files changed, 247 insertions, 44 deletions
diff --git a/hooks/server/ci.ts b/hooks/server/ci.ts
new file mode 100644
index 0000000..cdb8372
--- /dev/null
+++ b/hooks/server/ci.ts
@@ -0,0 +1,55 @@
+import {
+ FourOhFourActivityImpl,
+ getRequiredEnv,
+ HealthCheckActivityImpl,
+ type HealthChecker,
+ type IFourOhFourActivity,
+ type IHealthCheckActivity,
+ type ITraceable,
+ PenguenoRequest,
+ type ServerTrace,
+ TraceUtil,
+} from "@emprespresso/pengueno";
+import type { Job } from "@emprespresso/ci-model";
+import {
+ healthCheck as _healthCheck,
+ type IJobHookActivity,
+ type IJobQueuer,
+ JobHookActivityImpl,
+ LaminarJobQueuer,
+} from "@emprespresso/ci-hooks";
+
+export class LizCIServer {
+ constructor(
+ healthCheck: HealthChecker = _healthCheck,
+ jobQueuer: IJobQueuer<ITraceable<Job, ServerTrace>> = new LaminarJobQueuer(
+ getRequiredEnv("LAMINAR_URL").fold((err, val) =>
+ err ? "https://ci.liz.coffee" : val
+ ),
+ ),
+ private readonly healthCheckActivity: IHealthCheckActivity =
+ new HealthCheckActivityImpl(healthCheck),
+ private readonly jobHookActivity: IJobHookActivity =
+ new JobHookActivityImpl(jobQueuer),
+ private readonly fourOhFourActivity: IFourOhFourActivity =
+ new FourOhFourActivityImpl(),
+ ) {}
+
+ private route(req: ITraceable<PenguenoRequest, ServerTrace>) {
+ const url = new URL(req.get().url);
+ if (url.pathname === "/health") {
+ return this.healthCheckActivity.checkHealth(req);
+ }
+ if (url.pathname === "/job") {
+ return this.jobHookActivity.processHook(req);
+ }
+ return this.fourOhFourActivity.fourOhFour(req);
+ }
+
+ public serve(req: Request): Promise<Response> {
+ return PenguenoRequest.from(req)
+ .bimap(TraceUtil.withClassTrace(this))
+ .map(this.route)
+ .get();
+ }
+}
diff --git a/hooks/server/health.ts b/hooks/server/health.ts
index 41dfcb4..2f67aa4 100644
--- a/hooks/server/health.ts
+++ b/hooks/server/health.ts
@@ -1,23 +1,25 @@
import {
getRequiredEnv,
getStdout,
+ type HealthChecker,
type HealthCheckInput,
HealthCheckOutput,
type IEither,
type ITraceable,
+ type ServerTrace,
TraceUtil,
} from "@emprespresso/pengueno";
-export const healthCheck = <Trace>(
- input: ITraceable<HealthCheckInput, Trace>,
+export const healthCheck: HealthChecker = (
+ input: ITraceable<HealthCheckInput, ServerTrace>,
): Promise<IEither<Error, HealthCheckOutput>> =>
input.bimap(TraceUtil.withFunctionTrace(healthCheck))
.move(getRequiredEnv("LAMINAR_HOST"))
- // we need to test LAMINAR_HOST is propagated to getStdout for other procedures
- .map(({ item }) => item.moveRight(["laminarc", "show-jobs"]))
+ // ensure LAMINAR_HOST is propagated to getStdout for other procedures
+ .map((e) => e.get().moveRight(["laminarc", "show-jobs"]))
.map((i) =>
- i.item.mapRight(i.move.apply)
+ i.get().mapRight(i.move.apply)
.flatMapAsync(getStdout.apply)
- .then((gotJobs) => gotJobs.moveRight(HealthCheckOutput.YAASQUEEN))
+ .then((gotJobs) => gotJobs.moveRight(HealthCheckOutput.YAASSSLAYQUEEN))
)
- .item;
+ .get();
diff --git a/hooks/server/job/activity.ts b/hooks/server/job/activity.ts
new file mode 100644
index 0000000..14ea459
--- /dev/null
+++ b/hooks/server/job/activity.ts
@@ -0,0 +1,100 @@
+import {
+ Either,
+ ErrorSource,
+ type IActivity,
+ type IEither,
+ type ITraceable,
+ jsonModel,
+ JsonResponse,
+ LogLevel,
+ Metric,
+ PenguenoError,
+ type PenguenoRequest,
+ type ServerTrace,
+ TraceUtil,
+ validateExecutionEntries,
+} from "@emprespresso/pengueno";
+import { isJob, type Job } from "@emprespresso/ci-model";
+import type { IJobQueuer } from "@emprespresso/ci-hooks";
+
+const wellFormedJobMetric = Metric.fromName("Job.WellFormed");
+
+const jobJsonTransformer = (
+ j: ITraceable<unknown, ServerTrace>,
+): IEither<PenguenoError, Job> =>
+ j.bimap(TraceUtil.withMetricTrace(wellFormedJobMetric))
+ .map((tJson) => {
+ if (!isJob(tJson) || !validateExecutionEntries(tJson)) {
+ const err = "seems like a pwetty mawfomed job \\(-.-)/";
+ tJson.trace.addTrace(LogLevel.WARN).trace(err);
+ return Either.left<PenguenoError, Job>(new PenguenoError(err, 400));
+ }
+ return Either.right<PenguenoError, Job>(tJson);
+ })
+ .peek((tJob) =>
+ tJob.trace.trace(
+ tJob.get().fold((err) =>
+ err ? wellFormedJobMetric.failure : wellFormedJobMetric.success
+ ),
+ )
+ )
+ .get();
+
+export interface IJobHookActivity {
+ processHook: IActivity;
+}
+
+const jobHookRequestMetric = Metric.fromName("JobHook.process");
+export class JobHookActivityImpl implements IJobHookActivity {
+ constructor(
+ private readonly queuer: IJobQueuer<ITraceable<Job, ServerTrace>>,
+ ) {}
+
+ private trace(r: ITraceable<PenguenoRequest, ServerTrace>) {
+ return r.bimap(TraceUtil.withClassTrace(this))
+ .bimap(
+ TraceUtil.withMetricTrace(jobHookRequestMetric),
+ );
+ }
+
+ public processHook(r: ITraceable<PenguenoRequest, ServerTrace>) {
+ return this.trace(r).map(jsonModel(jobJsonTransformer))
+ .map(async (tEitherJobJson) => {
+ const eitherJob = await tEitherJobJson.get();
+ return eitherJob.flatMapAsync(async (job) => {
+ const eitherQueued = await tEitherJobJson.move(job)
+ .map(this.queuer.queue)
+ .get();
+ return eitherQueued.mapLeft((e) => new PenguenoError(e.message, 500));
+ });
+ })
+ .peek(
+ TraceUtil.promiseify((tJob) =>
+ tJob.get().fold(
+ (err: PenguenoError | undefined, _val: string | undefined) => {
+ if (!err) {
+ tJob.trace.trace(jobHookRequestMetric.success);
+ tJob.trace.trace(`all queued up and weady to go :D !! ${_val}`);
+ return;
+ }
+ tJob.trace.trace(
+ err.source === ErrorSource.SYSTEM
+ ? jobHookRequestMetric.failure
+ : jobHookRequestMetric.warn,
+ );
+ tJob.trace.addTrace(err.source).trace(`${err}`);
+ },
+ )
+ ),
+ )
+ .map(
+ TraceUtil.promiseify((tEitherQueuedJob) =>
+ new JsonResponse(r, tEitherQueuedJob.get(), {
+ status: tEitherQueuedJob.get()
+ .fold(({ status }, _val) => _val ? 200 : status),
+ })
+ ),
+ )
+ .get();
+ }
+}
diff --git a/hooks/server/job/mod.ts b/hooks/server/job/mod.ts
new file mode 100644
index 0000000..6b4ae85
--- /dev/null
+++ b/hooks/server/job/mod.ts
@@ -0,0 +1,2 @@
+export * from "./activity.ts";
+export * from "./queuer.ts";
diff --git a/hooks/server/job/queuer.ts b/hooks/server/job/queuer.ts
new file mode 100644
index 0000000..6094183
--- /dev/null
+++ b/hooks/server/job/queuer.ts
@@ -0,0 +1,78 @@
+import {
+ getStdout,
+ type IEither,
+ type ITraceable,
+ LogLevel,
+ type Mapper,
+ memoize,
+ Metric,
+ type ServerTrace,
+ TraceUtil,
+} from "@emprespresso/pengueno";
+import type { Job } from "@emprespresso/ci-model";
+
+type QueuePosition = string;
+export class QueueError extends Error {}
+export interface IJobQueuer<TJob> {
+ queue: Mapper<TJob, Promise<IEither<QueueError, QueuePosition>>>;
+}
+
+export class LaminarJobQueuer
+ implements IJobQueuer<ITraceable<Job, ServerTrace>> {
+ constructor(
+ private readonly queuePositionPrefix: string,
+ ) {}
+
+ private static GetJobTypeTrace = (jobType: string) =>
+ `LaminarJobQueue.Queue.${jobType}`;
+ private static JobTypeMetrics = memoize((jobType: string) =>
+ Metric.fromName(LaminarJobQueuer.GetJobTypeTrace(jobType))
+ );
+
+ public queue(j: ITraceable<Job, ServerTrace>) {
+ const { type: jobType } = j.get();
+ const trace = LaminarJobQueuer.GetJobTypeTrace(jobType);
+ const metric = LaminarJobQueuer.JobTypeMetrics(trace);
+
+ return j
+ .bimap(TraceUtil.withTrace(trace))
+ .bimap(TraceUtil.withMetricTrace(metric))
+ .map((j) => {
+ const { type: jobType, arguments: args } = j.get();
+ const laminarCommand = [
+ "laminarc",
+ "queue",
+ jobType,
+ ...Object.entries(args).map(([key, val]) => `"${key}"="${val}"`),
+ ];
+ return laminarCommand;
+ })
+ .peek((c) =>
+ c.trace.trace(
+ `im so excited to see how this queue job will end!! (>ᴗ<): ${c.get().toString()}`,
+ )
+ )
+ .map(getStdout)
+ .peek(
+ TraceUtil.promiseify((q) =>
+ q.trace.trace(
+ q.get().fold((err, _val) => err ? metric.failure : metric.success),
+ )
+ ),
+ )
+ .map(TraceUtil.promiseify((q) =>
+ q.get().mapRight((stdout) => {
+ q.trace.addTrace(LogLevel.DEBUG).trace(`stdout ${stdout}`);
+ const [jobName, jobId] = stdout.split(":");
+ const jobUrl = `${this.queuePositionPrefix}/jobs/${jobName}/${jobId}`;
+
+ q.trace.trace(`all queued up and weady to go~ (˘ω˘) => ${jobUrl}`);
+ return jobUrl;
+ }).mapLeft((err) => {
+ q.trace.addTrace(LogLevel.ERROR).trace(err.toString());
+ return err;
+ })
+ ))
+ .get();
+ }
+}
diff --git a/hooks/server/mod.ts b/hooks/server/mod.ts
index b635b05..0a520f9 100644
--- a/hooks/server/mod.ts
+++ b/hooks/server/mod.ts
@@ -1,37 +1,3 @@
-import {
- getRequiredEnv,
- getStdout,
- type HealthCheckInput,
- HealthCheckOutput,
- type IEither,
- type ITraceable,
- LogTraceable,
- TraceUtil,
-} from "@emprespresso/pengueno";
-
-export class LizCIServer {
- private constructor(
- private readonly healthCheckActivity = HealthCheckActivity(healthCheck),
- private readonly jobHookActivity = JobHookActivity(jobQueuer),
- private readonly fourOhFourActivity = FourOhFourActivity(),
- ) {}
-
- private async route(req: LogTraceable<Request>) {
- return req.flatMap((req) => {
- const { item: request } = req;
- const url = new URL(request.url);
- if (url.pathname === "/health") {
- return this.healthCheckActivity.healthCheck(req);
- }
- if (url.pathname === "/job") {
- return this.jobHookActivity.processHook(req);
- }
- });
- }
-
- public async serve(req: Request): Promise<Response> {
- return LogTraceable(req).bimap(TraceUtil.withClassTrace(this)).map(
- this.route,
- );
- }
-}
+export * from "./ci.ts";
+export * from "./health.ts";
+export * from "./job/mod.ts";