| ... | @@ -0,0 +1,346 @@ |
| 1 | --- |
| 2 | layout: "#src/blog/tags/blog-layout.marko" |
| 3 | meta: |
| 4 | title: Clover's Progress API, Modular Abstractions, and "Good" API Design |
| 5 | description: yo we meow these |
| 6 | keywords: ["webdev", "software design"] |
| 7 | authors: ["clover caruso"] |
| 8 | embed: |
| 9 | thumbnail: /open-graph/next-js.png |
| 10 | canonical: /blog/webdev/progress-and-api-design |
| 11 | date: "Mar 10th, 2026" |
| 12 | --- |
| 13 | |
| 14 | -- A small demo here |
| 15 | |
| 16 | Great Libraries begin as small helpers for a specialized use case, then |
| 17 | extracted into their own projects because they are deemed useful. When a small |
| 18 | component of one project becomes its own piece of software, it's critical to |
| 19 | design the abstraction to be simple, understandable and modular. |
| 20 | |
| 21 | In this post, we'll take a look thru two of my recent library projects: |
| 22 | [`@clo/lib/progress.ts`][progress] and [`@clo/react-mutation`]. Both of these |
| 23 | libraries are written with great care to their API surface. They are also great |
| 24 | examples since they are mostly written from scratch (Progress depends on |
| 25 | `node:process`, React Mutation depends on React) and are easy to analyze. |
| 26 | |
| 27 | > While this post is going to be focused on web development with TypeScript, |
| 28 | > the overall ideas translate to any language or tool. For example, a carefully |
| 29 | > designed `interface` could be represented in C as a pointer table, or in Rust |
| 30 | > with a `dyn` trait, obviously with proper consideration to the problem. |
| 31 | |
| 32 | <table-of-contents /> |
| 33 | |
| 34 | ## Why is a *Progress Bar* Library Exciting? |
| 35 | |
| 36 | Everything in Clover Progress is modular. For an introduction into how it's |
| 37 | actually used, we'll start with instrumenting a little video encoding workflow. |
| 38 | |
| 39 | ```tsx diff |
| 40 | +import * as progress from "lib/progress.ts"; |
| 41 | |
| 42 | // these other libraries will not be focused on that much |
| 43 | import * as ffmpeg from "lib/subprocess/ffmpeg.ts"; |
| 44 | import * as queue from "lib/queue.ts"; |
| 45 | import * as fs from "node:fs/promises"; |
| 46 | import * as path from "node:path"; |
| 47 | |
| 48 | export async function mediaScanner( |
| 49 | rootDir: string, |
| 50 | + // accept `Ref` into any function you'd like to trace |
| 51 | + progress: progress.Ref, |
| 52 | ) { |
| 53 | + // Automatically called `rootNode.end()` with the `using` syntax. |
| 54 | + using rootNode = progress.start(`Scan ${rootDir}`, { total: 1 }); |
| 55 | + |
| 56 | + // With a `progress.Node`, changing the status is done with setters |
| 57 | + rootNode.text = "Scanning..."; // to change the status text |
| 58 | + rootNode.value = 0; // to change the number of completed items |
| 59 | + rootNode.total = 1; // to change the number of total items |
| 60 | |
| 61 | - let active = 1; |
| 62 | const completion = Promise.withResolvers<void>(); |
| 63 | |
| 64 | // `queue.wrap` returns a function that limits concurrency to |
| 65 | // the number of cpu cores available (also usable as a priority queue) |
| 66 | const recurse = queue.wrap(async (file: string) => { |
| 67 | + // Progress Nodes can have children with `.start()` |
| 68 | + // Since it is not given a `total`, this won't have a bar. |
| 69 | + using fileNode = rootNode.start(file); |
| 70 | |
| 71 | await new Promise((resolve) => setTimeout(resolve, 100)); // demo |
| 72 | |
| 73 | const stat = await fs.stat(file); |
| 74 | if (stat.isDirectory()) { |
| 75 | const children = await fs.readdir(file); |
| 76 | |
| 77 | + // Mutation schedules a re-render, batched reasonably. |
| 78 | + rootNode.total += children.length; |
| 79 | - active += children.length; |
| 80 | |
| 81 | for (const child of children) { |
| 82 | recurse(path.join(file, child)); |
| 83 | } |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | if (file.endsWith(".mov")) { |
| 88 | + // in my library, there is also a wrapper for spawning `ffmpeg` with |
| 89 | + // automatic progress tracking. we'll track this under the file node. |
| 90 | await ffmpeg.spawn({ |
| 91 | args: ["-i", file, "-c:v", "libx264", file.replace(".mov", ".mp4"), "-y"], |
| 92 | + progress: fileNode.start("encode h.264 mp4"), |
| 93 | }); |
| 94 | + // (the ffmpeg helper calls `.end()` for us. |
| 95 | } |
| 96 | |
| 97 | + rootNode.value += 1; // increment the progress by one |
| 98 | |
| 99 | + // You can use the value and total as regular variables. |
| 100 | + if (rootNode.value === rootNode.total) { |
| 101 | - if (--active === 0) { |
| 102 | completion.resolve(); // all done! |
| 103 | } |
| 104 | }); |
| 105 | |
| 106 | recurse(rootDir); |
| 107 | |
| 108 | await completion.promise; |
| 109 | } |
| 110 | ``` |
| 111 | |
| 112 | To run it, an existing progress node could be passed, or the global `progress` |
| 113 | module also satisfies this interface (`Ref` is simply just anything with the |
| 114 | `start` function). |
| 115 | |
| 116 | ```ts |
| 117 | import * as progress from "@clo/lib/progress.ts"; |
| 118 | |
| 119 | await mediaScanner("/Users/clo/media", progress); |
| 120 | |
| 121 | // or compose as a part of a larger program |
| 122 | export function doTheMediaScanningPart(ref: progress.Ref) { |
| 123 | await mediaScanner("/Users/clo/media", ref); |
| 124 | |
| 125 | using _ = ref.start("upload resulting files"); |
| 126 | // ... |
| 127 | } |
| 128 | ``` |
| 129 | |
| 130 | The above example is a very, very abridged version of the [`file-scan.ts`] |
| 131 | script that powers my website's [file viewer]. But with just this code, we've |
| 132 | shown a real world use case made better with this simple progress tracing. Watch |
| 133 | as the logs for each `ffmpeg` process are displayed under their respective node, |
| 134 | and then when the process finishes each encoding's logs are grouped together. |
| 135 | This has made it much easier for me to debug errors when they happen, especially |
| 136 | on long encoding sessions when I was first writing the script. |
| 137 | |
| 138 | [`file-scan.ts`]: https://git.paperclover.net/clo/sitegen/src/branch/master/src/file-viewer/bin/file-scan.ts |
| 139 | [file viewer]: /file |
| 140 | |
| 141 | <clover-video |
| 142 | file="/2026/progress blog post/01 - file viewer clone.mp4" |
| 143 | /> |
| 144 | |
| 145 | I've still been exploring more uses of Clover Progress, but here are some more |
| 146 | little demos. |
| 147 | |
| 148 | -- TODO: make all of these visual demos with asciinema / real demo |
| 149 | |
| 150 | - DB Migrations |
| 151 | - At my work, we used an [early version] of Clover Progress to visualize the |
| 152 | long-running migrations. Top level `console.log`s don't interfere with the |
| 153 | Terminal UI, making it easy to add this to an existing codebase. The |
| 154 | estimation algorithm was added upstream after we kept copy-pasting it |
| 155 | between migrations. |
| 156 | - Developer CLIs |
| 157 | - The presentation of `value`/`total` can be customized, for example |
| 158 | `units: "bytes"`. Progress trees are just amazing for visualizing |
| 159 | parallel or multi-threaded work. |
| 160 | - HTTP Server |
| 161 | - In development, separate trees can be used to show different requests, or |
| 162 | also identify slow routes by visually spotting them in the log. This example |
| 163 | can be tested with the simple HTTP server provided by `@clo/lib/http`. |
| 164 | - Server${'<->'}Browser IPC |
| 165 | - A headless progress instance can be created with `new progress.Root`, and |
| 166 | that root can be serialized into a `ReadableStream` to be decoded and |
| 167 | rendered in a browser. |
| 168 | - AI Sub-agents |
| 169 | - Thinking traces and complex tool calls from concurrent agents are hard to |
| 170 | visualize. This demo isn't really concrete yet, but I'm looking to |
| 171 | optionally integrate Clover Progress into a friend's [AI SDK project]. |
| 172 | |
| 173 | [early version]: https://jsr.io/@clo/console |
| 174 | |
| 175 | ## The Most Important Aspect of Library Design |
| 176 | |
| 177 | Before I dive into concepts , I want to share the most important thing about |
| 178 | library design: **you MUST drive library decisions from |
| 179 | real-world testing**, otherwise you have no idea what actually works or not. An |
| 180 | idea may seem great on paper, but with its hidden flaws only revealled after |
| 181 | it's done. |
| 182 | |
| 183 | As one creates more and more libraries, this becomes less of a concern. I'm |
| 184 | able to somewhat correctly predict how an API will feel to use (insert joke |
| 185 | aboout Next.js 16), so I can get pretty far without testing. But even then, the |
| 186 | feedback provided from testing will always shine light on the gaps, especially |
| 187 | when *other* people test it. |
| 188 | |
| 189 | With my library demo out of the way, let's take a look at some fun patterns I've |
| 190 | found: |
| 191 | |
| 192 | ## Trivial Interfaces |
| 193 | |
| 194 | `progress` mostly revolves around one interface, `progress.Ref`, a reference |
| 195 | point for reporting progress. Functions that can report live progress take it as |
| 196 | a parameter. |
| 197 | |
| 198 | ```ts |
| 199 | import * as progress from "@clo/lib/progress.ts"; |
| 200 | import { delay } from "@clo/lib/async.ts"; |
| 201 | |
| 202 | // (imported as progress.Ref) |
| 203 | interface Ref { |
| 204 | /** |
| 205 | * creates a new trackable unit of work as a child of this one. |
| 206 | * when given an estimate, a progress bar is rendered. |
| 207 | */ |
| 208 | start(text: string, opts?: StartOptions): Node; |
| 209 | } |
| 210 | |
| 211 | async function doInterestingWork(p: progress.Ref) { |
| 212 | const node = p.start("doing some interesting work"); |
| 213 | |
| 214 | const subtask1 = node.start("subtask", { total: 10 }); |
| 215 | const subtask2 = node.start("subtask", { total: 30 }); |
| 216 | |
| 217 | for (let i = 0; i < 30; i += 1) { |
| 218 | subtask1.value += 1; |
| 219 | if (i % 3 === 0) subtask2.value += 1; |
| 220 | await delay(100); |
| 221 | } |
| 222 | |
| 223 | subtask1.end(); |
| 224 | subtask2.end(); |
| 225 | |
| 226 | node.end(); |
| 227 | } |
| 228 | ``` |
| 229 | |
| 230 | > To make `progress.Node` easier to use, it aliases `end` to |
| 231 | > `[Symbol.dispose]`, which can be used with the recently stabilized |
| 232 | > [`using` syntax][using]. I'll be doing that for the rest of this post. |
| 233 | |
| 234 | By taking in the `Ref` parameter (that only declares `start` instead of a full |
| 235 | `Node`), it makes this function modular to however the caller wants to report |
| 236 | progress. There are four primary ways to create a valid Ref, and they all flow |
| 237 | extremely naturally when instrumenting code. |
| 238 | |
| 239 | - `progress.Node` implements `start` to create sub-nodes. I could pass |
| 240 | `subtask1` to another function to report its progress within the sub-task. |
| 241 | - The progress module exports `start`, which means the module namespace import |
| 242 | satisfies the interface, eg `doInterestingWork(progress)`. In Node.js, tree |
| 243 | shaking isn't worth worrying about, but in the browser you could also pass |
| 244 | `progress.global` or `{ start: progress.start }` if you really wanted to be sure. |
| 245 | - A headless progress tree created via `new progress.Root()`, which is explained |
| 246 | in the next section. |
| 247 | - `progress.nullNode` returns a no-op `Node` where the `start` function returns |
| 248 | itself, all setters are no-ops. Part of the design of `Node` is that most of the |
| 249 | fields are optional, meaning a no-op `Node` implementation can just ignore the |
| 250 | existence of all of most of its fields. |
| 251 | |
| 252 | ## Headless Design |
| 253 | |
| 254 | A pattern I love for many reasons is the *headless design* pattern, where |
| 255 | something connected to global state is built up with. For Clover Progress, it |
| 256 | is possible to construct a `Root` node that does not render to a screen. |
| 257 | Instead, it takes in host APIs and acts as an event emitter. |
| 258 | |
| 259 | ```ts |
| 260 | const root = new progress.Root({ |
| 261 | delay, // optionally pass a different timer function |
| 262 | now, // optionally pass a different "now" function |
| 263 | }); |
| 264 | root.on("change", (activeItems: progress.ReadOnlyNode[]) => { |
| 265 | console.log(activeItems); // update the screen |
| 266 | }); |
| 267 | |
| 268 | // root has a start function, so this works with no edits |
| 269 | // to the actual codebase. |
| 270 | mediaScanner("C:\\media", root); |
| 271 | ``` |
| 272 | |
| 273 | There's actually a second layer to this. The code used to implement TUI |
| 274 | "widgets", the items in the terminal that persist after console logs, is a more |
| 275 | advanced version of this. In addition to taking timing APIs, it also takes a |
| 276 | handle to the terminal output. By providing a system environment, a few |
| 277 | functions are returned. The most important, `startWidget`, is what the Clover |
| 278 | Progress TUI is made up on. With this abstraction boundary, the progress code |
| 279 | does not need to worry about redrawing the screen, but instead just formatting |
| 280 | the ANSI output. |
| 281 | |
| 282 | ```ts |
| 283 | // @clo/lib/log.ts |
| 284 | export function headlessWidgetHost(env: HeadlessWidgetEnv): HeadlessWidgetHost; |
| 285 | |
| 286 | /** {@linkcode widgetHost}'s input takes terminal i/o as well as timing APIs */ |
| 287 | export interface HeadlessWidgetEnv { |
| 288 | /** recieves ANSI escape sequences for interactive data */ |
| 289 | writeInteractive(text: string): void; |
| 290 | /** recieves log content (from `writeLine`) */ |
| 291 | writeOutput(text: string): void; |
| 292 | /** monotonic milliseconds */ |
| 293 | now(): ReturnType<typeof performance.now>; |
| 294 | /** after resolving, `now()` should have increased by the delay time */ |
| 295 | delay: typeof async.delay; |
| 296 | /** called often. */ |
| 297 | getSize(): { columns: number; rows: number }; |
| 298 | } |
| 299 | |
| 300 | /** an implementation of an ANSI-based widget host */ |
| 301 | export interface HeadlessWidgetHost { |
| 302 | /** see the top-level {@linkcode writeLine} function */ |
| 303 | writeLine(text: string): void; |
| 304 | /** see the top-level {@linkcode getDrawLock} function */ |
| 305 | getDrawLock(): ts.Dispose; |
| 306 | /** see the top-level {@linkcode startWidget} function */ |
| 307 | startWidget(widget: Widget): ts.Dispose; |
| 308 | /** stop all widgets and remove all timers. */ |
| 309 | cancel(): void; |
| 310 | /** generic delay function */ |
| 311 | delay?: typeof async.delay; |
| 312 | /** generic now function */ |
| 313 | now?: typeof performance.now; |
| 314 | } |
| 315 | ``` |
| 316 | |
| 317 | What I love about this is it means my code doesn't have any dependencies, |
| 318 | except for an *optional* dependency on `node:process` if you use the global |
| 319 | progress node. |
| 320 | |
| 321 | ### Testing |
| 322 | |
| 323 | -- theyre just beautiful holy shit |
| 324 | |
| 325 | ### Alternate Platforms |
| 326 | |
| 327 | -- talk about browser progress more |
| 328 | |
| 329 | ### Serialization |
| 330 | |
| 331 | -- talk about encodeByteStream |
| 332 | -- this use case is still being proven |
| 333 | |
| 334 | ## Good Abstractions Should be Hard to Design |
| 335 | |
| 336 | (or, why i don't want to release a billion libraries) |
| 337 | |
| 338 | ### Overcooked Design |
| 339 | |
| 340 | -- It's very easy to get carried away, especially in javascript |
| 341 | -- Avoid Unreadable Generics |
| 342 | -- Please do not change the language (cough cough Next) |
| 343 | |
| 344 | ### Okay so I might have actually overcooked it |
| 345 | |
| 346 | ... |