Rust plugin SDK

Development These docs follow the development version and change with every merge.

Last updated View as Markdown

This page shows how to write a Bookclerk plugin in Rust with bookclerk-plugin-sdk (api_version = 3). A Rust plugin is a native guest, a binary the host runs in its own jail, or a workerd guest when compiled to Wasm with the SDK's workerd glue. Depend on this crate alone, never on bookclerk-plugin-host, which pulls in the host's internals.

Install

[dependencies]
bookclerk-plugin-sdk = { git = "https://github.com/Bookclerk/bookclerk", package = "bookclerk-plugin-sdk" }
# Database guests also need:
# bookclerk-plugin-sdk = { …, features = ["db"] }
Feature Purpose
(default) The Cap'n Proto guest runner, fetch and upload path helpers, the callback tunnel, and the ABI re-exports
db SeaORM to Workers RPC DTO helpers for database guests
http Native HTTPS through the workerd socket proxy

Author model

A native guest implements PluginWorker (describe, and open(invocation, bindings) -> Entrypoints) and calls serve, the stdin and stdout Cap'n Proto runner. The entrypoints it returns are the same named entrypoints the other SDKs export as classes: storefront, storage, remote library, database adapter, CLI, OIDC, metadata, covers, metadata files, notifier and model plugin (ai). The crate root re-exports the DTOs and helpers a guest needs; prefer use bookclerk_plugin_sdk::… over reaching into submodules.

Identity (apiVersion, id, capabilities) comes from plugin.toml; describe only refines displayName and similar fields.

A [[databases]] binding is taken from the open bindings with DatabaseBinding::take_named_from_bindings and used as on D1 (prepare, bind, all, first, batch). Its limits() returns the session's DbCapabilities; all() reads through the session's streamed budget when it advertises one, iterate() walks the same read one row at a time without holding the whole result, chunk() splits a long statement list into batches that each fit one request, and write_chunks() commits those batches resumably. Any cap that is hit is a PluginError with PluginErrorCode::LimitExceeded and a typed limit(); see Working within database limits. A guest's tests open the same binding with bookclerk_db_testkit::BindingDatabase under bookclerk_db_testkit::selected_profile(), so bookclerk-plugin test . runs them under every profile (see Testing against the limits). A storefront's scan can hand its paging to scan_page(&params, fetch), which slices the store's own pages into replies the host accepts; see Paged scans. examples/plugins-echo-native-rust does all of this end to end in its notes table.

The socket proxy

A native guest has no ambient network. It receives an inherited link (fd:<n> on Unix, handle:<n> on Windows) in BOOKCLERK_SOCKET_PROXY and multiplexes CONNECT streams over it with the mux module; net opens mediated TCP sockets, the equivalent of Workers connect(), and the http feature puts an HTTPS client on top. Only hosts the plugin's [capabilities.network] grants name are reachable.

Large downloads

A storefront that writes a title into the fetchTitle work folder should download it with bookclerk_plugin_sdk::download::Download (feature http) rather than reading the body into memory. It streams the body to <dest>.part and, when the connection drops, stalls (no data for the idle timeout, 60 seconds by default) or the CDN answers 408, 429 or 5xx, asks again for only the missing bytes with Range, and If-Range when the CDN sent an ETag or Last-Modified. A CDN that ignores the range gets the whole file again; an answer for another range or a changed length starts over, so bytes are never spliced from two versions.

use bookclerk_plugin_sdk::download::Download;

let done = Download::new()
    .expected_size(store_size) // when the store states it
    .to_file(&work_dir.join("book.m4b"), || http.get(&url))
    .await?;

The closure builds a fresh request for each attempt (URL, auth, cookies); the download adds the range headers. DownloadError::is_transient tells a failure worth another fetchTitle from a refusal. The decisions themselves are the sans-IO functions in bookclerk_plugin_sdk::resume, which a guest with its own HTTP stack can reuse.

Note

The host clears the work folder after every fetchTitle, so a download resumes within one call. A partial kept across failed attempts or a host restart is not supported yet.

Older SDKs that only opened a pathname or named-pipe proxy cannot reach the host and fail closed; rebuild guests against this SDK. Pathname, abstract: and \\.\pipe\ forms remain for tests.

Pushed sockets

A plugin that declares [sockets] (see Pushed sockets) receives Sockets on Bindings::sockets in open and may return a SocketHandler on Entrypoints::socket_handler. The host holds each connection, answers the declared heartbeats and calls the handler once per message, so the plugin process may sleep in between. The sockets module wraps one socket id in HostWebSocket (send_text, close, serialize_attachment, deserialize_attachment), the same surface the TypeScript and Python SDKs give their handlers, and text_heartbeat("2", "3") builds a heartbeat pair. Attachments are JSON of at most 2 KiB, so a socket reads the same from every SDK. SocketHandler::message returns a SocketMessageOk; a remote library sets poll_events when a message announced a new user, and the host calls poll_events right away instead of at its next scheduled poll. The Audiobookshelf plugin, written in TypeScript, is a worked example of the same conversation (crates/bookclerk-plugins/optional/integration-audiobookshelf/src/push.ts).

Inbound webhooks

A plugin that declares [[webhooks]] (see Inbound webhooks) receives Webhooks on Bindings::webhooks in open (url, pull and ack, with WebhookPullRequest and WebhookAckRequest), and may return a WebhookHandler on Entrypoints::webhook_handler, whose delivered the host calls on a running guest once a request is stored. bookclerk_plugin_abi::webhooks has the checks the host applies, so a plugin can validate a pull before sending it.

Author tools

The bookclerk-plugin author CLI (check, fmt, sync-embed, package, smoke and test) lives in the separate bookclerk-plugin-tools crate, so a guest that depends on this SDK never links bookclerk-workerd. Install it once, then run it from the plugin's directory:

cargo install --git https://github.com/Bookclerk/bookclerk bookclerk-plugin-tools
cargo install --git https://github.com/Bookclerk/bookclerk bookclerk-db-testkit  # the kit `test` serves
bookclerk-plugin check .
bookclerk-plugin smoke .
bookclerk-plugin test .    # the plugin's suite under every database profile

Inside a Bookclerk checkout, cargo plugin -- check <dir> is an alias for the same binary (.cargo/config.toml).

Next steps

Reference

The sections below are generated from the crate's source: the crate root, with its items and re-exports, and one page per public module.

Guest-only Bookclerk plugin SDK.

For third-party Rust plugin authors of native and workerd plugins (api_version = 3). Depend on this crate from a standalone plugin workspace, not on the host bookclerk-plugin-host crate. The Rust SDK guide (docs/plugins/sdk/rust/README.md, published with this reference) covers the author model, the socket proxy and the author CLI; the entry points are:

Need Entry point
Native guest (runtime = "native") PluginWorker / serve (api_version = 3)
Fetch / upload work paths fetch_work_dir, upload_file_path
Mediated TCP sockets connect_socket / net (Workers connect() equivalent)
Host-held WebSockets that let the plugin sleep ([sockets]) sockets / HostWebSocket
Native HTTPS through the socket proxy feature http → http::Client
Resumable large downloads (store audio, archives) feature http → download::Download; decisions in resume
OAuth callback without guest listen callback_tunnel
Workerd / Wasm guests workerd + npm @bookclerk/plugin-sdk
ABI DTOs / method names protocol (re-exports bookclerk-plugin-abi)
Database guest session / atomic execution feature db → database_adapter
Author CLI (check / fmt / sync-embed / package / smoke) separate crate bookclerk-plugin-tools (cargo plugin)

Crate-root pub use items are the stable import surface for guests (describe-metadata DTOs, PluginError, fetch path helpers, tunnel types). Prefer use bookclerk_plugin_sdk::… over reaching into submodules unless you need module-level docs.

Item Kind Summary
ChunkCaps struct Caps DatabaseBinding::chunk splits a batch by when the session's limits are not to be used.
D1ExecResult struct Cloudflare D1ExecResult.
D1Meta struct Cloudflare D1Result::meta shape.
D1Result struct Cloudflare D1Result projection.
DatabaseBinding struct Host-mediated typed SQL surface for plugin guests.
DatabaseBindingOptions struct Options for DatabaseBinding.
PreparedStatement struct Cloudflare-style prepared statement.
RetryToken struct Explicit retry identity: reuse both operationId and requestHash.
RowStream struct Rows of one read, handed out one at a time (PreparedStatement::iterate).
WriteChunksError struct A DatabaseBinding::write_chunks run that failed part way.
WriteProgress struct Where a DatabaseBinding::write_chunks run stands.
FetchWorkDir struct An open fetch work directory received from the host for one fetchTitle call.
UploadFile struct An open upload file received from the host for one putFile call.
StorePage struct One page of a storefront's own library listing, as the plugin fetched it.
SdkError enum Errors from the guest stdio loop and SDK helpers (not plugin business logic).
db_value_from_sea function Fallible SeaORM → bookclerk_plugin_abi::DbValue bridge.
proxy_rows_from_typed function Builds SeaORM proxy rows from a typed statement result.
chunk_indexes function Greedy split of typed into index runs that each fit one request.
execute_reply_to_d1_results function Maps a typed execute reply to Cloudflare D1Result per statement.
statement_result_to_d1_result function Maps one typed statement result to Cloudflare D1Result.
write_chunks_operation_id function The operation id DatabaseBinding::write_chunks sends for the batch that starts at offset of the write named key.
fetch_work_dir function Resolves the directory a fetchTitle call should write into.
upload_file_path function Resolves the local file path for a putFile call.
decode_json function Deserialize a role-method JSON argument.
encode_json function Serialize a role-method JSON result.
encode_atomic_result function Encodes an atomic result; an oversized scalar after commit is unavailable.
page_rows function Page a JSON array of rows. limit == 0 means MAX_LIST_PAGE.
manifest_capabilities function Parses plugin.toml source and returns the PluginCapabilities a guest must advertise from describe().
manifest_media function Parses plugin.toml source and returns the MediaSupport a guest must advertise from describe().
fd_proc_path function Builds the OS path that refers to an open descriptor by number.
recv_passed_fd function Receives one file descriptor from the host side channel (SCM_RIGHTS).
scan_page function Answers one scan call from the storefront's own pages.
serve function Serves a PluginWorker on stdin/stdout (Cap'n Proto RPC).
Result type alias Result alias for guest helpers that fail with SdkError.
MAX_WRITE_KEY_BYTES constant Longest key DatabaseBinding::write_chunks accepts, in bytes.
PLUGIN_FD_CHANNEL constant Fixed descriptor number the host leaves open for the plugin side channel.
PLUGIN_FD_CHANNEL_ENV constant Environment variable the host would set to the decimal form of PLUGIN_FD_CHANNEL.

Re-exports

Modules

  • callback_tunnel: Multiplexed byte tunnel for host-owned OAuth callback listeners.
  • database_adapter: Database adapter helpers for third-party database plugin authors.
  • download: Resumable downloads to a file for native guests.
  • http: Native guest HTTP through the workerd socket proxy.
  • mux: Bidirectional multiplexed byte streams with per-stream credit windows.
  • net: Mediated TCP sockets for native guests (Workers connect() equivalent).
  • protocol: Shared role method names and typed method payloads.
  • resume: Sans-IO decisions for resuming an interrupted HTTP download.
  • sockets: Host-brokered WebSockets ([sockets]) for native guests.
  • workerd: Workerd guest bridge — same crate::PluginWorker contract as native.
  • methods: Role capability method name constants (camelCase wire strings).

Structs

ChunkCaps

pub struct ChunkCaps {
    pub max_statements: u32,
    pub max_request_bytes: u32,
}

Caps DatabaseBinding::chunk splits a batch by when the session's limits are not to be used.

Fields

  • max_statements: Statements per request (0 = no cap).
  • max_request_bytes: Encoded request bytes per request (0 = no cap).

Implements: Clone, Copy, Debug, Default, Eq, PartialEq

D1ExecResult

pub struct D1ExecResult {
    pub count: u32,
    pub duration: f64,
}

Cloudflare D1ExecResult.

Fields

  • count: Number of statements executed (one per non-empty exec line).
  • duration: Total duration in milliseconds.

Implements: Clone, Debug, PartialEq

D1Meta

pub struct D1Meta {
    pub duration: f64,
    pub changes: u64,
    pub last_row_id: i64,
    pub changed_db: bool,
    pub rows_read: u32,
    pub rows_written: u64,
}

Cloudflare D1Result::meta shape.

Fields

  • duration: Engine-reported SQL duration in milliseconds.
  • changes: Rows changed by the statement (rowsAffected).
  • last_row_id: Last inserted row id when the adapter exposes it (else 0).
  • changed_db: true when changes > 0.
  • rows_read: Rows returned to the guest for this statement.
  • rows_written: Rows written (changes for DML).

Implements: Clone, Debug, PartialEq

D1Result

pub struct D1Result {
    pub success: bool,
    pub results: Option<Vec<HashMap<String, DbValue>>>,
    pub meta: D1Meta,
}

Cloudflare D1Result projection.

Fields

  • success: Always true on success; errors are returned as Result::Err.
  • results: Row maps for selects; None when not applicable (DML).
  • meta: Cloudflare-shaped timing and change metadata.

Implements: Clone, Debug, PartialEq

DatabaseBinding

pub struct DatabaseBinding {
    /* private fields */
}

Host-mediated typed SQL surface for plugin guests.

Row-returning reads go through GuestDatabase.executeStreamed whenever the session advertises a streamed budget (limits(), fetched once per binding), so a result past the inline caps still arrives whole; sessions that do not stream, or answer unsupported, are read inline.

DatabaseBinding::from_session

pub fn from_session(session: Arc<dyn GuestDatabase>) -> Self

Wraps a host-granted GuestDatabase.

DatabaseBinding::from_session_with

pub fn from_session_with(
    session: Arc<dyn GuestDatabase>,
    options: DatabaseBindingOptions,
) -> Self

Wraps a host-granted session with request-budget knobs.

DatabaseBinding::take_named_from_bindings

pub fn take_named_from_bindings(bindings: &mut Bindings, name: &str) -> Option<Self>

Takes the named plugin database binding name from the open Bindings.

Named bindings come from plugin.toml [[databases]] after operator approval: each is an isolated plugin-owned database (full DML plus idempotent CREATE/DROP TABLE/INDEX with IF [NOT] EXISTS), physically separate from the Bookclerk library and from every other plugin. Production invocations never inject the host library.

DatabaseBinding::limits

pub async fn limits(&self) -> Result<DbCapabilities>

The negotiated limits of the granted session (DbCapabilities).

Use it to size a batch or a read before sending: max_request_bytes, max_statements, max_result_bytes, max_result_rows and the rest.

Errors

Returns unsupported when the host session predates GuestDatabase.limits.

DatabaseBinding::chunk

pub async fn chunk(
    &self,
    statements: Vec<PreparedStatement>,
    caps: Option<ChunkCaps>,
) -> Result<Vec<Vec<PreparedStatement>>>

Splits statements into batches that each fit one request.

for batch in db.chunk(stmts, None).await? { db.batch(batch, None).await?; }. Each batch is atomic; the loop is not. The caps come from the session's limits (max_statements, and the tighter of the session's and the binding's max_request_bytes) unless caps is given; zero caps given explicitly mean one batch. A single statement larger than the request cap is yielded alone, so Self::batch reports the typed error. Batches are sized with the UUID-shaped retry id the binding mints; a caller-chosen retry id that is longer leaves that much less room.

Errors

Returns unsupported when neither the session's limits nor caps are available, and PluginError::invalid_params when a statement is missing terminal intent.

DatabaseBinding::write_chunks

pub async fn write_chunks(
    &self,
    statements: Vec<PreparedStatement>,
    from: usize,
    key: &str,
    caps: Option<ChunkCaps>,
    stop: impl FnMut(usize) -> bool,
) -> Result<WriteProgress, WriteChunksError>

Writes statements in batches that fit one request, resumably.

The batches are the ones Self::chunk would yield for statements[from..], each committed with Self::batch under an operation id derived from key and the batch's offset (see write_chunks_operation_id). Store the returned next (for example in a job checkpoint) and call again with the same list, the same key and from = next to carry on: a batch whose reply was lost is resent under the same id and the host replays its receipt. Receipts are kept for 24 hours; a batch resent later runs again, so a write that may pause that long uses statements safe to repeat.

stop is asked before each batch with the number of statements committed so far; returning true pauses the run there (a time budget, a cancellation flag). The list and the caps must not change between calls with one key, or a resent batch no longer matches its receipt and the host answers conflict.

Arguments
  • statements - The whole list, the same on every call.
  • from - Statements already committed; 0 on the first call.
  • key - Names this write, stable across resumes (a job id plus a step name); at most MAX_WRITE_KEY_BYTES bytes.
  • caps - As for Self::chunk; None uses the session's limits.
  • stop - Asked before each batch whether to pause.
Errors

Returns a WriteChunksError whose next is the statements committed so far: invalid_params when key is empty or too long or from is past the list, the error Self::chunk returns, or the error of the batch that failed.

DatabaseBinding::prepare

pub fn prepare(&self, sql: impl Into<String>) -> PreparedStatement

Prepare one canonical-SQL statement (? placeholders).

DatabaseBinding::batch

pub async fn batch(
    &self,
    statements: Vec<PreparedStatement>,
    retry: Option<RetryToken>,
) -> Result<Vec<D1Result>>

Run prepared statements as one typed atomic batch.

Errors

Returns when a statement is missing terminal intent, the encoded request exceeds maxRequestBytes, or execute fails.

DatabaseBinding::exec

pub async fn exec(
    &self,
    query: impl Into<String>,
    retry: Option<RetryToken>,
) -> Result<D1ExecResult>

Execute raw SQL without bind parameters (Cloudflare D1Database::exec).

Bookclerk accepts one or more newline-separated statements like D1. Each non-empty line is executed as one prepared statement in a single typed atomic batch.

Errors

Returns when the query is empty or batch fails.

DatabaseBinding::execute

pub async fn execute(
    &self,
    batch: Vec<TypedDbStatement>,
    retry: Option<RetryToken>,
) -> Result<ExecuteReply>

Internal typed-batch transport. Prefer Self::prepare.

Errors

Returns when the batch is empty, the encoded request exceeds the negotiated cap, or execute fails.

Implements: Clone

DatabaseBindingOptions

pub struct DatabaseBindingOptions {
    pub max_request_bytes: u32,
    pub max_result_rows: u32,
    pub retry: Option<RetryToken>,
    pub deadline_unix_ms: u64,
}

Options for DatabaseBinding.

Fields

  • max_request_bytes: Negotiated maxRequestBytes (0 = unlimited).
  • max_result_rows: Default maxRows for PreparedStatement::all (0 = host adapter cap).
  • retry: Default retry token.
  • deadline_unix_ms: Guest-visible deadline (unix ms).

Implements: Clone, Debug, Default

PreparedStatement

pub struct PreparedStatement {
    /* private fields */
}

Cloudflare-style prepared statement.

PreparedStatement::bind

pub fn bind(self, values: Vec<DbValue>) -> Self

Replace bound parameters.

PreparedStatement::as_run

pub fn as_run(self) -> Self

Mark DML intent for DatabaseBinding::batch.

PreparedStatement::as_first

pub fn as_first(self) -> Self

Mark maxRows = 1 row intent for DatabaseBinding::batch.

Preserves the caller SQL; the host enforces the one-row bound at execution.

PreparedStatement::as_all

pub fn as_all(self) -> Self

Mark row-returning intent for DatabaseBinding::batch.

PreparedStatement::run

pub async fn run(self, retry: Option<RetryToken>) -> Result<D1Result>

Execute as Cloudflare run() (functionally equivalent to Self::all).

Errors

Returns when execute fails.

PreparedStatement::first

pub async fn first(
    self,
    retry: Option<RetryToken>,
) -> Result<Option<Vec<(String, DbValue)>>>

First row as a name→value map, or None (Cloudflare first() without colName).

Errors

Returns when execute fails.

PreparedStatement::first_column

pub async fn first_column(
    self,
    col_name: &str,
    retry: Option<RetryToken>,
) -> Result<Option<DbValue>>

One column from the first row, or None when no row exists.

Errors

Returns when execute fails or the named column is absent from the row (Cloudflare first(colName) throws D1_ERROR in that case).

PreparedStatement::raw

pub async fn raw(self, retry: Option<RetryToken>) -> Result<Vec<Vec<DbValue>>>

Positional cell values per row (Cloudflare raw()).

Errors

Returns when execute fails.

PreparedStatement::all

pub async fn all(self, retry: Option<RetryToken>) -> Result<D1Result>

Execute as a row-returning query. Returns a Cloudflare-shaped D1Result.

Errors

Returns when execute fails.

PreparedStatement::iterate

pub fn iterate(self, retry: Option<RetryToken>) -> RowStream

Rows one at a time from the same single-snapshot streamed read as Self::all, without holding the whole result.

let mut rows = db.prepare("SELECT id, path FROM edition_files").iterate(None);
while let Some(row) = rows.next().await {
    let row = row?;
    // ...
}

Nothing is sent until the first RowStream::next. On a session that streams, rows are decoded as their frames arrive and each is handed out once, so memory stays near one frame however large the result is. The read still fails closed (limit_exceeded) past the session's streamed budget, after the rows that fit were handed out. On a session that does not stream, or answers unsupported before any row arrived, the rows come from one inline read like Self::all. Dropping the stream stops reading it.

Implements: Clone

RetryToken

pub struct RetryToken {
    pub operation_id: String,
    pub request_hash: String,
}

Explicit retry identity: reuse both operationId and requestHash.

Fields

  • operation_id: Caller-chosen idempotency key.
  • request_hash: Canonical Cap'n request hash stamped by the host.

Implements: Clone, Debug, Eq, PartialEq

RowStream

pub struct RowStream {
    /* private fields */
}

Rows of one read, handed out one at a time (PreparedStatement::iterate).

Each row is a column name → value map, the shape D1Result::results holds. The stream ends (None) after the last row, or after the first error it yields.

RowStream::next

pub async fn next(&mut self) -> Option<Result<HashMap<String, DbValue>>>

The next row, None once the read is over.

Errors

Yields (once, then None) the error the read fails with: a typed limit_exceeded past the session's budget, the adapter's error, an unavailable when the stream breaks off, or invalid_params when the reply does not answer the request or carries more rows than the statement's max_rows.

Implements: Debug

WriteChunksError

pub struct WriteChunksError {
    pub next: usize,
    pub error: PluginError,
}

A DatabaseBinding::write_chunks run that failed part way.

Fields

  • next: Statements committed before the failure; resume with from = next. The failed batch may have committed with its reply lost: resuming resends it under the same operation id, so the host replays its receipt instead of writing it twice.
  • error: Why the batch at next failed.

Implements: Debug, Display, Error

WriteProgress

pub struct WriteProgress {
    pub next: usize,
    pub done: bool,
}

Where a DatabaseBinding::write_chunks run stands.

Fields

  • next: Statements committed from the start of the list; pass it back as from to resume. Always a batch boundary.
  • done: True when every statement is committed; false when stop paused the run between batches.

Implements: Clone, Copy, Debug, Eq, PartialEq

FetchWorkDir

pub struct FetchWorkDir {
    /* private fields */
}

An open fetch work directory received from the host for one fetchTitle call.

Holds the descriptor open for its lifetime so /proc/self/fd/N (or /dev/fd/N) stays valid for the duration of the call. When the side channel is not armed, falls back to the cache_dir field on FetchTitleParams from the RPC params (absolute path string the host already prepared inside the guest jail).

FetchWorkDir::open

pub fn open(params: &FetchTitleParams) -> Result<Self>

Resolves the directory a fetchTitle call should write downloaded audio into.

Uses the cache_dir field on params (hosts pass a jail-granted directory under the guest TMPDIR). When PLUGIN_FD_CHANNEL_ENV is set, receives one SCM_RIGHTS directory FD instead — hosts do not set this env; do not arm it without a matching host send.

Arguments
  • params - Host fetchTitle params; cache_dir is the work directory unless the unused FD side channel is armed.
Returns

A FetchWorkDir whose Self::path is valid for the rest of the RPC.

Errors

Returns SdkError when the side channel env is set but recv_passed_fd fails, or when FD → path mapping fails on this OS.

FetchWorkDir::path

pub fn path(&self) -> &Path

Absolute filesystem path of the fetch work directory.

On Unix with a passed FD this is typically /proc/self/fd/N (Linux) or /dev/fd/N (macOS/BSD). Keep self alive while writing under this path.

Implements: Deref

UploadFile

pub struct UploadFile {
    /* private fields */
}

An open upload file received from the host for one putFile call.

Same FD-lifetime rules as [FetchWorkDir]: keep the value alive while reading the path so the /proc/self/fd/N symlink remains valid.

UploadFile::open

pub fn open(local_path: Option<&str>) -> Result<Self>

Resolves the local file path for a putFile upload.

Uses local_path from the RPC params. When PLUGIN_FD_CHANNEL_ENV is set, receives one SCM_RIGHTS file FD instead — hosts do not set this env (destinations stream bytes). Do not arm it without a matching send.

Arguments
  • local_path - Optional absolute path from host params; ignored when the FD channel is active. Must be Some and non-empty when the channel is inactive.
Returns

An UploadFile whose Self::path points at the bytes to upload.

Errors

Returns SdkError when neither an FD nor a usable local_path is available, or when receiving/mapping the FD fails.

UploadFile::path

pub fn path(&self) -> &Path

Absolute filesystem path of the file the host wants uploaded.

Keep self alive for the duration of the read so a passed FD path stays valid.

Implements: Deref

StorePage

pub struct StorePage {
    pub books: Vec<ScanBook>,
    pub removed: Vec<String>,
    pub next: String,
    pub sync_token: String,
    pub complete: bool,
    pub store_pages: Option<u32>,
}

One page of a storefront's own library listing, as the plugin fetched it.

Fields

  • books: Titles on this store page, in the store's order; any number of them.
  • removed: Product ids gone from the account since ScanParams::sync_token, on a delta pass only; any number of them.
  • next: The storefront's own cursor for the store page after this one; empty when this is the last store page.
  • sync_token: On the last store page: the token the host sends as ScanParams::sync_token on the account's next pass. Ignored on earlier pages.
  • complete: On the last store page: whether the pass listed every title the account holds (a full pass). Ignored on earlier pages.
  • store_pages: Storefront requests this fetch took; None counts one.

Implements: Clone, Debug, Default, Eq, PartialEq

Enums

SdkError

pub enum SdkError {
    Message(String),
    Io(Error),
    Json(Error),
}

Errors from the guest stdio loop and SDK helpers (not plugin business logic).

Prefer mapping operator-visible failures into bookclerk_plugin_abi::PluginError inside crate::PluginWorker methods. Use SdkError for framing, JSON, and filesystem problems in the SDK itself.

Variants

  • Message: Operator-facing or diagnostic text with no structured ABI error code.

    Built via SdkError::message. Typical sources: oversize RPC frames, missing side-channel descriptors, or authoring-tool validation failures.

  • Io: Underlying OS I/O failure (stdio, files, sockets) while running SDK helpers.

  • Json: JSON serialize/deserialize failure for Workers RPC request or response lines.

SdkError::message

pub fn message(msg: impl Into<String>) -> Self

Builds a SdkError::Message from any displayable string.

Arguments
  • msg - Human-readable explanation (no secret values).
Returns

An SdkError suitable for helper APIs returning Result.

Implements: Debug, Display, Error, From<Error>, From<SdkError>

Functions

db_value_from_sea

pub fn db_value_from_sea(v: &Value) -> Result<DbValue, String>

Fallible SeaORM → bookclerk_plugin_abi::DbValue bridge.

Errors

Returns a static reason when the SeaORM value is outside the universal domain, or TEXT contains U+0000.

proxy_rows_from_typed

pub fn proxy_rows_from_typed(stmt: &StatementResult) -> Result<Vec<ProxyRow>, String>

Builds SeaORM proxy rows from a typed statement result.

Errors

Returns when the result is not positional.

chunk_indexes

pub fn chunk_indexes(
    typed: &[TypedDbStatement],
    max_statements: u32,
    max_request_bytes: u32,
) -> Result<Vec<Vec<usize>>>

Greedy split of typed into index runs that each fit one request.

Sizes are estimated per statement against one probe statement and each run is verified by one exact encode; a run the estimate let through is halved until it fits, and a lone statement over the cap is yielded on its own. 0 lifts a cap.

Errors

Returns when a statement cannot be encoded (U+0000 in SQL or TEXT).

execute_reply_to_d1_results

pub fn execute_reply_to_d1_results(reply: &ExecuteReply) -> Vec<D1Result>

Maps a typed execute reply to Cloudflare D1Result per statement.

statement_result_to_d1_result

pub fn statement_result_to_d1_result(
    stmt: &StatementResult,
    timing: &DbTiming,
) -> D1Result

Maps one typed statement result to Cloudflare D1Result.

write_chunks_operation_id

pub fn write_chunks_operation_id(key: &str, offset: usize) -> String

The operation id DatabaseBinding::write_chunks sends for the batch that starts at offset of the write named key.

It is UUID-shaped, so DatabaseBinding::chunk sizes the batches for it: the first 16 bytes of SHA-256 over "bookclerk-write-chunks\0" + key + "\0" + offset (decimal), as lowercase hex grouped 8-4-4-4-12. The TypeScript and Python SDKs derive the same id, so a write resumed from another SDK replays the same receipts.

fetch_work_dir

pub fn fetch_work_dir(params: &FetchTitleParams) -> Result<FetchWorkDir>

Resolves the directory a fetchTitle call should write into.

Thin wrapper around FetchWorkDir::open.

Arguments

Returns

Open work directory for this RPC.

Errors

Propagates FetchWorkDir::open failures.

upload_file_path

pub fn upload_file_path(local_path: Option<&str>) -> Result<UploadFile>

Resolves the local file path for a putFile call.

Thin wrapper around UploadFile::open.

Arguments

Returns

Open upload file handle for this RPC.

Errors

Propagates UploadFile::open failures.

decode_json

pub fn decode_json<T: DeserializeOwned>(json: &str) -> Result<T, PluginError>

Deserialize a role-method JSON argument.

Empty input is treated as {}.

Errors

Returns PluginError::invalid_params when the payload is not valid JSON for T.

encode_json

pub fn encode_json<T: Serialize>(value: T) -> Result<String, PluginError>

Serialize a role-method JSON result.

Errors

Returns PluginError::invalid_params when serialization fails, or PluginError::payload_too_large when the encoded size exceeds MAX_SCALAR_BYTES.

encode_atomic_result

pub fn encode_atomic_result<T: Serialize>(value: T) -> Result<String, PluginError>

Encodes an atomic result; an oversized scalar after commit is unavailable.

Errors

Returns PluginError::payload_too_large mapped to PluginError::unavailable so the host retries the same operationId.

page_rows

pub fn page_rows<T: Serialize>(
    rows: &[T],
    cursor: &str,
    limit: u32,
) -> Result<QueryPage, PluginError>

Page a JSON array of rows. limit == 0 means MAX_LIST_PAGE.

Errors

Returns PluginError::invalid_cursor for a non-numeric cursor, or PluginError::payload_too_large when the page exceeds MAX_SCALAR_BYTES.

manifest_capabilities

pub fn manifest_capabilities(
    manifest_toml: &str,
) -> Result<PluginCapabilities, PluginError>

Parses plugin.toml source and returns the PluginCapabilities a guest must advertise from describe().

Keeping the manifest as the single source of truth means the host's widening check (manifest vs describe vs operator grant) cannot drift: the guest embeds the same file the host installed.

Arguments

  • manifest_toml - Contents of the plugin's plugin.toml, typically include_str!("../plugin.toml").

Returns

The typed capability declaration in manifest order.

Errors

Returns PluginErrorCode::Internal when the manifest does not parse or fails validation — a build defect, not a runtime condition.

Examples

use bookclerk_plugin_sdk::manifest_capabilities;

let caps = manifest_capabilities(r#"
api_version = 3
id = "echo"
runtime = "native"
command = "./echo"
entrypoints = ["cli"]

[capabilities.network]
mode = "deny"
"#).unwrap();
assert_eq!(caps.entrypoints.len(), 1);

manifest_media

pub fn manifest_media(manifest_toml: &str) -> Result<MediaSupport, PluginError>

Parses plugin.toml source and returns the MediaSupport a guest must advertise from describe().

The host refuses a storefront or metadata provider whose described media differs from its manifest's [media] table, so deriving it from the embedded manifest keeps the two equal.

Arguments

  • manifest_toml - Contents of the plugin's plugin.toml, typically include_str!("../plugin.toml").

Returns

The [media] declaration in its wire shape; empty lists for a plugin without the table.

Errors

Returns PluginErrorCode::Internal when the manifest does not parse or fails validation (including a storefront without [media]).

fd_proc_path

pub fn fd_proc_path(fd: i32) -> PathBuf

Builds the OS path that refers to an open descriptor by number.

Linux uses /proc/self/fd/{fd}; macOS and other Unix use /dev/fd/{fd}. The path is only valid while the descriptor remains open in this process.

Arguments

  • fd - Open raw file descriptor previously received from the host.

Returns

PathBuf that can be passed to std / tokio filesystem APIs for as long as fd stays open.

recv_passed_fd

pub fn recv_passed_fd() -> Result<i32>

Receives one file descriptor from the host side channel (SCM_RIGHTS).

Blocks until the host sends a control message on PLUGIN_FD_CHANNEL. Hosts do not send; prefer path strings unless you are implementing a native shortcut that actually sendmsgs.

Returns

Raw OS file descriptor owned by the caller. Prefer wrapping it immediately (see crate::FetchWorkDir / crate::UploadFile) so Drop closes it.

Errors

Returns SdkError when PLUGIN_FD_CHANNEL_ENV is unset or not equal to PLUGIN_FD_CHANNEL, when recvmsg fails, or when the platform does not support the side channel (non-Unix).

scan_page

pub async fn scan_page<F, Fut>(
    params: &ScanParams,
    fetch: F,
) -> Result<ScanPage, PluginError>
where
    F: FnOnce(String, &ScanParams) -> Fut,
    Fut: Future<Output = Result<StorePage, PluginError>>,

Answers one scan call from the storefront's own pages.

Fetches the store page params.cursor names and returns at most MAX_SCAN_PAGE_BOOKS of its titles and removed ids. A larger store page is returned over several calls, each fetching it again. The pass ends on the last slice of the store page whose StorePage::next is empty, which carries that page's sync_token and complete.

Arguments

  • params - The scan call's params.
  • fetch - Fetches the store page a storefront cursor names (empty for the first), given the call's params.

Returns

The reply for this call.

Errors

Returns the fetch's error unchanged; an invalid_cursor PluginError when the cursor was not written by this helper or no longer fits the store page (the store changed mid-pass), so the host restarts the pass; and an internal one when a store cursor is too long for a scan cursor.

serve

pub async fn serve(plugin: impl PluginWorker) -> Result<()>

Serves a PluginWorker on stdin/stdout (Cap'n Proto RPC).

Must run on a current-thread tokio runtime inside a LocalSet (this helper creates the LocalSet). Abort is capability drop / stream cancel.

Errors

Returns SdkError when the vat fails.

Type aliases

Result

pub type Result<T> = Result<T, SdkError>;

Result alias for guest helpers that fail with SdkError.

Constants

MAX_WRITE_KEY_BYTES

pub const MAX_WRITE_KEY_BYTES: usize = 256;

Longest key DatabaseBinding::write_chunks accepts, in bytes.

PLUGIN_FD_CHANNEL

pub const PLUGIN_FD_CHANNEL: i32 = 3;

Fixed descriptor number the host leaves open for the plugin side channel.

Always 3 (after stdin/stdout/stderr). Guests must not close or reuse this FD for other purposes while the channel is active.

PLUGIN_FD_CHANNEL_ENV

pub const PLUGIN_FD_CHANNEL_ENV: &str = "BOOKCLERK_PLUGIN_FD_CHANNEL";

Environment variable the host would set to the decimal form of PLUGIN_FD_CHANNEL.

Hosts do not set this. Presence still arms crate::FetchWorkDir::open / crate::UploadFile::open to call recv_passed_fd instead of path strings — only set it when the host is actually sending an FD.

Source: docs/plugins/sdk/rust/README.md at main · View as Markdown