| 1 | # `bkt` |
| 2 | |
| 3 | [](https://github.com/dimo414/bkt/releases) |
| 4 | [](https://crates.io/crates/bkt) |
| 5 | [](https://docs.rs/bkt) |
| 6 | [](https://github.com/dimo414/bkt/actions) |
| 7 | [](https://github.com/dimo414/bkt/issues) |
| 8 | [](https://github.com/dimo414/bkt/blob/master/LICENSE) |
| 9 | |
| 10 | `bkt` (pronounced "bucket") is a subprocess caching utility written in Rust, |
| 11 | inspired by [bash-cache](https://github.com/dimo414/bash-cache). |
| 12 | Wrapping expensive process invocations with `bkt` allows callers to reuse recent |
| 13 | invocations without complicating their application logic. This can be useful in |
| 14 | shell prompts, interactive applications such as [`fzf`](#fzf), and long-running |
| 15 | programs that poll other processes. |
| 16 | |
| 17 | `bkt` is available as a standalone binary as well as a |
| 18 | [Rust library](https://crates.io/crates/bkt). See https://docs.rs/bkt/ for |
| 19 | library documentation. This README covers the `bkt` binary. |
| 20 | |
| 21 | ## Installation |
| 22 | |
| 23 | Run `cargo install bkt` to compile and install `bkt` locally. You will need to |
| 24 | [install `cargo`](https://doc.rust-lang.org/cargo/getting-started/installation.html) |
| 25 | if it's not already on your system. |
| 26 | |
| 27 | Pre-compiled binaries for common platforms are attached to each |
| 28 | [release](https://github.com/dimo414/bkt/releases) (starting with 0.5). Please |
| 29 | open an issue or send a PR if you would like releases to include binaries for |
| 30 | additional platforms. |
| 31 | |
| 32 | Package manager support is being tracked |
| 33 | [here](https://github.com/dimo414/bkt/issues/12); volunteers are welcome. |
| 34 | |
| 35 | [](https://repology.org/project/bkt/versions) |
| 36 | |
| 37 | ## Usage |
| 38 | |
| 39 | ``` |
| 40 | bkt [--ttl=DURATION] [--stale=DURATION] [--cwd] [--env=ENV ...] [--modtime=FILE ...] [--scope=SCOPE] [--discard-failures] [--warm|--force] -- <command>... |
| 41 | ``` |
| 42 | |
| 43 | The easiest way to use `bkt` is to simply prefix the command you intend to |
| 44 | cache with `bkt --`, for example: |
| 45 | |
| 46 | ```shell |
| 47 | # Execute and cache an invocation of 'date +%s.%N' |
| 48 | $ bkt -- date +%s.%N |
| 49 | 1631992417.080884000 |
| 50 | |
| 51 | # A subsequent invocation reuses the same cached output |
| 52 | $ bkt -- date +%s.%N |
| 53 | 1631992417.080884000 |
| 54 | ``` |
| 55 | |
| 56 | When `bkt` is passed a command it hasn't seen before (or recently) it executes |
| 57 | the command synchronously and caches its stdout, stderr, and exit code. Calling |
| 58 | `bkt` again with the same command reads the data from the cache and outputs it |
| 59 | as if the command had been run again. |
| 60 | |
| 61 | ### Cache Lifespan |
| 62 | |
| 63 | Two flags, `--ttl` and `--stale`, configure how long cached data is preserved. |
| 64 | By default `bkt` uses a TTL (Time to Live) of 60 seconds, meaning cached |
| 65 | data older than sixty seconds will be discarded and the backing command re-run. |
| 66 | Passing a different value, such as `--ttl=1d`, will change how long the cached |
| 67 | data is considered valid. The default TTL can be overriden by defining a |
| 68 | `BKT_TTL` environment variable. |
| 69 | |
| 70 | When the data expires `bkt` has to re-execute the command synchronously, which |
| 71 | can introduce unexpected slowness. To avoid this, pass `--stale` with a shorter |
| 72 | duration than the TTL. When the cached data is older than the stale threshold |
| 73 | this causes `bkt` to refresh the cache in the background while still promptly |
| 74 | returning the cached data. |
| 75 | |
| 76 | Both flags (and `BKT_TTL`) accept duration strings such as `10s` or |
| 77 | `1hour 30min`. The exact syntax is defined in the |
| 78 | [humantime](https://docs.rs/humantime/2.1.0/humantime/fn.parse_duration.html) |
| 79 | library. |
| 80 | |
| 81 | ### Execution Environment |
| 82 | |
| 83 | Some commands' behavior depends on more than just the command line arguments. |
| 84 | It's possible to adjust how `bkt` caches such commands so that unrelated |
| 85 | invocations are cached separately. |
| 86 | |
| 87 | #### Working Directory |
| 88 | |
| 89 | For example, attempting to cache `pwd` will not work as expected by default: |
| 90 | |
| 91 | ```shell |
| 92 | $ $ bkt -- pwd |
| 93 | /tmp/foo |
| 94 | |
| 95 | $ cd ../bar |
| 96 | |
| 97 | # Cached output for 'pwd' is reused even though the directory has changed |
| 98 | $ bkt -- pwd |
| 99 | /tmp/foo |
| 100 | ``` |
| 101 | |
| 102 | To have `bkt` key off the current working directory in addition to the command |
| 103 | line arguments pass `--cwd`: |
| 104 | |
| 105 | ```shell |
| 106 | $ bkt --cwd -- pwd |
| 107 | /tmp/foo |
| 108 | |
| 109 | $ cd ../bar |
| 110 | |
| 111 | $ bkt --cwd -- pwd |
| 112 | /tmp/bar |
| 113 | ``` |
| 114 | |
| 115 | #### Environment Variables |
| 116 | |
| 117 | Similarly, to specify one or more environment variables as relevant for the |
| 118 | command being cached use `--env`, such as `--env=LANG`. This flag can be |
| 119 | provided multiple times to key off additional variables. Invocations with |
| 120 | different values for any of the given variables will be cached separately. |
| 121 | |
| 122 | #### File Modifications |
| 123 | |
| 124 | It is also possible to have `bkt` check the last-modified time of one or more |
| 125 | files and include this in the cache key using `--modtime`. For instance passing |
| 126 | `--modtime=/etc/passwd` would cause the backing command to be re-executed any |
| 127 | time `/etc/passwd` is modified. |
| 128 | |
| 129 | ### Refreshing Manually |
| 130 | |
| 131 | It's also possible to trigger refreshes manually using `--force` or `--warm`. |
| 132 | The former behaves exactly as if the cached data was not found, executing the |
| 133 | process and caching the result. This is useful if you know the cached data |
| 134 | is no longer up-to-date, e.g. because something external changed. |
| 135 | |
| 136 | Alternatively, it can be useful to refresh the cache asynchronously, which |
| 137 | `--warm` provides. This triggers a refresh in the background but immediately |
| 138 | ends the current process with no output. This is useful if you expect |
| 139 | additional invocations in the near future and want to ensure they get a cache |
| 140 | hit. Note that until the warming process completes concurrent calls may still |
| 141 | see a cache miss and trigger their own invocation. |
| 142 | |
| 143 | ### Setting a Cache Scope |
| 144 | |
| 145 | Cached data is persisted to disk (but see [below](#cache_dir)), and is |
| 146 | available to any process that invokes `bkt`. Generally this is desirable, but |
| 147 | certain usages may want to isolate their invocations from other potential |
| 148 | concurrent calls. |
| 149 | |
| 150 | To do so pass `--scope=...` with a sufficiently unique argument, such as a fixed |
| 151 | label for the calling program, the current process ID, or a timestamp. |
| 152 | |
| 153 | ```shell |
| 154 | $ bkt -- date +%s.%N |
| 155 | 1631992417.080884000 |
| 156 | |
| 157 | # Changing the scope causes the command to be cached separately |
| 158 | $ bkt --scope=foo -- date +%s.%N |
| 159 | 1631992418.010562000 |
| 160 | ``` |
| 161 | |
| 162 | Alternatively, define a `BKT_SCOPE` environment variable to configure a |
| 163 | consistent scope across invocations. This can be useful within a script to |
| 164 | ensure all commands share a scope. |
| 165 | |
| 166 | ```shell |
| 167 | #!/bin/bash |
| 168 | |
| 169 | # Set a unique scope for this script invocation using the PID and current time |
| 170 | export BKT_SCOPE="my_script_$$_$(date -Ins)" |
| 171 | ``` |
| 172 | |
| 173 | ### Discarding Failed Invocations |
| 174 | |
| 175 | By default, all invocations are cached regardless of their output or exit code. |
| 176 | In situations where failures should not be cached pass `--discard-failures` to |
| 177 | only persist successful invocations (those that return a `0` exit code). |
| 178 | |
| 179 | **WARNING:** Passing this flag can cause the backing command to be invoked more |
| 180 | frequently than the `--ttl` would suggest, which in turn can create unexpected |
| 181 | load. If the backing command is failing due to an outage or bug (such as an |
| 182 | overloaded website) triggering additional calls can exacerbate the issue and |
| 183 | effectively DDoS the hampered system. It is generally safer *not* to set this |
| 184 | flag and instead make the client robust to occasional failures. |
| 185 | |
| 186 | <a name="cache_dir"></a> |
| 187 | ### Changing the Cache Directory |
| 188 | |
| 189 | By default, cached data is stored under `/tmp` or a similar temporary directory; |
| 190 | this can be customized via the `--cache-dir` flag or by defining a |
| 191 | `BKT_CACHE_DIR` environment variable. |
| 192 | |
| 193 | If a `BKT_TMPDIR` environment variable is defined it wil be used instead of the |
| 194 | system's temporary directory. Although `BKT_TMPDIR` and `BKT_CACHE_DIR` have |
| 195 | similar effects `BKT_TMPDIR` is intended to be used to configure the global |
| 196 | cache location (e.g. by declaring it in your `.bashrc` or similar), while |
| 197 | `--cache-dir`/`BKT_CACHE_DIR` should be used to customize the cache location |
| 198 | for a given set of invocations that shouldn't use the default cache directory. |
| 199 | |
| 200 | Note that the choice of directory can affect `bkt`'s performance: if the cache |
| 201 | is stored under a [`tmpfs`](https://en.wikipedia.org/wiki/Tmpfs) or solid-state |
| 202 | partition it will be significantly faster than caching to a spinning disk. |
| 203 | |
| 204 | ## Security and Privacy |
| 205 | |
| 206 | The default cache directory is potentially world-readable. On Unix the cache |
| 207 | directory is created with `700` permissions, meaning only the current user can |
| 208 | access it, but this is not foolproof. |
| 209 | |
| 210 | You can customize the cache directory (see [above](#cache_dir)) to a location |
| 211 | you trust such as `~/.bkt`, but note that your home directory may be slower than |
| 212 | the temporary directory selected by default. |
| 213 | |
| 214 | In general, if you are not the only user of your system it's wise to configure |
| 215 | your `TMPDIR` to a location only you can access. If that is not possible use |
| 216 | `BKT_TMPDIR` to configure a custom temporary directory specifically for `bkt`. |
| 217 | |
| 218 | ## Patterns and Tips |
| 219 | |
| 220 | **Please share how you're using `bkt` on the |
| 221 | [Discussion Board](https://github.com/dimo414/bkt/discussions/categories/show-and-tell)!** |
| 222 | |
| 223 | <a name="fzf"></a> |
| 224 | ### Speeding up `fzf` and other preview tools |
| 225 | |
| 226 | `bkt` works well with interactive tools like |
| 227 | [`fzf`](https://github.com/junegunn/fzf) that execute other commands. Because |
| 228 | `fzf` executes the `--preview` command every time an element is selected it can |
| 229 | be slow and tedious to browse when the command takes a long time to run. Using |
| 230 | `bkt` allows each selection's preview to be cached. Compare: |
| 231 | |
| 232 | ```shell |
| 233 | $ printf '%s\n' 1 0.2 3 0.1 5 | \ |
| 234 | fzf --preview="bash -c 'sleep {}; echo {}'" |
| 235 | |
| 236 | $ printf '%s\n' 1 0.2 3 0.1 5 | \ |
| 237 | fzf --preview="bkt --ttl=10m --stale=10s -- bash -c 'sleep {}; echo {}'" |
| 238 | ``` |
| 239 | |
| 240 | You'll generally want to use a long TTL and a short stale duration so that |
| 241 | even if you leave `fzf` running for a while the cache remains warm and is |
| 242 | refreshed in the background. You may also want to set a `--scope` if it's |
| 243 | important to invalidate the cache on subsequent invocations. |
| 244 | |
| 245 | Note: one downside to using `bkt` is, currently, `bkt` doesn't |
| 246 | [stream](https://github.com/junegunn/fzf/pull/2215) the backing process' output. |
| 247 | This means when `bkt` has a cache miss the preview will be absent until the |
| 248 | process completes, even if partial output could be displayed sooner. |
| 249 | |
| 250 | ### Using `bkt` only if installed |
| 251 | |
| 252 | You may want to distribute shell scripts that utilize `bkt` without requiring |
| 253 | every user also install `bkt`. By wrapping `bkt` in a shell function your script |
| 254 | can cleanly invoke `bkt` if available without complicating your users' workflow. |
| 255 | Of course if they choose to install `bkt` they'll get a faster script as a |
| 256 | result! |
| 257 | |
| 258 | ``` |
| 259 | # Cache commands using bkt if installed |
| 260 | if command -v bkt >&/dev/null; then |
| 261 | bkt() { command bkt "$@"; } |
| 262 | else |
| 263 | # If bkt isn't installed skip its arguments and just execute directly. |
| 264 | # Optionally write a msg to stderr suggesting users install bkt. |
| 265 | bkt() { |
| 266 | while [[ "$1" == --* ]]; do shift; done |
| 267 | "$@" |
| 268 | } |
| 269 | fi |
| 270 | |
| 271 | # Now you can call bkt (the function) just like you'd call bkt (the binary): |
| 272 | bkt -- expensive_cmd ... |
| 273 | ``` |
| 274 | |
| 275 | ### Decorating commands with `bkt` in shell scripts |
| 276 | |
| 277 | It is sometimes helpful to cache _all_ invocations of a command in a shell |
| 278 | script or in your shell environment. You can use a decorator function pattern |
| 279 | similar to what bash-cache does to enable caching transparently, like so: |
| 280 | |
| 281 | ```shell |
| 282 | # This is Bash syntax, but other shells support similar syntax |
| 283 | expensive_cmd() { |
| 284 | bkt [bkt args ...] -- expensive_cmd "$@" |
| 285 | } |
| 286 | ``` |
| 287 | |
| 288 | Calls to `expensive_cmd` in your shell will now go through `bkt` behind the |
| 289 | scenes. This can be useful for brevity and consistency but obviously changing |
| 290 | behavior like this is a double-edged-sword, so use with caution. Should you |
| 291 | need to bypass the cache for a single invocation Bash provides the |
| 292 | [`command` builtin](https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html#index-command), |
| 293 | so `command expensive_cmd ...` will invoke `expensive_cmd` directly. Other |
| 294 | shells provide similar features. |