Skip to content
Myr

session.ts

This file

Path

apps/cli/src/hook/session.ts

120 lines · 3.5 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

The walk stopped after 200 commits: lines older than 1e46e9a point at it.

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 1why, one step back
1// A cache: a file that cannot be read is no file, and one that cannot be written is skipped.

Fill the README's numbers from the live swarm and core-loop runs on dev-oscabriel, and record their throwawaysoscabrielbefore adoption1e46e9a

lines 2–120why, one step back
2import { Brand } from "@repo/brand";
3import { NoneOrMore } from "@repo/protocol/domain/common";4import { Policy } from "@repo/protocol/domain/policy";5import { Config, Effect, FileSystem, Hash, Option, Path, Schema } from "effect";67import { HookClaim } from "./decide.ts";89export const SessionState = Schema.Struct({10 claim: Schema.optionalKey(HookClaim),11 holds: NoneOrMore,12 judge: Policy.fields.judge,13 root: Schema.String,14 why: Schema.optionalKey(Schema.String),15});1617export type SessionState = typeof SessionState.Type;1819export class SessionUnsaved extends Schema.TaggedError<SessionUnsaved>()(20 "SessionUnsaved",21 { reason: Schema.String }22) {23 override get message() {24 return `this session's facts are not kept between events: ${this.reason}`;25 }26}2728const File = Schema.fromJsonString(SessionState);2930const decodeFile = Schema.decodeUnknownEffect(File);3132const encodeFile = Schema.encodeEffect(File);3334const Env = Config.all({35 home: Config.option(Config.NonEmptyString("HOME")),36 stateHome: Config.option(Config.NonEmptyString("XDG_STATE_HOME")),37});3839/** Owner only, like the credentials file: it names the repo and the claim. */40const FILE_MODE = 0o600;4142const DIR_MODE = 0o700;4344const fileNameOf = (session: string) =>45 /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(session)46 ? `${session}.json`47 : `${session.replaceAll(/[^A-Za-z0-9._-]/gu, "_").slice(0, 64)}-${Hash.string(session).toString(36)}.json`;4849const fileOf = (session: string) =>50 Effect.gen(function* () {51 const path = yield* Path.Path;5253 const env = yield* Effect.orElseSucceed(Env, () => ({54 home: Option.none<string>(),55 stateHome: Option.none<string>(),56 }));5758 return Option.map(59 Option.orElse(env.stateHome, () =>60 Option.map(env.home, (home) => path.join(home, ".local", "state"))61 ),62 (state) => path.join(state, Brand.slug, "hooks", fileNameOf(session))63 );64 });6566export const loadSession = (67 session: string68): Effect.Effect<69 Option.Option<SessionState>,70 never,71 FileSystem.FileSystem | Path.Path72> =>73 Effect.gen(function* () {74 const fs = yield* FileSystem.FileSystem;75 const file = yield* fileOf(session);7677 if (Option.isNone(file) || !(yield* fs.exists(file.value))) {78 return Option.none();79 }8081 return Option.some(82 yield* Effect.flatMap(fs.readFileString(file.value), decodeFile)83 );84 }).pipe(Effect.orElseSucceed(() => Option.none<SessionState>()));8586export const saveSession = (87 session: string,88 state: SessionState89): Effect.Effect<void, SessionUnsaved, FileSystem.FileSystem | Path.Path> =>90 Effect.gen(function* () {91 const fs = yield* FileSystem.FileSystem;92 const path = yield* Path.Path;9394 const file = yield* Effect.flatMap(fileOf(session), (at) =>95 Effect.fromOption(at).pipe(96 Effect.mapError(97 () =>98 new SessionUnsaved({99 reason: "neither XDG_STATE_HOME nor HOME is set",100 })101 )102 )103 );104105 const staged = `${file}.tmp`;106107 yield* fs108 .makeDirectory(path.dirname(file), { mode: DIR_MODE, recursive: true })109 .pipe(110 Effect.andThen(111 Effect.flatMap(encodeFile(state), (text) =>112 fs.writeFileString(staged, text, { mode: FILE_MODE })113 )114 ),115 Effect.andThen(fs.rename(staged, file)),116 Effect.mapError(117 () => new SessionUnsaved({ reason: `could not write ${file}` })118 )119 );120 });