| Title: | Persistent Disk Cache Shared Between Processes |
|---|---|
| Description: | A persistent, size-bounded cache that several 'R' processes on one machine can share, in the style of the 'Python' library 'diskcache'. Keys map to values that outlive the session, expire on a clock, carry tags for bulk invalidation, and are evicted when the cache grows past a limit. Metadata and small values live in a transactional 'libmdbx' database through the 'mdbx' package, and larger values are stored as content-addressed files. Functions can be memoised across sessions and processes, and the cache can be used through the 'cachem' interface. |
| Authors: | Pedro Baltazar [aut, cre, cph] |
| Maintainer: | Pedro Baltazar <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0 |
| Built: | 2026-12-01 09:56:29 UTC |
| Source: | https://github.com/pedrobtz/dazcache |
Returns an object with the methods of a cachem cache — get(), set(),
exists(), remove(), reset(), keys(), prune(), size() and
info() — so code written for cachem, such as memoise::memoise() and
Shiny's bindCache(), can store in a cache. Keys follow cachem's rule,
lower-case letters, digits, _ and -, and are stored under prefix.
as_cachem(cache, ..., prefix = "cachem/", expire = NULL, codec = NULL)as_cachem(cache, ..., prefix = "cachem/", expire = NULL, codec = NULL)
cache |
A cache, from |
... |
Must be empty. |
prefix |
Where in the cache the keys live. It must end with a
character a cachem key cannot contain, such as |
expire, codec
|
Passed to |
A list of functions with class c("dazcache_cachem", "cachem").
s <- local_cache() cache <- as_cachem(s) cache$set("answer", 42) cache$get("answer") cache$keys() slow_double <- function(x) x * 2 fast_double <- memoise::memoise(slow_double, cache = cache) fast_double(21)s <- local_cache() cache <- as_cachem(s) cache$set("answer", 42) cache$get("answer") cache$keys() slow_double <- function(x) x * 2 fast_double <- memoise::memoise(slow_double, cache = cache) fast_double(21)
cache() opens the cache in directory dir, creating it if needed, and
returns a handle for the other cache_*() functions. Any number of R
processes on the machine can open the same directory at once; they share it
safely.
local_cache() opens a cache that closes when the calling function returns,
in a new temporary directory unless you give one, which is then deleted. At
the top level there is no function to return from, so nothing closes it:
call cache_close() yourself. with_cache() opens one, passes it to a
function, and closes it afterwards.
cache_close() closes a handle, cache_is_open() says whether it is open,
and cache_dir() returns its directory.
cache( dir, ..., size_limit = 1024^3, eviction = c("least-recently-stored", "least-recently-used", "least-frequently-used", "none"), inline_max = 32 * 1024, codec = codec_auto(), codecs = list(), durability = c("safe", "fast", "unsafe"), map_size = 1024^3, cull_limit = 10L, timeout = 60, readonly = FALSE, create = TRUE ) cache_close(cache) cache_is_open(cache) cache_dir(cache) local_cache(dir = NULL, ..., .local_envir = parent.frame()) with_cache(dir, fn, ...)cache( dir, ..., size_limit = 1024^3, eviction = c("least-recently-stored", "least-recently-used", "least-frequently-used", "none"), inline_max = 32 * 1024, codec = codec_auto(), codecs = list(), durability = c("safe", "fast", "unsafe"), map_size = 1024^3, cull_limit = 10L, timeout = 60, readonly = FALSE, create = TRUE ) cache_close(cache) cache_is_open(cache) cache_dir(cache) local_cache(dir = NULL, ..., .local_envir = parent.frame()) with_cache(dir, fn, ...)
dir |
The cache's directory. |
... |
Must be empty. |
size_limit |
The size, in bytes, the cache is kept under. |
eviction |
Which entries make room when the cache is over |
inline_max |
Values whose encoding is smaller than this many bytes are
kept inside the database; the rest, from exactly |
codec |
The default codec for writes; see |
codecs |
A list of your own codecs, made with |
durability |
|
map_size |
The most the database file may grow to, in bytes: a whole
number of at least 1 MiB ( |
cull_limit |
How many entries one eviction step removes at most, up
to |
timeout |
How long, in seconds, a write waits for another process's
write to finish before raising |
readonly |
Open for reading only. |
create |
Create the directory and the cache if they do not exist. |
cache |
A cache, from |
.local_envir |
The environment whose exit closes the cache. |
fn |
A function of one argument, the open cache. |
size_limit, eviction, inline_max and codec belong to the store and are
fixed when it is created: a later cache() that passes a different value
raises dazcache_config_conflict, and one that leaves them out uses the stored
values. The other settings belong to this handle only.
A second cache() on a directory this process already has open shares the
same underlying database; each handle is closed separately. While a
read-only handle is open, the same process cannot open the directory for
writing: close it first. A handle that is dropped without being closed
releases its share when it is garbage-collected; cache_close() releases it
at once.
A handle cannot be used from a forked child process, such as a
parallel::mclapply() worker; open the cache inside the worker instead,
which works whether or not the parent has it open.
Opening a cache that exists only reads it, so it never waits for another
process's write. Writes take the cache's one write lock in turn, waiting up
to timeout seconds. On Linux and Windows the lock of a process killed
while writing is released at once. On macOS and other platforms it is not:
every later write raises dazcache_busy until every process with the cache
open has closed it, after which the next to open it recovers the lock.
Reads are not affected.
cache() and local_cache() return a dazcache_cache.
with_cache() returns what fn returns. cache_close() returns the cache,
invisibly; cache_is_open() TRUE or FALSE; and cache_dir() the
cache's directory, normalised.
dir <- tempfile("cache-") s <- cache(dir) cache_set(s, "greeting", "hello") cache_get(s, "greeting") cache_close(s) unlink(dir, recursive = TRUE) f <- function() { s <- local_cache() cache_set(s, "n", 1:3) cache_get(s, "n") } f()dir <- tempfile("cache-") s <- cache(dir) cache_set(s, "greeting", "hello") cache_get(s, "greeting") cache_close(s) unlink(dir, recursive = TRUE) f <- function() { s <- local_cache() cache_set(s, "n", 1:3) cache_get(s, "n") } f()
Compares every index, reference count and counter with what the entries
imply, and every stored file with its records. Returns one row per problem
found. With repair = TRUE it fixes them, in one transaction: rebuilding
index rows, recounting, removing entries whose file is gone or damaged, and
deleting files and staging leftovers nothing refers to.
A crash leaves at most unreferenced files; cache_check(repair = TRUE) is
how they are reclaimed. hash = TRUE also reads every stored file and
checks its bytes against its name, which is slow on a large cache.
cache_check(cache, ..., repair = FALSE, hash = FALSE)cache_check(cache, ..., repair = FALSE, hash = FALSE)
cache |
A cache, from |
... |
Must be empty. |
repair |
Fix what is found. |
hash |
Verify the content of every stored file. |
A data frame with columns kind, key, path, detail and
repaired, one row per finding. The kinds are index_orphan,
index_missing, record_corrupt, value_orphan, value_missing,
value_corrupt, blob_missing, blob_orphan, blob_corrupt,
blob_mode, refcount_drift, counter_drift, tmp_stale and
reader_stale.
s <- local_cache() cache_set(s, "a", runif(1e4)) cache_check(s)s <- local_cache() cache_set(s, "a", runif(1e4)) cache_check(s)
cache_cull() reclaims expired entries, then evicts the least recently
stored entries until what the entries hold is within size_limit, in
transactions of at most cull_limit entries. Every write already runs one
such step when the cache is over its limit, so the limit holds without a
background process; cache_cull() finishes the job at once.
cache_evict() deletes every entry carrying a tag, or every entry whose key
begins with a prefix. cache_clear() deletes everything.
The limit counts the bytes entries hold, inline and in files. The database
file itself keeps the pages it frees for reuse rather than shrinking, so
cache_volume(), which reports bytes on disk, can stay above the limit.
cache_cull(cache) cache_evict(cache, ..., tag = NULL, prefix = NULL) cache_clear(cache)cache_cull(cache) cache_evict(cache, ..., tag = NULL, prefix = NULL) cache_clear(cache)
cache |
A cache, from |
... |
Must be empty. |
tag |
Delete every entry carrying this tag. |
prefix |
Delete every entry whose key begins with this string. |
The cache, invisibly.
s <- local_cache(size_limit = 1e5, inline_max = 1000) for (i in 1:20) cache_set(s, paste0("k", i), runif(1000)) cache_count(s) cache_cull(s) cache_count(s) cache_set(s, "a", 1, tags = "group") cache_set(s, "b", 2, tags = c("group", "other")) cache_evict(s, tag = "group") cache_has(s, c("a", "b")) cache_clear(s) cache_count(s)s <- local_cache(size_limit = 1e5, inline_max = 1000) for (i in 1:20) cache_set(s, paste0("k", i), runif(1000)) cache_count(s) cache_cull(s) cache_count(s) cache_set(s, "a", 1, tags = "group") cache_set(s, "b", 2, tags = c("group", "other")) cache_evict(s, tag = "group") cache_has(s, c("a", "b")) cache_clear(s) cache_count(s)
cache_entries() returns one row per live entry. prefix and tag select
entries through the cache's indexes; filter the rest with ordinary data
frame tools. cache_info() returns the row for one key, or NULL.
cache_stats() returns one row describing the whole cache.
cache_entries(cache, ..., prefix = NULL, tag = NULL, n = Inf) cache_info(cache, key) cache_stats(cache)cache_entries(cache, ..., prefix = NULL, tag = NULL, n = Inf) cache_info(cache, key) cache_stats(cache)
cache |
A cache, from |
... |
Must be empty. |
prefix |
Only keys whose text begins with this string. |
tag |
Only entries carrying this tag. |
n |
The most keys to return. |
key |
A key. |
cache_entries() and cache_info() return a data frame with columns
key, bytes, codec, inline, blob, tags (a list of character
vectors), shape, stored, accessed, hits and expires (NA for
never). In this release accessed is always stored and hits always 0:
reads are not yet recorded. cache_stats() returns a one-row data frame
with count, bytes_inline, bytes_blob, volume, size_limit,
evictions, expired, eviction, durability, format_version and
key_encoding_version.
s <- local_cache() cache_set(s, "a", 1:10, tags = "small") cache_set(s, "b", "text", expire = 3600) cache_entries(s) cache_entries(s, tag = "small") cache_info(s, "b") cache_stats(s)s <- local_cache() cache_set(s, "a", 1:10, tags = "small") cache_set(s, "b", "text", expire = 3600) cache_entries(s) cache_entries(s, tag = "small") cache_info(s, "b") cache_stats(s)
An expired entry is already absent to every read; cache_expire() removes it
and frees its space. It walks entries from the earliest deadline, in
transactions of at most cull_limit entries (see cache()), so it never
holds the write lock for long. It can be run at any time, by any process:
it cannot change what a read returns.
cache_expire(cache, ..., n = Inf)cache_expire(cache, ..., n = Inf)
cache |
A cache, from |
... |
Must be empty. |
n |
The most entries to remove. |
The cache, invisibly.
s <- local_cache() cache_set(s, "brief", 1, expire = 0) cache_count(s) cache_expire(s) cache_count(s)s <- local_cache() cache_set(s, "brief", 1, expire = 0) cache_count(s) cache_expire(s) cache_count(s)
cache_get() returns the value stored under a key. A missing key is an error
of class dazcache_not_found unless default is supplied, in which case
default is returned; a stored NULL is a value like any other.
cache_mget() reads several keys at once and returns a named list in the
order asked. cache_has() says which keys have an entry.
A key is a string, a key from cache_key(), or any value that can be a key;
see cache_key().
cache_get(cache, key, default) cache_mget(cache, keys, default) cache_has(cache, keys)cache_get(cache, key, default) cache_mget(cache, keys, default) cache_has(cache, keys)
cache |
A cache, from |
key |
A key. |
default |
Returned for a missing key. Leave it out to make a missing key an error. |
keys |
A character vector of keys, or a list of keys. |
cache_get() returns the value. cache_mget() returns a list named
by each key's text. cache_has() returns a logical vector, one element per
key.
s <- local_cache() cache_set(s, "a", 1) cache_get(s, "a") cache_get(s, "b", default = NA) try(cache_get(s, "b")) cache_has(s, c("a", "b")) cache_mget(s, c("a", "b"), default = NULL)s <- local_cache() cache_set(s, "a", 1) cache_get(s, "a") cache_get(s, "b", default = NA) try(cache_get(s, "b")) cache_has(s, c("a", "b")) cache_mget(s, c("a", "b"), default = NULL)
Each of these is one transaction, so it is atomic across processes: eight
processes calling cache_incr() on one key produce eight increments.
cache_add() writes only if the key has no entry, and returns whether it
did. An expired entry counts as none.
cache_pop() returns an entry's value and deletes it. It deletes nothing
when the entry's file is missing or the wrong size, but bytes that cannot
be decoded are found only after the delete: the pop raises the codec's
error and the damaged entry is gone.
cache_touch() gives an entry a new deadline without rewriting its value.
It does nothing to a missing key.
cache_incr() and cache_decr() add to or subtract from a counter and
return its new value. A missing key starts at default. Counters hold
whole numbers within ±2^53; a key holding anything else is a
dazcache_type_error.
cache_incr(cache, key, ..., by = 1, default = 0) cache_decr(cache, key, ..., by = 1, default = 0) cache_add(cache, key, value, ..., expire = NULL, tags = NULL, codec = NULL) cache_pop(cache, key, default) cache_touch(cache, key, expire)cache_incr(cache, key, ..., by = 1, default = 0) cache_decr(cache, key, ..., by = 1, default = 0) cache_add(cache, key, value, ..., expire = NULL, tags = NULL, codec = NULL) cache_pop(cache, key, default) cache_touch(cache, key, expire)
cache |
A cache, from |
key |
A key. |
... |
Must be empty. |
by |
The amount to add or subtract, a whole number. |
default |
For |
value |
The value to store. |
expire |
When the entry expires: |
tags |
A character vector of up to 16 tags, each at most 256 bytes, to
group entries for |
codec |
The codec to write with, or |
cache_add() returns TRUE or FALSE. cache_pop() returns the
value; for an entry written with codec_file(), whose file leaves the
cache with it, the path of a copy in the session's temporary directory,
which the caller owns. cache_touch() returns the cache, invisibly. cache_incr() and
cache_decr() return the new count, a double.
s <- local_cache() cache_add(s, "lock", Sys.getpid(), expire = 30) cache_add(s, "lock", Sys.getpid()) cache_incr(s, "hits") cache_incr(s, "hits", by = 10) cache_decr(s, "hits") cache_set(s, "job", "payload") cache_pop(s, "job") cache_has(s, "job")s <- local_cache() cache_add(s, "lock", Sys.getpid(), expire = 30) cache_add(s, "lock", Sys.getpid()) cache_incr(s, "hits") cache_incr(s, "hits", by = 10) cache_decr(s, "hits") cache_set(s, "job", "payload") cache_pop(s, "job") cache_has(s, "job")
Every function that takes a key accepts a string, a dazcache_key, or any
value the canonical encoding covers. cache_key() builds a key from values;
cache_key_chr() returns the canonical text a key is stored under, and
cache_key_hash() its SHA-256.
A single string is its own text: "XSWX/2026-08-29" is stored under exactly
those bytes. Anything else — numbers, dates, vectors, lists, data frames, or
several values — is written in a specified text encoding in which field order
does not matter, 1L and 1 agree, and a timestamp's time zone is not part
of its identity. A string that begins like an encoded value ({, (, ~,
#, D{, or a type tag such as s:) is escaped so the two can never
collide.
Functions, environments, connections, S4 objects and external pointers have
no encoding and raise dazcache_key_invalid.
cache_keys() lists keys as their text. A plain string key's text is the
string itself and can be passed back as it is, but a structured key's text,
such as "{n=i:1}", would be taken as a string. cache_key_text() turns a
listed text back into the key it lists.
cache_key(...) cache_key_chr(key) cache_key_text(text) cache_key_hash(key)cache_key(...) cache_key_chr(key) cache_key_text(text) cache_key_hash(key)
... |
Values that make up the key: one unnamed value, or several values
that are either all named or all unnamed. Named values are ordered by name,
so their order does not matter. Supports |
key |
A string, a |
text |
One key's text, as |
cache_key() and cache_key_text() return a dazcache_key.
cache_key_chr() returns the canonical text as a string, and
cache_key_hash() the SHA-256 of that text as 64 lower-case hex
characters.
cache_key("XSWX/2026-08-29") k <- cache_key(exchange = "XSWX", date = as.Date("2026-08-29")) k identical(k, cache_key(date = as.Date("2026-08-29"), exchange = "XSWX")) cache_key_chr(list(n = 1L, p = 0.1)) cache_key_hash("XSWX/2026-08-29") # A listed structured key, used again. s <- local_cache() cache_set(s, list(n = 1), "one") listed <- cache_keys(s) listed cache_get(s, cache_key_text(listed))cache_key("XSWX/2026-08-29") k <- cache_key(exchange = "XSWX", date = as.Date("2026-08-29")) k identical(k, cache_key(date = as.Date("2026-08-29"), exchange = "XSWX")) cache_key_chr(list(n = 1L, p = 0.1)) cache_key_hash("XSWX/2026-08-29") # A listed structured key, used again. s <- local_cache() cache_set(s, list(n = 1), "one") listed <- cache_keys(s) listed cache_get(s, cache_key_text(listed))
cache_keys() returns keys in the order they are stored: the text of each
key, as cache_key_chr() gives it. A structured key's text is not itself
that key; pass it through cache_key_text() to use it again. Use prefix
for keys that begin with a string, and start with n to page through a
large cache: start is inclusive, so drop the first key of every page after
the first.
A key of up to 512 bytes is stored as itself, so those keys come in byte
order. A longer key is stored under # and a digest of its text, and sorts
there, among keys beginning with #, in no meaningful order. prefix still
matches it by its text, which the cache keeps for keys up to 4096 bytes; of
a longer key it keeps the first 256 bytes, so a prefix longer than that
does not match it, and it is listed as its digest.
cache_count() returns the number of entries, including expired ones that
cache_expire() has not reclaimed yet. cache_volume() returns the bytes
the cache occupies on disk: its database file and every stored file.
cache_keys(cache, ..., prefix = NULL, start = NULL, n = Inf) cache_count(cache) cache_volume(cache)cache_keys(cache, ..., prefix = NULL, start = NULL, n = Inf) cache_count(cache) cache_volume(cache)
cache |
A cache, from |
... |
Must be empty. |
prefix |
Only keys whose text begins with this string. |
start |
Begin at this key, inclusive: a key's text as |
n |
The most keys to return. |
cache_keys() returns a character vector, cache_count() an integer,
and cache_volume() a number of bytes.
s <- local_cache() for (k in c("prices/a", "prices/b", "volumes/a")) cache_set(s, k, 1) cache_keys(s) cache_keys(s, prefix = "prices/") cache_keys(s, start = "prices/b", n = 2) cache_count(s)s <- local_cache() for (k in c("prices/a", "prices/b", "volumes/a")) cache_set(s, k, 1) cache_keys(s) cache_keys(s, prefix = "prices/") cache_keys(s, start = "prices/b", n = 2) cache_count(s)
cache_memoise() returns a function that looks each call up in the cache
first, and on a miss calls f and stores what it returns. The cache outlives
the session and is shared by every process using the cache.
The key of a call is the function's name, version and its arguments,
matched to f's formals with defaults filled in: f(1) and
f(1, verbose = FALSE) are one entry when FALSE is the default. It does
not depend on f's code; change version when a change in meaning should
invalidate what is stored. An argument that cannot be part of a key — a
connection, an environment, a function — is an error at call time: leave it
out with omit, or supply key.
Two processes missing the same call at once both run f, and one result
is kept. That is duplicated work, never a wrong result.
If the cache cannot store a result because its write lock stayed busy, it is
full or it is read-only, the result is returned anyway, with a warning of
class dazcache_memoise_unstored. A codec that cannot store it is an error.
Inside cache_transact(), a memoised call joins the transaction: a result
computed there is kept only if the block commits, and f runs while the
block holds the cache's write lock. Keep slow producers out of blocks. A
producer that hands its work to another process writing the same cache, such
as a callr or mirai worker, makes that process wait for the lock, and it
fails with a dazcache_busy error after its timeout.
A result stored as a file, with codec = codec_file(), is the path of the
cached file on a miss as on a hit, not the path f returned.
cache_memoise_key() returns the key a call would use, cache_forget()
deletes one call's entry, and cache_forget_all() every entry of the
function.
cache_memoise( f, cache, ..., expire = NULL, tags = NULL, codec = NULL, key = NULL, omit = NULL, version = 1L, name = NULL ) cache_memoise_key(f, ...) cache_forget(f, ...) cache_forget_all(f) is_cache_memoised(f)cache_memoise( f, cache, ..., expire = NULL, tags = NULL, codec = NULL, key = NULL, omit = NULL, version = 1L, name = NULL ) cache_memoise_key(f, ...) cache_forget(f, ...) cache_forget_all(f) is_cache_memoised(f)
f |
A function. |
cache |
A cache, from |
... |
For |
expire, tags, codec
|
Passed to |
key |
|
omit |
Names of arguments to leave out of the key. |
version |
A whole number, part of every key, up to |
name |
The function's name in its keys. Defaults to the name |
cache_memoise() returns the memoised function.
cache_memoise_key() returns a key's text. cache_forget() and
cache_forget_all() return the memoised function, invisibly.
is_cache_memoised() returns TRUE or FALSE.
s <- local_cache() slow_square <- function(x, verbose = FALSE) { Sys.sleep(0.1) x^2 } fast_square <- cache_memoise(slow_square, s) fast_square(4) fast_square(4) cache_memoise_key(fast_square, 4) cache_forget(fast_square, 4) # Keep an argument out of the key. fit <- cache_memoise( function(data_id, verbose = FALSE) data_id * 2, s, name = "fit", omit = "verbose" ) identical(cache_memoise_key(fit, 1), cache_memoise_key(fit, 1, verbose = TRUE))s <- local_cache() slow_square <- function(x, verbose = FALSE) { Sys.sleep(0.1) x^2 } fast_square <- cache_memoise(slow_square, s) fast_square(4) fast_square(4) cache_memoise_key(fast_square, 4) cache_forget(fast_square, 4) # Keep an argument out of the key. fit <- cache_memoise( function(data_id, verbose = FALSE) data_id * 2, s, name = "fit", omit = "verbose" ) identical(cache_memoise_key(fit, 1), cache_memoise_key(fit, 1, verbose = TRUE))
An entry of inline_max bytes or more, or one written with a file-backed
codec such as codec_file(), is stored as a file. cache_path() returns its
path without reading it, so other tools can read it in place.
The file is read-only, and identical content is one file however many keys refer to it. The path is valid while the entry lives: deleting, replacing or expiring the entry, from any process, may remove the file. Copy the file if you need it to outlive the entry.
cache_path(cache, key)cache_path(cache, key)
cache |
A cache, from |
key |
A key. |
The path, a string. A missing key is a dazcache_not_found error,
and an entry stored inline a dazcache_type_error.
s <- local_cache() cache_set(s, "numbers", runif(1e5)) path <- cache_path(s, "numbers") file.size(path) identical(readRDS(path), cache_get(s, "numbers"))s <- local_cache() cache_set(s, "numbers", runif(1e5)) path <- cache_path(s, "numbers") file.size(path) identical(readRDS(path), cache_get(s, "numbers"))
cache_set() stores a value under a key, replacing any entry there.
cache_mset() stores every element of a named list, in one transaction.
cache_delete() removes the entries for the keys given, in one transaction;
keys with no entry are ignored.
All three return the cache invisibly, so they chain with |>.
cache_set(cache, key, value, ..., expire = NULL, tags = NULL, codec = NULL) cache_mset(cache, values, ..., expire = NULL, tags = NULL, codec = NULL) cache_delete(cache, keys)cache_set(cache, key, value, ..., expire = NULL, tags = NULL, codec = NULL) cache_mset(cache, values, ..., expire = NULL, tags = NULL, codec = NULL) cache_delete(cache, keys)
cache |
A cache, from |
key |
A key. |
value |
The value to store. |
... |
Must be empty. |
expire |
When the entry expires: |
tags |
A character vector of up to 16 tags, each at most 256 bytes, to
group entries for |
codec |
The codec to write with, or |
values |
A named list: each name is a key, each element its value. |
keys |
A character vector of keys, or a list of keys. |
The cache, invisibly.
s <- local_cache() s |> cache_set("a", 1) |> cache_mset(list(b = "two", c = 3:5)) cache_keys(s) cache_delete(s, c("a", "b")) cache_keys(s)s <- local_cache() s |> cache_set("a", 1) |> cache_mset(list(b = "two", c = 3:5)) cache_keys(s) cache_delete(s, c("a", "b")) cache_keys(s)
code runs with one write transaction open on the cache. Every write inside
it commits together when code finishes, or none does if it raises an error
or is interrupted, and reads inside it see its own writes. Leaving code
early with return(), break or next is finishing it: the writes commit.
A nested cache_transact() joins the outer one.
The transaction holds the cache's write lock for as long as code runs, so
other processes' writes wait: keep it short, and never compute a value
inside it that takes long to produce. A function made with
cache_memoise() joins the block too, so on a miss its producer runs with the
lock held. It is also the fastest way to write
many entries, since the cost of making a write durable is paid once.
If the process is killed while code runs, nothing it wrote is kept. On
macOS, and every platform but Linux and Windows, its lock is not released
either: see "Details" in cache().
Name the cache inside code as usual: there is no implicit one.
cache_transact(cache, code)cache_transact(cache, code)
cache |
A cache, from |
code |
Code to run, in the calling environment. |
The value of code.
s <- local_cache() cache_set(s, "balance", 100) cache_transact(s, { cache_set(s, "balance", cache_get(s, "balance") - 30) cache_incr(s, "withdrawals") }) cache_get(s, "balance") # An error undoes the whole block. try(cache_transact(s, { cache_set(s, "balance", 0) stop("changed my mind") })) cache_get(s, "balance")s <- local_cache() cache_set(s, "balance", 100) cache_transact(s, { cache_set(s, "balance", cache_get(s, "balance") - 30) cache_incr(s, "withdrawals") }) cache_get(s, "balance") # An error undoes the whole block. try(cache_transact(s, { cache_set(s, "balance", 0) stop("changed my mind") })) cache_get(s, "balance")
length(s) is cache_count(); s[[key]] is cache_get(), an error on a
miss; s[[key]] <- value is cache_set(); as.list(s) reads every value,
warning above 1000 entries and refusing above 100,000. names(), [ and
$ are not provided: listing is cache_keys(), and a subset of a cache is
not a cache.
## S3 method for class 'dazcache_cache' length(x) ## S3 method for class 'dazcache_cache' x[[i, ...]] ## S3 replacement method for class 'dazcache_cache' x[[i, ...]] <- value ## S3 method for class 'dazcache_cache' as.list(x, ...)## S3 method for class 'dazcache_cache' length(x) ## S3 method for class 'dazcache_cache' x[[i, ...]] ## S3 replacement method for class 'dazcache_cache' x[[i, ...]] <- value ## S3 method for class 'dazcache_cache' as.list(x, ...)
x |
A cache. |
i |
A key. |
... |
Must be empty. |
value |
The value to store. |
length() an integer; [[ the value; [[<- the cache;
as.list() a named list.
s <- local_cache() s[["a"]] <- 1 s[["a"]] length(s) as.list(s)s <- local_cache() s[["a"]] <- 1 s[["a"]] length(s) as.list(s)
A codec turns a value into a file and back. The cache records which codec wrote each entry and always decodes with that one, so changing the default never makes stored entries unreadable.
codec_auto(), the default, stores a raw vector or a single string as its
bytes (codec_raw()) and everything else with codec_rds(). It never picks
a codec that loses information or needs a suggested package.
codec_rds() stores an R object with serialize(), losslessly, with
the exceptions serialize() has: an external pointer comes back null and
a connection as a number that no longer refers to it. It refuses either
as the value itself; one inside a list or an environment is stored, dead.
codec_raw() stores a raw vector, or a single string as its UTF-8 bytes,
exactly as they are.
codec_file() stores a copy of an existing file; reading the entry back
gives the path of the stored copy, which is read-only. Always file-backed.
codec() defines your own. Every process that reads its entries must pass
it to cache() in codecs.
codec( name, encode, decode, ..., ext = NULL, version = 1L, supports = NULL, always_file = FALSE ) codec_auto() codec_rds(compress = FALSE) codec_raw() codec_file()codec( name, encode, decode, ..., ext = NULL, version = 1L, supports = NULL, always_file = FALSE ) codec_auto() codec_rds(compress = FALSE) codec_raw() codec_file()
name |
A name for the codec, not one of the built-in names. An entry
records only this name, so a cache refuses a second, different codec under
a name it already knows: give a changed codec a new name or |
encode |
|
decode |
|
... |
Must be empty. |
ext |
A file extension for the stored file, without the dot, or |
version |
A whole number, raised when the encoding changes. An entry written by a newer version than the handle knows is refused. |
supports |
|
always_file |
|
compress |
Passed to |
A codec: a list with class dazcache_codec.
codec_auto() codec_rds() # A codec that stores a character vector as lines of text. lines <- codec( "lines", encode = function(value, path) writeLines(value, path, useBytes = TRUE), decode = function(path, meta) readLines(path, encoding = "UTF-8"), ext = "txt", supports = function(value) is.character(value) && !anyNA(value) ) linescodec_auto() codec_rds() # A codec that stores a character vector as lines of text. lines <- codec( "lines", encode = function(value, path) writeLines(value, path, useBytes = TRUE), decode = function(path, meta) readLines(path, encoding = "UTF-8"), ext = "txt", supports = function(value) is.character(value) && !anyNA(value) ) lines
Every error dazcache raises inherits from dazcache_error, and from exactly
one class that says what went wrong. Catch the specific class to tell "compute
it again" apart from "the store is broken":
| Class | Raised when |
dazcache_key_invalid |
An object the key encoding does not cover; a partially named vector; an anonymous memoised function without name |
dazcache_not_found |
A read of an absent or expired key without default; cache() with create = FALSE on a missing directory |
dazcache_type_error |
A counter operation on a non-counter or past 2^53; a path or lazy read of an entry of the wrong shape; a value a codec cannot store; an expire that is NA or NaN |
dazcache_codec_error |
Encoding or decoding failed; a codec's package is not installed; a record names a codec the handle does not know |
dazcache_blob_corrupt |
A read finds the bytes behind a record, a file or an inline value, missing or not the size its record holds |
dazcache_busy |
The write lock was not acquired within timeout |
dazcache_store_full |
The database reached its map_size |
dazcache_readonly |
A write on a read-only handle |
dazcache_config_conflict |
An explicit store-level setting disagrees with the stored one |
dazcache_version_unsupported |
The store was written by a newer format or key encoding |
dazcache_forked |
A handle used in a process that did not open it |
dazcache_closed |
A verb on a closed handle |
dazcache_unsupported |
The platform or this release cannot do it |
dazcache_engine_error |
Any other failure of the storage engine, with the original condition as parent
|
Conditions carry structured fields where they apply, such as key, dir,
path and codec, so a handler can act on them without parsing the message.
dazcache raises one warning, of class dazcache_memoise_unstored and
dazcache_warning: a memoised function computed a result but the cache was
busy, full or read-only, so it was returned without being stored. Its
parent is the error that prevented storing it.