MCPcopy Create free account
hub / github.com/Effect-TS/effect / layerKvs

Function layerKvs

packages/effect/src/ui/QueryPersistence.ts:156–268  ·  view source on GitHub ↗
(options: {
  readonly prefix: string
  readonly maxAge: Duration.Input
  readonly version?: string | undefined
})

Source from the content-addressed store, hash-verified

154 * @since 4.2.0
155 */
156export const layerKvs = (options: {
157 readonly prefix: string
158 readonly maxAge: Duration.Input
159 readonly version?: string | undefined
160}): Layer.Layer<never, never, KeyValueStore.KeyValueStore> => {
161 const maxAge = Duration.toMillis(options.maxAge)
162 // JSON keeps prefixes apart: `["app",` doesn't start `["app/u1",…`.
163 const start = JSON.stringify([options.prefix]).slice(0, -1) + ","
164 const keyOf = (def: Def, argsKey: string) => JSON.stringify([options.prefix, def.name, argsKey])
165 return Layer.effect(
166 queryCore.Persistence,
167 Effect.gen(function*() {
168 const store = yield* KeyValueStore.KeyValueStore
169 const clock = yield* Clock.Clock
170 const now = clock.currentTimeMillisUnsafe()
171 const saved = new Map<string, Saved>()
172 const keys = yield* Effect.orElseSucceed(store.keys, () => [])
173 yield* Effect.forEach(
174 keys.filter((key) => key.startsWith(start)),
175 // A failed read skips the key: only a value read is pruned.
176 (key) =>
177 store.get(key).pipe(
178 Effect.flatMap((text) => {
179 const entry = parse(text)
180 if (
181 entry !== undefined && entry.version === options.version &&
182 now - entry.savedAt <= maxAge
183 ) {
184 saved.set(key, entry)
185 return Effect.void
186 }
187 return store.remove(key)
188 }),
189 Effect.ignore
190 ),
191 { concurrency: "unbounded", discard: true }
192 )
193
194 /** The keys the store is behind on, each with the report of its failed write. */
195 const dirty = new Map<string, () => void>()
196 const latch = Latch.makeUnsafe()
197 const immediate = Latch.makeUnsafe()
198 const flush = Effect.suspend(() => {
199 const writes = Array.from(dirty)
200 dirty.clear()
201 latch.closeUnsafe()
202 immediate.closeUnsafe()
203 return Effect.forEach(
204 writes,
205 ([key, onFailure]) => {
206 const entry = saved.get(key)
207 return entry === undefined
208 ? Effect.ignore(store.remove(key))
209 : Effect.try(() => JSON.stringify(entry)).pipe(
210 Effect.flatMap((text) => store.set(key, text)),
211 Effect.catch(() => Effect.sync(onFailure))
212 )
213 },

Callers

nothing calls this directly

Calls 15

sliceMethod · 0.80
fromMethod · 0.80
addFinalizerMethod · 0.80
parseFunction · 0.70
keyOfFunction · 0.70
persistedFunction · 0.70
reportFunction · 0.70
failedFunction · 0.70
forEachMethod · 0.65
pipeMethod · 0.65
getMethod · 0.65

Tested by

no test coverage detected