saddle-observability 0.3.25

Saddle structured logging and trace correlation
Documentation
//! Compiled consumer contract, not production startup/admission wiring.
use saddle_core::*;
use saddle_observability::{
    root_diagnostic::{request_child_view, request_identity_group},
    *,
};

fn call(rpc: &str, span: u64, module: &str, service: &str, operation: &str) -> CallContext {
    CallContext::new(
        "saddle".into(),
        module.into(),
        service.into(),
        operation.into(),
        TraceId::from_u128(1),
        SpanId::from_u64(span),
    )
    .with_trace_correlation_id(TraceCorrelationId::new("opaque-gateway-trace").unwrap())
    .with_rpc_correlation_id(RpcCorrelationId::new(rpc))
}

// Runtime supplies the actual task number and original physical pair. Numeric
// observation is not a permit; this function never mints a replacement pair.
fn database_source(
    view: &RequestExecutionView,
    request: &DbPhysicalRequestHalf,
    execution: &DbPhysicalExecutionHalf,
    output: Option<&EmergencyDiagnosticHandle>,
    original: &(dyn std::error::Error + 'static),
) -> RootRequestFailure {
    let checked = request
        .project_diagnostic_context(execution, view.clone())
        .ok()
        .unwrap();
    let db = view
        .in_db_scope(&checked)
        .unwrap()
        .with_db_operation(RegisteredContextOperation::checked("mapping.checks.A").unwrap());
    let diagnostic = BoundedDiagnostic::capture(
        DiagnosticCategory::UnexpectedError,
        CaptureSite::Origin,
        BoundedDiagnosticCause::new(
            DiagnosticStage::RequestDb,
            DiagnosticCode::new("db.decode.type").unwrap(),
        )
        .with_column(Some(0), Some(2)),
    );
    RootDiagnosticScope::new(&db, output).source_error_with_facts(
        original,
        diagnostic,
        DiagnosticCode::new("db.decode").unwrap(),
        RootRequestEvent::Database,
        RootOutcomeFacts {
            axes: DiagnosticOutcomeAxes {
                operation: OperationOutcome::Failed,
                ..Default::default()
            },
            transaction: ContextFact::Present(RequestTransactionFact::Unknown),
        },
    )
}

fn main() {
    // Storage contract exercise only. R0/A/R must reserve the exact layouts before
    // this constructor is enabled in a real admitted or rejection path.
    let mut publisher = RequestRootPublisher::create(
        ContextLabel::checked("saddle").unwrap(),
        ContextFact::NotEstablished,
    )
    .unwrap();
    let root = publisher.reference();
    let early = root.view(
        RequestLocalFacts::new(RequestViewPhase::Reading).with_task(ContextFact::Present(17)),
    );
    let read_error = std::io::Error::from(std::io::ErrorKind::UnexpectedEof);
    let early_failure = RootDiagnosticScope::new(&early, None).source_error(
        &read_error,
        DiagnosticStage::RequestDecode,
        RootRequestEvent::Ingress,
        RootOutcomeFacts::default(),
    );
    let event = EventContext::new(
        RequestIdentity::new("request-a").unwrap(),
        RouteIdentity::new("example.live").unwrap(),
        1,
    )
    .unwrap();
    assert!(
        publisher
            .publish(
                request_identity_group(
                    &call("0", 1, "entry", "app", "example.live"),
                    &event,
                    ContextFact::Present(ContextLabel::checked("local").unwrap())
                )
                .unwrap()
            )
            .is_ok()
    );
    let active = early
        .refresh(&root)
        .unwrap()
        .with_phase(RequestViewPhase::Handler);
    // Formal Boundary style: real child Call and event originate from its actual
    // ProfuseContract request. Obs validates rather than inventing a child RPC.
    let child_event = EventContext::new(
        RequestIdentity::new("request-a").unwrap(),
        RouteIdentity::new("receipt.invoke").unwrap(),
        1,
    )
    .unwrap();
    let child = request_child_view(
        &active,
        &call("0.1", 2, "local", "profusecontract", "invoke"),
        &child_event,
    )
    .unwrap();
    assert!(active.same_request(&child));
    let (_, issuer) = DbPhysicalDispositionIssuer::issue().into_startup_and_request_issuer();
    let (request, execution) = issuer.issue_request().unwrap();
    // Real D passes &sqlx::Error here before driver_ref/business mapping. This
    // standalone example uses the standard Error contract, with no DB dependency.
    let raw_error = std::io::Error::new(
        std::io::ErrorKind::PermissionDenied,
        "original driver description",
    );
    let db_failure = database_source(&active, &request, &execution, None, &raw_error);
    drop(raw_error);
    let supervised = RootSupervisionReturn::<()>::failed(
        db_failure.map_classification(DiagnosticCode::new("handler.failed").unwrap()),
    );
    let failure = supervised.consume().err().unwrap();
    // Public projections contain no source body or root. Real Runtime must also
    // finish the original physical pair, then drop all views before settlement.
    let public = failure
        .finish(&active, None, RootOutcomeFacts::default())
        .ok()
        .unwrap();
    let early_public = early_failure
        .finish(&active, None, RootOutcomeFacts::default())
        .ok()
        .unwrap();
    let observer = Observer::with_writer(ObserverConfig::default(), std::io::sink()).unwrap();
    let completed = RootDiagnosticScope::new(&active, None)
        .start_stage(&observer, RootRequestEvent::Response)
        .finish_nonfailure(RootOutcomeFacts {
            axes: DiagnosticOutcomeAxes {
                operation: OperationOutcome::Succeeded,
                ..Default::default()
            },
            ..Default::default()
        })
        .ok()
        .unwrap();
    assert_eq!(completed, DiagnosticSubmission::OutputUnavailable);
    assert_eq!(
        RootDiagnosticScope::new(&active, None).ordinary(
            &observer,
            RootRequestEvent::Handler,
            RootOutcomeFacts::default()
        ),
        DiagnosticSubmission::Enqueued
    );
    drop((publisher, root, early, active, child));
    assert_eq!(
        public.source_submission(),
        DiagnosticSubmission::OutputUnavailable
    );
    assert_eq!(
        early_public.terminal_submission(),
        DiagnosticSubmission::OutputUnavailable
    );
    for (name, (payload, shared)) in ["root", "view", "child"]
        .into_iter()
        .zip(saddle_core::request_context::request_context_layouts())
    {
        println!(
            "layout {name}: payload={} align={} arc_allocation={} arc_align={}",
            payload.size(),
            payload.align(),
            shared.size(),
            shared.align()
        );
    }
    println!(
        "layout receipt={} public={} root_ref={} view_ref={} identity_input={} bounded_detail={} borrowed_stage={}",
        size_of::<RootRequestFailure>(),
        size_of::<PublicRequestFailure>(),
        size_of::<RequestRootRef>(),
        size_of::<RequestExecutionView>(),
        size_of::<RequestIdentityGroup>(),
        size_of::<BoundedDiagnostic>(),
        size_of::<RootActiveStage<'static>>()
    );
    println!("C consumer contract GO; production reservation/lifecycle NOT_RUN");
    let layout = saddle_observability::root_diagnostic::request_logging_layouts();
    let (stream, cycle, payload) = saddle_observability::root_diagnostic::original_capture_layout();
    println!(
        "layout original_stream={} align={} cycle_detector={} align={} payload_limit={} total_content_limit=none",
        stream.size(),
        stream.align(),
        cycle.size(),
        cycle.align(),
        payload
    );
    println!(
        "layout source_frame={} source_record={} emergency_packet={} emergency_slots={} ordinary_command={} ordinary_payload_max={}",
        layout.source_frame.size(),
        layout.source_record.size(),
        layout.emergency_packet.size(),
        layout.emergency_slots,
        layout.ordinary_command.size(),
        layout.ordinary_encoded_bytes_max
    );
}