Skip to content

Server-side Kindle→EPUB conversion (mobi/azw/azw3) for in-app reading - #171

Merged
Quick104 merged 5 commits into
mainfrom
feature/kindle-epub-conversion
Jun 17, 2026
Merged

Quick104 merged 5 commits into
mainfrom
feature/kindle-epub-conversion

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

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 mobitool compiled to wasm32-wasi, executed by wazero (pure Go). The .wasm is go:embed-ed, so the build stays CGO_ENABLED=0 and 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.
  • Read handler — serveEbook converts 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.
  • Admin gate — off-by-default server setting ebook.kindle_conversion_enabled, read per request (toggles without restart).
  • Capability endpoint — GET /api/v1/ebooks/capability → {enabled, source_formats, served_format, header contract}; enabled only 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

The converted-EPUB engine internal/ebookconvert/mobitool.wasm is a committed prebuilt artifact (so normal go build needs no wasi-sdk). The reproducible recipe lives in tools/mobitool-wasm/Dockerfile (wasi-sdk 25, libmobi 9062742, zlib 1.3.1→wasm; built + smoke-tested on native amd64). It is not yet wired into the main Dockerfile or CI. Before/with merge, CI should:

  • Run tools/mobitool-wasm on amd64 and verify the committed mobitool.wasm matches a rebuild (via the bundled smoke conversion + recorded sha256; note mobitool -v embeds __DATE__/__TIME__ so byte-for-byte reproducibility is not guaranteed — gate on the smoke conversion, not a bit-identical hash).
  • Treat a bumped libmobi/wasi-sdk as a deliberate artifact refresh (the cache key includes the module fingerprint, so old conversions invalidate automatically).
  • libmobi is LGPL-3.0-or-later; the committed artifact + tools/mobitool-wasm/README.md (pinned source, build flags, license notice) satisfy the relink obligation.

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)
  • Enable ebook.kindle_conversion_enabled; read a DRM-free mobi/azw3 → in-app EPUB; confirm X-Silo-Ebook-Conversion: converted
  • Read a DRM/encrypted Kindle file → failed header + raw fallback
  • Flag off → raw bytes + original MIME unchanged
  • GET /ebooks/capability reflects the flag + module init

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added admin-controlled Kindle-family (MOBI/AZW/AZW3) → EPUB conversion for the in-app reader with on-disk caching.
    • Conversion-aware response headers/ETags and a GET /api/v1/ebooks/capability endpoint for client capability discovery.
  • Bug Fixes
    • Improved request handling for HEAD requests to avoid triggering conversions while preserving the conversion contract.
  • Documentation
    • Added an end-to-end design spec and tooling documentation for the embedded WASM converter approach.
  • Tests
    • Added coverage for converter validation, DRM failure behavior, caching/negative caching, singleflight, and eviction semantics.
  • Chores
    • Added the WASM runtime dependency, CI workflow, and WASM build tooling with provenance verification.

claude added 3 commits June 17, 2026 01:50
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>
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an end-to-end server-side Kindle-family (MOBI/AZW/AZW3) → EPUB conversion feature: a Docker-built mobitool.wasm artifact (libmobi compiled to wasm32-wasi) executed in-process via wazero, an on-disk singleflight cache with negative caching and budget eviction, a new serveEbook handler path with a capability endpoint, and API wiring behind an admin settings flag.

Changes

Kindle→EPUB Conversion Pipeline

Layer / File(s) Summary
Design specification for Kindle→EPUB server-side conversion
docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md
Full design document covering WASM build approach with build spike findings and DRM detection method, ebookconvert converter interface and execution model, on-disk cache with singleflight and negative caching, handler serving contract with ETag rules and byte-range semantics, admin gating and capability endpoint, explicit client failure contract, test categories, spike sequencing, risks and validation items, artifact commit guardrails, out-of-scope items, and project commit/deploy rules.
mobitool WASM artifact build toolchain
tools/mobitool-wasm/Dockerfile, tools/mobitool-wasm/README.md, internal/ebookconvert/mobitool.wasm.sha256, internal/ebookconvert/testdata/README.md
Multi-stage Dockerfile compiles libmobi/mobitool to wasm32-wasi with a wasm-compiled zlib, runs a smoke conversion test, and exports mobitool.wasm plus SHA-256 checksum. README documents pinned component versions, build configuration notes (libxml2-free, separate wasm zlib), Docker rebuild instructions, and runtime DRM behavior observations.
ebookconvert error taxonomy, Converter, and EPUB validation
internal/ebookconvert/errors.go, internal/ebookconvert/converter.go, internal/ebookconvert/converter_test.go, internal/ebookconvert/provenance_test.go
Declares five exported error sentinels for deterministic vs transient failure classification. Embeds mobitool.wasm; implements Options, Converter, NewConverter (wazero runtime + WASI snapshot), Convert with semaphore-gated per-call sandboxed execution, error classification, DRM/Print-Replica detection, EPUB OCF ZIP validation, and safe file delivery. Tests cover happy-path fixtures, DRM/oversize/corrupt/concurrent/cancelled/timeout/closed cases, and EPUB validation rejection. Provenance test verifies embedded WASM SHA-256 against recorded checksum.
On-disk singleflight EPUB cache
internal/ebookconvert/cache.go, internal/ebookconvert/cache_test.go
Implements SourceKey (file identity + wasm fingerprint), Cache with GetOrConvert (fast-path hit, TTL negative cache, per-key singleflight, atomic rename), Lookup (non-converting check), and mtime-ordered budget eviction. Tests cover miss→hit idempotency, modtime key invalidation, DRM negative caching, singleflight concurrency, eviction enforcement, and caller cancellation semantics.
serveEbook handler, EbookConverter interface, capability endpoint, and EbookReaderHandler wiring
internal/api/handlers/ebook_convert_serve.go, internal/api/handlers/ebook_reader.go, internal/api/handlers/ebook_convert_serve_test.go
Adds ConversionHeader, EbookConverter interface, EbookConversion feature container, Kindle format detection, serveEbook dispatch with context-cancellation propagation, serveConvertedEpub (ETag from SourceKey, http.ServeContent), serveRawKindleFallback, serveKindleHead (cache-only HEAD), and HandleConversionCapability JSON endpoint. EbookReaderHandler gains a Conversion field and HandleReadFile delegates to serveEbook. Tests verify all enabled/disabled/fallback/capability/context-cancel/HEAD paths.
buildEbookConversion startup wiring, admin flag gate, and router registration
internal/api/ebook_conversion.go, internal/api/ebook_conversion_test.go, internal/api/router.go, go.mod
buildEbookConversion initializes Converter and Cache at startup (returns nil on failure), reads ebook.kindle_conversion_enabled via isTruthySetting with 3-second TTL caching per request, and resolves cache directory from TranscodeDir. Router assigns the result to ebookReaderHandler.Conversion and adds GET /ebooks/capability. go.mod adds wazero v1.12.0.
Conversion testing and CI smoke test workflow
.github/workflows/ebookconvert.yml
GitHub Actions workflow triggers on changes under internal/ebookconvert/** and tools/mobitool-wasm/**, enforces per-ref concurrency, runs go test ./internal/ebookconvert/... with GOWORK=off on self-hosted Linux runner to execute fixture smoke conversions and validate embedded WASM SHA-256 provenance.

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
Loading
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}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.91% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: server-side Kindle-to-EPUB conversion capability for in-app reading, directly aligned with the PR's primary objective.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/kindle-epub-conversion

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Handle request cancellation/timeouts before writing a 500.

serveEbook now intentionally propagates context.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 value

Line number reference may drift.

Line 44 references serveEbookInline at ebook_reader.go:602 as the current read handler. Line numbers shift with edits; consider a structural reference (e.g., "the current inline-read handler in ebook_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 win

Negative-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.neg can 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.sum is excluded by !**/*.sum
  • internal/ebookconvert/mobitool.wasm is excluded by !**/*.wasm
📒 Files selected for processing (19)
  • docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md
  • go.mod
  • internal/api/ebook_conversion.go
  • internal/api/handlers/ebook_convert_serve.go
  • internal/api/handlers/ebook_convert_serve_test.go
  • internal/api/handlers/ebook_reader.go
  • internal/api/router.go
  • internal/ebookconvert/cache.go
  • internal/ebookconvert/cache_test.go
  • internal/ebookconvert/converter.go
  • internal/ebookconvert/converter_test.go
  • internal/ebookconvert/errors.go
  • internal/ebookconvert/mobitool.wasm.sha256
  • internal/ebookconvert/testdata/README.md
  • internal/ebookconvert/testdata/sample-cp1252.mobi
  • internal/ebookconvert/testdata/sample-drm-v1.mobi
  • internal/ebookconvert/testdata/sample-ncx.mobi
  • tools/mobitool-wasm/Dockerfile
  • tools/mobitool-wasm/README.md

Comment thread internal/ebookconvert/cache_test.go Resolved
Comment thread internal/ebookconvert/cache.go Resolved
Comment thread internal/ebookconvert/cache.go Resolved
Comment thread internal/ebookconvert/converter.go Resolved
Comment thread tools/mobitool-wasm/Dockerfile Resolved
Comment on lines +18 to +27
## 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
## 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

@Quick104
Quick104 force-pushed the feature/kindle-epub-conversion branch from f4d2c3e to a67fbe4 Compare June 17, 2026 14:32
@Quick104
Quick104 self-requested a review as a June 17, 2026 14:32
…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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
internal/api/handlers/ebook_convert_serve_test.go (1)

183-254: 💤 Low value

Consider tracking Lookup calls explicitly for test clarity.

The HEAD tests verify that GetOrConvert wasn't called by checking conv.calls == 0, which is correct. However, they don't explicitly verify that Lookup was called. While the correct headers indirectly prove Lookup was invoked, adding a lookupCalls counter to fakeConverter would 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 win

Consider adding -v for 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

📥 Commits

Reviewing files that changed from the base of the PR and between a67fbe4 and 5960645.

📒 Files selected for processing (14)
  • .github/workflows/ebookconvert.yml
  • docs/superpowers/specs/2026-06-17-kindle-epub-conversion-design.md
  • internal/api/ebook_conversion.go
  • internal/api/ebook_conversion_test.go
  • internal/api/handlers/ebook_convert_serve.go
  • internal/api/handlers/ebook_convert_serve_test.go
  • internal/ebookconvert/cache.go
  • internal/ebookconvert/cache_test.go
  • internal/ebookconvert/converter.go
  • internal/ebookconvert/converter_test.go
  • internal/ebookconvert/errors.go
  • internal/ebookconvert/provenance_test.go
  • tools/mobitool-wasm/Dockerfile
  • tools/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

Comment thread .github/workflows/ebookconvert.yml Resolved
Comment thread .github/workflows/ebookconvert.yml Resolved
Comment thread .github/workflows/ebookconvert.yml Outdated
- name: Smoke-convert fixtures + verify wasm provenance
env:
GOWORK: off
run: go test ./internal/ebookconvert/... -count=1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +177 to +180
ctx, cancel := context.WithCancel(context.Background())
cancel() // caller bails before the conversion can finish
_, _ = c.GetOrConvert(ctx, src, key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

Comment on lines +105 to +107
if err := c.Convert(ctx, filepath.Join("testdata", "sample-ncx.mobi"), dst); err == nil {
t.Fatal("expected error on canceled context")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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.

@Quick104
Quick104 merged commit 77f7d8b into main Jun 17, 2026
@Quick104
Quick104 deleted the feature/kindle-epub-conversion branch June 17, 2026 17:09
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants