persist.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import { Platform, usePlatform } from "@/context/platform"
  2. import { makePersisted, type AsyncStorage, type SyncStorage } from "@solid-primitives/storage"
  3. import { checksum } from "@opencode-ai/util/encode"
  4. import { createResource, type Accessor } from "solid-js"
  5. import type { SetStoreFunction, Store } from "solid-js/store"
  6. type InitType = Promise<string> | string | null
  7. type PersistedWithReady<T> = [Store<T>, SetStoreFunction<T>, InitType, Accessor<boolean>]
  8. type PersistTarget = {
  9. storage?: string
  10. key: string
  11. legacy?: string[]
  12. migrate?: (value: unknown) => unknown
  13. }
  14. const LEGACY_STORAGE = "default.dat"
  15. const GLOBAL_STORAGE = "opencode.global.dat"
  16. const LOCAL_PREFIX = "opencode."
  17. const fallback = new Map<string, boolean>()
  18. const CACHE_MAX_ENTRIES = 500
  19. const CACHE_MAX_BYTES = 8 * 1024 * 1024
  20. type CacheEntry = { value: string; bytes: number }
  21. const cache = new Map<string, CacheEntry>()
  22. const cacheTotal = { bytes: 0 }
  23. function cacheDelete(key: string) {
  24. const entry = cache.get(key)
  25. if (!entry) return
  26. cacheTotal.bytes -= entry.bytes
  27. cache.delete(key)
  28. }
  29. function cachePrune() {
  30. for (;;) {
  31. if (cache.size <= CACHE_MAX_ENTRIES && cacheTotal.bytes <= CACHE_MAX_BYTES) return
  32. const oldest = cache.keys().next().value as string | undefined
  33. if (!oldest) return
  34. cacheDelete(oldest)
  35. }
  36. }
  37. function cacheSet(key: string, value: string) {
  38. const bytes = value.length * 2
  39. if (bytes > CACHE_MAX_BYTES) {
  40. cacheDelete(key)
  41. return
  42. }
  43. const entry = cache.get(key)
  44. if (entry) cacheTotal.bytes -= entry.bytes
  45. cache.delete(key)
  46. cache.set(key, { value, bytes })
  47. cacheTotal.bytes += bytes
  48. cachePrune()
  49. }
  50. function cacheGet(key: string) {
  51. const entry = cache.get(key)
  52. if (!entry) return
  53. cache.delete(key)
  54. cache.set(key, entry)
  55. return entry.value
  56. }
  57. function fallbackDisabled(scope: string) {
  58. return fallback.get(scope) === true
  59. }
  60. function fallbackSet(scope: string) {
  61. fallback.set(scope, true)
  62. }
  63. function quota(error: unknown) {
  64. if (error instanceof DOMException) {
  65. if (error.name === "QuotaExceededError") return true
  66. if (error.name === "NS_ERROR_DOM_QUOTA_REACHED") return true
  67. if (error.name === "QUOTA_EXCEEDED_ERR") return true
  68. if (error.code === 22 || error.code === 1014) return true
  69. return false
  70. }
  71. if (!error || typeof error !== "object") return false
  72. const name = (error as { name?: string }).name
  73. if (name === "QuotaExceededError" || name === "NS_ERROR_DOM_QUOTA_REACHED") return true
  74. if (name && /quota/i.test(name)) return true
  75. const code = (error as { code?: number }).code
  76. if (code === 22 || code === 1014) return true
  77. const message = (error as { message?: string }).message
  78. if (typeof message !== "string") return false
  79. if (/quota/i.test(message)) return true
  80. return false
  81. }
  82. type Evict = { key: string; size: number }
  83. function evict(storage: Storage, keep: string, value: string) {
  84. const total = storage.length
  85. const indexes = Array.from({ length: total }, (_, index) => index)
  86. const items: Evict[] = []
  87. for (const index of indexes) {
  88. const name = storage.key(index)
  89. if (!name) continue
  90. if (!name.startsWith(LOCAL_PREFIX)) continue
  91. if (name === keep) continue
  92. const stored = storage.getItem(name)
  93. items.push({ key: name, size: stored?.length ?? 0 })
  94. }
  95. items.sort((a, b) => b.size - a.size)
  96. for (const item of items) {
  97. storage.removeItem(item.key)
  98. cacheDelete(item.key)
  99. try {
  100. storage.setItem(keep, value)
  101. cacheSet(keep, value)
  102. return true
  103. } catch (error) {
  104. if (!quota(error)) throw error
  105. }
  106. }
  107. return false
  108. }
  109. function write(storage: Storage, key: string, value: string) {
  110. try {
  111. storage.setItem(key, value)
  112. cacheSet(key, value)
  113. return true
  114. } catch (error) {
  115. if (!quota(error)) throw error
  116. }
  117. try {
  118. storage.removeItem(key)
  119. cacheDelete(key)
  120. storage.setItem(key, value)
  121. cacheSet(key, value)
  122. return true
  123. } catch (error) {
  124. if (!quota(error)) throw error
  125. }
  126. const ok = evict(storage, key, value)
  127. return ok
  128. }
  129. function snapshot(value: unknown) {
  130. return JSON.parse(JSON.stringify(value)) as unknown
  131. }
  132. function isRecord(value: unknown): value is Record<string, unknown> {
  133. return typeof value === "object" && value !== null && !Array.isArray(value)
  134. }
  135. function merge(defaults: unknown, value: unknown): unknown {
  136. if (value === undefined) return defaults
  137. if (value === null) return value
  138. if (Array.isArray(defaults)) {
  139. if (Array.isArray(value)) return value
  140. return defaults
  141. }
  142. if (isRecord(defaults)) {
  143. if (!isRecord(value)) return defaults
  144. const result: Record<string, unknown> = { ...defaults }
  145. for (const key of Object.keys(value)) {
  146. if (key in defaults) {
  147. result[key] = merge((defaults as Record<string, unknown>)[key], (value as Record<string, unknown>)[key])
  148. } else {
  149. result[key] = (value as Record<string, unknown>)[key]
  150. }
  151. }
  152. return result
  153. }
  154. return value
  155. }
  156. function parse(value: string) {
  157. try {
  158. return JSON.parse(value) as unknown
  159. } catch {
  160. return undefined
  161. }
  162. }
  163. function normalize(defaults: unknown, raw: string, migrate?: (value: unknown) => unknown) {
  164. const parsed = parse(raw)
  165. if (parsed === undefined) return
  166. const migrated = migrate ? migrate(parsed) : parsed
  167. const merged = merge(defaults, migrated)
  168. return JSON.stringify(merged)
  169. }
  170. function workspaceStorage(dir: string) {
  171. const head = dir.slice(0, 12) || "workspace"
  172. const sum = checksum(dir) ?? "0"
  173. return `opencode.workspace.${head}.${sum}.dat`
  174. }
  175. function localStorageWithPrefix(prefix: string): SyncStorage {
  176. const base = `${prefix}:`
  177. const scope = `prefix:${prefix}`
  178. const item = (key: string) => base + key
  179. return {
  180. getItem: (key) => {
  181. const name = item(key)
  182. const cached = cacheGet(name)
  183. if (fallbackDisabled(scope)) return cached ?? null
  184. const stored = (() => {
  185. try {
  186. return localStorage.getItem(name)
  187. } catch {
  188. fallbackSet(scope)
  189. return null
  190. }
  191. })()
  192. if (stored === null) return cached ?? null
  193. cacheSet(name, stored)
  194. return stored
  195. },
  196. setItem: (key, value) => {
  197. const name = item(key)
  198. if (fallbackDisabled(scope)) return
  199. try {
  200. if (write(localStorage, name, value)) return
  201. } catch {
  202. fallbackSet(scope)
  203. return
  204. }
  205. fallbackSet(scope)
  206. },
  207. removeItem: (key) => {
  208. const name = item(key)
  209. cacheDelete(name)
  210. if (fallbackDisabled(scope)) return
  211. try {
  212. localStorage.removeItem(name)
  213. } catch {
  214. fallbackSet(scope)
  215. }
  216. },
  217. }
  218. }
  219. function localStorageDirect(): SyncStorage {
  220. const scope = "direct"
  221. return {
  222. getItem: (key) => {
  223. const cached = cacheGet(key)
  224. if (fallbackDisabled(scope)) return cached ?? null
  225. const stored = (() => {
  226. try {
  227. return localStorage.getItem(key)
  228. } catch {
  229. fallbackSet(scope)
  230. return null
  231. }
  232. })()
  233. if (stored === null) return cached ?? null
  234. cacheSet(key, stored)
  235. return stored
  236. },
  237. setItem: (key, value) => {
  238. if (fallbackDisabled(scope)) return
  239. try {
  240. if (write(localStorage, key, value)) return
  241. } catch {
  242. fallbackSet(scope)
  243. return
  244. }
  245. fallbackSet(scope)
  246. },
  247. removeItem: (key) => {
  248. cacheDelete(key)
  249. if (fallbackDisabled(scope)) return
  250. try {
  251. localStorage.removeItem(key)
  252. } catch {
  253. fallbackSet(scope)
  254. }
  255. },
  256. }
  257. }
  258. export const PersistTesting = {
  259. localStorageDirect,
  260. localStorageWithPrefix,
  261. normalize,
  262. }
  263. export const Persist = {
  264. global(key: string, legacy?: string[]): PersistTarget {
  265. return { storage: GLOBAL_STORAGE, key, legacy }
  266. },
  267. workspace(dir: string, key: string, legacy?: string[]): PersistTarget {
  268. return { storage: workspaceStorage(dir), key: `workspace:${key}`, legacy }
  269. },
  270. session(dir: string, session: string, key: string, legacy?: string[]): PersistTarget {
  271. return { storage: workspaceStorage(dir), key: `session:${session}:${key}`, legacy }
  272. },
  273. scoped(dir: string, session: string | undefined, key: string, legacy?: string[]): PersistTarget {
  274. if (session) return Persist.session(dir, session, key, legacy)
  275. return Persist.workspace(dir, key, legacy)
  276. },
  277. }
  278. export function removePersisted(target: { storage?: string; key: string }, platform?: Platform) {
  279. const isDesktop = platform?.platform === "desktop" && !!platform.storage
  280. if (isDesktop) {
  281. return platform.storage?.(target.storage)?.removeItem(target.key)
  282. }
  283. if (!target.storage) {
  284. localStorageDirect().removeItem(target.key)
  285. return
  286. }
  287. localStorageWithPrefix(target.storage).removeItem(target.key)
  288. }
  289. export function persisted<T>(
  290. target: string | PersistTarget,
  291. store: [Store<T>, SetStoreFunction<T>],
  292. ): PersistedWithReady<T> {
  293. const platform = usePlatform()
  294. const config: PersistTarget = typeof target === "string" ? { key: target } : target
  295. const defaults = snapshot(store[0])
  296. const legacy = config.legacy ?? []
  297. const isDesktop = platform.platform === "desktop" && !!platform.storage
  298. const currentStorage = (() => {
  299. if (isDesktop) return platform.storage?.(config.storage)
  300. if (!config.storage) return localStorageDirect()
  301. return localStorageWithPrefix(config.storage)
  302. })()
  303. const legacyStorage = (() => {
  304. if (!isDesktop) return localStorageDirect()
  305. if (!config.storage) return platform.storage?.()
  306. return platform.storage?.(LEGACY_STORAGE)
  307. })()
  308. const storage = (() => {
  309. if (!isDesktop) {
  310. const current = currentStorage as SyncStorage
  311. const legacyStore = legacyStorage as SyncStorage
  312. const api: SyncStorage = {
  313. getItem: (key) => {
  314. const raw = current.getItem(key)
  315. if (raw !== null) {
  316. const next = normalize(defaults, raw, config.migrate)
  317. if (next === undefined) {
  318. current.removeItem(key)
  319. return null
  320. }
  321. if (raw !== next) current.setItem(key, next)
  322. return next
  323. }
  324. for (const legacyKey of legacy) {
  325. const legacyRaw = legacyStore.getItem(legacyKey)
  326. if (legacyRaw === null) continue
  327. const next = normalize(defaults, legacyRaw, config.migrate)
  328. if (next === undefined) {
  329. legacyStore.removeItem(legacyKey)
  330. continue
  331. }
  332. current.setItem(key, next)
  333. legacyStore.removeItem(legacyKey)
  334. return next
  335. }
  336. return null
  337. },
  338. setItem: (key, value) => {
  339. current.setItem(key, value)
  340. },
  341. removeItem: (key) => {
  342. current.removeItem(key)
  343. },
  344. }
  345. return api
  346. }
  347. const current = currentStorage as AsyncStorage
  348. const legacyStore = legacyStorage as AsyncStorage | undefined
  349. const api: AsyncStorage = {
  350. getItem: async (key) => {
  351. const raw = await current.getItem(key)
  352. if (raw !== null) {
  353. const next = normalize(defaults, raw, config.migrate)
  354. if (next === undefined) {
  355. await current.removeItem(key).catch(() => undefined)
  356. return null
  357. }
  358. if (raw !== next) await current.setItem(key, next)
  359. return next
  360. }
  361. if (!legacyStore) return null
  362. for (const legacyKey of legacy) {
  363. const legacyRaw = await legacyStore.getItem(legacyKey)
  364. if (legacyRaw === null) continue
  365. const next = normalize(defaults, legacyRaw, config.migrate)
  366. if (next === undefined) {
  367. await legacyStore.removeItem(legacyKey).catch(() => undefined)
  368. continue
  369. }
  370. await current.setItem(key, next)
  371. await legacyStore.removeItem(legacyKey)
  372. return next
  373. }
  374. return null
  375. },
  376. setItem: async (key, value) => {
  377. await current.setItem(key, value)
  378. },
  379. removeItem: async (key) => {
  380. await current.removeItem(key)
  381. },
  382. }
  383. return api
  384. })()
  385. const [state, setState, init] = makePersisted(store, { name: config.key, storage })
  386. const isAsync = init instanceof Promise
  387. const [ready] = createResource(
  388. () => init,
  389. async (initValue) => {
  390. if (initValue instanceof Promise) await initValue
  391. return true
  392. },
  393. { initialValue: !isAsync },
  394. )
  395. return [state, setState, init, () => ready() === true]
  396. }