|
| 1 | +export * as SessionExpiry from "./expiry.js" |
| 2 | + |
| 3 | +import path from "path" |
| 4 | +import { and, asc, isNull, lt } from "drizzle-orm" |
| 5 | +import { parse, type ParseError } from "jsonc-parser" |
| 6 | +import { Clock, Duration, Effect, Layer, Option, Schedule, Schema } from "effect" |
| 7 | +import { FSUtil } from "@opencode/util/fs-util" |
| 8 | +import { Global } from "@opencode/util/global" |
| 9 | +import { makeGlobalNode } from "@opencode/util/effect/app-node" |
| 10 | +import { Database } from "../database/database.js" |
| 11 | +import { Job } from "../job.js" |
| 12 | +import { Session } from "../session.js" |
| 13 | +import { SessionExecution } from "./execution.js" |
| 14 | +import { SessionTable } from "./sql.js" |
| 15 | + |
| 16 | +const SWEEP_INTERVAL = Duration.hours(1) |
| 17 | + |
| 18 | +const decodeSessions = Schema.decodeUnknownOption(Schema.DurationFromString) |
| 19 | + |
| 20 | +/** Projects `storage.sessions` from one global config file, like the CLI updater's `update` policy. */ |
| 21 | +export function decodeMaxAge(text: string) { |
| 22 | + const errors: ParseError[] = [] |
| 23 | + const input: unknown = parse(text, errors, { allowTrailingComma: true }) |
| 24 | + if (errors.length || typeof input !== "object" || input === null || !("storage" in input)) return |
| 25 | + const storage = input.storage |
| 26 | + if (typeof storage !== "object" || storage === null || !("sessions" in storage)) return |
| 27 | + return Option.getOrUndefined(decodeSessions(storage.sessions)) |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Reads `storage.sessions` from the global config directory only. Project config is never read, |
| 32 | + * so a project cannot delete another project's Sessions. Later files win, as with `update`. |
| 33 | + */ |
| 34 | +export const configured = Effect.fn("SessionExpiry.configured")(function* () { |
| 35 | + const global = yield* Global.Service |
| 36 | + const fs = yield* FSUtil.Service |
| 37 | + const values = yield* Effect.forEach(["config.json", "opencode.json", "opencode.jsonc"], (name) => |
| 38 | + fs.readFileStringSafe(path.join(global.config, name)).pipe( |
| 39 | + Effect.map((text) => (text === undefined ? undefined : decodeMaxAge(text))), |
| 40 | + Effect.orElseSucceed(() => undefined), |
| 41 | + ), |
| 42 | + ) |
| 43 | + return values.findLast((value) => value !== undefined) |
| 44 | +}) |
| 45 | + |
| 46 | +/** |
| 47 | + * Deletes top-level Sessions, with their children, whose last activity is older than `maxAge`. |
| 48 | + * Returns the deleted Session count. |
| 49 | + */ |
| 50 | +export const expire = Effect.fn("SessionExpiry.expire")(function* (maxAge: Duration.Duration) { |
| 51 | + const { db } = yield* Database.Service |
| 52 | + const execution = yield* SessionExecution.Service |
| 53 | + const jobs = yield* Job.Service |
| 54 | + const sessions = yield* Session.Service |
| 55 | + const cutoff = (yield* Clock.currentTimeMillis) - Duration.toMillis(maxAge) |
| 56 | + // Suspended Sessions belong to restart recovery, which resumes or terminalizes them. |
| 57 | + const expired = yield* db |
| 58 | + .select({ id: SessionTable.id }) |
| 59 | + .from(SessionTable) |
| 60 | + .where( |
| 61 | + and(isNull(SessionTable.parent_id), isNull(SessionTable.time_suspended), lt(SessionTable.time_updated, cutoff)), |
| 62 | + ) |
| 63 | + .orderBy(asc(SessionTable.time_updated)) |
| 64 | + .all() |
| 65 | + .pipe(Effect.orDie) |
| 66 | + if (expired.length === 0) return 0 |
| 67 | + // Waiting on a question, a long tool call, or a background job emits no activity. |
| 68 | + const occupied = new Set([ |
| 69 | + ...(yield* execution.active), |
| 70 | + ...(yield* jobs.runningBackground).flatMap((recovery) => |
| 71 | + recovery.kind === "shell" ? [recovery.sessionID] : [recovery.childSessionID, recovery.parentSessionID], |
| 72 | + ), |
| 73 | + ]) |
| 74 | + const removable = expired.filter((row) => !occupied.has(row.id)) |
| 75 | + yield* Effect.forEach( |
| 76 | + removable, |
| 77 | + (row) => sessions.remove(row.id).pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void)), |
| 78 | + { discard: true }, |
| 79 | + ) |
| 80 | + return removable.length |
| 81 | +}) |
| 82 | + |
| 83 | +/** Applies the global `storage.sessions` config. Unset keeps every Session. */ |
| 84 | +export const sweep = Effect.fn("SessionExpiry.sweep")(function* () { |
| 85 | + const maxAge = yield* configured() |
| 86 | + if (maxAge === undefined) return |
| 87 | + const millis = Duration.toMillis(maxAge) |
| 88 | + if (!Number.isFinite(millis) || millis <= 0) { |
| 89 | + yield* Effect.logWarning("storage.sessions must be a finite positive duration") |
| 90 | + return |
| 91 | + } |
| 92 | + const count = yield* expire(maxAge) |
| 93 | + if (count === 0) return |
| 94 | + yield* Effect.logInfo("deleted expired sessions", { count, maxAge: Duration.format(maxAge) }) |
| 95 | +}) |
| 96 | + |
| 97 | +export const node = makeGlobalNode({ |
| 98 | + name: "session-expiry-sweep", |
| 99 | + layer: Layer.effectDiscard( |
| 100 | + sweep().pipe( |
| 101 | + Effect.ignoreCause({ log: "Error", message: "Session expiry sweep failed" }), |
| 102 | + Effect.repeat(Schedule.spaced(SWEEP_INTERVAL)), |
| 103 | + Effect.forkScoped, |
| 104 | + ), |
| 105 | + ), |
| 106 | + deps: [Database.node, FSUtil.node, Global.node, Job.node, Session.node, SessionExecution.node], |
| 107 | +}) |
0 commit comments