persist.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. import { Platform, usePlatform } from "@/context/platform"
  2. import { makePersisted, type AsyncStorage, type SyncStorage } from "@solid-primitives/storage"
  3. import { checksum } from "@opencode-ai/core/util/encode"
  4. import { createResource, type Accessor } from "solid-js"
  5. import type { SetStoreFunction, Store } from "solid-js/store"
  6. import { pathKey } from "@/utils/path-key"
  7. type InitType = Promise<string> | string | null
  8. type PersistedWithReady<T> = [
  9. Store<T>,
  10. SetStoreFunction<T>,
  11. InitType,
  12. Accessor<boolean> & { promise: undefined | Promise<any> },
  13. ]
  14. type PersistTarget = {
  15. storage?: string
  16. legacyStorageNames?: string[]
  17. key: string
  18. legacy?: string[]
  19. migrate?: (value: unknown) => unknown
  20. }
  21. const LEGACY_STORAGE = "default.dat"
  22. const GLOBAL_STORAGE = "opencode.global.dat"
  23. const LOCAL_PREFIX = "opencode."
  24. const fallback = new Map<string, boolean>()
  25. const CACHE_MAX_ENTRIES = 500
  26. const CACHE_MAX_BYTES = 8 * 1024 * 1024
  27. type CacheEntry = { value: string; bytes: number }
  28. const cache = new Map<string, CacheEntry>()
  29. const cacheTotal = { bytes: 0 }
  30. function cacheDelete(key: string) {
  31. const entry = cache.get(key)
  32. if (!entry) return
  33. cacheTotal.bytes -= entry.bytes
  34. cache.delete(key)
  35. }
  36. function cachePrune() {
  37. for (;;) {
  38. if (cache.size <= CACHE_MAX_ENTRIES && cacheTotal.bytes <= CACHE_MAX_BYTES) return
  39. const oldest = cache.keys().next().value as string | undefined
  40. if (!oldest) return
  41. cacheDelete(oldest)
  42. }
  43. }
  44. function cacheSet(key: string, value: string) {
  45. const bytes = value.length * 2
  46. if (bytes > CACHE_MAX_BYTES) {
  47. cacheDelete(key)
  48. return
  49. }
  50. const entry = cache.get(key)
  51. if (entry) cacheTotal.bytes -= entry.bytes
  52. cache.delete(key)
  53. cache.set(key, { value, bytes })
  54. cacheTotal.bytes += bytes
  55. cachePrune()
  56. }
  57. function cacheGet(key: string) {
  58. const entry = cache.get(key)
  59. if (!entry) return
  60. cache.delete(key)
  61. cache.set(key, entry)
  62. return entry.value
  63. }
  64. function fallbackDisabled(scope: string) {
  65. return fallback.get(scope) === true
  66. }
  67. function fallbackSet(scope: string) {
  68. fallback.set(scope, true)
  69. }
  70. function quota(error: unknown) {
  71. if (error instanceof DOMException) {
  72. if (error.name === "QuotaExceededError") return true
  73. if (error.name === "NS_ERROR_DOM_QUOTA_REACHED") return true
  74. if (error.name === "QUOTA_EXCEEDED_ERR") return true
  75. if (error.code === 22 || error.code === 1014) return true
  76. return false
  77. }
  78. if (!error || typeof error !== "object") return false
  79. const name = (error as { name?: string }).name
  80. if (name === "QuotaExceededError" || name === "NS_ERROR_DOM_QUOTA_REACHED") return true
  81. if (name && /quota/i.test(name)) return true
  82. const code = (error as { code?: number }).code
  83. if (code === 22 || code === 1014) return true
  84. const message = (error as { message?: string }).message
  85. if (typeof message !== "string") return false
  86. if (/quota/i.test(message)) return true
  87. return false
  88. }
  89. type Evict = { key: string; size: number }
  90. function evict(storage: Storage, keep: string, value: string) {
  91. const total = storage.length
  92. const indexes = Array.from({ length: total }, (_, index) => index)
  93. const items: Evict[] = []
  94. for (const index of indexes) {
  95. const name = storage.key(index)
  96. if (!name) continue
  97. if (!name.startsWith(LOCAL_PREFIX)) continue
  98. if (name === keep) continue
  99. const stored = storage.getItem(name)
  100. items.push({ key: name, size: stored?.length ?? 0 })
  101. }
  102. items.sort((a, b) => b.size - a.size)
  103. for (const item of items) {
  104. storage.removeItem(item.key)
  105. cacheDelete(item.key)
  106. try {
  107. storage.setItem(keep, value)
  108. cacheSet(keep, value)
  109. return true
  110. } catch (error) {
  111. if (!quota(error)) throw error
  112. }
  113. }
  114. return false
  115. }
  116. function write(storage: Storage, key: string, value: string) {
  117. try {
  118. storage.setItem(key, value)
  119. cacheSet(key, value)
  120. return true
  121. } catch (error) {
  122. if (!quota(error)) throw error
  123. }
  124. try {
  125. storage.removeItem(key)
  126. cacheDelete(key)
  127. storage.setItem(key, value)
  128. cacheSet(key, value)
  129. return true
  130. } catch (error) {
  131. if (!quota(error)) throw error
  132. }
  133. const ok = evict(storage, key, value)
  134. return ok
  135. }
  136. function snapshot(value: unknown) {
  137. return JSON.parse(JSON.stringify(value)) as unknown
  138. }
  139. function isRecord(value: unknown): value is Record<string, unknown> {
  140. return typeof value === "object" && value !== null && !Array.isArray(value)
  141. }
  142. function merge(defaults: unknown, value: unknown): unknown {
  143. if (value === undefined) return defaults
  144. if (value === null) return value
  145. if (Array.isArray(defaults)) {
  146. if (Array.isArray(value)) return value
  147. return defaults
  148. }
  149. if (isRecord(defaults)) {
  150. if (!isRecord(value)) return defaults
  151. const result: Record<string, unknown> = { ...defaults }
  152. for (const key of Object.keys(value)) {
  153. if (key in defaults) {
  154. result[key] = merge((defaults as Record<string, unknown>)[key], (value as Record<string, unknown>)[key])
  155. } else {
  156. result[key] = (value as Record<string, unknown>)[key]
  157. }
  158. }
  159. return result
  160. }
  161. return value
  162. }
  163. function parse(value: string) {
  164. try {
  165. return JSON.parse(value) as unknown
  166. } catch {
  167. return undefined
  168. }
  169. }
  170. function normalize(defaults: unknown, raw: string, migrate?: (value: unknown) => unknown) {
  171. const parsed = parse(raw)
  172. if (parsed === undefined) return
  173. const migrated = migrate ? migrate(parsed) : parsed
  174. const merged = merge(defaults, migrated)
  175. return JSON.stringify(merged)
  176. }
  177. function readCurrent(input: {
  178. storage: SyncStorage
  179. key: string
  180. defaults: unknown
  181. migrate?: (value: unknown) => unknown
  182. }) {
  183. const raw = input.storage.getItem(input.key)
  184. if (raw === null) return
  185. const next = normalize(input.defaults, raw, input.migrate)
  186. if (next === undefined) {
  187. input.storage.removeItem(input.key)
  188. return null
  189. }
  190. if (raw !== next) input.storage.setItem(input.key, next)
  191. return next
  192. }
  193. function migrateLegacy(input: {
  194. current: SyncStorage
  195. legacyStore?: SyncStorage
  196. stores: SyncStorage[]
  197. keys: string[]
  198. key: string
  199. defaults: unknown
  200. migrate?: (value: unknown) => unknown
  201. }) {
  202. for (const store of input.stores) {
  203. const raw = store.getItem(input.key)
  204. if (raw === null) continue
  205. const next = normalize(input.defaults, raw, input.migrate)
  206. if (next === undefined) {
  207. store.removeItem(input.key)
  208. continue
  209. }
  210. input.current.setItem(input.key, next)
  211. store.removeItem(input.key)
  212. return next
  213. }
  214. if (!input.legacyStore) return null
  215. for (const key of input.keys) {
  216. const raw = input.legacyStore.getItem(key)
  217. if (raw === null) continue
  218. const next = normalize(input.defaults, raw, input.migrate)
  219. if (next === undefined) {
  220. input.legacyStore.removeItem(key)
  221. continue
  222. }
  223. input.current.setItem(input.key, next)
  224. input.legacyStore.removeItem(key)
  225. return next
  226. }
  227. return null
  228. }
  229. async function readCurrentAsync(input: {
  230. storage: AsyncStorage
  231. key: string
  232. defaults: unknown
  233. migrate?: (value: unknown) => unknown
  234. }) {
  235. const raw = await input.storage.getItem(input.key)
  236. if (raw === null) return
  237. const next = normalize(input.defaults, raw, input.migrate)
  238. if (next === undefined) {
  239. await input.storage.removeItem(input.key).catch(() => undefined)
  240. return null
  241. }
  242. if (raw !== next) await input.storage.setItem(input.key, next)
  243. return next
  244. }
  245. async function removeAsync(storage: AsyncStorage, key: string) {
  246. try {
  247. await storage.removeItem(key)
  248. } catch {}
  249. }
  250. async function migrateLegacyAsync(input: {
  251. current: AsyncStorage
  252. legacyStore?: AsyncStorage
  253. stores: AsyncStorage[]
  254. keys: string[]
  255. key: string
  256. defaults: unknown
  257. migrate?: (value: unknown) => unknown
  258. }) {
  259. for (const store of input.stores) {
  260. const raw = await store.getItem(input.key)
  261. if (raw === null) continue
  262. const next = normalize(input.defaults, raw, input.migrate)
  263. if (next === undefined) {
  264. await removeAsync(store, input.key)
  265. continue
  266. }
  267. await input.current.setItem(input.key, next)
  268. await store.removeItem(input.key)
  269. return next
  270. }
  271. if (!input.legacyStore) return null
  272. for (const key of input.keys) {
  273. const raw = await input.legacyStore.getItem(key)
  274. if (raw === null) continue
  275. const next = normalize(input.defaults, raw, input.migrate)
  276. if (next === undefined) {
  277. await removeAsync(input.legacyStore, key)
  278. continue
  279. }
  280. await input.current.setItem(input.key, next)
  281. await input.legacyStore.removeItem(key)
  282. return next
  283. }
  284. return null
  285. }
  286. function workspaceStorage(dir: string) {
  287. const head = (dir.slice(0, 12) || "workspace").replace(/[^a-zA-Z0-9._-]/g, "-")
  288. const sum = checksum(dir) ?? "0"
  289. return `opencode.workspace.${head}.${sum}.dat`
  290. }
  291. function legacyWorkspaceStorage(dir: string) {
  292. const storage = workspaceStorage(pathKey(dir))
  293. const result = new Set<string>()
  294. const raw = workspaceStorage(dir)
  295. if (raw !== storage) result.add(raw)
  296. const key = pathKey(dir)
  297. const drive = key.length >= 3 && key[1] === ":" && key[2] === "/"
  298. if (drive) {
  299. const backslash = workspaceStorage(key.replaceAll("/", "\\"))
  300. if (backslash !== storage) result.add(backslash)
  301. }
  302. if (result.size === 0) return
  303. return [...result]
  304. }
  305. function localStorageWithPrefix(prefix: string): SyncStorage {
  306. const base = `${prefix}:`
  307. const scope = `prefix:${prefix}`
  308. const item = (key: string) => base + key
  309. return {
  310. getItem: (key) => {
  311. const name = item(key)
  312. const cached = cacheGet(name)
  313. if (fallbackDisabled(scope)) return cached ?? null
  314. const stored = (() => {
  315. try {
  316. return localStorage.getItem(name)
  317. } catch {
  318. fallbackSet(scope)
  319. return null
  320. }
  321. })()
  322. if (stored === null) return cached ?? null
  323. cacheSet(name, stored)
  324. return stored
  325. },
  326. setItem: (key, value) => {
  327. const name = item(key)
  328. if (fallbackDisabled(scope)) return
  329. try {
  330. if (write(localStorage, name, value)) return
  331. } catch {
  332. fallbackSet(scope)
  333. return
  334. }
  335. fallbackSet(scope)
  336. },
  337. removeItem: (key) => {
  338. const name = item(key)
  339. cacheDelete(name)
  340. if (fallbackDisabled(scope)) return
  341. try {
  342. localStorage.removeItem(name)
  343. } catch {
  344. fallbackSet(scope)
  345. }
  346. },
  347. }
  348. }
  349. function localStorageDirect(): SyncStorage {
  350. const scope = "direct"
  351. return {
  352. getItem: (key) => {
  353. const cached = cacheGet(key)
  354. if (fallbackDisabled(scope)) return cached ?? null
  355. const stored = (() => {
  356. try {
  357. return localStorage.getItem(key)
  358. } catch {
  359. fallbackSet(scope)
  360. return null
  361. }
  362. })()
  363. if (stored === null) return cached ?? null
  364. cacheSet(key, stored)
  365. return stored
  366. },
  367. setItem: (key, value) => {
  368. if (fallbackDisabled(scope)) return
  369. try {
  370. if (write(localStorage, key, value)) return
  371. } catch {
  372. fallbackSet(scope)
  373. return
  374. }
  375. fallbackSet(scope)
  376. },
  377. removeItem: (key) => {
  378. cacheDelete(key)
  379. if (fallbackDisabled(scope)) return
  380. try {
  381. localStorage.removeItem(key)
  382. } catch {
  383. fallbackSet(scope)
  384. }
  385. },
  386. }
  387. }
  388. export const PersistTesting = {
  389. localStorageDirect,
  390. localStorageWithPrefix,
  391. migrateLegacy,
  392. normalize,
  393. workspaceStorage,
  394. }
  395. export const Persist = {
  396. global(key: string, legacy?: string[]): PersistTarget {
  397. return { storage: GLOBAL_STORAGE, key, legacy }
  398. },
  399. workspace(dir: string, key: string, legacy?: string[]): PersistTarget {
  400. const storage = workspaceStorage(pathKey(dir))
  401. return { storage, legacyStorageNames: legacyWorkspaceStorage(dir), key: `workspace:${key}`, legacy }
  402. },
  403. session(dir: string, session: string, key: string, legacy?: string[]): PersistTarget {
  404. const storage = workspaceStorage(pathKey(dir))
  405. return {
  406. storage,
  407. legacyStorageNames: legacyWorkspaceStorage(dir),
  408. key: `session:${session}:${key}`,
  409. legacy,
  410. }
  411. },
  412. scoped(dir: string, session: string | undefined, key: string, legacy?: string[]): PersistTarget {
  413. if (session) return Persist.session(dir, session, key, legacy)
  414. return Persist.workspace(dir, key, legacy)
  415. },
  416. }
  417. export function removePersisted(
  418. target: { storage?: string; legacyStorageNames?: string[]; key: string },
  419. platform?: Platform,
  420. ) {
  421. const isDesktop = platform?.platform === "desktop" && !!platform.storage
  422. if (isDesktop) {
  423. void platform.storage?.(target.storage)?.removeItem(target.key)
  424. for (const storage of target.legacyStorageNames ?? []) {
  425. void platform.storage?.(storage)?.removeItem(target.key)
  426. }
  427. return
  428. }
  429. if (!target.storage) {
  430. localStorageDirect().removeItem(target.key)
  431. return
  432. }
  433. localStorageWithPrefix(target.storage).removeItem(target.key)
  434. for (const storage of target.legacyStorageNames ?? []) {
  435. localStorageWithPrefix(storage).removeItem(target.key)
  436. }
  437. }
  438. export function persisted<T>(
  439. target: string | PersistTarget,
  440. store: [Store<T>, SetStoreFunction<T>],
  441. ): PersistedWithReady<T> {
  442. const platform = usePlatform()
  443. const config: PersistTarget = typeof target === "string" ? { key: target } : target
  444. const defaults = snapshot(store[0])
  445. const legacy = config.legacy ?? []
  446. const isDesktop = platform.platform === "desktop" && !!platform.storage
  447. const currentStorage = (() => {
  448. if (isDesktop) return platform.storage?.(config.storage)
  449. if (!config.storage) return localStorageDirect()
  450. return localStorageWithPrefix(config.storage)
  451. })()
  452. const legacyStorage = (() => {
  453. if (!isDesktop) return localStorageDirect()
  454. if (!config.storage) return platform.storage?.()
  455. return platform.storage?.(LEGACY_STORAGE)
  456. })()
  457. const legacyStorageNames = config.legacyStorageNames ?? []
  458. const storage = (() => {
  459. if (!isDesktop) {
  460. const current = currentStorage as SyncStorage
  461. const legacyStore = legacyStorage as SyncStorage
  462. const legacyStores = legacyStorageNames.map(localStorageWithPrefix)
  463. const api: SyncStorage = {
  464. getItem: (key) => {
  465. const value = readCurrent({ storage: current, key, defaults, migrate: config.migrate })
  466. if (value !== undefined) return value
  467. return migrateLegacy({
  468. current,
  469. legacyStore,
  470. stores: legacyStores,
  471. keys: legacy,
  472. key,
  473. defaults,
  474. migrate: config.migrate,
  475. })
  476. },
  477. setItem: (key, value) => {
  478. current.setItem(key, value)
  479. },
  480. removeItem: (key) => {
  481. current.removeItem(key)
  482. },
  483. }
  484. return api
  485. }
  486. const current = currentStorage as AsyncStorage
  487. const legacyStore = legacyStorage as AsyncStorage | undefined
  488. const legacyStores = legacyStorageNames
  489. .map((name) => platform.storage?.(name) as AsyncStorage | undefined)
  490. .filter((x) => !!x)
  491. const api: AsyncStorage = {
  492. getItem: async (key) => {
  493. const value = await readCurrentAsync({ storage: current, key, defaults, migrate: config.migrate })
  494. if (value !== undefined) return value
  495. return migrateLegacyAsync({
  496. current,
  497. legacyStore,
  498. stores: legacyStores,
  499. keys: legacy,
  500. key,
  501. defaults,
  502. migrate: config.migrate,
  503. })
  504. },
  505. setItem: async (key, value) => {
  506. await current.setItem(key, value)
  507. },
  508. removeItem: async (key) => {
  509. await current.removeItem(key)
  510. },
  511. }
  512. return api
  513. })()
  514. const [state, setState, init] = makePersisted(store, { name: config.key, storage })
  515. const isAsync = init instanceof Promise
  516. const [ready] = createResource(
  517. () => init,
  518. async (initValue) => {
  519. if (initValue instanceof Promise) await initValue
  520. return true
  521. },
  522. { initialValue: !isAsync },
  523. )
  524. return [
  525. state,
  526. setState,
  527. init,
  528. Object.assign(() => (ready.loading ? false : ready.latest === true), {
  529. promise: init instanceof Promise ? init : undefined,
  530. }),
  531. ]
  532. }