apoc 0.9.1

Agentic process control for LLMs
Documentation
//! Read-only projections of durable apoc activity.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Commands whose invocation records must not feed their own observation stream.
pub const CONSUMER_COMMANDS: &[&str] = &[
    "observe capabilities",
    "observe projects",
    "observe snapshot",
    "observe watch",
    "observe tracks",
    "observe rows",
    "observe get",
];
pub const PROJECTION_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ObserveScope {
    Global,
    Project {
        scope_kind: crate::model::InvocationScopeKind,
        key: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ObserveQuery {
    pub scope: ObserveScope,
    pub track: Option<String>,
    pub id: Option<String>,
    pub limit: u32,
    pub byte_limit: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ObserveCursor {
    pub instance: String,
    pub projection_version: u32,
    pub query_digest: String,
    /// Decimal strings preserve integer precision in browser clients.
    pub sequence: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Observation {
    pub id: String,
    pub revision: String,
    pub source: String,
    pub source_id: String,
    pub scope_kind: String,
    pub scope_key: Option<String>,
    pub track: String,
    pub label: String,
    pub status: String,
    pub start_time_ns: String,
    pub end_time_ns: Option<String>,
    pub execution_id: Option<String>,
    pub parent_id: Option<String>,
    pub deleted: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ObservePage {
    pub rows: Vec<Observation>,
    pub cursor: ObserveCursor,
    /// Snapshot pagination token; watch starts only after all pages are read.
    pub next_page: Option<String>,
    pub has_more: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ObserveTrack {
    pub id: String,
    pub rows: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ObserveProject {
    pub scope_kind: String,
    pub key: String,
    pub rows: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ObserveCapabilities {
    pub projection_version: u32,
    pub sources: Vec<String>,
    pub max_rows: u32,
    pub max_bytes: u32,
    pub source_clock: String,
    pub historical_backfill: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct SnapshotPosition {
    pub cursor: ObserveCursor,
    pub after: u64,
}

pub(crate) fn digest(query: &ObserveQuery) -> Result<String, String> {
    use sha2::{Digest, Sha256};
    // Page sizes can change without changing stream membership.
    let value = serde_json::to_vec(&(&query.scope, &query.track, &query.id))
        .map_err(|error| error.to_string())?;
    Ok(format!("{:x}", Sha256::digest(value)))
}

#[derive(Debug, Clone, Serialize, Deserialize, incurs::Options)]
pub struct ObserveReadOptions {
    /// Include every workspace in this apoc instance.
    #[serde(default)]
    pub global: bool,
    /// Select the canonical project containing this directory.
    pub cwd: Option<String>,
    /// Exact track identifier.
    pub track: Option<String>,
    /// Exact observation identifier.
    pub id: Option<String>,
    /// Maximum rows per page, from 1 through 1000.
    #[serde(default = "default_limit")]
    #[incurs(default = 100)]
    pub limit: u32,
    /// Maximum encoded row bytes, from 1024 through 1048576.
    #[serde(default = "default_bytes")]
    #[incurs(default = 262144)]
    pub byte_limit: u32,
    /// JSON cursor from the completed snapshot or previous watch.
    pub cursor: Option<String>,
    /// Snapshot pagination token.
    pub next_page: Option<String>,
    /// Bounded watch wait in milliseconds, at most 30000.
    #[serde(default)]
    #[incurs(default = 0)]
    pub timeout_ms: u64,
}
fn default_limit() -> u32 {
    100
}
fn default_bytes() -> u32 {
    262144
}

impl ObserveReadOptions {
    pub(crate) fn query(&self, caller_cwd: Option<&str>) -> Result<ObserveQuery, String> {
        if self.global && self.cwd.is_some() {
            return Err("OBSERVE_INVALID_SCOPE: global and cwd are mutually exclusive".into());
        }
        let scope = if self.global {
            ObserveScope::Global
        } else {
            let cwd = match self.cwd.as_deref() {
                Some(path) if std::path::Path::new(path).is_absolute() => path.to_owned(),
                Some(path) => std::path::Path::new(caller_cwd.ok_or("OBSERVE_MISSING_CWD")?)
                    .join(path)
                    .to_string_lossy()
                    .into_owned(),
                None => caller_cwd.ok_or("OBSERVE_MISSING_CWD")?.to_owned(),
            };
            let canonical = std::fs::canonicalize(cwd).map_err(|error| error.to_string())?;
            let scope = crate::history::invocation_scope(canonical.to_str());
            ObserveScope::Project {
                scope_kind: scope.kind,
                key: scope.key.ok_or("OBSERVE_MISSING_SCOPE")?,
            }
        };
        Ok(ObserveQuery {
            scope,
            track: self.track.clone(),
            id: self.id.clone(),
            limit: self.limit,
            byte_limit: self.byte_limit,
        })
    }
}