Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LayoutCommandApprovals.ts

63 lines2.4 KB

1import { ProjectId, TaskFolderError, type WorktreeLayoutCommandKind } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Digest from "effect/crypto/Digest";
4import * as Effect from "effect/Effect";
5import * as Hex from "effect/encoding/Hex";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8import * as SqlClient from "effect/sql/SqlClient";
9import * as SqlSchema from "effect/sql/SqlSchema";
10​
11/**
12 * Which of a project's `worktreeLayout` commands a person approved, by the hash of the exact
13 * text. This side only reads. Recording an approval is `LayoutCommandApprovalWrites`, which only
14 * the client RPC that a person's session calls may import
15 * (t3code/no-layout-command-approval-writes).
16 */
17export class LayoutCommandApprovals extends Context.Service<
18 LayoutCommandApprovals,
19 {
20 readonly isApproved: (input: {
21 readonly projectId: ProjectId;
22 readonly kind: WorktreeLayoutCommandKind;
23 readonly command: string;
24 }) => Effect.Effect<boolean, TaskFolderError>;
25 }
26>()("t3/workspace/LayoutCommandApprovals") {}
27​
28export const failed = (cause: unknown) =>
29 new TaskFolderError({
30 operation: "approve",
31 detail: "Could not read the worktree layout command approvals.",
32 cause,
33 });
34​
35/** What an approval is of: the text itself, so one changed character asks again. */
36export const commandHash = (digest: Digest.Digest["Service"], command: string) =>
37 digest
38 .digest(Digest.sha256, new TextEncoder().encode(command))
39 .pipe(Effect.map(Hex.encode), Effect.mapError(failed));
40​
41const make = Effect.gen(function* () {
42 const sql = yield* SqlClient.SqlClient;
43 const digest = yield* Digest.Digest;
44​
45 const findHash = SqlSchema.findOneOption({
46 Request: Schema.Struct({ projectId: ProjectId, kind: Schema.String }),
47 Result: Schema.Struct({ commandHash: Schema.String }),
48 execute: ({ projectId, kind }) => sql`
49 SELECT command_hash AS "commandHash" FROM layout_command_approvals
50 WHERE project_id = ${projectId} AND kind = ${kind}
51 `,
52 });
53​
54 return LayoutCommandApprovals.of({
55 isApproved: Effect.fn("LayoutCommandApprovals.isApproved")(function* (input) {
56 const approved = yield* findHash(input).pipe(Effect.mapError(failed));
57 if (approved._tag === "None") return false;
58 return approved.value.commandHash === (yield* commandHash(digest, input.command));
59 }),
60 });
61});
62​
63export const layer = Layer.effect(LayoutCommandApprovals, make);