Rust plugin SDK
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.
[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 |
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(¶ms, 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.
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.
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.
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).
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.
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).
- plugin.toml: declare the entrypoints the guest serves.
- Entrypoints, events and the ABI: every method and event in detail.
bookclerk_plugin_abiandbookclerk_plugin_manifest: the ABI and manifest crates the SDK re-exports.- Try the Echo example: complete
native and workerd Rust plugins under
examples/.
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. |
callback_tunnel::TunnelGuestcallback_tunnel::TunnelHostcallback_tunnel::TunnelStreamnet::connectasconnect_socketnet::nested_native_jail_requestednet::ConnectOptionsnet::PluginSocketnet::SecureTransportnet::SocketAddressnet::GUEST_IPC_DIR_ENVnet::NESTED_NATIVE_JAIL_ENVnet::OWN_USER_AGENT_HOSTS_ENVnet::SESSION_CHALLENGE_ENVnet::SESSION_CHALLENGE_LENnet::SOCKET_PROXY_ABSTRACT_PREFIXnet::SOCKET_PROXY_ENVnet::SOCKET_PROXY_WRITE_ENVnet::TEST_EXTRA_CANDIDATE_ENVnet::TEST_EXTRA_CANDIDATE_WRITE_ENVnet::TEST_EXTRA_ENDPOINT_ENVnet::TEST_EXTRA_ENDPOINT_WRITE_ENVnet::USER_AGENT_ENVprotocol::Abridgementprotocol::AccountCredentialprotocol::AuthenticateUserParamsprotocol::Brandprotocol::CatalogCapabilitiesprotocol::CatalogDetailprotocol::CatalogDetailParamsprotocol::CatalogFieldprotocol::CatalogHitprotocol::CatalogHitsprotocol::CatalogSortprotocol::ChapterKindprotocol::ChapterMarkerprotocol::CliArgprotocol::CliArgKindprotocol::CliArgSpecprotocol::CliCommandSpecprotocol::CliInvokeParamsprotocol::CliInvokeResultprotocol::CliSchemaprotocol::ConfigOptionprotocol::ConfigOptionValueprotocol::Creditprotocol::CreditLevelprotocol::CreditRoleprotocol::EventPollResultprotocol::ExpandCandidatesParamsprotocol::Explicitnessprotocol::ExpressionKindprotocol::ExternalUserprotocol::FetchOptionsprotocol::FetchTitleParamsprotocol::FetchedFileprotocol::FetchedFileRoleprotocol::Identifierprotocol::IdentifierSchemeprotocol::ListDealsParamsprotocol::ListeningProgressprotocol::LoginCompleteParamsprotocol::LoginParamsprotocol::LoginResultprotocol::LoginStartResultprotocol::MediaKindprotocol::MediaSupportprotocol::OfferedAacProfileprotocol::OfferedCodecprotocol::OutputLocalContextDtoprotocol::OutputS3ContextDtoprotocol::PlainFetchprotocol::PortalAuthModeprotocol::PurchaseHintprotocol::PurchaseHintParamsprotocol::PurchaseHintResultprotocol::PurchaseHintsParamsprotocol::PurchaseHintsResultprotocol::QualityOfferprotocol::QualityOffersParamsprotocol::QualityOffersResultprotocol::RevokeAccountParamsprotocol::S3CredentialsDtoprotocol::ScanBookprotocol::ScanLibraryParamsprotocol::ScanPageprotocol::ScanParamsprotocol::SearchCatalogParamsprotocol::SeriesEntryprotocol::SourceAccountprotocol::SourceAccountsprotocol::SyncListeningResultprotocol::TitleQualityOfferprotocol::WorkKindprotocol::MAX_RPC_LINE_BYTESprotocol::PROTOCOL_NAMEsockets::HostWebSocketsockets::SocketAutoResponsesockets::SocketClosedsockets::SocketConnectRequestsockets::SocketFramesockets::SocketHandlersockets::SocketHeadersockets::SocketInfosockets::SocketMessagesockets::Socketsbookclerk_plugin_abi::aibookclerk_plugin_abi::byte_source_from_async_readbookclerk_plugin_abi::canonical_execute_request_hashbookclerk_plugin_abi::connect_pluginbookclerk_plugin_abi::database_adapter_config_from_bindingsbookclerk_plugin_abi::decode_db_value_bytesbookclerk_plugin_abi::decode_execute_request_bytesbookclerk_plugin_abi::decode_execute_result_reply_bytesbookclerk_plugin_abi::encoded_db_value_bytesbookclerk_plugin_abi::encoded_execute_reply_bytesbookclerk_plugin_abi::encoded_execute_request_bytesbookclerk_plugin_abi::encoded_execute_result_reply_bytesbookclerk_plugin_abi::encoded_statement_result_bytesbookclerk_plugin_abi::hint_resultbookclerk_plugin_abi::negotiate_rpc_featuresbookclerk_plugin_abi::pull_byte_source_to_writerbookclerk_plugin_abi::purchase_hint_results_one_by_onebookclerk_plugin_abi::require_plugin_migration_registrationbookclerk_plugin_abi::serve_pluginbookclerk_plugin_abi::serve_plugin_stdiobookclerk_plugin_abi::sql_payload_bytesbookclerk_plugin_abi::sql_payload_exceedsbookclerk_plugin_abi::stream_copy_keysbookclerk_plugin_abi::AdapterBackupOpsbookclerk_plugin_abi::AdapterDatabaseSessionbookclerk_plugin_abi::AdapterExecuteRequestbookclerk_plugin_abi::BindingValuesbookclerk_plugin_abi::Bindingsbookclerk_plugin_abi::ByteRangebookclerk_plugin_abi::Cancellationbookclerk_plugin_abi::ChangesPagebookclerk_plugin_abi::ChangesRequestbookclerk_plugin_abi::ContentSourcebookclerk_plugin_abi::ContentSourceClientbookclerk_plugin_abi::CopyResultbookclerk_plugin_abi::CoverFetchParamsbookclerk_plugin_abi::CoverFetcherbookclerk_plugin_abi::CoverFetcherClientbookclerk_plugin_abi::CoverImagebookclerk_plugin_abi::CoverImagesbookclerk_plugin_abi::Databasebookclerk_plugin_abi::DatabaseAdapterConfigbookclerk_plugin_abi::DatabaseClientbookclerk_plugin_abi::DbBootstrapbookclerk_plugin_abi::DbCapabilitiesbookclerk_plugin_abi::DbColumnbookclerk_plugin_abi::DbIdentityHighWaterbookclerk_plugin_abi::DbPlanStatementKindbookclerk_plugin_abi::DbResultSelectionbookclerk_plugin_abi::DbRowbookclerk_plugin_abi::DbTimingbookclerk_plugin_abi::DbTypebookclerk_plugin_abi::DbValuebookclerk_plugin_abi::Destinationbookclerk_plugin_abi::DestinationClientbookclerk_plugin_abi::DestinationServerbookclerk_plugin_abi::DiagnoseResultbookclerk_plugin_abi::DomainEventbookclerk_plugin_abi::Entrypointsbookclerk_plugin_abi::EventConsumerbookclerk_plugin_abi::EventConsumerClientbookclerk_plugin_abi::EventPublisherbookclerk_plugin_abi::EventPublisherClientbookclerk_plugin_abi::EventReadPagebookclerk_plugin_abi::EventReadRequestbookclerk_plugin_abi::EventResultbookclerk_plugin_abi::ExecuteReplybookclerk_plugin_abi::ExecuteRequestbookclerk_plugin_abi::ExecuteStreambookclerk_plugin_abi::ExecuteStreamLimitsbookclerk_plugin_abi::ExtensibleConfigbookclerk_plugin_abi::GuestDatabasebookclerk_plugin_abi::HealthOkbookclerk_plugin_abi::HostBindingsbookclerk_plugin_abi::Invocationbookclerk_plugin_abi::IsolationReqbookclerk_plugin_abi::JobCheckpointbookclerk_plugin_abi::JobControllerbookclerk_plugin_abi::JobInvocationbookclerk_plugin_abi::JobInvocationLeasebookclerk_plugin_abi::JobOutcomebookclerk_plugin_abi::JobRunnerbookclerk_plugin_abi::JobRunnerClientbookclerk_plugin_abi::KeyOutcomebookclerk_plugin_abi::KeyPairbookclerk_plugin_abi::KvDeleteOkbookclerk_plugin_abi::KvGetOkbookclerk_plugin_abi::KvListKeybookclerk_plugin_abi::KvListOkbookclerk_plugin_abi::KvListOptionsbookclerk_plugin_abi::KvNamespacebookclerk_plugin_abi::KvNamespaceClientbookclerk_plugin_abi::KvPutOkbookclerk_plugin_abi::KvPutOptionsbookclerk_plugin_abi::LimitExceededbookclerk_plugin_abi::ListOptionsbookclerk_plugin_abi::ListPagebookclerk_plugin_abi::MetadataChapterbookclerk_plugin_abi::MetadataChaptersbookclerk_plugin_abi::MetadataChaptersParamsbookclerk_plugin_abi::MetadataFieldbookclerk_plugin_abi::MetadataFileParseParamsbookclerk_plugin_abi::MetadataFileParsedbookclerk_plugin_abi::MetadataFileRecordbookclerk_plugin_abi::MetadataFileRenderParamsbookclerk_plugin_abi::MetadataFileRenderedbookclerk_plugin_abi::MetadataFilesbookclerk_plugin_abi::MetadataFilesClientbookclerk_plugin_abi::MetadataLookupParamsbookclerk_plugin_abi::MetadataProviderbookclerk_plugin_abi::MetadataProviderClientbookclerk_plugin_abi::MetadataRecordbookclerk_plugin_abi::MetadataSearchParamsbookclerk_plugin_abi::MoveManyPagebookclerk_plugin_abi::MoveManyRequestbookclerk_plugin_abi::MoveManyTargetbookclerk_plugin_abi::MoveOptionsbookclerk_plugin_abi::MoveResultbookclerk_plugin_abi::NamedKvBindingbookclerk_plugin_abi::NamedQueueBindingbookclerk_plugin_abi::NeverCancelbookclerk_plugin_abi::NotificationAlertActionbookclerk_plugin_abi::NotificationAudiencebookclerk_plugin_abi::NotificationFieldbookclerk_plugin_abi::NotificationMessagebookclerk_plugin_abi::NotificationRaiserbookclerk_plugin_abi::NotificationRaiserClientbookclerk_plugin_abi::NotificationSeveritybookclerk_plugin_abi::Notifierbookclerk_plugin_abi::NotifierClientbookclerk_plugin_abi::NotifyDestinationbookclerk_plugin_abi::NotifyDestinationKindbookclerk_plugin_abi::NotifyRaiseParamsbookclerk_plugin_abi::NotifyRaisedbookclerk_plugin_abi::NotifySendParamsbookclerk_plugin_abi::NotifySentbookclerk_plugin_abi::NotifyValidateParamsbookclerk_plugin_abi::NotifyValidatedbookclerk_plugin_abi::ObjectChangebookclerk_plugin_abi::ObjectChangeKindbookclerk_plugin_abi::ObjectInfobookclerk_plugin_abi::ObjectMetadatabookclerk_plugin_abi::Oidcbookclerk_plugin_abi::OidcClientbookclerk_plugin_abi::OidcClientTemplatebookclerk_plugin_abi::OpenedEntrypointsbookclerk_plugin_abi::PluginClibookclerk_plugin_abi::PluginCliClientbookclerk_plugin_abi::PluginClientbookclerk_plugin_abi::PluginDescribebookclerk_plugin_abi::PluginErrorbookclerk_plugin_abi::PluginErrorCodebookclerk_plugin_abi::PluginEventbookclerk_plugin_abi::PluginMigrationbookclerk_plugin_abi::PluginMigrationOpbookclerk_plugin_abi::PluginServerbookclerk_plugin_abi::PluginWorkerbookclerk_plugin_abi::ProgressSinkbookclerk_plugin_abi::PublishOkbookclerk_plugin_abi::PutResultbookclerk_plugin_abi::QueryPagebookclerk_plugin_abi::QueueBatchbookclerk_plugin_abi::QueueConsumerbookclerk_plugin_abi::QueueConsumerClientbookclerk_plugin_abi::QueueMessagebookclerk_plugin_abi::QueueProducerbookclerk_plugin_abi::QueueResultbookclerk_plugin_abi::QueueRetrybookclerk_plugin_abi::QueueSendMessagebookclerk_plugin_abi::QueueSendOkbookclerk_plugin_abi::ReadResultbookclerk_plugin_abi::RemoteLibrarybookclerk_plugin_abi::RemoteLibraryClientbookclerk_plugin_abi::ScalarLimitsbookclerk_plugin_abi::Sourcebookclerk_plugin_abi::SourceClientbookclerk_plugin_abi::SourceServerbookclerk_plugin_abi::StatementResultbookclerk_plugin_abi::StreamCopyHandlerbookclerk_plugin_abi::StreamCopySpecbookclerk_plugin_abi::TypedDbStatementbookclerk_plugin_abi::WriteOptionsbookclerk_plugin_abi::FEATURE_SCALAR_LIMITSbookclerk_plugin_abi::FEATURE_STORAGE_CHANGESbookclerk_plugin_abi::FEATURE_STORAGE_CONDITIONAL_WRITEbookclerk_plugin_abi::FEATURE_STORAGE_COPYbookclerk_plugin_abi::FEATURE_STORAGE_DELETE_MANYbookclerk_plugin_abi::FEATURE_STORAGE_HEAD_MANYbookclerk_plugin_abi::FEATURE_STORAGE_MOVEbookclerk_plugin_abi::FEATURE_STORAGE_MOVE_MANYbookclerk_plugin_abi::FEATURE_STORAGE_TRANSLATE_KEYSbookclerk_plugin_abi::FEATURE_STREAMSbookclerk_plugin_abi::MAX_BATCH_KEYSbookclerk_plugin_abi::MAX_CHANGES_CURSOR_BYTESbookclerk_plugin_abi::MAX_CHANGES_PAGEbookclerk_plugin_abi::MAX_EVENT_CURSOR_BYTESbookclerk_plugin_abi::MAX_KV_KEY_BYTESbookclerk_plugin_abi::MAX_KV_METADATA_BYTESbookclerk_plugin_abi::MAX_KV_VALUE_BYTESbookclerk_plugin_abi::MAX_LIST_PAGEbookclerk_plugin_abi::MAX_METADATA_FILE_BYTESbookclerk_plugin_abi::MAX_METADATA_FILE_CHAPTERSbookclerk_plugin_abi::MAX_METADATA_FILE_DESCRIPTION_BYTESbookclerk_plugin_abi::MAX_METADATA_FILE_LIST_ENTRIESbookclerk_plugin_abi::MAX_METADATA_FILE_TEXT_BYTESbookclerk_plugin_abi::MAX_NOTIFICATION_FIELDSbookclerk_plugin_abi::MAX_NOTIFICATION_FIELD_BYTESbookclerk_plugin_abi::MAX_NOTIFICATION_HTML_BYTESbookclerk_plugin_abi::MAX_NOTIFICATION_TEXT_BYTESbookclerk_plugin_abi::MAX_NOTIFICATION_TITLE_BYTESbookclerk_plugin_abi::MAX_NOTIFIER_ADDRESS_BYTESbookclerk_plugin_abi::MAX_PLUGIN_MIGRATION_OPSbookclerk_plugin_abi::MAX_PLUGIN_MIGRATION_REGISTRATION_BYTESbookclerk_plugin_abi::MAX_PLUGIN_MIGRATION_TOTAL_OPSbookclerk_plugin_abi::MAX_REFRESHED_CREDENTIAL_BYTESbookclerk_plugin_abi::MAX_SCALAR_BYTESbookclerk_plugin_abi::MAX_SCAN_CURSOR_BYTESbookclerk_plugin_abi::MAX_SCAN_PAGE_BOOKSbookclerk_plugin_abi::MAX_STREAM_WINDOW_BYTESbookclerk_plugin_abi::PRODUCT_API_VERSIONbookclerk_plugin_abi::SQL_CONTRACT_VERSIONbookclerk_plugin_abi::STORAGE_OPERATION_FEATURESbookclerk_plugin_abi::AiEmbedTextbookclerk_plugin_abi::AiInputbookclerk_plugin_abi::AiModelbookclerk_plugin_abi::AiModelListbookclerk_plugin_abi::AiModelsbookclerk_plugin_abi::AiModelsClientbookclerk_plugin_abi::AiOutputbookclerk_plugin_abi::AiRunOkbookclerk_plugin_abi::AiRunParamsbookclerk_plugin_abi::AiRunnerbookclerk_plugin_abi::AiRunnerClientbookclerk_plugin_abi::AiTaskbookclerk_plugin_abi::AiTextEmbeddingsInputbookclerk_plugin_abi::AiTextEmbeddingsOutputbookclerk_plugin_abi::AiTextRolebookclerk_plugin_abi::MAX_AI_EMBED_DIMENSIONSbookclerk_plugin_abi::MAX_AI_EMBED_TEXTSbookclerk_plugin_abi::MAX_AI_EMBED_TEXT_BYTESbookclerk_plugin_abi::MAX_AI_LANGUAGESbookclerk_plugin_abi::MAX_AI_MODELSbookclerk_plugin_abi::MAX_AI_MODEL_NAME_BYTES
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 (Workersconnect()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 — samecrate::PluginWorkercontract as native.methods: Role capability method name constants (camelCase wire strings).
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
pub struct D1ExecResult {
pub count: u32,
pub duration: f64,
}
Cloudflare D1ExecResult.
Fields
count: Number of statements executed (one per non-emptyexecline).duration: Total duration in milliseconds.
Implements: Clone, Debug, PartialEq
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 (else0).changed_db:truewhenchanges > 0.rows_read: Rows returned to the guest for this statement.rows_written: Rows written (changesfor DML).
Implements: Clone, Debug, PartialEq
pub struct D1Result {
pub success: bool,
pub results: Option<Vec<HashMap<String, DbValue>>>,
pub meta: D1Meta,
}
Cloudflare D1Result projection.
Fields
success: Alwaystrueon success; errors are returned asResult::Err.results: Row maps for selects;Nonewhen not applicable (DML).meta: Cloudflare-shaped timing and change metadata.
Implements: Clone, Debug, PartialEq
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.
pub fn from_session(session: Arc<dyn GuestDatabase>) -> Self
Wraps a host-granted GuestDatabase.
pub fn from_session_with(
session: Arc<dyn GuestDatabase>,
options: DatabaseBindingOptions,
) -> Self
Wraps a host-granted session with request-budget knobs.
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.
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.
Returns unsupported when the host session predates
GuestDatabase.limits.
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.
Returns unsupported when neither the session's limits nor caps
are available, and PluginError::invalid_params when a statement
is missing terminal intent.
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.
statements- The whole list, the same on every call.from- Statements already committed;0on the first call.key- Names this write, stable across resumes (a job id plus a step name); at mostMAX_WRITE_KEY_BYTESbytes.caps- As forSelf::chunk;Noneuses the session's limits.stop- Asked before each batch whether to pause.
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.
pub fn prepare(&self, sql: impl Into<String>) -> PreparedStatement
Prepare one canonical-SQL statement (? placeholders).
pub async fn batch(
&self,
statements: Vec<PreparedStatement>,
retry: Option<RetryToken>,
) -> Result<Vec<D1Result>>
Run prepared statements as one typed atomic batch.
Returns when a statement is missing terminal intent, the encoded
request exceeds maxRequestBytes, or execute fails.
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.
Returns when the query is empty or batch fails.
pub async fn execute(
&self,
batch: Vec<TypedDbStatement>,
retry: Option<RetryToken>,
) -> Result<ExecuteReply>
Internal typed-batch transport. Prefer Self::prepare.
Returns when the batch is empty, the encoded request exceeds the
negotiated cap, or execute fails.
Implements: Clone
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: NegotiatedmaxRequestBytes(0= unlimited).max_result_rows: DefaultmaxRowsforPreparedStatement::all(0= host adapter cap).retry: Default retry token.deadline_unix_ms: Guest-visible deadline (unix ms).
Implements: Clone, Debug, Default
pub struct PreparedStatement {
/* private fields */
}
Cloudflare-style prepared statement.
pub fn bind(self, values: Vec<DbValue>) -> Self
Replace bound parameters.
pub fn as_run(self) -> Self
Mark DML intent for DatabaseBinding::batch.
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.
pub fn as_all(self) -> Self
Mark row-returning intent for DatabaseBinding::batch.
pub async fn run(self, retry: Option<RetryToken>) -> Result<D1Result>
Execute as Cloudflare run() (functionally equivalent to Self::all).
Returns when execute fails.
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).
Returns when execute fails.
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.
Returns when execute fails or the named column is absent from the row
(Cloudflare first(colName) throws D1_ERROR in that case).
pub async fn raw(self, retry: Option<RetryToken>) -> Result<Vec<Vec<DbValue>>>
Positional cell values per row (Cloudflare raw()).
Returns when execute fails.
pub async fn all(self, retry: Option<RetryToken>) -> Result<D1Result>
Execute as a row-returning query. Returns a Cloudflare-shaped D1Result.
Returns when execute fails.
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
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
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.
pub async fn next(&mut self) -> Option<Result<HashMap<String, DbValue>>>
The next row, None once the read is over.
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
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 withfrom = 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 atnextfailed.
Implements: Debug, Display, Error
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 asfromto resume. Always a batch boundary.done: True when every statement is committed; false whenstoppaused the run between batches.
Implements: Clone, Copy, Debug, Eq, PartialEq
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).
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.
params- HostfetchTitleparams;cache_diris the work directory unless the unused FD side channel is armed.
A FetchWorkDir whose Self::path is valid for the rest of the RPC.
Returns SdkError when the side channel env is set but
recv_passed_fd fails, or when FD → path mapping fails on this OS.
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
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.
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.
local_path- Optional absolute path from host params; ignored when the FD channel is active. Must beSomeand non-empty when the channel is inactive.
An UploadFile whose Self::path points at the bytes to upload.
Returns SdkError when neither an FD nor a usable local_path is
available, or when receiving/mapping the FD fails.
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
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 sinceScanParams::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 asScanParams::sync_tokenon 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;Nonecounts one.
Implements: Clone, Debug, Default, Eq, PartialEq
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.
pub fn message(msg: impl Into<String>) -> Self
Builds a SdkError::Message from any displayable string.
msg- Human-readable explanation (no secret values).
An SdkError suitable for helper APIs returning Result.
Implements: Debug, Display, Error, From<Error>, From<SdkError>
pub fn db_value_from_sea(v: &Value) -> Result<DbValue, String>
Fallible SeaORM → bookclerk_plugin_abi::DbValue bridge.
Returns a static reason when the SeaORM value is outside the universal domain, or TEXT contains U+0000.
pub fn proxy_rows_from_typed(stmt: &StatementResult) -> Result<Vec<ProxyRow>, String>
Builds SeaORM proxy rows from a typed statement result.
Returns when the result is not positional.
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.
Returns when a statement cannot be encoded (U+0000 in SQL or TEXT).
pub fn execute_reply_to_d1_results(reply: &ExecuteReply) -> Vec<D1Result>
Maps a typed execute reply to Cloudflare D1Result per statement.
pub fn statement_result_to_d1_result(
stmt: &StatementResult,
timing: &DbTiming,
) -> D1Result
Maps one typed statement result to Cloudflare D1Result.
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.
pub fn fetch_work_dir(params: &FetchTitleParams) -> Result<FetchWorkDir>
Resolves the directory a fetchTitle call should write into.
Thin wrapper around FetchWorkDir::open.
params- HostfetchTitleparams (seeFetchWorkDir::open).
Open work directory for this RPC.
Propagates FetchWorkDir::open failures.
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.
local_path- Optional path from host params (seeUploadFile::open).
Open upload file handle for this RPC.
Propagates UploadFile::open failures.
pub fn decode_json<T: DeserializeOwned>(json: &str) -> Result<T, PluginError>
Deserialize a role-method JSON argument.
Empty input is treated as {}.
Returns PluginError::invalid_params when the payload is not valid JSON for T.
pub fn encode_json<T: Serialize>(value: T) -> Result<String, PluginError>
Serialize a role-method JSON result.
Returns PluginError::invalid_params when serialization fails, or
PluginError::payload_too_large when the encoded size exceeds
MAX_SCALAR_BYTES.
pub fn encode_atomic_result<T: Serialize>(value: T) -> Result<String, PluginError>
Encodes an atomic result; an oversized scalar after commit is unavailable.
Returns PluginError::payload_too_large mapped to
PluginError::unavailable so the host retries the same operationId.
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.
Returns PluginError::invalid_cursor for a non-numeric cursor, or
PluginError::payload_too_large when the page exceeds MAX_SCALAR_BYTES.
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.
manifest_toml- Contents of the plugin'splugin.toml, typicallyinclude_str!("../plugin.toml").
The typed capability declaration in manifest order.
Returns PluginErrorCode::Internal when the manifest does not parse or
fails validation — a build defect, not a runtime condition.
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);
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.
manifest_toml- Contents of the plugin'splugin.toml, typicallyinclude_str!("../plugin.toml").
The [media] declaration in its wire shape; empty lists for a plugin
without the table.
Returns PluginErrorCode::Internal when the manifest does not parse or
fails validation (including a storefront without [media]).
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.
fd- Open raw file descriptor previously received from the host.
PathBuf that can be passed to std / tokio filesystem APIs for as long as
fd stays open.
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.
Raw OS file descriptor owned by the caller. Prefer wrapping it immediately
(see crate::FetchWorkDir / crate::UploadFile) so Drop closes it.
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).
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.
params- The scan call's params.fetch- Fetches the store page a storefront cursor names (empty for the first), given the call's params.
The reply for this call.
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.
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.
Returns SdkError when the vat fails.
pub type Result<T> = Result<T, SdkError>;
Result alias for guest helpers that fail with SdkError.
pub const MAX_WRITE_KEY_BYTES: usize = 256;
Longest key DatabaseBinding::write_chunks accepts, in bytes.
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.
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