identities-d1.ts
This file
Path
apps/platform/src/adapters/identities-d1.ts
48 lines · 1.6 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–48why, one step back1import { Handle } from "@repo/protocol/ids";2import { Array, Effect, Layer, Option, Schema } from "effect";3import { SqlClient } from "effect/sql/SqlClient";45import { handleKey } from "../auth/accounts.ts";6import { Identities, IdentityTaken } from "../auth/identities.ts";78const Rows = Schema.Array(Schema.Struct({ handle_key: Handle }));910const decodeRows = Schema.decodeUnknownEffect(Rows);1112export const IdentitiesD1 = Layer.effect(13 Identities,14 Effect.gen(function* () {15 const sql = yield* SqlClient;1617 const handleOf = (provider: string, subject: string) =>18 sql`19 SELECT handle_key FROM identities20 WHERE provider = ${provider} AND subject = ${subject}`.pipe(21 Effect.flatMap(decodeRows),22 Effect.orDie,23 Effect.map((rows) =>24 Option.map(Array.head(rows), (row) => row.handle_key)25 )26 );2728 return Identities.of({29 handleOf,30 // One statement decides who holds the subject, however two links race;31 // a subject already held is fine only when it names the same handle.32 link: (provider, subject, handle) =>33 sql`34 INSERT INTO identities (provider, subject, handle_key)35 VALUES (${provider}, ${subject}, ${handleKey(handle)})36 ON CONFLICT (provider, subject) DO NOTHING`.pipe(37 Effect.orDie,38 Effect.andThen(handleOf(provider, subject)),39 Effect.filterOrFail(40 (held) =>41 Option.exists(held, (linked) => linked === handleKey(handle)),42 () => new IdentityTaken({ provider, subject })43 ),44 Effect.asVoid45 ),46 });47 })48);