Repository navigation
Server-side Kindle→EPUB conversion (mobi/azw/azw3) for in-app reading - #171
Conversation
Server-side MOBI/AZW/AZW3 -> EPUB conversion so the Android in-app reader
can render Kindle-family ebooks. Conversion runs in-process via libmobi's
mobitool compiled to wasm32-wasi, executed by wazero (pure Go) -- no cgo,
no external binary, arch-independent, sandboxed untrusted input.
This commit lands the design + the validated build artifact (spike done):
- docs/.../2026-06-17-kindle-epub-conversion-design.md (Codex-reviewed;
9 review fixes folded in: failure contract, strong cache key + negative
cache, wazero command-module specifics, FS-sandbox tightening,
double-gated capability, serve headers, .wasm guardrails).
- tools/mobitool-wasm/{Dockerfile,README.md}: reproducible build of
mobitool.wasm (wasi-sdk 25, libmobi 9062742, zlib 1.3.1->wasm), with a
smoke-conversion gate. Build proven on native amd64.
- internal/ebookconvert/mobitool.wasm (+ .sha256): canonical artifact,
built on amd64. go:embed target for the converter package (next).
Spike proven on amd64: -e EPUB path works with --with-libxml2=no (internal
xmlwriter); converts MOBI6/KF8/HUFF-CDIC/unicode -> well-formed EPUB;
verified end-to-end under wazero (WASI preopen + argv + _start). Build
gotcha: link libmobi against real (wasm) zlib, not --with-zlib=no, to avoid
miniz duplicate-symbol clash with mobitool's zip miniz. DRM gotcha:
mobitool prints "Document is encrypted" to stdout but exits 0 -> detect via
stdout + output validation, not exit code.
Not yet implemented: internal/ebookconvert Go package (wazero harness +
cache + singleflight), read-handler wiring, admin flag, client capability.
v1-scope proposal required before PR.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
internal/ebookconvert: in-process MOBI/AZW/AZW3 -> EPUB via the embedded mobitool.wasm on wazero. Converter compiles the module once and instantiates per conversion (isolated). Cache adds on-disk, singleflighted, size-bounded, negative-cached conversion keyed by file identity + module fingerprint. 18 tests pass (DRM-free->valid EPUB, DRM->ErrDRMProtected + no output, oversize/corrupt/missing/timeout/cancel/after-close, 6/8-way concurrent, EPUB structural validation incl. stored-mimetype + container rootfile, cache miss/hit/key-change/singleflight/eviction/negative-cache). Codex review fixes folded in: - timeout/cancel classified before generic nonzero exit (WithCloseOnContextDone surfaces sys.ExitError special codes); no more bogus "exit <huge>". - DRM detection scoped to known mobitool diagnostic LINES (Document is encrypted / DRM key not found / Invalid DRM pid / DRM expired / DRM support not included) -> no false-positive on book text; Print Replica -> clear fail. - WithMemoryLimitPages cap; capped stdout/stderr writers; MaxOutputBytes. - read-only fs.FS input mount + dedicated writable out dir; documented that FS isolation ultimately relies on running as a non-root user (memory-safety is the WASM boundary). validateEpub now requires STORED mimetype + verifies the container.xml OPF rootfile exists. Atomic moveFile. Closed-guard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…dpoint
Server now transparently serves Kindle-family ebooks as EPUB when the admin
flag ebook.kindle_conversion_enabled is on and the WASM converter initialized.
- handlers.EbookConversion (converter + per-request flag predicate) on the read
handler; HandleReadFile -> h.serveEbook. Kindle + enabled -> cached EPUB with
X-Silo-Ebook-Conversion: converted, epub MIME, ETag = exact conversion cache
key, must-revalidate. Failure (DRM/corrupt/oversize/unservable) -> raw
original + X-Silo-Ebook-Conversion: failed + no-store, so the client opens
externally. Context cancel propagates (not a conversion verdict).
- GET /api/v1/ebooks/capability advertises {enabled, source_formats,
served_format, header contract}; enabled only when flag on AND converter
wired (double gate) so the Android client can decide whether to flip
mobi/azw/azw3 to in-app.
- router: buildEbookConversion compiles the module once at startup (feature off
if it fails), cache dir is a sibling of TranscodeDir, flag read per request.
Codex review fixes folded in: ETag derived from the exact SourceKey cache key
(id+size+mtime+oshash+module version), not a weaker hash; no-store on the raw
fallback; open/stat failure of a produced EPUB falls back to raw per the
contract instead of 500. 10 handler tests pass.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
📝 WalkthroughWalkthroughAdds an end-to-end server-side Kindle-family (MOBI/AZW/AZW3) → EPUB conversion feature: a Docker-built ChangesKindle→EPUB Conversion Pipeline
Sequence Diagram(s)sequenceDiagram
participant Client as Android Client
participant Router as HTTP Router
participant Handler as EbookReaderHandler
participant Cache as ebookconvert.Cache
participant Conv as Converter (wazero)
rect rgba(100, 150, 255, 0.5)
note over Client,Router: GET /api/v1/ebooks/:id/read
Client->>Router: request Kindle file
Router->>Handler: serveEbook(w, r, file)
end
rect rgba(100, 200, 150, 0.5)
note over Handler,Cache: Conversion active + Kindle format
Handler->>Cache: GetOrConvert(ctx, srcPath, SourceKey)
alt cache hit
Cache-->>Handler: cachedEpubPath
else cache miss
Cache->>Conv: Convert(ctx, srcPath, tmpPath)
Conv-->>Cache: ok or ErrDRMProtected/ErrConversionFailed
Cache-->>Handler: cachedEpubPath or error
end
end
rect rgba(255, 180, 100, 0.5)
note over Handler,Client: Serve result
alt conversion succeeded
Handler-->>Client: 200/206 EPUB + X-Silo-Ebook-Conversion: converted
else ctx cancelled
Handler-->>Client: propagated error (no conversion header)
else conversion failed
Handler-->>Client: raw Kindle bytes + X-Silo-Ebook-Conversion: failed
end
end
sequenceDiagram
participant Client as Android Client
participant Router as HTTP Router
participant Handler as EbookReaderHandler
Client->>Router: GET /api/v1/ebooks/capability
Router->>Handler: HandleConversionCapability(w, r)
Handler-->>Client: 200 JSON {enabled, sourceFormats, headerValues}
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/api/handlers/ebook_reader.go (1)
136-142:⚠️ Potential issue | 🟠 Major | ⚡ Quick winHandle request cancellation/timeouts before writing a 500.
serveEbooknow intentionally propagatescontext.Canceled/context.DeadlineExceeded, but this block classifies them as internal failures. That turns disconnect/timeout paths into false 500s.Suggested fix
if err := h.serveEbook(w, r, file); err != nil { + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return + } if errors.Is(err, catalog.ErrItemNotFound) { writeError(w, http.StatusNotFound, "not_found", "Ebook file not found") return } writeError(w, http.StatusInternalServerError, "internal_error", "Failed to serve ebook file") }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/ebook_reader.go` around lines 136 - 142, The error handling block for the serveEbook method call is treating context cancellation and deadline exceeded errors as internal server failures, which incorrectly returns 500 status codes for client disconnects and timeouts. Add explicit checks for errors.Is(err, context.Canceled) and errors.Is(err, context.DeadlineExceeded) before the existing catalog.ErrItemNotFound check, and handle these context errors appropriately (typically by returning without writing an error response) so that only genuine internal failures trigger the 500 response.
🧹 Nitpick comments (2)
docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md (1)
44-44: 💤 Low valueLine number reference may drift.
Line 44 references
serveEbookInlineatebook_reader.go:602as the current read handler. Line numbers shift with edits; consider a structural reference (e.g., "the current inline-read handler inebook_reader.go") to future-proof the spec.Consider revising:
- `serveEbookInline` currently (in `ebook_reader.go`) `os.Open`s `file.FilePath` and `http.ServeContent`s it with `ebookMimeType(...)`.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md` at line 44, The specification document contains a hardcoded line number reference (`:602`) pointing to `serveEbookInline` in `ebook_reader.go` at line 44. Remove the specific line number from the reference and replace it with a more durable structural reference such as "currently (in `ebook_reader.go`)" instead of the current format that includes `:602`. This ensures the documentation remains accurate even when the actual line numbers change due to code edits.internal/ebookconvert/cache.go (1)
159-171: ⚡ Quick winNegative-cache entries are not proactively pruned.
Expired keys are only removed when the same key is looked up again. With many one-off failures,
c.negcan grow indefinitely over process lifetime.Also applies to: 176-183
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/ebookconvert/cache.go` around lines 159 - 171, The negativeLookup method (and the similar method at lines 176-183) only removes expired entries from the c.neg map during a lookup of that same key, allowing stale entries to accumulate indefinitely and consume unbounded memory. Implement proactive pruning by adding a background maintenance routine (such as a periodic ticker-based cleanup goroutine) that iterates through the c.neg map and removes all entries where time.Now() is after the expiry time. This cleanup should run at regular intervals or be triggered during other cache maintenance operations to prevent unbounded growth of the negative cache.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md`:
- Line 50: Update the admin setting name in the specification document from
`ebook_kindle_conversion_enabled` to `ebook.kindle_conversion_enabled` to match
the canonical setting name used in the actual implementation in
`internal/api/ebook_conversion.go`. This ensures consistency between the design
documentation and the codebase by using the correct dot notation format for the
setting identifier.
- Line 38: The cache key description in the design spec claims to include
"output options" alongside converter build ID, libmobi commit/version, and build
flags, but the actual implementation in SourceKey.hash() within
internal/ebookconvert/cache.go only hashes source identity (file_id + size +
mtime_ns + content_hash) and converter identity (moduleVersion). Update the
design doc to remove references to "output options", "libmobi commit/version",
and "build flags" from the cache key specification, replacing them with only
what is actually implemented: source identity components and the moduleVersion
as converter identity.
In `@internal/ebookconvert/cache_test.go`:
- Around line 71-72: The GetOrConvert method calls on lines 71-72 are discarding
errors by using the blank identifier, which means conversion failures will not
be caught and the test may pass despite errors occurring. Replace the blank
identifier with an error variable for both GetOrConvert calls and add explicit
assertions (e.g., require.NoError) to verify that the conversions succeeded
before proceeding with path comparisons.
In `@internal/ebookconvert/cache.go`:
- Around line 150-152: The GetOrConvert function calls c.enforceBudget() which
may delete the file at dst (when it exceeds MaxBytes), but still returns dst as
a successful result on the next line. After calling c.enforceBudget(), check
whether the file at dst still exists. If the file was deleted by budget
enforcement, return an appropriate error instead of returning the path to a
deleted file. Apply the same fix to the other location mentioned (also around
lines 214-221) where this pattern appears.
- Around line 126-145: The c.conv.Convert call within the c.group.Do
singleflight closure uses the caller's ctx parameter, which causes all coalesced
callers to fail if any single caller's context is canceled. Replace ctx with
context.Background() in the c.conv.Convert(ctx, srcPath, tmpPath) invocation so
that the shared conversion work is decoupled from individual caller contexts and
one caller's cancellation does not fail the operation for other concurrent
requests sharing the same key.
In `@internal/ebookconvert/converter.go`:
- Around line 244-251: The parent context deadline exceeded errors are not being
properly propagated because the first condition only returns non-deadline parent
errors. When the parent context deadline expires, the code falls through to the
per-call timeout check which reclassifies it as a conversion failure. Modify the
condition checking parent.Err() to also return the parent error when it is a
DeadlineExceeded error, ensuring parent deadline errors are propagated directly
before evaluating the run.Err() and instErr deadline checks. This will prevent
misclassification of request-level deadlines as conversion failures.
In `@tools/mobitool-wasm/Dockerfile`:
- Around line 66-70: Replace the unsafe Wasmtime installer script piping command
(curl -fsSL https://wasmtime.dev/install.sh | bash) with a direct download of a
specific pinned release from the official Wasmtime GitHub Releases page.
Download the appropriate release artifact for the target architecture, compute
and verify its SHA256 checksum against the published checksum to ensure
integrity before extraction and use. Then extract the wasmtime binary from the
downloaded archive and update the subsequent path reference from
/root/.wasmtime/bin/wasmtime to point to the extracted binary location to ensure
the smoke test can locate and execute the wasmtime command properly.
In `@tools/mobitool-wasm/README.md`:
- Around line 18-27: Add blank lines to separate the pinned versions table from
surrounding content in the README.md file. Insert a blank line after the "##
Pinned versions" heading and before the table begins, and insert another blank
line after the table ends (after the "zlib | 1.3.1 (compiled to wasm) |" row)
and before the "License:" text starts. This will satisfy the MD058 markdownlint
rule which requires proper spacing around tables.
---
Outside diff comments:
In `@internal/api/handlers/ebook_reader.go`:
- Around line 136-142: The error handling block for the serveEbook method call
is treating context cancellation and deadline exceeded errors as internal server
failures, which incorrectly returns 500 status codes for client disconnects and
timeouts. Add explicit checks for errors.Is(err, context.Canceled) and
errors.Is(err, context.DeadlineExceeded) before the existing
catalog.ErrItemNotFound check, and handle these context errors appropriately
(typically by returning without writing an error response) so that only genuine
internal failures trigger the 500 response.
---
Nitpick comments:
In `@docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md`:
- Line 44: The specification document contains a hardcoded line number reference
(`:602`) pointing to `serveEbookInline` in `ebook_reader.go` at line 44. Remove
the specific line number from the reference and replace it with a more durable
structural reference such as "currently (in `ebook_reader.go`)" instead of the
current format that includes `:602`. This ensures the documentation remains
accurate even when the actual line numbers change due to code edits.
In `@internal/ebookconvert/cache.go`:
- Around line 159-171: The negativeLookup method (and the similar method at
lines 176-183) only removes expired entries from the c.neg map during a lookup
of that same key, allowing stale entries to accumulate indefinitely and consume
unbounded memory. Implement proactive pruning by adding a background maintenance
routine (such as a periodic ticker-based cleanup goroutine) that iterates
through the c.neg map and removes all entries where time.Now() is after the
expiry time. This cleanup should run at regular intervals or be triggered during
other cache maintenance operations to prevent unbounded growth of the negative
cache.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fe0851e6-ad52-480e-b236-6bab194bbd8a
📥 Commits
Reviewing files that changed from the base of the PR and between 7abfb5a and f4d2c3eb01918808333163adce4e08486a751012.
⛔ Files ignored due to path filters (2)
go.sumis excluded by!**/*.suminternal/ebookconvert/mobitool.wasmis excluded by!**/*.wasm
📒 Files selected for processing (19)
docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.mdgo.modinternal/api/ebook_conversion.gointernal/api/handlers/ebook_convert_serve.gointernal/api/handlers/ebook_convert_serve_test.gointernal/api/handlers/ebook_reader.gointernal/api/router.gointernal/ebookconvert/cache.gointernal/ebookconvert/cache_test.gointernal/ebookconvert/converter.gointernal/ebookconvert/converter_test.gointernal/ebookconvert/errors.gointernal/ebookconvert/mobitool.wasm.sha256internal/ebookconvert/testdata/README.mdinternal/ebookconvert/testdata/sample-cp1252.mobiinternal/ebookconvert/testdata/sample-drm-v1.mobiinternal/ebookconvert/testdata/sample-ncx.mobitools/mobitool-wasm/Dockerfiletools/mobitool-wasm/README.md
| ## Pinned versions | ||
| | Component | Version / commit | | ||
| |-----------|------------------| | ||
| | wasi-sdk | 25.0 | | ||
| | libmobi | `906274205c11944b628da1c553b255acb1af7c55` | | ||
| | zlib | 1.3.1 (compiled to wasm) | | ||
|
|
||
| License: libmobi is **LGPL-3.0-or-later**; shipping the unmodified compiled | ||
| artifact + this build recipe satisfies the relink obligation. zlib is zlib-license. | ||
|
|
There was a problem hiding this comment.
Add blank lines around the pinned-versions table to keep markdownlint clean.
The table should be surrounded by blank lines to satisfy MD058.
Suggested fix
## Pinned versions
+
| Component | Version / commit |
|-----------|------------------|
| wasi-sdk | 25.0 |
| libmobi | `906274205c11944b628da1c553b255acb1af7c55` |
| zlib | 1.3.1 (compiled to wasm) |
+
License: libmobi is **LGPL-3.0-or-later**; shipping the unmodified compiled
artifact + this build recipe satisfies the relink obligation. zlib is zlib-license.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ## Pinned versions | |
| | Component | Version / commit | | |
| |-----------|------------------| | |
| | wasi-sdk | 25.0 | | |
| | libmobi | `906274205c11944b628da1c553b255acb1af7c55` | | |
| | zlib | 1.3.1 (compiled to wasm) | | |
| License: libmobi is **LGPL-3.0-or-later**; shipping the unmodified compiled | |
| artifact + this build recipe satisfies the relink obligation. zlib is zlib-license. | |
| ## Pinned versions | |
| | Component | Version / commit | | |
| |-----------|------------------| | |
| | wasi-sdk | 25.0 | | |
| | libmobi | `906274205c11944b628da1c553b255acb1af7c55` | | |
| | zlib | 1.3.1 (compiled to wasm) | | |
| License: libmobi is **LGPL-3.0-or-later**; shipping the unmodified compiled | |
| artifact + this build recipe satisfies the relink obligation. zlib is zlib-license. |
🧰 Tools
🪛 markdownlint-cli2 (0.22.1)
[warning] 19-19: Tables should be surrounded by blank lines
(MD058, blanks-around-tables)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tools/mobitool-wasm/README.md` around lines 18 - 27, Add blank lines to
separate the pinned versions table from surrounding content in the README.md
file. Insert a blank line after the "## Pinned versions" heading and before the
table begins, and insert another blank line after the table ends (after the
"zlib | 1.3.1 (compiled to wasm) |" row) and before the "License:" text starts.
This will satisfy the MD058 markdownlint rule which requires proper spacing
around tables.
Source: Linters/SAST tools
f4d2c3e to
a67fbe4
Compare
…erification Addresses adversarial review + CodeRabbit findings on the Kindle->EPUB feature. Correctness: - Stop poisoning the negative cache on transient timeouts. Introduce ErrConversionTimedOut (distinct, non-wrapping ErrConversionFailed); classify the per-call timeout as transient and propagate a caller's cancel/deadline verbatim instead of reclassifying it as a conversion failure. remember() now only caches deterministic verdicts (DRM / failed), so a one-off timeout under load no longer wedges a convertible book onto raw-fallback for 6h. - Detach the singleflight conversion from any single caller's context (DoChan + context.WithoutCancel), so one caller cancelling no longer aborts the shared work for the others; the cache is still populated for the next reader. - enforceBudget never evicts the entry it is about to return, and skips other conversions' in-flight "converting-*" temp files. - Cache hits refresh mtime so the mtime-ordered budget eviction is a real LRU, not FIFO. Read path: - HEAD is now cache-only via Cache.Lookup: a hit serves real converted headers, a negatively-cached source serves the failed contract, a miss advertises the converted representation cheaply without triggering a (minute-long, ~1 GiB) conversion. The GET still delivers the body + authoritative verdict. - The admin flag is read through a short-TTL predicate so the read path and the capability endpoint no longer hit the DB per request. Artifact / build: - Add an in-code provenance test (embedded mobitool.wasm matches its recorded sha256) and a self-hosted CI job that runs the ebookconvert smoke conversions + provenance check, so the committed wasm can't silently rot. - Pin + checksum-verify wasmtime in the build Dockerfile (drop curl|bash). Docs: correct the design doc cache-key + setting-name descriptions, document the HEAD/timeout/LRU semantics and resource limits, note DRM-marker brittleness, and fix the README markdown table. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (2)
internal/api/handlers/ebook_convert_serve_test.go (1)
183-254: 💤 Low valueConsider tracking
Lookupcalls explicitly for test clarity.The HEAD tests verify that
GetOrConvertwasn't called by checkingconv.calls == 0, which is correct. However, they don't explicitly verify thatLookupwas called. While the correct headers indirectly proveLookupwas invoked, adding alookupCallscounter tofakeConverterwould make the test assertions more explicit and maintainable.📊 Optional improvement to track Lookup calls
type fakeConverter struct { epubPath string err error calls int lookupPath string lookupErr error lookupOK bool + lookupCalls int } func (f *fakeConverter) GetOrConvert(_ context.Context, _ string, _ ebookconvert.SourceKey) (string, error) { f.calls++ return f.epubPath, f.err } func (f *fakeConverter) Lookup(_ ebookconvert.SourceKey) (string, error, bool) { + f.lookupCalls++ return f.lookupPath, f.lookupErr, f.lookupOK }Then in the HEAD tests, add assertions like:
if conv.lookupCalls != 1 { t.Fatalf("HEAD should call Lookup exactly once, got %d", conv.lookupCalls) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/ebook_convert_serve_test.go` around lines 183 - 254, The HEAD tests (TestServeEbook_HeadDoesNotConvertOnMiss, TestServeEbook_HeadServesCachedConverted, TestServeEbook_HeadDRMReturnsFailed) verify that conversions weren't triggered by checking conv.calls == 0, but they don't explicitly verify that Lookup was called. Add a lookupCalls counter field to the fakeConverter struct and increment it in the Lookup method, then add assertions in each of these three test functions to verify that conv.lookupCalls equals 1, making the tests more explicit about verifying that Lookup was actually invoked rather than relying on indirect evidence from response headers..github/workflows/ebookconvert.yml (1)
49-49: ⚡ Quick winConsider adding
-vfor verbose test output.The smoke test runs real WASM conversions and provenance checks. Without
-v, CI logs will only show package-level results, making it harder to debug which specific fixture or validation failed.📋 Proposed enhancement
- run: go test ./internal/ebookconvert/... -count=1 + run: go test ./internal/ebookconvert/... -count=1 -v🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/ebookconvert.yml at line 49, The go test command for the ebookconvert package currently runs without the -v verbose flag, which limits CI log output to only package-level results. Add the -v flag to the go test ./internal/ebookconvert/... -count=1 command to enable verbose output, which will show individual test results and make it easier to identify which specific fixture or validation failed during debugging.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.github/workflows/ebookconvert.yml:
- Line 37: Replace the semantic version tags in the action references with
specific commit hashes to comply with the project's security policy. Update the
`actions/checkout@v5` reference and the other action reference at line 40 by
replacing the version tags (such as `@v5` and `@v6`) with their corresponding commit
hashes. This pins the actions to specific immutable commits rather than mutable
tags, preventing tag-rewriting attacks.
- Around line 36-37: The checkout step using `actions/checkout@v5` is missing
the `persist-credentials: false` parameter, which creates a security
vulnerability on self-hosted runners where persisted credentials in
`.git/config` could leak to subsequent workflow steps. Add the
`persist-credentials: false` input parameter to the checkout action to disable
credential persistence and mitigate this vulnerability.
- Line 49: The test command `go test ./internal/ebookconvert/... -count=1` lacks
an explicit timeout, which could cause the CI workflow to hang indefinitely if a
test becomes unresponsive. Add the `-timeout` flag to the go test command to
enforce a maximum execution time for the entire test run, ensuring the workflow
can progress even if individual tests hang. Choose an appropriate timeout value
that allows your tests to complete under normal conditions.
In `@internal/ebookconvert/cache_test.go`:
- Around line 177-180: The test is discarding the error returned from
GetOrConvert when called with a canceled context by using blank identifiers.
Instead of ignoring this error, capture the returned error value and explicitly
assert that it is not nil and represents a context cancellation (using errors.Is
with context.Canceled). This ensures the test validates that the GetOrConvert
method properly handles the canceled caller path rather than just passing
silently.
In `@internal/ebookconvert/converter_test.go`:
- Around line 105-107: The test for the Convert method with a canceled context
currently only checks that any error is returned, not specifically a context
cancellation error. Modify the error assertion to verify that the error returned
from c.Convert is specifically a context cancellation error (such as
context.Canceled) rather than accepting any non-nil error. This ensures the test
properly validates that context cancellation is being handled correctly and not
misclassified as a different type of error.
---
Nitpick comments:
In @.github/workflows/ebookconvert.yml:
- Line 49: The go test command for the ebookconvert package currently runs
without the -v verbose flag, which limits CI log output to only package-level
results. Add the -v flag to the go test ./internal/ebookconvert/... -count=1
command to enable verbose output, which will show individual test results and
make it easier to identify which specific fixture or validation failed during
debugging.
In `@internal/api/handlers/ebook_convert_serve_test.go`:
- Around line 183-254: The HEAD tests (TestServeEbook_HeadDoesNotConvertOnMiss,
TestServeEbook_HeadServesCachedConverted, TestServeEbook_HeadDRMReturnsFailed)
verify that conversions weren't triggered by checking conv.calls == 0, but they
don't explicitly verify that Lookup was called. Add a lookupCalls counter field
to the fakeConverter struct and increment it in the Lookup method, then add
assertions in each of these three test functions to verify that conv.lookupCalls
equals 1, making the tests more explicit about verifying that Lookup was
actually invoked rather than relying on indirect evidence from response headers.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: fd16f3db-0f0d-4352-be88-117e0d68a3a5
📒 Files selected for processing (14)
.github/workflows/ebookconvert.ymldocs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.mdinternal/api/ebook_conversion.gointernal/api/ebook_conversion_test.gointernal/api/handlers/ebook_convert_serve.gointernal/api/handlers/ebook_convert_serve_test.gointernal/ebookconvert/cache.gointernal/ebookconvert/cache_test.gointernal/ebookconvert/converter.gointernal/ebookconvert/converter_test.gointernal/ebookconvert/errors.gointernal/ebookconvert/provenance_test.gotools/mobitool-wasm/Dockerfiletools/mobitool-wasm/README.md
✅ Files skipped from review due to trivial changes (2)
- tools/mobitool-wasm/README.md
- docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/api/handlers/ebook_convert_serve.go
- tools/mobitool-wasm/Dockerfile
- internal/ebookconvert/converter.go
- internal/ebookconvert/cache.go
| - name: Smoke-convert fixtures + verify wasm provenance | ||
| env: | ||
| GOWORK: off | ||
| run: go test ./internal/ebookconvert/... -count=1 |
There was a problem hiding this comment.
Add an explicit timeout to the test command.
The test command has no timeout bound. While the converter itself enforces per-conversion timeouts, a hung test runner could block CI indefinitely (relying only on the GitHub Actions job-level timeout).
⏱️ Proposed fix
- run: go test ./internal/ebookconvert/... -count=1
+ run: go test ./internal/ebookconvert/... -count=1 -timeout=5m📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| run: go test ./internal/ebookconvert/... -count=1 | |
| run: go test ./internal/ebookconvert/... -count=1 -timeout=5m |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @.github/workflows/ebookconvert.yml at line 49, The test command `go test
./internal/ebookconvert/... -count=1` lacks an explicit timeout, which could
cause the CI workflow to hang indefinitely if a test becomes unresponsive. Add
the `-timeout` flag to the go test command to enforce a maximum execution time
for the entire test run, ensuring the workflow can progress even if individual
tests hang. Choose an appropriate timeout value that allows your tests to
complete under normal conditions.
| ctx, cancel := context.WithCancel(context.Background()) | ||
| cancel() // caller bails before the conversion can finish | ||
| _, _ = c.GetOrConvert(ctx, src, key) | ||
|
|
There was a problem hiding this comment.
Validate the canceled caller result explicitly.
Line 179 ignores the returned error, so this test can still pass if cancellation handling regresses for the caller path.
Suggested fix
- _, _ = c.GetOrConvert(ctx, src, key)
+ if _, err := c.GetOrConvert(ctx, src, key); !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, want context.Canceled", err)
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ctx, cancel := context.WithCancel(context.Background()) | |
| cancel() // caller bails before the conversion can finish | |
| _, _ = c.GetOrConvert(ctx, src, key) | |
| ctx, cancel := context.WithCancel(context.Background()) | |
| cancel() // caller bails before the conversion can finish | |
| if _, err := c.GetOrConvert(ctx, src, key); !errors.Is(err, context.Canceled) { | |
| t.Fatalf("got %v, want context.Canceled", err) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ebookconvert/cache_test.go` around lines 177 - 180, The test is
discarding the error returned from GetOrConvert when called with a canceled
context by using blank identifiers. Instead of ignoring this error, capture the
returned error value and explicitly assert that it is not nil and represents a
context cancellation (using errors.Is with context.Canceled). This ensures the
test validates that the GetOrConvert method properly handles the canceled caller
path rather than just passing silently.
| if err := c.Convert(ctx, filepath.Join("testdata", "sample-ncx.mobi"), dst); err == nil { | ||
| t.Fatal("expected error on canceled context") | ||
| } |
There was a problem hiding this comment.
Assert the exact cancellation error, not just “any error.”
Line 105 currently accepts any non-nil error, so this test can pass even if cancellation is misclassified.
Suggested fix
- if err := c.Convert(ctx, filepath.Join("testdata", "sample-ncx.mobi"), dst); err == nil {
- t.Fatal("expected error on canceled context")
- }
+ err := c.Convert(ctx, filepath.Join("testdata", "sample-ncx.mobi"), dst)
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v, want context.Canceled", err)
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if err := c.Convert(ctx, filepath.Join("testdata", "sample-ncx.mobi"), dst); err == nil { | |
| t.Fatal("expected error on canceled context") | |
| } | |
| err := c.Convert(ctx, filepath.Join("testdata", "sample-ncx.mobi"), dst) | |
| if !errors.Is(err, context.Canceled) { | |
| t.Fatalf("got %v, want context.Canceled", err) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/ebookconvert/converter_test.go` around lines 105 - 107, The test for
the Convert method with a canceled context currently only checks that any error
is returned, not specifically a context cancellation error. Modify the error
assertion to verify that the error returned from c.Convert is specifically a
context cancellation error (such as context.Canceled) rather than accepting any
non-nil error. This ensures the test properly validates that context
cancellation is being handled correctly and not misclassified as a different
type of error.
…Silo-Server#171) * Kindle->EPUB conversion: design + proven wasm build pipeline Server-side MOBI/AZW/AZW3 -> EPUB conversion so the Android in-app reader can render Kindle-family ebooks. Conversion runs in-process via libmobi's mobitool compiled to wasm32-wasi, executed by wazero (pure Go) -- no cgo, no external binary, arch-independent, sandboxed untrusted input. This commit lands the design + the validated build artifact (spike done): - docs/.../2026-06-17-kindle-epub-conversion-design.md (Codex-reviewed; 9 review fixes folded in: failure contract, strong cache key + negative cache, wazero command-module specifics, FS-sandbox tightening, double-gated capability, serve headers, .wasm guardrails). - tools/mobitool-wasm/{Dockerfile,README.md}: reproducible build of mobitool.wasm (wasi-sdk 25, libmobi 9062742, zlib 1.3.1->wasm), with a smoke-conversion gate. Build proven on native amd64. - internal/ebookconvert/mobitool.wasm (+ .sha256): canonical artifact, built on amd64. go:embed target for the converter package (next). Spike proven on amd64: -e EPUB path works with --with-libxml2=no (internal xmlwriter); converts MOBI6/KF8/HUFF-CDIC/unicode -> well-formed EPUB; verified end-to-end under wazero (WASI preopen + argv + _start). Build gotcha: link libmobi against real (wasm) zlib, not --with-zlib=no, to avoid miniz duplicate-symbol clash with mobitool's zip miniz. DRM gotcha: mobitool prints "Document is encrypted" to stdout but exits 0 -> detect via stdout + output validation, not exit code. Not yet implemented: internal/ebookconvert Go package (wazero harness + cache + singleflight), read-handler wiring, admin flag, client capability. v1-scope proposal required before PR. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * ebookconvert: converter core + cache (Codex-reviewed) internal/ebookconvert: in-process MOBI/AZW/AZW3 -> EPUB via the embedded mobitool.wasm on wazero. Converter compiles the module once and instantiates per conversion (isolated). Cache adds on-disk, singleflighted, size-bounded, negative-cached conversion keyed by file identity + module fingerprint. 18 tests pass (DRM-free->valid EPUB, DRM->ErrDRMProtected + no output, oversize/corrupt/missing/timeout/cancel/after-close, 6/8-way concurrent, EPUB structural validation incl. stored-mimetype + container rootfile, cache miss/hit/key-change/singleflight/eviction/negative-cache). Codex review fixes folded in: - timeout/cancel classified before generic nonzero exit (WithCloseOnContextDone surfaces sys.ExitError special codes); no more bogus "exit <huge>". - DRM detection scoped to known mobitool diagnostic LINES (Document is encrypted / DRM key not found / Invalid DRM pid / DRM expired / DRM support not included) -> no false-positive on book text; Print Replica -> clear fail. - WithMemoryLimitPages cap; capped stdout/stderr writers; MaxOutputBytes. - read-only fs.FS input mount + dedicated writable out dir; documented that FS isolation ultimately relies on running as a non-root user (memory-safety is the WASM boundary). validateEpub now requires STORED mimetype + verifies the container.xml OPF rootfile exists. Atomic moveFile. Closed-guard. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * ebookconvert: wire Kindle->EPUB into the read handler + capability endpoint Server now transparently serves Kindle-family ebooks as EPUB when the admin flag ebook.kindle_conversion_enabled is on and the WASM converter initialized. - handlers.EbookConversion (converter + per-request flag predicate) on the read handler; HandleReadFile -> h.serveEbook. Kindle + enabled -> cached EPUB with X-Silo-Ebook-Conversion: converted, epub MIME, ETag = exact conversion cache key, must-revalidate. Failure (DRM/corrupt/oversize/unservable) -> raw original + X-Silo-Ebook-Conversion: failed + no-store, so the client opens externally. Context cancel propagates (not a conversion verdict). - GET /api/v1/ebooks/capability advertises {enabled, source_formats, served_format, header contract}; enabled only when flag on AND converter wired (double gate) so the Android client can decide whether to flip mobi/azw/azw3 to in-app. - router: buildEbookConversion compiles the module once at startup (feature off if it fails), cache dir is a sibling of TranscodeDir, flag read per request. Codex review fixes folded in: ETag derived from the exact SourceKey cache key (id+size+mtime+oshash+module version), not a weaker hash; no-store on the raw fallback; open/stat failure of a produced EPUB falls back to raw per the contract instead of 500. 10 handler tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(ebookconvert): harden conversion cache, HEAD path, and artifact verification Addresses adversarial review + CodeRabbit findings on the Kindle->EPUB feature. Correctness: - Stop poisoning the negative cache on transient timeouts. Introduce ErrConversionTimedOut (distinct, non-wrapping ErrConversionFailed); classify the per-call timeout as transient and propagate a caller's cancel/deadline verbatim instead of reclassifying it as a conversion failure. remember() now only caches deterministic verdicts (DRM / failed), so a one-off timeout under load no longer wedges a convertible book onto raw-fallback for 6h. - Detach the singleflight conversion from any single caller's context (DoChan + context.WithoutCancel), so one caller cancelling no longer aborts the shared work for the others; the cache is still populated for the next reader. - enforceBudget never evicts the entry it is about to return, and skips other conversions' in-flight "converting-*" temp files. - Cache hits refresh mtime so the mtime-ordered budget eviction is a real LRU, not FIFO. Read path: - HEAD is now cache-only via Cache.Lookup: a hit serves real converted headers, a negatively-cached source serves the failed contract, a miss advertises the converted representation cheaply without triggering a (minute-long, ~1 GiB) conversion. The GET still delivers the body + authoritative verdict. - The admin flag is read through a short-TTL predicate so the read path and the capability endpoint no longer hit the DB per request. Artifact / build: - Add an in-code provenance test (embedded mobitool.wasm matches its recorded sha256) and a self-hosted CI job that runs the ebookconvert smoke conversions + provenance check, so the committed wasm can't silently rot. - Pin + checksum-verify wasmtime in the build Dockerfile (drop curl|bash). Docs: correct the design doc cache-key + setting-name descriptions, document the HEAD/timeout/LRU semantics and resource limits, note DRM-marker brittleness, and fix the README markdown table. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * ci: remove ebookconvert workflow --------- Co-authored-by: Claude Code <noreply@anthropic.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com>
Summary
Lets clients render Kindle-family ebooks (mobi / azw / azw3) in-app by converting them to EPUB server-side, in-process, on demand, served transparently through the existing read endpoint. No external converter binary, no cgo.
Conversion runs libmobi's
mobitoolcompiled towasm32-wasi, executed bywazero(pure Go). The.wasmisgo:embed-ed, so the build staysCGO_ENABLED=0and the artifact is architecture-independent (one wasm runs on amd64/arm64). Untrusted ebook bytes are parsed inside the WASM sandbox.Design doc:
docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md.What's included
internal/ebookconvert— converter (compile-once wazero module, per-conversion sandboxed scratch, timeout/size/memory/concurrency caps, stdout-scoped DRM detection, EPUB structural validation) + on-disk cache (singleflight, negative caching, size-budget eviction, key = file id+size+mtime+OSHash+module version). 18 tests.serveEbookconverts Kindle reads to EPUB when enabled. Success →application/epub+zip+X-Silo-Ebook-Conversion: converted+ ETag (= exact cache key) + must-revalidate. Failure (DRM/corrupt/oversize) → raw original +X-Silo-Ebook-Conversion: failed+no-store, so clients fall back to opening externally. 10 tests.ebook.kindle_conversion_enabled, read per request (toggles without restart).GET /api/v1/ebooks/capability→{enabled, source_formats, served_format, header contract};enabledonly when the flag is on and the WASM module initialized (double gate).How it works
Admin enables the flag → on read of a mobi/azw/azw3, the server converts to EPUB (cached, singleflighted) and serves it transparently → the capability endpoint tells clients to treat Kindle formats as in-app. DRM-free only; encrypted input is rejected and falls back to external-open.
CI / build — follow-up needed
Deployment note
The WASM sandbox is a memory-safety boundary; filesystem isolation for the writable output mount relies on running the server as a non-root service user (the container already does). See the design doc's "Filesystem sandboxing" section.
Process gate
This adds a new user-facing capability. Per
docs/architecture/v1-scope.md, it should have a v1 capability proposal tracked on the Silo v1 project before merge.Test plan
go build ./...,go vet,go test ./internal/ebookconvert/ ./internal/api/handlers/— green (28 tests)ebook.kindle_conversion_enabled; read a DRM-free mobi/azw3 → in-app EPUB; confirmX-Silo-Ebook-Conversion: convertedfailedheader + raw fallbackGET /ebooks/capabilityreflects the flag + module init🤖 Generated with Claude Code
Summary by CodeRabbit
GET /api/v1/ebooks/capabilityendpoint for client capability discovery.HEADrequests to avoid triggering conversions while preserving the conversion contract.