loonfs-api 0.2.0

Wire types and durable-format codecs for LoonFS.
Documentation
//! The capability document (API spec, "Capability discovery"): the
//! profiles and feature keys a deployment advertises, which clients gate
//! on instead of guessing from the backend kind.

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use thiserror::Error;

/// The protocol generation this build speaks.
pub const PROTOCOL_VERSION: &str = "v0";

/// The mandatory data plane.
pub const PROFILE_CORE_V0: &str = "core/v0";
/// The optional maintenance plane.
pub const PROFILE_ADMIN_V0: &str = "admin/v0";
/// The optional derived-index query plane.
pub const PROFILE_QUERY_V0: &str = "query/v0";

/// Gates namespace creation.
pub const FEATURE_NAMESPACES_CREATE: &str = "core.namespaces.create";
/// Gates namespace forking.
pub const FEATURE_NAMESPACES_FORK: &str = "core.namespaces.fork";
/// Gates namespace deletion.
pub const FEATURE_NAMESPACES_DELETE: &str = "core.namespaces.delete";
/// Gates direct upload sessions that are authorized with short-lived presigned URLs.
pub const FEATURE_UPLOADS_DIRECT_PUT: &str = "core.uploads.direct_put";
/// Starting presigned `direct_multipart` upload sessions.
pub const FEATURE_UPLOADS_DIRECT_MULTIPART: &str = "core.uploads.direct_multipart";
/// Gates download grants that are authorized with short-lived presigned
/// URLs. It rests on the same proof the two upload keys do, and is
/// advertised with them, because a deployment that lets a client write an
/// object it is too large to proxy back has to be able to hand it back.
pub const FEATURE_DOWNLOADS_DIRECT_GET: &str = "core.downloads.direct_get";
/// Gates grep-index content search: the serving half of the capability;
/// the namespace's verified steady-state grep root is the data half.
pub const FEATURE_QUERY_GREP: &str = "query.grep";

/// Advisory limit: the largest request body accepted for service-proxied
/// upload content requests.
pub const LIMIT_UPLOAD_MAX_CONTENT_BYTES: &str = "upload.max_content_bytes";
/// Advisory limit: the largest file content a service-proxied read will
/// buffer and return in one response.
pub const LIMIT_DOWNLOAD_MAX_CONTENT_BYTES: &str = "download.max_content_bytes";
/// Advisory limit: how many service-proxied upload bodies the deployment
/// buffers at once; requests past the cap answer `server_busy`.
pub const LIMIT_UPLOAD_MAX_CONCURRENT: &str = "upload.max_concurrent";
/// Advisory limit: how many service-proxied content reads the deployment
/// materializes at once; requests past the cap answer `server_busy`.
pub const LIMIT_DOWNLOAD_MAX_CONCURRENT: &str = "download.max_concurrent";
/// Advisory limit: the most path operations one commit may carry; a longer
/// list answers `invalid_request` before planning.
pub const LIMIT_COMMIT_MAX_OPERATIONS: &str = "commit.max_operations";
/// Advisory limit: the most content tokens one commit may carry.
pub const LIMIT_COMMIT_MAX_CONTENT_TOKENS: &str = "commit.max_content_tokens";
/// Advisory limit: the most distinct external content refs one commit's
/// operations may name.
pub const LIMIT_COMMIT_MAX_EXTERNAL_CONTENT_REFS: &str = "commit.max_external_content_refs";
/// Advisory limit: the largest accepted commit `message`, in bytes.
pub const LIMIT_COMMIT_MAX_MESSAGE_BYTES: &str = "commit.max_message_bytes";
/// Advisory capability key for the default page size applied when callers omit `limit`.
pub const LIMIT_PAGINATION_DEFAULT: &str = "pagination.default_limit";
/// Advisory capability key for the largest page size accepted by a deployment.
pub const LIMIT_PAGINATION_MAX: &str = "pagination.max_limit";
/// Advisory limit: the smallest accepted `grace_window_ms` on a `gc`
/// request; smaller values answer `invalid_request`. Derived from the
/// publication budgets, not tuned.
pub const LIMIT_GC_MIN_GRACE_WINDOW_MS: &str = "maintenance.gc.min_grace_window_ms";
/// Advisory limit: matches per grep page when the request omits `limit`.
pub const LIMIT_QUERY_GREP_DEFAULT: &str = "query.grep.default_limit";
/// Advisory limit: the largest accepted grep page limit. Distinct from the
/// pagination keys — a grep item costs a verified file read, not a row.
pub const LIMIT_QUERY_GREP_MAX: &str = "query.grep.max_limit";
/// Advisory limit: files a plan-less `allow_scan` grep will scan before
/// refusing with `query_unindexable`.
pub const LIMIT_QUERY_GREP_SCAN_BUDGET_FILES: &str = "query.grep.scan_budget_files";
/// Advisory limit: unindexed-tail revisions one grep scans exhaustively
/// before failing with `index_lagging`.
pub const LIMIT_QUERY_GREP_TAIL_BUDGET_FILES: &str = "query.grep.tail_budget_files";

/// A deployment's self-description (API spec, "Capability discovery").
///
/// A remote client fetches this from `GET /v0/capabilities` and caches it; an
/// embedded engine exposes the same document as a constant. SDK gating logic
/// is therefore identical for both backends: check [`supports`] or
/// [`has_profile`], and treat a `not_supported` error as authoritative when
/// the two disagree.
///
/// [`supports`]: CapabilityDocument::supports
/// [`has_profile`]: CapabilityDocument::has_profile
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct CapabilityDocument {
    /// The protocol generation, currently `v0`.
    pub protocol_version: String,
    /// Advertised profiles, each `plane/version`. All-or-nothing: every
    /// required op of an advertised profile is implemented.
    pub profiles: Vec<String>,
    /// Named features and whether this deployment supports them. An absent
    /// key means unsupported.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub features: BTreeMap<String, bool>,
    /// Advisory numeric limits clients may use to pre-validate requests.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub limits: BTreeMap<String, u64>,
}

/// Violation of the capability document rules.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum CapabilityDocumentError {
    /// Reports a feature whose dotted plane prefix has no advertised profile.
    #[error(
        "feature `{feature}` is not parented by an advertised profile \
         (its first dotted segment must be one of the advertised plane names)"
    )]
    UnparentedFeature {
        /// Feature key rejected while validating the deployment document.
        feature: String,
    },
}

impl CapabilityDocument {
    /// Whether a profile (for example `core/v0`) is advertised.
    pub fn has_profile(&self, profile: &str) -> bool {
        self.profiles.iter().any(|advertised| advertised == profile)
    }

    /// Whether a feature is advertised as supported. Absent keys are
    /// unsupported.
    pub fn supports(&self, feature: &str) -> bool {
        self.features.get(feature).copied().unwrap_or(false)
    }

    /// Checks the feature-key rule (API spec, "Capability discovery"): every
    /// feature key's first dotted segment must be the plane name of an
    /// advertised profile.
    pub fn validate(&self) -> Result<(), CapabilityDocumentError> {
        for feature in self.features.keys() {
            if !self.feature_is_parented(feature) {
                return Err(CapabilityDocumentError::UnparentedFeature {
                    feature: feature.clone(),
                });
            }
        }
        Ok(())
    }

    /// Drops feature keys that violate the feature-key rule, the
    /// client-side "ignore" handling for malformed documents.
    pub fn retain_well_formed(&mut self) {
        let advertised_planes: Vec<&str> = self.profiles.iter().map(|p| plane_name(p)).collect();
        self.features
            .retain(|feature, _| feature_is_parented(&advertised_planes, feature));
    }

    fn feature_is_parented(&self, feature: &str) -> bool {
        let advertised_planes: Vec<&str> = self.profiles.iter().map(|p| plane_name(p)).collect();
        feature_is_parented(&advertised_planes, feature)
    }
}

fn feature_is_parented(planes: &[&str], feature: &str) -> bool {
    match feature.split('.').next() {
        Some(plane) if !plane.is_empty() => planes.contains(&plane),
        _ => false,
    }
}

/// The plane name of a profile: `core/v0` has plane `core`.
fn plane_name(profile: &str) -> &str {
    profile.split('/').next().unwrap_or(profile)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn document() -> CapabilityDocument {
        CapabilityDocument {
            protocol_version: PROTOCOL_VERSION.to_owned(),
            profiles: vec![PROFILE_CORE_V0.to_owned(), PROFILE_ADMIN_V0.to_owned()],
            features: BTreeMap::from([
                (FEATURE_NAMESPACES_CREATE.to_owned(), true),
                (FEATURE_NAMESPACES_DELETE.to_owned(), false),
            ]),
            limits: BTreeMap::new(),
        }
    }

    #[test]
    fn supports_and_has_profile_answer_gating_questions() {
        let document = document();
        assert!(document.has_profile(PROFILE_CORE_V0));
        assert!(!document.has_profile("query/v0"));
        assert!(document.supports(FEATURE_NAMESPACES_CREATE));
        // Advertised-false and absent keys are both unsupported.
        assert!(!document.supports(FEATURE_NAMESPACES_DELETE));
        assert!(!document.supports(FEATURE_NAMESPACES_FORK));
    }

    #[test]
    fn feature_keys_must_be_parented_by_an_advertised_profile() {
        let mut document = document();
        document
            .features
            .insert("query.index.fulltext".to_owned(), true);

        assert_eq!(
            document.validate(),
            Err(CapabilityDocumentError::UnparentedFeature {
                feature: "query.index.fulltext".to_owned(),
            })
        );

        document.retain_well_formed();
        assert!(document.validate().is_ok());
        assert!(!document.features.contains_key("query.index.fulltext"));
        assert!(document.features.contains_key(FEATURE_NAMESPACES_CREATE));
    }

    #[test]
    fn capability_document_round_trips_and_tolerates_unknown_fields() {
        let document = document();
        let encoded = serde_json::to_string(&document).expect("encode");
        let decoded: CapabilityDocument = serde_json::from_str(&encoded).expect("decode");
        assert_eq!(decoded, document);

        let future = encoded.replacen('{', "{\"field_from_the_future\":true,", 1);
        let decoded: CapabilityDocument =
            serde_json::from_str(&future).expect("unknown fields are ignored");
        assert_eq!(decoded, document);
    }
}