storage.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import { LayerNode } from "@kirincode-ai/core/effect/layer-node"
  2. import path from "path"
  3. import { Global } from "@kirincode-ai/core/global"
  4. import { FSUtil } from "@kirincode-ai/core/fs-util"
  5. import { Effect, Exit, Layer, Option, RcMap, Schema, Context, TxReentrantLock } from "effect"
  6. import { NonNegativeInt } from "@kirincode-ai/core/schema"
  7. import { Git } from "@/git"
  8. type Migration = (dir: string, fs: FSUtil.Interface, git: Git.Interface) => Effect.Effect<void, FSUtil.Error>
  9. export class NotFoundError extends Schema.TaggedErrorClass<NotFoundError>()("NotFoundError", {
  10. message: Schema.String,
  11. }) {
  12. static isInstance(input: unknown): input is NotFoundError {
  13. return input instanceof NotFoundError
  14. }
  15. }
  16. export type Error = FSUtil.Error | NotFoundError
  17. const RootFile = Schema.Struct({
  18. path: Schema.optional(
  19. Schema.Struct({
  20. root: Schema.optional(Schema.String),
  21. }),
  22. ),
  23. })
  24. const SessionFile = Schema.Struct({
  25. id: Schema.String,
  26. })
  27. const MessageFile = Schema.Struct({
  28. id: Schema.String,
  29. })
  30. const DiffFile = Schema.Struct({
  31. additions: NonNegativeInt,
  32. deletions: NonNegativeInt,
  33. })
  34. const SummaryFile = Schema.Struct({
  35. id: Schema.String,
  36. projectID: Schema.String,
  37. summary: Schema.Struct({ diffs: Schema.Array(DiffFile) }),
  38. })
  39. const decodeRoot = Schema.decodeUnknownOption(RootFile)
  40. const decodeSession = Schema.decodeUnknownOption(SessionFile)
  41. const decodeMessage = Schema.decodeUnknownOption(MessageFile)
  42. const decodeSummary = Schema.decodeUnknownOption(SummaryFile)
  43. export interface Interface {
  44. readonly remove: (key: string[]) => Effect.Effect<void, FSUtil.Error>
  45. readonly read: <T>(key: string[]) => Effect.Effect<T, Error>
  46. readonly update: <T>(key: string[], fn: (draft: T) => void) => Effect.Effect<T, Error>
  47. readonly write: <T>(key: string[], content: T) => Effect.Effect<void, FSUtil.Error>
  48. readonly list: (prefix: string[]) => Effect.Effect<string[][], FSUtil.Error>
  49. }
  50. export class Service extends Context.Service<Service, Interface>()("@kirincode/Storage") {}
  51. function file(dir: string, key: string[]) {
  52. return path.join(dir, ...key) + ".json"
  53. }
  54. function missing(err: unknown) {
  55. if (!err || typeof err !== "object") return false
  56. if ("code" in err && err.code === "ENOENT") return true
  57. if ("reason" in err && err.reason && typeof err.reason === "object" && "_tag" in err.reason) {
  58. return err.reason._tag === "NotFound"
  59. }
  60. return false
  61. }
  62. function parseMigration(text: string) {
  63. const value = Number.parseInt(text, 10)
  64. return Number.isNaN(value) ? 0 : value
  65. }
  66. const MIGRATIONS: Migration[] = [
  67. Effect.fn("Storage.migration.1")(function* (dir: string, fs: FSUtil.Interface, git: Git.Interface) {
  68. const project = path.resolve(dir, "../project")
  69. if (!(yield* fs.isDir(project))) return
  70. const projectDirs = yield* fs.glob("*", {
  71. cwd: project,
  72. include: "all",
  73. })
  74. for (const projectDir of projectDirs) {
  75. const full = path.join(project, projectDir)
  76. if (!(yield* fs.isDir(full))) continue
  77. yield* Effect.logInfo(`migrating project ${projectDir}`)
  78. let projectID = projectDir
  79. let worktree = "/"
  80. if (projectID !== "global") {
  81. for (const msgFile of yield* fs.glob("storage/session/message/*/*.json", {
  82. cwd: full,
  83. absolute: true,
  84. })) {
  85. const json = decodeRoot(yield* fs.readJson(msgFile), { onExcessProperty: "preserve" })
  86. const root = Option.isSome(json) ? json.value.path?.root : undefined
  87. if (!root) continue
  88. worktree = root
  89. break
  90. }
  91. if (!worktree) continue
  92. if (!(yield* fs.isDir(worktree))) continue
  93. const result = yield* git.run(["rev-list", "--max-parents=0", "--all"], {
  94. cwd: worktree,
  95. })
  96. const [id] = result
  97. .text()
  98. .split("\n")
  99. .filter(Boolean)
  100. .map((x) => x.trim())
  101. .toSorted()
  102. if (!id) continue
  103. projectID = id
  104. yield* fs.writeWithDirs(
  105. path.join(dir, "project", projectID + ".json"),
  106. JSON.stringify(
  107. {
  108. id,
  109. vcs: "git",
  110. worktree,
  111. time: {
  112. created: Date.now(),
  113. initialized: Date.now(),
  114. },
  115. },
  116. null,
  117. 2,
  118. ),
  119. )
  120. yield* Effect.logInfo(`migrating sessions for project ${projectID}`)
  121. for (const sessionFile of yield* fs.glob("storage/session/info/*.json", {
  122. cwd: full,
  123. absolute: true,
  124. })) {
  125. const dest = path.join(dir, "session", projectID, path.basename(sessionFile))
  126. yield* Effect.logInfo("copying", { sessionFile, dest })
  127. const session = yield* fs.readJson(sessionFile)
  128. const info = decodeSession(session, { onExcessProperty: "preserve" })
  129. yield* fs.writeWithDirs(dest, JSON.stringify(session, null, 2))
  130. if (Option.isNone(info)) continue
  131. yield* Effect.logInfo(`migrating messages for session ${info.value.id}`)
  132. for (const msgFile of yield* fs.glob(`storage/session/message/${info.value.id}/*.json`, {
  133. cwd: full,
  134. absolute: true,
  135. })) {
  136. const next = path.join(dir, "message", info.value.id, path.basename(msgFile))
  137. yield* Effect.logInfo("copying", {
  138. msgFile,
  139. dest: next,
  140. })
  141. const message = yield* fs.readJson(msgFile)
  142. const item = decodeMessage(message, { onExcessProperty: "preserve" })
  143. yield* fs.writeWithDirs(next, JSON.stringify(message, null, 2))
  144. if (Option.isNone(item)) continue
  145. yield* Effect.logInfo(`migrating parts for message ${item.value.id}`)
  146. for (const partFile of yield* fs.glob(`storage/session/part/${info.value.id}/${item.value.id}/*.json`, {
  147. cwd: full,
  148. absolute: true,
  149. })) {
  150. const out = path.join(dir, "part", item.value.id, path.basename(partFile))
  151. const part = yield* fs.readJson(partFile)
  152. yield* Effect.logInfo("copying", {
  153. partFile,
  154. dest: out,
  155. })
  156. yield* fs.writeWithDirs(out, JSON.stringify(part, null, 2))
  157. }
  158. }
  159. }
  160. }
  161. }
  162. }),
  163. Effect.fn("Storage.migration.2")(function* (dir: string, fs: FSUtil.Interface) {
  164. for (const item of yield* fs.glob("session/*/*.json", {
  165. cwd: dir,
  166. absolute: true,
  167. })) {
  168. const raw = yield* fs.readJson(item)
  169. const session = decodeSummary(raw, { onExcessProperty: "preserve" })
  170. if (Option.isNone(session)) continue
  171. const diffs = session.value.summary.diffs
  172. yield* fs.writeWithDirs(
  173. path.join(dir, "session_diff", session.value.id + ".json"),
  174. JSON.stringify(diffs, null, 2),
  175. )
  176. yield* fs.writeWithDirs(
  177. path.join(dir, "session", session.value.projectID, session.value.id + ".json"),
  178. JSON.stringify(
  179. {
  180. ...(raw as Record<string, unknown>),
  181. summary: {
  182. additions: diffs.reduce((sum, x) => sum + x.additions, 0),
  183. deletions: diffs.reduce((sum, x) => sum + x.deletions, 0),
  184. },
  185. },
  186. null,
  187. 2,
  188. ),
  189. )
  190. }
  191. }),
  192. ]
  193. const layer = Layer.effect(
  194. Service,
  195. Effect.gen(function* () {
  196. const fs = yield* FSUtil.Service
  197. const git = yield* Git.Service
  198. const locks = yield* RcMap.make({
  199. lookup: () => TxReentrantLock.make(),
  200. idleTimeToLive: 0,
  201. })
  202. const state = yield* Effect.cached(
  203. Effect.gen(function* () {
  204. const dir = path.join(Global.Path.data, "storage")
  205. const marker = path.join(dir, "migration")
  206. const migration = yield* fs.readFileString(marker).pipe(
  207. Effect.map(parseMigration),
  208. Effect.catchIf(missing, () => Effect.succeed(0)),
  209. Effect.orElseSucceed(() => 0),
  210. )
  211. for (let i = migration; i < MIGRATIONS.length; i++) {
  212. yield* Effect.logInfo("running migration", { index: i })
  213. const step = MIGRATIONS[i]!
  214. const exit = yield* Effect.exit(step(dir, fs, git))
  215. if (Exit.isFailure(exit)) {
  216. yield* Effect.logError("failed to run migration", { index: i, cause: exit.cause })
  217. break
  218. }
  219. yield* fs.writeWithDirs(marker, String(i + 1))
  220. }
  221. return { dir }
  222. }),
  223. )
  224. const fail = (target: string): Effect.Effect<never, NotFoundError> =>
  225. Effect.fail(new NotFoundError({ message: `Resource not found: ${target}` }))
  226. const wrap = <A>(target: string, body: Effect.Effect<A, FSUtil.Error>) =>
  227. body.pipe(Effect.catchIf(missing, () => fail(target)))
  228. const writeJson = Effect.fnUntraced(function* (target: string, content: unknown) {
  229. yield* fs.writeWithDirs(target, JSON.stringify(content, null, 2))
  230. })
  231. const withResolved = <A, E>(
  232. key: string[],
  233. fn: (target: string, rw: TxReentrantLock.TxReentrantLock) => Effect.Effect<A, E>,
  234. ): Effect.Effect<A, E | FSUtil.Error> =>
  235. Effect.scoped(
  236. Effect.gen(function* () {
  237. const target = file((yield* state).dir, key)
  238. return yield* fn(target, yield* RcMap.get(locks, target))
  239. }),
  240. )
  241. const remove: Interface["remove"] = Effect.fn("Storage.remove")(function* (key: string[]) {
  242. yield* withResolved(key, (target, rw) =>
  243. TxReentrantLock.withWriteLock(rw, fs.remove(target).pipe(Effect.catchIf(missing, () => Effect.void))),
  244. )
  245. })
  246. const read: Interface["read"] = <T>(key: string[]) =>
  247. Effect.gen(function* () {
  248. const value = yield* withResolved(key, (target, rw) =>
  249. TxReentrantLock.withReadLock(rw, wrap(target, fs.readJson(target))),
  250. )
  251. return value as T
  252. })
  253. const update: Interface["update"] = <T>(key: string[], fn: (draft: T) => void) =>
  254. Effect.gen(function* () {
  255. const value = yield* withResolved(key, (target, rw) =>
  256. TxReentrantLock.withWriteLock(
  257. rw,
  258. Effect.gen(function* () {
  259. const content = yield* wrap(target, fs.readJson(target))
  260. fn(content as T)
  261. yield* writeJson(target, content)
  262. return content
  263. }),
  264. ),
  265. )
  266. return value as T
  267. })
  268. const write: Interface["write"] = (key: string[], content: unknown) =>
  269. Effect.gen(function* () {
  270. yield* withResolved(key, (target, rw) => TxReentrantLock.withWriteLock(rw, writeJson(target, content)))
  271. })
  272. const list: Interface["list"] = Effect.fn("Storage.list")(function* (prefix: string[]) {
  273. const dir = (yield* state).dir
  274. const cwd = path.join(dir, ...prefix)
  275. const result = yield* fs
  276. .glob("**/*", {
  277. cwd,
  278. include: "file",
  279. })
  280. .pipe(Effect.catch(() => Effect.succeed<string[]>([])))
  281. return result
  282. .map((x) => [...prefix, ...x.slice(0, -5).split(path.sep)])
  283. .toSorted((a, b) => a.join("/").localeCompare(b.join("/")))
  284. })
  285. return Service.of({
  286. remove,
  287. read,
  288. update,
  289. write,
  290. list,
  291. })
  292. }),
  293. )
  294. export const node = LayerNode.make({ service: Service, layer: layer, deps: [FSUtil.node, Git.node] })
  295. export * as Storage from "./storage"