storage.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { describe, expect } from "bun:test"
  2. import path from "path"
  3. import { LayerNode } from "@kirincode-ai/core/effect/layer-node"
  4. import { Effect, Exit, Layer } from "effect"
  5. import { FSUtil } from "@kirincode-ai/core/fs-util"
  6. import { CrossSpawnSpawner } from "@kirincode-ai/core/cross-spawn-spawner"
  7. import { Git } from "../../src/git"
  8. import { Global } from "@kirincode-ai/core/global"
  9. import { Storage } from "@/storage/storage"
  10. import { tmpdirScoped } from "../fixture/fixture"
  11. import { testEffect } from "../lib/effect"
  12. const dir = path.join(Global.Path.data, "storage")
  13. const it = testEffect(LayerNode.compile(LayerNode.group([Storage.node, FSUtil.node, CrossSpawnSpawner.node])))
  14. const scope = Effect.fnUntraced(function* () {
  15. const root = ["storage_test", crypto.randomUUID()]
  16. const fs = yield* FSUtil.Service
  17. const svc = yield* Storage.Service
  18. yield* Effect.addFinalizer(() =>
  19. fs.remove(path.join(dir, ...root), { recursive: true, force: true }).pipe(Effect.ignore),
  20. )
  21. return { root, svc }
  22. })
  23. // remap(root) rewrites any path under Global.Path.data to live under `root` instead.
  24. // Used by remappedFs to build an FSUtil that Storage thinks is the real global
  25. // data dir but actually targets a tmp dir — letting migration tests stage legacy layouts.
  26. // NOTE: only the 6 methods below are intercepted. If Storage starts using a different
  27. // FSUtil method that touches Global.Path.data, add it here.
  28. function remap(root: string, file: string) {
  29. if (file === Global.Path.data) return root
  30. if (file.startsWith(Global.Path.data + path.sep)) return path.join(root, path.relative(Global.Path.data, file))
  31. return file
  32. }
  33. function remappedFs(root: string) {
  34. return Layer.effect(
  35. FSUtil.Service,
  36. Effect.gen(function* () {
  37. const fs = yield* FSUtil.Service
  38. return FSUtil.Service.of({
  39. ...fs,
  40. isDir: (file) => fs.isDir(remap(root, file)),
  41. readJson: (file) => fs.readJson(remap(root, file)),
  42. writeWithDirs: (file, content, mode) => fs.writeWithDirs(remap(root, file), content, mode),
  43. readFileString: (file) => fs.readFileString(remap(root, file)),
  44. remove: (file) => fs.remove(remap(root, file)),
  45. glob: (pattern, options) =>
  46. fs.glob(pattern, options?.cwd ? { ...options, cwd: remap(root, options.cwd) } : options),
  47. })
  48. }),
  49. ).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
  50. }
  51. // Layer.fresh forces a new Storage instance — without it, Effect's in-test layer cache
  52. // returns the outer testEffect's Storage (which uses the real FSUtil), not a new
  53. // one built on top of remappedFs.
  54. const remappedStorage = (root: string) =>
  55. Layer.fresh(LayerNode.compile(Storage.node, [[FSUtil.node, remappedFs(root)]]))
  56. describe("Storage", () => {
  57. it.live("round-trips JSON content", () =>
  58. Effect.gen(function* () {
  59. const { root, svc } = yield* scope()
  60. const key = [...root, "session_diff", "roundtrip"]
  61. const value = [{ file: "a.ts", additions: 2, deletions: 1 }]
  62. yield* svc.write(key, value)
  63. expect(yield* svc.read<typeof value>(key)).toEqual(value)
  64. }),
  65. )
  66. it.live("maps missing reads to NotFoundError", () =>
  67. Effect.gen(function* () {
  68. const { root, svc } = yield* scope()
  69. const error = yield* Effect.flip(svc.read([...root, "missing", "value"]))
  70. expect(error).toBeInstanceOf(Storage.NotFoundError)
  71. expect(error._tag).toBe("NotFoundError")
  72. expect(error.message).toContain(path.join(...root, "missing", "value") + ".json")
  73. }),
  74. )
  75. it.live("update on missing key throws NotFoundError", () =>
  76. Effect.gen(function* () {
  77. const { root, svc } = yield* scope()
  78. const error = yield* Effect.flip(
  79. svc.update<{ value: number }>([...root, "missing", "key"], (draft) => {
  80. draft.value += 1
  81. }),
  82. )
  83. expect(error).toBeInstanceOf(Storage.NotFoundError)
  84. expect(error._tag).toBe("NotFoundError")
  85. }),
  86. )
  87. it.live("write overwrites existing value", () =>
  88. Effect.gen(function* () {
  89. const { root, svc } = yield* scope()
  90. const key = [...root, "overwrite", "test"]
  91. yield* svc.write<{ v: number }>(key, { v: 1 })
  92. yield* svc.write<{ v: number }>(key, { v: 2 })
  93. expect(yield* svc.read<{ v: number }>(key)).toEqual({ v: 2 })
  94. }),
  95. )
  96. it.live("remove on missing key is a no-op", () =>
  97. Effect.gen(function* () {
  98. const { root, svc } = yield* scope()
  99. yield* svc.remove([...root, "nonexistent", "key"])
  100. }),
  101. )
  102. it.live("list on missing prefix returns empty", () =>
  103. Effect.gen(function* () {
  104. const { root, svc } = yield* scope()
  105. expect(yield* svc.list([...root, "nonexistent"])).toEqual([])
  106. }),
  107. )
  108. it.live("serializes concurrent updates for the same key", () =>
  109. Effect.gen(function* () {
  110. const { root, svc } = yield* scope()
  111. const key = [...root, "counter", "shared"]
  112. yield* svc.write(key, { value: 0 })
  113. yield* Effect.all(
  114. Array.from({ length: 25 }, () =>
  115. svc.update<{ value: number }>(key, (draft) => {
  116. draft.value += 1
  117. }),
  118. ),
  119. { concurrency: "unbounded" },
  120. )
  121. expect(yield* svc.read<{ value: number }>(key)).toEqual({ value: 25 })
  122. }),
  123. )
  124. it.live("concurrent reads do not block each other", () =>
  125. Effect.gen(function* () {
  126. const { root, svc } = yield* scope()
  127. const key = [...root, "concurrent", "reads"]
  128. yield* svc.write(key, { ok: true })
  129. const results = yield* Effect.all(
  130. Array.from({ length: 10 }, () => svc.read(key)),
  131. { concurrency: "unbounded" },
  132. )
  133. expect(results).toHaveLength(10)
  134. for (const r of results) expect(r).toEqual({ ok: true })
  135. }),
  136. )
  137. it.live("nested keys create deep paths", () =>
  138. Effect.gen(function* () {
  139. const { root, svc } = yield* scope()
  140. const key = [...root, "a", "b", "c", "deep"]
  141. yield* svc.write<{ nested: boolean }>(key, { nested: true })
  142. expect(yield* svc.read<{ nested: boolean }>(key)).toEqual({ nested: true })
  143. expect(yield* svc.list([...root, "a"])).toEqual([key])
  144. }),
  145. )
  146. it.live("lists and removes stored entries", () =>
  147. Effect.gen(function* () {
  148. const { root, svc } = yield* scope()
  149. const a = [...root, "list", "a"]
  150. const b = [...root, "list", "b"]
  151. const prefix = [...root, "list"]
  152. yield* svc.write(b, { value: 2 })
  153. yield* svc.write(a, { value: 1 })
  154. expect(yield* svc.list(prefix)).toEqual([a, b])
  155. yield* svc.remove(a)
  156. expect(yield* svc.list(prefix)).toEqual([b])
  157. const exit = yield* svc.read(a).pipe(Effect.exit)
  158. expect(Exit.isFailure(exit)).toBe(true)
  159. }),
  160. )
  161. it.live("migration 2 runs when marker contents are invalid", () =>
  162. Effect.gen(function* () {
  163. const fs = yield* FSUtil.Service
  164. const tmp = yield* tmpdirScoped()
  165. const storage = path.join(tmp, "storage")
  166. const diffs = [
  167. { additions: 2, deletions: 1 },
  168. { additions: 3, deletions: 4 },
  169. ]
  170. yield* fs.writeWithDirs(path.join(storage, "migration"), "wat")
  171. yield* fs.writeWithDirs(
  172. path.join(storage, "session", "proj_test", "ses_test.json"),
  173. JSON.stringify({
  174. id: "ses_test",
  175. projectID: "proj_test",
  176. title: "legacy",
  177. summary: { diffs },
  178. }),
  179. )
  180. yield* Effect.gen(function* () {
  181. const svc = yield* Storage.Service
  182. expect(yield* svc.list(["session_diff"])).toEqual([["session_diff", "ses_test"]])
  183. expect(yield* svc.read<typeof diffs>(["session_diff", "ses_test"])).toEqual(diffs)
  184. expect(
  185. yield* svc.read<{
  186. id: string
  187. projectID: string
  188. title: string
  189. summary: { additions: number; deletions: number }
  190. }>(["session", "proj_test", "ses_test"]),
  191. ).toEqual({
  192. id: "ses_test",
  193. projectID: "proj_test",
  194. title: "legacy",
  195. summary: { additions: 5, deletions: 5 },
  196. })
  197. }).pipe(Effect.provide(remappedStorage(tmp)))
  198. expect(yield* fs.readFileString(path.join(storage, "migration"))).toBe("2")
  199. }),
  200. )
  201. it.live("migration 1 tolerates malformed legacy records", () =>
  202. Effect.gen(function* () {
  203. const fs = yield* FSUtil.Service
  204. const tmp = yield* tmpdirScoped({ git: true })
  205. const storage = path.join(tmp, "storage")
  206. const legacy = path.join(tmp, "project", "legacy")
  207. yield* fs.writeWithDirs(path.join(legacy, "storage", "session", "message", "probe", "0.json"), "[]")
  208. yield* fs.writeWithDirs(
  209. path.join(legacy, "storage", "session", "message", "probe", "1.json"),
  210. JSON.stringify({ path: { root: tmp } }),
  211. )
  212. yield* fs.writeWithDirs(
  213. path.join(legacy, "storage", "session", "info", "ses_legacy.json"),
  214. JSON.stringify({ id: "ses_legacy", title: "legacy" }),
  215. )
  216. yield* fs.writeWithDirs(
  217. path.join(legacy, "storage", "session", "message", "ses_legacy", "msg_legacy.json"),
  218. JSON.stringify({ role: "user", text: "hello" }),
  219. )
  220. yield* Effect.gen(function* () {
  221. const svc = yield* Storage.Service
  222. const projects = yield* svc.list(["project"])
  223. expect(projects).toHaveLength(1)
  224. const project = projects[0]![1]
  225. expect(yield* svc.list(["session", project])).toEqual([["session", project, "ses_legacy"]])
  226. expect(yield* svc.read<{ id: string; title: string }>(["session", project, "ses_legacy"])).toEqual({
  227. id: "ses_legacy",
  228. title: "legacy",
  229. })
  230. expect(yield* svc.read<{ role: string; text: string }>(["message", "ses_legacy", "msg_legacy"])).toEqual({
  231. role: "user",
  232. text: "hello",
  233. })
  234. }).pipe(Effect.provide(remappedStorage(tmp)))
  235. expect(yield* fs.readFileString(path.join(storage, "migration"))).toBe("2")
  236. }),
  237. )
  238. it.live("failed migrations do not advance the marker", () =>
  239. Effect.gen(function* () {
  240. const fs = yield* FSUtil.Service
  241. const tmp = yield* tmpdirScoped()
  242. const storage = path.join(tmp, "storage")
  243. const legacy = path.join(tmp, "project", "legacy")
  244. yield* fs.writeWithDirs(path.join(legacy, "storage", "session", "message", "probe", "0.json"), "{")
  245. yield* Effect.gen(function* () {
  246. const svc = yield* Storage.Service
  247. expect(yield* svc.list(["project"])).toEqual([])
  248. }).pipe(Effect.provide(remappedStorage(tmp)))
  249. const exit = yield* fs.access(path.join(storage, "migration")).pipe(Effect.exit)
  250. expect(Exit.isFailure(exit)).toBe(true)
  251. }),
  252. )
  253. })