bookclerk_integrations
Outbound integrations and SPA portal APIs.
Host binaries should depend on Integration / IntegrationRegistry only.
First-party adapters (e.g. Audiobookshelf) live in
bookclerk-plugin-integration-* crates and run as staged external guests.
| Item | Kind | Summary |
|---|---|---|
Integration |
trait | Downstream consumer of acquired books / identity signals (e.g. Audiobookshelf). |
AiRouter |
struct | Routes model runs to the deployed model plugins. |
RoutedModel |
struct | One model a deployed plugin serves, as the router lists it. |
Brand |
struct | Visual identity for a store or integration in the portal UI. |
PortalState |
struct | Shared state for portal handlers. |
IntegrationRegistry |
struct | Fan-out registry for configured integrations. |
MintedClaimTicket |
struct | Freshly minted claim ticket (includes plaintext once). |
EventSubscription |
struct | Declared durable onEvent subscription (mirrors plugin.toml). |
IntegrationContext |
struct | Context passed when starting background watchers. |
ProvidedOidcClient |
struct | Host-side copy of a guest oidcClients template (no ABI crate dependency). |
QueueSubscription |
struct | Declared [[queues.consumers]] row (mirrors plugin.toml): the queue the integration's queue(batch) trigger consumes and its redelivery policy. |
ScheduledInvocation |
struct | One fire of a [triggers] crons schedule, as the host delivers it to the scheduled(controller) trigger. |
CoverHeaders |
struct | The caching headers an image server sent with one answer, verbatim as the covers plugin passed them on (each at most the ABI's maxCoverHeaderBytes); None for a header it did not send. |
ExternalUser |
struct | External user resolved via integration credential login or watcher. |
FetchedCover |
struct | One image a covers plugin downloaded, or why it could not. |
IntegrationHealth |
struct | Health snapshot for one integration. |
ListeningProgressSnapshot |
struct | One listening / progress row from any integration (ABS, plugins, …). |
SyncListeningProviderResult |
struct | Per-integration outcome from crate::IntegrationRegistry::sync_listening_progress_all. |
SyncListeningSummary |
struct | Result of syncing listening progress across one or more integrations. |
IntegrationError |
enum | Errors from outbound integrations and the connect portal. |
from_config |
function | Construct an empty registry (no in-process adapters). |
register_builtins |
function | Register first-party integrations into an existing registry. |
upsert_listening_snapshots |
function | Upsert provider-agnostic listening snapshots into listening_progress. |
mint_for_external_user |
function | Mint a claim ticket for an external user (daemon watcher / CLI). |
portal_identity_from_headers |
function | Resolve a portal identity from the request cookie, if present and valid. |
portal_spa_router |
function | The SPA Accounts / claim routes with their state, ready to nest. |
portal_spa_routes |
function | The SPA Accounts / claim routes, before state: the daemon nests them at /api/portal and lists them in its OpenAPI document. |
redeem_lose_next_responses |
function | Drop the next N successful redeem HTTP responses after the DB commit. |
generate_token |
function | Generate a URL-safe random token. |
identity_from_session |
function | Resolve identity from a portal session cookie value. |
mint_claim_ticket |
function | Ensure identity exists and mint a claim ticket. |
redeem_ticket_to_session |
function | Redeem a claim ticket into a portal session cookie value (plaintext). |
redeem_ticket_to_session_with_client |
function | Redeem a claim ticket and mint a portal session with optional client metadata. |
session_for_identity |
function | Create a portal session for an already-resolved identity (credential login). |
session_for_identity_with_client |
function | Create a portal session for an identity with optional client metadata. |
ticket_portal_url |
function | Build a shareable SPA claim URL when public_origin is configured. |
Result |
type alias | Result alias for this crate. |
ImageSrc |
type alias | See PortalState::image_src. |
AI_LIST_TIMEOUT |
constant | Longest a model plugin may take to list its models. Listing loads no model, so this mostly covers waking a sleeping plugin. |
AI_RUN_TIMEOUT |
constant | Longest one model run may take before the router gives up on it. A full batch on the largest first-party model on one slow core fits; a caller with a shorter deadline passes its own. |
MAX_REGISTERED_INTEGRATIONS |
constant | Hard ceiling on registered integrations (plugin discovery is user-influenced). |
bookclerk_plugin_abi::DomainEventbookclerk_plugin_abi::EventResultbookclerk_plugin_abi::QueueBatchbookclerk_plugin_abi::QueueMessagebookclerk_plugin_abi::QueueResultbookclerk_plugin_abi::QueueRetrytickets::hash_token
pub trait Integration: Send + Sync {
fn id(&self) -> &str;
fn plugin_key(&self) -> &str;
fn plugin_instance_id(&self) -> Option<&str>;
fn display_name(&self) -> &str;
fn start<'life0, 'async_trait>(
&'life0 self,
ctx: IntegrationContext,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn stop<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn deliver_domain_event<'life0, 'async_trait>(
&'life0 self,
event: DomainEvent,
) -> Pin<Box<dyn Future<Output = Result<EventResult>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn deliver_domain_event_cancelable<'life0, 'async_trait>(
&'life0 self,
event: DomainEvent,
cancel: Arc<AtomicBool>,
) -> Pin<Box<dyn Future<Output = Result<EventResult>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn event_subscriptions(&self) -> Vec<EventSubscription>;
fn queue_subscriptions(&self) -> Vec<QueueSubscription>;
fn cron_schedules(&self) -> Vec<CronSchedule>;
fn run_scheduled_cancelable<'life0, 'async_trait>(
&'life0 self,
invocation: ScheduledInvocation,
_cancel: Arc<AtomicBool>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn deliver_queue_batch_cancelable<'life0, 'async_trait>(
&'life0 self,
batch: QueueBatch,
_cancel: Arc<AtomicBool>,
) -> Pin<Box<dyn Future<Output = Result<Vec<QueueResult>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn health<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<IntegrationHealth>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn supports_credential_login(&self) -> bool;
fn authenticate_user<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
_username: &'life1 str,
_password: &'life2 str,
) -> Pin<Box<dyn Future<Output = Result<ExternalUser>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,;
fn supports_library_scan(&self) -> bool;
fn scan_library<'life0, 'async_trait>(
&'life0 self,
_force: bool,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn supports_listening_sync(&self) -> bool;
fn sync_listening_progress<'life0, 'life1, 'async_trait>(
&'life0 self,
_library: &'life1 LibraryStore,
) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,;
fn supports_metadata(&self) -> bool;
fn metadata_lookup<'life0, 'async_trait>(
&'life0 self,
_params: MetadataLookupParams,
) -> Pin<Box<dyn Future<Output = Result<Vec<MetadataRecord>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn metadata_search<'life0, 'async_trait>(
&'life0 self,
_params: MetadataSearchParams,
) -> Pin<Box<dyn Future<Output = Result<Vec<MetadataRecord>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn metadata_chapters<'life0, 'async_trait>(
&'life0 self,
_params: MetadataChaptersParams,
) -> Pin<Box<dyn Future<Output = Result<MetadataChapters>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn metadata_unsupported(&self) -> IntegrationError;
fn supports_covers(&self) -> bool;
fn fetch_covers<'life0, 'async_trait>(
&'life0 self,
_params: CoverFetchParams,
) -> Pin<Box<dyn Future<Output = Result<Vec<FetchedCover>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn supports_ai(&self) -> bool;
fn ai_models<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<AiModelList, PluginError>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn ai_run<'life0, 'async_trait>(
&'life0 self,
_params: AiRunParams,
) -> Pin<Box<dyn Future<Output = Result<AiRunOk, PluginError>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn supports_notifier(&self) -> bool;
fn notify_send<'life0, 'async_trait>(
&'life0 self,
_params: NotifySendParams,
) -> Pin<Box<dyn Future<Output = Result<Result<NotifySent, PluginError>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn notify_validate_destination<'life0, 'async_trait>(
&'life0 self,
_params: NotifyValidateParams,
) -> Pin<Box<dyn Future<Output = Result<Result<NotifyValidated, PluginError>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn notifier_unsupported(&self) -> IntegrationError;
fn diagnose<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Vec<String>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
fn portal_brand(&self) -> Option<Brand>;
fn provided_oidc_clients<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Vec<ProvidedOidcClient>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,;
}
Downstream consumer of acquired books / identity signals (e.g. Audiobookshelf).
fn id(&self) -> &str
Display / CLI alias (audiobookshelf, …). Globally unique within one
installation; durable identity is Self::plugin_key.
fn plugin_key(&self) -> &str
Provenance-qualified PluginKey when this adapter is an external guest.
Defaults to Self::id for in-crate test doubles.
fn plugin_instance_id(&self) -> Option<&str>
Plugin instance that owns this deployed integration.
None for transitional startup and in-crate adapters. Two deployed
instances of one key each return their own id. Reload keeps a session
only when this id is a present deployment.
fn display_name(&self) -> &str
Human-facing name for portal / CLI (defaults to Self::id).
fn start<'life0, 'async_trait>(
&'life0 self,
ctx: IntegrationContext,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Start background tasks (user watchers, etc.).
fn stop<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Stop background tasks started by Self::start.
Default: no-op. Implementations that spawn poll loops should cancel them idempotently so config reload can replace the registry safely.
fn deliver_domain_event<'life0, 'async_trait>(
&'life0 self,
event: DomainEvent,
) -> Pin<Box<dyn Future<Output = Result<EventResult>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Deliver one versioned outbox DomainEvent and return a durable
EventResult.
Delivery is at-least-once: consume idempotently on
DomainEvent::deduplication_key. Return Reject for event types or
schema versions this integration does not understand, Retry for
transient downstream failures, and Ack once the effect is durable.
Returning Err is treated like a retryable transport failure.
fn deliver_domain_event_cancelable<'life0, 'async_trait>(
&'life0 self,
event: DomainEvent,
cancel: Arc<AtomicBool>,
) -> Pin<Box<dyn Future<Output = Result<EventResult>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Like Self::deliver_domain_event, aborting when cancel is set (fence loss).
Returns IntegrationError::Message "fence lost" when cancel is set,
or whatever Self::deliver_domain_event returns.
fn event_subscriptions(&self) -> Vec<EventSubscription>
Durable outbox subscriptions. Empty means this integration is not a subscriber.
fn queue_subscriptions(&self) -> Vec<QueueSubscription>
Declared [[queues.consumers]] rows. Empty means this integration
consumes no plugin-owned queue.
fn cron_schedules(&self) -> Vec<CronSchedule>
Declared [triggers] crons schedules. Empty means this integration
has no scheduled(controller) trigger.
fn run_scheduled_cancelable<'life0, 'async_trait>(
&'life0 self,
invocation: ScheduledInvocation,
_cancel: Arc<AtomicBool>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Run one cron fire through the scheduled(controller) trigger,
aborting when cancel is set (fence loss or operator cancel).
Returns an error when the handler throws or the call fails; the host
retries the fire with backoff. The default returns
IntegrationError::Message because the integration declares no
crons.
fn deliver_queue_batch_cancelable<'life0, 'async_trait>(
&'life0 self,
batch: QueueBatch,
_cancel: Arc<AtomicBool>,
) -> Pin<Box<dyn Future<Output = Result<Vec<QueueResult>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Deliver one ordered QueueBatch to the queue(batch) trigger and
return exactly one QueueResult per message, aborting when cancel
is set (fence loss).
Delivery is at-least-once: consume idempotently on
bookclerk_plugin_abi::QueueMessage::id. Returning Err is treated
like a retryable transport failure.
The default returns IntegrationError::Message because the
integration declares no queue consumers.
fn health<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<IntegrationHealth>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Probes connectivity and configuration for this integration.
A health snapshot suitable for CLI / SPA status views.
Returns an error when the probe itself fails unexpectedly (transports);
soft failures should usually set IntegrationHealth::ok to false.
fn supports_credential_login(&self) -> bool
Whether this integration may appear as a portal username/password login.
Default: false. Integrations that implement credential login override
this (typically gated by a config flag such as allow_credential_login).
fn authenticate_user<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
_username: &'life1 str,
_password: &'life2 str,
) -> Pin<Box<dyn Future<Output = Result<ExternalUser>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
Validate end-user credentials (portal return visits / self-service).
Default: returns an error. Only called when
Self::supports_credential_login is true.
fn supports_library_scan(&self) -> bool
Whether this integration can trigger a remote library scan.
fn scan_library<'life0, 'async_trait>(
&'life0 self,
_force: bool,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Trigger a remote library scan (optional force rescan).
Default: unsupported. Hosts (CLI / daemon) call this via the registry instead of talking to a specific adapter client.
fn supports_listening_sync(&self) -> bool
Whether this integration can sync listening / progress into the library DB.
Default: false. Ranking treats listening as optional — when no
integration syncs (or recommend filters exclude it), discovery still
runs on owned-library taste alone.
fn sync_listening_progress<'life0, 'life1, 'async_trait>(
&'life0 self,
_library: &'life1 LibraryStore,
) -> Pin<Box<dyn Future<Output = Result<usize>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
Pull listening / progress rows into the generic listening_progress table.
Implementations must tag rows with Self::id as provider. Hosts
fan this out via crate::IntegrationRegistry::sync_listening_progress_all
so one or more integrations can contribute.
Default: unsupported.
fn supports_metadata(&self) -> bool
Whether this integration exports the metadata entrypoint
(bibliographic lookups, searches and chapter layouts).
Default: false.
fn metadata_lookup<'life0, 'async_trait>(
&'life0 self,
_params: MetadataLookupParams,
) -> Pin<Box<dyn Future<Output = Result<Vec<MetadataRecord>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Edition records for a set of identifiers (MetadataProvider.lookup).
Default: unsupported.
fn metadata_search<'life0, 'async_trait>(
&'life0 self,
_params: MetadataSearchParams,
) -> Pin<Box<dyn Future<Output = Result<Vec<MetadataRecord>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Edition records matching a title and author (MetadataProvider.search).
Default: unsupported.
fn metadata_chapters<'life0, 'async_trait>(
&'life0 self,
_params: MetadataChaptersParams,
) -> Pin<Box<dyn Future<Output = Result<MetadataChapters>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Chapter layout of one edition (MetadataProvider.chapters).
Default: unsupported.
fn metadata_unsupported(&self) -> IntegrationError
The error the default metadata methods return.
fn supports_covers(&self) -> bool
Whether this integration exports the covers entrypoint (downloads
cover images on the host's behalf).
Default: false.
fn fetch_covers<'life0, 'async_trait>(
&'life0 self,
_params: CoverFetchParams,
) -> Pin<Box<dyn Future<Output = Result<Vec<FetchedCover>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Downloads params.urls through the covers entrypoint
(CoverFetcher.fetchCovers), refusing any body over
params.max_bytes and sending each URL's conditions, when it has
any, as conditional request headers.
Returns one FetchedCover per URL, in request order; a URL that
failed carries error instead of failing the call, and one the
server answered 304 Not Modified carries not_modified.
Default: unsupported.
fn supports_ai(&self) -> bool
Whether this integration exports the ai entrypoint (serves models).
Default: false.
fn ai_models<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<AiModelList, PluginError>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
The models this integration serves now (AiModels.models), already
checked and limited to the tasks its manifest declares.
Errors keep the plugin's code, so the model router can tell a missing model from a plugin that is down.
Default: unsupported.
fn ai_run<'life0, 'async_trait>(
&'life0 self,
_params: AiRunParams,
) -> Pin<Box<dyn Future<Output = Result<AiRunOk, PluginError>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Runs one of this integration's models (AiModels.run);
params.model is the plugin's own model id. The reply is as the
plugin sent it: the model router checks it against the listing.
Default: unsupported.
fn supports_notifier(&self) -> bool
Whether this integration exports the notifier entrypoint (delivers
notifications to destinations).
Default: false.
fn notify_send<'life0, 'async_trait>(
&'life0 self,
_params: NotifySendParams,
) -> Pin<Box<dyn Future<Output = Result<Result<NotifySent, PluginError>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Delivers one checked notification through Notifier.send.
The guest's own answer: a bookclerk_plugin_abi::NotifySent or
the bookclerk_plugin_abi::PluginError it raised, which the send
job classifies (rate_limited and unavailable are retried).
An IntegrationError when the guest could not be reached, or by
default (the integration is not a notifier).
fn notify_validate_destination<'life0, 'async_trait>(
&'life0 self,
_params: NotifyValidateParams,
) -> Pin<Box<dyn Future<Output = Result<Result<NotifyValidated, PluginError>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Normalises a patron's address document through
Notifier.validateDestination.
The guest's own answer: the normalised document or the error it
raised (invalid_params for an address it refuses).
An IntegrationError when the guest could not be reached, or by
default.
fn notifier_unsupported(&self) -> IntegrationError
The error the default notifier methods return.
fn diagnose<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Vec<String>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Human-readable connectivity probe for CLI / ops (integrations test).
Default: summarizes Self::health.
fn portal_brand(&self) -> Option<Brand>
Optional portal brand for credential-login / connection UI.
Owned by the integration plugin; hosts must not hardcode provider colors.
fn provided_oidc_clients<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<Vec<ProvidedOidcClient>>> + Send + 'async_trait>>
where
Self: 'async_trait,
'life0: 'async_trait,
Plugin-provided Bookclerk-as-IdP client templates (oidcClients RPC).
Empty when the guest is not a relying party or the method is unsupported.
pub struct AiRouter {
/* private fields */
}
Routes model runs to the deployed model plugins.
pub fn new(integrations: Arc<RwLock<IntegrationRegistry>>) -> Self
A router over the node's live integrations.
integrations- The registry the deployment reconciler keeps.
The router, with no model chosen for any task.
pub fn choose(&self, task: AiTask, model: Option<(String, String)>)
Sets or clears the model a task alias resolves to.
task- The task (@library/text-embeddingsfor text embeddings).model- The chosen model as(plugin id, model id), orNoneto fall back to the first deployed model of the task.
pub async fn models(&self) -> Vec<RoutedModel>
Every model the deployed model plugins serve. A plugin that cannot list is left out and logged.
The models, by plugin in registration order.
pub async fn model_for(&self, task: AiTask) -> Option<RoutedModel>
The model a task alias names now.
task- The task.
The chosen model when it is deployed, else the first deployed model
of the task; None when nothing deployed performs the task.
pub async fn run(
&self,
caller: Option<&str>,
params: AiRunParams,
timeout: Duration,
) -> Result<AiRunOk, PluginError>
Runs a model by name and returns its checked output.
caller- Id of the plugin that asks, orNonefor the host's own features. A plugin cannot run its own models through the router: it would wait on itself.params- The model name (@<plugin id>/<model id>or a task alias) and the input.timeout- Longest the run may take; capped atAI_RUN_TIMEOUT.
The output with model set to the full name of the model that ran.
invalid_params for a malformed run or an input of another task
than the model's, not_found when nothing deployed serves the
model, deadline_exceeded when the plugin does not answer in time,
unavailable when it fails or sends a reply that fails
check_run_output, and the plugin's own invalid_params,
not_found, rate_limited and unavailable.
pub struct RoutedModel {
pub plugin: String,
pub model: AiModel,
}
One model a deployed plugin serves, as the router lists it.
Fields
plugin: Id of the plugin that serves the model (plugin.tomlid).model: The model as the plugin listed it.
pub fn name(&self) -> String
The name callers use for this model: @<plugin id>/<model id>.
Implements: Clone, Debug, Eq, PartialEq
pub struct Brand {
pub id: &'static str,
pub name: &'static str,
pub bg: &'static str,
pub fg: &'static str,
pub accent: &'static str,
pub icon_url: &'static str,
}
Visual identity for a store or integration in the portal UI.
Fields
id: Stable identifier for this item.name: Operator-facing brand name shown on portal connect buttons.bg: CSS background color for portal connect buttons (#RRGGBB).fg: CSS foreground / text color for portal connect buttons.accent: Optional accent (border / focus).icon_url: Remote favicon / app-icon URL (not stored in-repo).
pub fn logo_href(&self) -> &'static str
Favicon URL for <img src>.
Implements: Clone, Copy, Debug, From<SourceBrand>, Serialize
pub struct PortalState {
pub config: Arc<RwLock<Config>>,
pub library: Arc<RwLock<LibraryStore>>,
pub integrations: Arc<RwLock<IntegrationRegistry>>,
pub sources: Arc<RwLock<SourceRegistry>>,
pub image_src: ImageSrc,
}
Shared state for portal handlers.
Fields
config: Loaded Bookclerk configuration shared with portal handlers.library: Open library store used for identity / ticket / session rows.integrations: Configured outbound integration registry.sources: Content-source registry used for portal store connect / OAuth.image_src: Turns a brand's remote logo URL into a source the web app may load from its own origin, orNonewhen it cannot; the daemon signs it through its cover service.
Implements: Clone
pub struct IntegrationRegistry {
/* private fields */
}
Fan-out registry for configured integrations.
pub fn new() -> Self
Creates an empty registry with no integrations registered.
Newly constructed new value.
pub fn register(&mut self, integration: Arc<dyn Integration>)
Adds an integration to this registry (later entries keep their order).
Silently refuses registration once MAX_REGISTERED_INTEGRATIONS is
reached so health fan-out cannot allocate from an unbounded discovery set.
integration- Integration instance to register.
pub fn take_instance(&mut self, plugin_instance_id: &str) -> Vec<Arc<dyn Integration>>
Removes every registration of plugin_instance_id.
Other instances of the same plugin key stay. The caller stops each returned integration before publishing a replacement.
pub fn get(&self, id: &str) -> Option<Arc<dyn Integration>>
Returns the integration with this id, if registered.
id- Stable id to look up.
Some(...) when found / applicable; otherwise None.
pub fn all(&self) -> &[Arc<dyn Integration>]
Returns every registered integration in registration order.
pub fn is_empty(&self) -> bool
Returns true when no integrations are registered.
pub async fn start_all(&self, ctx: IntegrationContext) -> Result<()>
Start all integrations (background watchers).
ctx- Lifecycle context (e.g. external-user callback).
The successful result value for this operation.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn stop_all(&self)
Stop all integrations (background watchers). Errors are logged, not fatal.
pub async fn stop_except(&self, keep: &BTreeSet<String>)
Stops integrations that are not a present deployed instance.
keep is plugin instance ids. Config reload reattaches those guests
onto the replacement registry and leaves them running. A transitional
integration is stopped even when its plugin key has a deployment.
Errors are logged, not fatal.
pub async fn health_all(&self) -> Vec<IntegrationHealth>
Probes every registered integration and returns one health row each.
pub fn credential_login_providers(&self) -> Vec<Arc<dyn Integration>>
Integrations that currently offer portal username/password login.
pub fn listening_sync_providers(&self) -> Vec<Arc<dyn Integration>>
Integrations that can sync listening / progress.
pub fn metadata_providers(&self) -> Vec<Arc<dyn Integration>>
Integrations that export the metadata entrypoint, in registration order.
pub fn model_plugins(&self) -> Vec<Arc<dyn Integration>>
Integrations that export the ai entrypoint, in registration order.
pub fn cover_fetchers(&self) -> Vec<Arc<dyn Integration>>
Integrations that export the covers entrypoint, in registration order.
pub async fn sync_listening_progress_all(
&self,
library: &LibraryStore,
) -> SyncListeningSummary
Sync listening progress from every capable integration into the library DB.
Individual failures are recorded in the summary and do not abort siblings.
library- Open library store used for reads/writes.
crate::types::SyncListeningSummary result.
Implements: Clone, Default, MetadataProviders
pub struct MintedClaimTicket {
pub record: ClaimTicketRecord,
pub token: String,
pub identity: PortalIdentity,
pub portal_url: Option<String>,
}
Freshly minted claim ticket (includes plaintext once).
Fields
record: Persisted claim-ticket row (hash only; no plaintext token).token: Plaintext secret shown once at mint time; only a hash is persisted.identity: Portal identity bound to this ticket.portal_url: Shareable SPA claim URL whenpublic_originis configured.
Implements: Clone, Debug
pub struct EventSubscription {
pub event_type: String,
pub schema_versions: Vec<u32>,
pub supports_suspend: bool,
pub resource_class: String,
pub filter: Option<Value>,
pub message_retention_secs: Option<u32>,
}
Declared durable onEvent subscription (mirrors plugin.toml).
Fields
event_type: Event type (book_acquired).schema_versions: Schema versions this guest can consume.supports_suspend: WhetherEventResult::Suspendedis advertised for this type.resource_class: Concurrency class copied onto deliveries (default"network").filter: Optional host-owned payload object filter (top-level key equality).message_retention_secs: Seconds a due delivery may wait unleased before the host expires it;Noneuses the host default.
pub fn new(event_type: impl Into<String>, schema_versions: Vec<u32>) -> Self
Type + schema subscription with the default network resource class.
Implements: Clone, Debug, PartialEq
pub struct IntegrationContext {
pub on_external_user: Option<Arc<dyn Fn(ExternalUser) + Send + Sync>>,
}
Context passed when starting background watchers.
Fields
on_external_user: Optional callback when an external user is observed (claim minting).
Implements: Clone, Default
pub struct ProvidedOidcClient {
pub client_id: String,
pub display_name: String,
pub callback_path: String,
pub public_client: bool,
pub default_scopes: Vec<String>,
pub issue_refresh_token: bool,
pub origin_config_key: String,
}
Host-side copy of a guest oidcClients template (no ABI crate dependency).
Fields
client_id: OAuthclient_id.display_name: Operator-facing card title.callback_path: Path appended to the plugin origin.public_client: Public PKCE when true.default_scopes: Scopes for first materialization.issue_refresh_token: Whether new rows may issue refresh tokens.origin_config_key: Dotted config key for the player origin.
Implements: Clone, Debug, Eq, PartialEq
pub struct QueueSubscription {
pub queue: String,
pub max_retries: u32,
pub dead_letter_queue: Option<String>,
pub retry_delay_secs: u32,
pub message_retention_secs: Option<u32>,
}
Declared [[queues.consumers]] row (mirrors plugin.toml): the queue the
integration's queue(batch) trigger consumes and its redelivery policy.
Fields
queue: Queue name.max_retries: Redeliveries before a message is dead-lettered.dead_letter_queue: Queue that receives a copy oncemax_retriesis exhausted.retry_delay_secs: Seconds a retried message waits when the consumer names no delay.message_retention_secs: Seconds a due message may wait unleased before the host expires it;Noneuses the host default.
Implements: Clone, Debug, Eq, PartialEq
pub struct ScheduledInvocation {
pub cron: CronSchedule,
pub scheduled_time_ms: i64,
pub job_id: String,
pub attempt: u32,
pub deadline_unix_ms: u64,
}
One fire of a [triggers] crons schedule, as the host delivers it to
the scheduled(controller) trigger.
Fields
cron: The schedule that fired (normalized source is the handler'scron).scheduled_time_ms: Fire time in Unix milliseconds (a whole UTC minute): the handler'sscheduledTime. Retries of one fire keep it.job_id: Durable job id of this fire; stable across retries.attempt: Failure attempt, starting at 1.deadline_unix_ms: Lease expiry hint in Unix milliseconds; the host fence is authoritative.
Implements: Clone, Debug, Eq, PartialEq
pub struct CoverHeaders {
pub etag: Option<String>,
pub last_modified: Option<String>,
pub cache_control: Option<String>,
pub expires: Option<String>,
pub date: Option<String>,
pub age: Option<String>,
}
The caching headers an image server sent with one answer, verbatim as
the covers plugin passed them on (each at most the ABI's
maxCoverHeaderBytes); None for a header it did not send.
Fields
etag:ETag.last_modified:Last-Modified.cache_control:Cache-Control.expires:Expires.date:Date.age:Age.
Implements: Clone, Debug, Default, Eq, PartialEq
pub struct ExternalUser {
pub provider: String,
pub external_user_id: String,
pub display_name: Option<String>,
pub access_token: Option<String>,
}
External user resolved via integration credential login or watcher.
Fields
provider: Integration / storefront id that owns this external identity.external_user_id: Remote system's user id (never a Bookclerk user id).display_name: Optional human-facing name from the remote system.access_token: Ephemeral token from the remote system (e.g. ABS JWT). Never persisted.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct FetchedCover {
pub url: String,
pub body: Option<Vec<u8>>,
pub content_type: Option<String>,
pub error: Option<String>,
pub not_modified: bool,
pub headers: CoverHeaders,
}
One image a covers plugin downloaded, or why it could not.
The body is untrusted bytes as the remote server sent them: callers must sniff, decode and re-encode it before storing or serving it.
Fields
url: The requested URL, verbatim.body: Response body, at most themax_bytesthe call asked for;Nonewhen nothing was stored.content_type:Content-Typethe server sent. Advisory only.error: Why there is no body, as the plugin or the host sink reported it;Nonewhen there is a body or the image was not modified.not_modified: The server answered304 Not Modifiedto the URL's conditions: there is no body and the caller's copy is still current.headers: Upstream's caching headers, verbatim and untrusted: the caller parses and bounds them.
Implements: Clone, Debug, Default, Eq, PartialEq
pub struct IntegrationHealth {
pub id: String,
pub enabled: bool,
pub ok: bool,
pub detail: Option<String>,
}
Health snapshot for one integration.
Fields
id: Integration id this health row describes (audiobookshelf, …).enabled: When true, this feature or account is active.ok: When true, the last health probe succeeded.detail: Optional human-readable health or error detail.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct ListeningProgressSnapshot {
pub external_user_id: String,
pub external_item_id: String,
pub identity_id: Option<i64>,
pub title: Option<String>,
pub authors: Option<String>,
pub asin: Option<String>,
pub isbn: Option<String>,
pub progress: Option<f64>,
pub current_time_seconds: Option<f64>,
pub duration_seconds: Option<f64>,
pub is_finished: bool,
pub last_listened_at: Option<DateTime<Utc>>,
}
One listening / progress row from any integration (ABS, plugins, …).
Hosts upsert these into the generic listening_progress table; ranking never
sees the originating adapter—only these fields.
Fields
external_user_id: Remote system's user id (never a Bookclerk user id).external_item_id: Remote library item id for progress matching.identity_id: Bookclerk portal identity row id when already linked.title: Display title as shown on the storefront or library card.authors: Comma-separated author names when the storefront provides them.asin: Audible / Amazon ASIN when this edition is sold on Audible.isbn: Canonical ISBN-13 (or ISBN-10 normalized) when published.progress: Fraction complete in[0.0, 1.0]when the remote reports it.current_time_seconds: Playback position in seconds from the start of the title.duration_seconds: Total title duration in seconds when known.is_finished: When true, the remote marks this title as finished.last_listened_at: UTC timestamp of the last playback event when known.
Implements: Clone, Debug, Default, Deserialize<'de>, Serialize
pub struct SyncListeningProviderResult {
pub id: String,
pub upserted: usize,
pub error: Option<String>,
}
Per-integration outcome from crate::IntegrationRegistry::sync_listening_progress_all.
Fields
id: Stable identifier for this item.upserted: Number of listening_progress rows written or updated.error: Operator-facing error text when this step failed;Noneon success.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct SyncListeningSummary {
pub upserted: usize,
pub by_provider: Vec<SyncListeningProviderResult>,
}
Result of syncing listening progress across one or more integrations.
Fields
upserted: Number of listening_progress rows written or updated.by_provider: Per-integration breakdown of upsert counts and errors.
Implements: Clone, Debug, Default, Deserialize<'de>, Serialize
pub enum IntegrationError {
Api { status: u16, message: String },
Library(LibraryError),
Config(ConfigError),
Other(Error),
Message(String),
}
Errors from outbound integrations and the connect portal.
Variants
Api: Remote HTTP API returned a non-success status.status: HTTP status code from the remote API.message: Response body or summarized error text.
Library: Error propagated frombookclerk_library.Config: Error propagated frombookclerk_config.Other: Opaque error wrapped fromanyhow.Message: Operator-facing error text with no structured code.
pub fn message(msg: impl Into<String>) -> Self
Builds an error from a human-readable message string.
msg- Operator-facing error text.
Updated Self for chaining.
pub fn api(status: u16, message: impl Into<String>) -> Self
Builds an IntegrationError::Api from an HTTP status and response text.
status- HTTP status code from the remote API.message- Response body or summarized error text.
Updated Self for chaining.
Implements: Debug, Display, Error, From<ConfigError>, From<Error>, From<LibraryError>
pub fn from_config(_config: &Config) -> Result<IntegrationRegistry>
Construct an empty registry (no in-process adapters).
Hosts that also load plugins should prefer
bookclerk_plugin_host::load_integrations.
config- Loaded Bookclerk configuration.
On success, the inner IntegrationRegistry value.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub fn register_builtins(
_config: &Config,
_registry: &mut IntegrationRegistry,
) -> Result<()>
Register first-party integrations into an existing registry.
This function is intentionally a no-op; ABS and other adapters load as
external guests through bookclerk_plugin_host::load_integrations.
config- Loaded Bookclerk configuration.registry- Configured content-source or integration registry.
The successful result value for this operation.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn upsert_listening_snapshots(
library: &LibraryStore,
provider: &str,
items: &[ListeningProgressSnapshot],
) -> Result<usize>
Upsert provider-agnostic listening snapshots into listening_progress.
provider should be the integration id (audiobookshelf, plugin id, …).
The whole sync costs a few bulk statements, not a round trip chain per
item: portal identities and stored rows are read in chunks, each item's
ASIN and ISBN resolve to a work through the indexed edition_identifiers
table (titles are never compared), and the rows are written as atomic
batches sized to the database plugin's limits
(LibraryStore::upsert_listening_progress_batch).
A row is keyed by the work its identifiers resolved to. An item whose identifiers name no work in the library is not stored: there is no work to hold its progress, and the next sync stores it once the library has one.
When the sync changes what Discover reads from any stored row (see
TasteState: who the row belongs to, which work it is about, and how far
they got), publishes one listening_synced; a sync that changes nothing
Discover reads queues no refresh.
library- Open library store used for reads/writes.provider- Integration id.items- Snapshots the integration reported, in its order.
How many snapshots were stored: the items whose identifiers resolved to a work (reports of one row merge).
Returns an error when a store read or write fails. Batches written
before the failure stay, so a failed write still publishes
listening_synced (naming no identity: everyone refreshes).
pub async fn mint_for_external_user(
library: &LibraryStore,
config: &Config,
user: &ExternalUser,
created_by: &str,
) -> Result<MintedClaimTicket>
Mint a claim ticket for an external user (daemon watcher / CLI).
library- Open library store used for reads/writes.config- Loaded Bookclerk configuration.user- External user identity from an integration login/watcher.created_by- Actor string recorded on the claim ticket (daemon, CLI user, …).
On success, crate::Result<crate::tickets::MintedClaimTicket>.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn portal_identity_from_headers(
library: &LibraryStore,
headers: &HeaderMap,
) -> Option<PortalIdentity>
Resolve a portal identity from the request cookie, if present and valid.
library- Open library store used for reads/writes.headers- Incoming HTTP headers (cookie lookup).
Some(...) when found / applicable; otherwise None.
pub fn portal_spa_router(state: PortalState) -> Router
The SPA Accounts / claim routes with their state, ready to nest.
state- Shared portal state.
pub fn portal_spa_routes() -> OpenApiRouter<PortalState>
The SPA Accounts / claim routes, before state: the daemon nests them at
/api/portal and lists them in its OpenAPI document.
The routes, relative to their mount point.
pub fn redeem_lose_next_responses(n: i32)
Drop the next N successful redeem HTTP responses after the DB commit.
Production stays at 0. Tests inject a committed-but-lost first reply so the retry can recover the receipt through the real handler.
pub fn generate_token() -> String
Generate a URL-safe random token.
pub async fn identity_from_session(
library: &LibraryStore,
raw_session: &str,
) -> Result<Option<PortalIdentity>>
Resolve identity from a portal session cookie value.
library- Open library store used for reads/writes.raw_session- Plaintext portal session cookie value.
On success, the inner Option<PortalIdentity> value.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn mint_claim_ticket(
library: &LibraryStore,
integrations: &IntegrationsConfig,
user: &ExternalUser,
created_by: &str,
) -> Result<MintedClaimTicket>
Ensure identity exists and mint a claim ticket.
library- Open library store used for reads/writes.integrations- Integrations config (TTL, public origin, …).user- External user identity from an integration login/watcher.created_by- Actor string recorded on the claim ticket (daemon, CLI user, …).
On success, the inner MintedClaimTicket value.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn redeem_ticket_to_session(
library: &LibraryStore,
integrations: &IntegrationsConfig,
raw_ticket: &str,
nonce: &str,
) -> Result<(String, PortalIdentity)>
Redeem a claim ticket into a portal session cookie value (plaintext).
library- Open library store used for reads/writes.integrations- Integrations config (TTL, public origin, …).raw_ticket- Plaintext claim ticket from the SPA / share URL.
The successful result value for this operation.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn redeem_ticket_to_session_with_client(
library: &LibraryStore,
integrations: &IntegrationsConfig,
raw_ticket: &str,
nonce: &str,
client: Option<&SessionClientInfo>,
password_hash: Option<&str>,
password_fingerprint: Option<&str>,
) -> Result<(String, PortalIdentity)>
Redeem a claim ticket and mint a portal session with optional client metadata.
password_hash is applied in the same transaction as ticket consume and
session insert, and only while the ticket-bound local user has no password.
password_fingerprint is hashed into the atomic request so a retry with
a freshly salted Argon2id encoding still matches the receipt.
The raw session token is derived from the claim ticket, browser nonce, and process DEK so a lost atomic reply plus a new HTTP request reuse the same operation id. Possession of the used magic link without the nonce cannot recover the session.
Returns an error when the operation fails.
pub async fn session_for_identity(
library: &LibraryStore,
integrations: &IntegrationsConfig,
identity: &PortalIdentity,
) -> Result<String>
Create a portal session for an already-resolved identity (credential login).
library- Open library store used for reads/writes.integrations- Integrations config (TTL, public origin, …).identity- Already-resolved portal identity.
On success, the inner String value.
Returns an error when the underlying I/O, parse, network, or store operation fails.
pub async fn session_for_identity_with_client(
library: &LibraryStore,
integrations: &IntegrationsConfig,
identity: &PortalIdentity,
client: Option<&SessionClientInfo>,
) -> Result<String>
Create a portal session for an identity with optional client metadata.
Returns an error when the operation fails.
pub fn ticket_portal_url(integrations: &IntegrationsConfig, token: &str) -> Option<String>
Build a shareable SPA claim URL when public_origin is configured.
Opens the Bookclerk GUI invite page (/invite?ticket=).
integrations- Integrations config (TTL, public origin, …).token- Plaintext claim or session token.
Some(...) when found / applicable; otherwise None.
pub type Result<T> = Result<T, IntegrationError>;
Result alias for this crate.
pub type ImageSrc = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
pub const AI_LIST_TIMEOUT: Duration = _;
Longest a model plugin may take to list its models. Listing loads no model, so this mostly covers waking a sleeping plugin.
pub const AI_RUN_TIMEOUT: Duration = _;
Longest one model run may take before the router gives up on it. A full batch on the largest first-party model on one slow core fits; a caller with a shorter deadline passes its own.
pub const MAX_REGISTERED_INTEGRATIONS: usize = 256;
Hard ceiling on registered integrations (plugin discovery is user-influenced).
Generated from crates/bookclerk-integrations at main · View as Markdown