footing 0.1.1

Feature-gated foundations for Rust backend services
Documentation
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use super::{CURSOR_VERSION, CursorError, MAX_CURSOR_KIND_LENGTH, MAX_CURSOR_LENGTH};

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
struct CursorEnvelope<T> {
    version: u8,
    #[serde(skip_serializing_if = "Option::is_none")]
    kind: Option<String>,
    payload: T,
}

/// Encodes cursor.
pub fn encode_cursor<T>(value: &T) -> Result<String, CursorError>
where
    T: Serialize,
{
    encode_cursor_with_kind(None, value)
}

/// Decodes cursor.
pub fn decode_cursor<T>(cursor: &str) -> Result<T, CursorError>
where
    T: DeserializeOwned,
{
    decode_cursor_with_kind(None, cursor)
}

/// Encodes typed cursor.
pub fn encode_typed_cursor<T>(kind: impl Into<String>, value: &T) -> Result<String, CursorError>
where
    T: Serialize,
{
    encode_cursor_with_kind(Some(validate_cursor_kind(kind)?), value)
}

/// Decodes typed cursor.
pub fn decode_typed_cursor<T>(kind: &str, cursor: &str) -> Result<T, CursorError>
where
    T: DeserializeOwned,
{
    validate_cursor_kind(kind)?;
    decode_cursor_with_kind(Some(kind), cursor)
}

pub(super) fn encode_cursor_with_kind<T>(
    kind: Option<String>,
    value: &T,
) -> Result<String, CursorError>
where
    T: Serialize,
{
    let bytes = serde_json::to_vec(&CursorEnvelope {
        version: CURSOR_VERSION,
        kind,
        payload: value,
    })?;

    let cursor = URL_SAFE_NO_PAD.encode(bytes);
    validate_cursor_length(&cursor)?;
    Ok(cursor)
}

pub(super) fn decode_cursor_with_kind<T>(kind: Option<&str>, cursor: &str) -> Result<T, CursorError>
where
    T: DeserializeOwned,
{
    validate_cursor_length(cursor)?;

    let bytes = URL_SAFE_NO_PAD
        .decode(cursor)
        .map_err(|_| CursorError::InvalidEncoding)?;

    let envelope: CursorEnvelope<T> = serde_json::from_slice(&bytes)?;
    validate_cursor_envelope(&envelope, kind)?;
    Ok(envelope.payload)
}

fn validate_cursor_envelope<T>(
    envelope: &CursorEnvelope<T>,
    expected_kind: Option<&str>,
) -> Result<(), CursorError> {
    if envelope.version != CURSOR_VERSION {
        return Err(CursorError::UnsupportedVersion {
            actual: envelope.version,
        });
    }

    if let Some(actual) = &envelope.kind {
        validate_cursor_kind(actual)?;
    }

    if let Some(expected) = expected_kind
        && envelope.kind.as_deref() != Some(expected)
    {
        return Err(CursorError::KindMismatch {
            expected: expected.to_owned(),
            actual: envelope.kind.clone(),
        });
    }

    Ok(())
}

pub(super) fn validate_cursor_length(cursor: &str) -> Result<(), CursorError> {
    if cursor.is_empty() {
        return Err(CursorError::Empty);
    }

    if cursor.len() > MAX_CURSOR_LENGTH {
        return Err(CursorError::TooLarge {
            max: MAX_CURSOR_LENGTH,
        });
    }

    Ok(())
}

pub(super) fn validate_cursor_kind(kind: impl Into<String>) -> Result<String, CursorError> {
    let kind = kind.into();
    if kind.is_empty()
        || kind.len() > MAX_CURSOR_KIND_LENGTH
        || !kind
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(CursorError::InvalidKind);
    }

    Ok(kind)
}