Skip to content

Latest commit

 

History

History
878 lines (692 loc) · 30.4 KB

README.md

File metadata and controls

878 lines (692 loc) · 30.4 KB
apcore logo

apcore

Rust License OpenSSF Best Practices

Define once. Govern every call.

An embeddable microframework for application capabilities that agents and code can call.

MCP tells an agent what it can call. apcore decides whether this call — with these arguments, by this identity — should run at all, and leaves evidence that it did.

Think of apcore as a shared safety and validation checkpoint between callers (AI agents, Axum HTTP routes, CLIs, internal Rust services) and the real actions inside your application:

  • SaaS & support copilots — Validate inputs/outputs with JSON Schema / schemars and block destructive / requires_approval actions until approved.
  • Existing Rust backends → MCP / CLI / A2A — Implement Module (or use #[module] / YAML bindings) once so HTTP, MCP, CLI, and direct code share identical ACL, approval, and trace rules.
  • Safe multi-step automation — Default-deny caller_id → target_id ACLs, call-depth / cycle guards, x-sensitive redaction, structured ai_guidance error recovery, and W3C trace_id propagation.
cargo add apcore async-trait serde_json
cargo add tokio --features macros,rt-multi-thread

New to apcore? Follow the 5-Minute Getting Started Guide or jump straight to Quick Start below.

Highlights

  • Enforced contracts — Module trait, #[module] macro, schemars-derived or explicit JSON Schema Draft 2020-12 validation, and declarative YAML bindings.
  • Runtime governance — Behavioral annotations (readonly, destructive, requires_approval, idempotent, open_world), default-deny pattern ACLs, fail-closed async approval gates with Phase B resume, and call-depth / circular-call guards.
  • Middleware & observability — Onion-model middleware, W3C Trace Context spans, metrics, structured logging, x-sensitive redaction, and structured ModuleError recovery metadata (retryable, user_fixable, ai_guidance).
  • Async-native & modular — Built on tokio with default lightweight in-memory profile and opt-in Cargo features (config, discovery, observability, events, sys-modules, macros, full).

Cross-Language Feature Parity

The Python, TypeScript, and Rust SDKs share these protocol contracts. See the Rust changelog for release history.

Feature Python TypeScript Rust
Reserved namespace query API (#60) Yes Yes Yes
Event delivery semantics — retry + DLQ (#61) Yes Yes Yes
Streaming module interface (#62) Yes Yes Yes
ContextKey typed context accessors (#63) Yes Yes Yes
Middleware duplicate-name detection (#64) Yes Yes Yes
Registry load-ordering guarantees (#65) Yes Yes Yes
AsyncTaskManager (background task execution) Yes Yes Yes
ExtensionManager / ExtensionPoint (plugin registry) Yes Yes Yes
validate() withholds introspection from a denied caller (apcore#96) Yes Yes Yes
get_definition().dependencies is a parsed field (apcore#90) Yes Yes Yes

All three SDKs withhold module-level preflight and preview when the ACL denies access. Validation still reports the failed ACL check. A permitted call can receive the module's preflight or preview even if schema validation fails.

See the AsyncTaskManager and ExtensionManager source, plus the corresponding tests at tests/test_async_task.rs and tests/test_extensions.rs.

API Overview

Core

Type Description
APCore High-level client — register modules, call, stream, validate
Registry Module storage — discover, register, get, list, plus watch() for filesystem hot-reload (parity with apcore-python Registry.watch) and reload() for explicit re-discovery
Executor Execution engine — call with middleware pipeline, ACL, approval
Context Request context — trace ID, identity, call chain, cancel token
Config Configuration — from_defaults with env overrides, load YAML/JSON, get/set dot-path, validate, reload
Identity Caller identity — id, type, roles, attributes
Module Core trait for implementing schema-aware modules

Access Control & Approval

Type Description
ACL Access control — rule-based caller/target authorization
ApprovalHandler Pluggable approval gate trait
AlwaysDenyHandler / AutoApproveHandler Built-in approval handlers

Middleware

Type Description
Middleware Pipeline hooks — before/after/on_error interception
BeforeMiddleware / AfterMiddleware Single-phase middleware adapters
ObsLoggingMiddleware Structured logging middleware
RetryMiddleware Automatic retry with backoff
ErrorHistoryMiddleware Records errors into ErrorHistory
PlatformNotifyMiddleware Emits events on error rate/latency spikes

Schema

Type Description
SchemaLoader Load schemas from YAML or native types
SchemaValidator Validate data against schemas
export_generic / to_strict_schema Preserve the full JSON Schema or apply the A23 transform
RefResolver Resolve $ref references in JSON Schema

Observability

Type Description
TracingMiddleware Distributed tracing with span export
MetricsMiddleware / MetricsCollector Call count, latency, error rate metrics
ContextLogger Context-aware structured logging
ErrorHistory Ring buffer of recent errors with deduplication
UsageCollector Per-module usage statistics and trends

Events & Utilities

Type Description
EventEmitter Event system — subscribe, unsubscribe, emit, emit_filtered, flush
WebhookSubscriber Built-in event subscriber
CancelToken Cooperative cancellation token
BindingLoader Load modules from YAML binding files

See Cross-Language Feature Parity for the full parity matrix across Python, TypeScript, and Rust.

Documentation

For full documentation, including Quick Start guides for Python and Rust, visit: https://apcore.apstack.org/getting-started/

Requirements

  • Rust >= 1.86 (enforced by rust-version in Cargo.toml)
  • Tokio async runtime

Installation and feature profiles

APCore::new assembles the in-memory registry and executor. The default profile keeps Tokio runtime, macros, synchronization, and timers for streaming, cancellation, and managed lifecycle. Discovery, filesystem watching, YAML loading, and network delivery are opt-in.

Cargo feature Capability
config YAML configuration, file-backed ACLs, and bindings
discovery Filesystem module discovery and watching
sys-modules Configured system modules and event setup
events HTTP webhook delivery and OTLP transport
events-file JSONL event subscribers
full All runtime integrations above
macros Typed module declarations and governed handles

Use APCore::with_config or APCore::try_start with the required features for configured startup. Calls requiring approval are denied when a handler is missing. Destructive modules require approval by default. Configure an ApprovalHandler to resolve those calls or set the relevant ExecutionPolicy switch explicitly.

Add the crate to your project:

cargo add apcore
cargo add tokio --features macros,rt-multi-thread
cargo add serde_json async-trait

Enable full on the apcore dependency when the application uses all of the optional integrations.

Enable macros when declaring modules with #[apcore::module]. Use schemars 0.8 to derive schemas for the input and output types and Serde to serialize both types. The input type's serialized representation must include the values the handler relies on. The registered module uses the normal executor, including ACL and approval. See the typed module declarations.

Configured health summaries expose project.version when supplied. Explicit sys_modules.usage.retention_hours sets the cutoff for hourly usage buckets at collector startup. Without that setting, the collector keeps up to 168 occupied buckets per module.

Bare-name canonicalization

Use canonicalize_name for one external name, such as a CLI command or operation name. It returns a canonical segment or a structured diagnostic, always retaining the exact original input:

use apcore::{canonicalize_name, CanonicalNameError};

fn main() {
    let command = canonicalize_name("cat-file");
    assert_eq!(command.original_name, "cat-file");
    assert_eq!(command.canonical_name.as_deref(), Some("cat_file"));
    assert_eq!(command.error, None);

    let invalid = canonicalize_name("7z");
    assert_eq!(invalid.original_name, "7z");
    assert_eq!(invalid.canonical_name, None);
    assert_eq!(invalid.error, Some(CanonicalNameError::InvalidStart));
}

The function rejects non-ASCII input before trimming ASCII edge punctuation and whitespace, applies ASCII case boundaries, and replaces each internal separator run with one underscore. Existing underscores are preserved. Diagnostics are non_ascii, empty_name, invalid_start, and name_too_long, checked in that order. The candidate must start with an ASCII lowercase letter and must not exceed 192 characters; names are never prefixed or truncated. CanonicalNameResult and CanonicalNameError support serde and JSON Schema.

This API does not process a module ID hierarchy: api.GetUser becomes the single segment api_get_user. Existing normalize_to_canonical_id remains the strict, language-aware module ID API and still rejects hyphens. system is a valid bare segment; reserved namespaces and collisions must be checked when registering or scanning modules.

Quick Start

Simple client

use apcore::APCore;
use apcore::module::Module;
use apcore::context::Context;
use serde_json::{json, Value};

struct AddModule;

#[async_trait::async_trait]
impl Module for AddModule {
    fn description(&self) -> &str { "Add two integers" }

    fn input_schema(&self) -> Value {
        json!({"type": "object", "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}, "required": ["a", "b"]})
    }
    fn output_schema(&self) -> Value {
        json!({"type": "object", "properties": {"result": {"type": "integer"}}})
    }

    async fn execute(
        &self,
        input: Value,
        _ctx: &Context<Value>,
    ) -> Result<Value, apcore::errors::ModuleError> {
        let a = input["a"].as_i64().unwrap_or(0);
        let b = input["b"].as_i64().unwrap_or(0);
        Ok(json!({ "result": a + b }))
    }
}

#[tokio::main]
async fn main() {
    let mut client = APCore::new();
    client.register("math.add", Box::new(AddModule)).unwrap();

    let result = client
        .call("math.add", json!({"a": 10, "b": 5}), None, None)
        .await
        .unwrap();
    println!("{}", result); // {"result": 15}
}

With configuration

use apcore::APCore;

#[tokio::main]
async fn main() {
    // Load directly from file path
    let client = APCore::from_path("apcore.yaml").unwrap();

    // Or load and modify config before constructing
    // let config = Config::from_yaml_file(Path::new("apcore.yaml")).unwrap();
    // let client = APCore::with_config(config);
}

Module with typed schemas

use apcore::module::{Module, ModuleAnnotations};
use apcore::context::Context;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

#[derive(Serialize, Deserialize)]
struct GetUserInput {
    user_id: String,
}

#[derive(Serialize, Deserialize)]
struct GetUserOutput {
    id: String,
    name: String,
    email: String,
}

struct GetUserModule;

#[async_trait::async_trait]
impl Module for GetUserModule {
    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "user_id": { "type": "string" }
            },
            "required": ["user_id"]
        })
    }

    fn output_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "id": { "type": "string" },
                "name": { "type": "string" },
                "email": { "type": "string" }
            }
        })
    }

    fn description(&self) -> &str { "Get user details by ID" }

    // Annotations (readonly, idempotent, etc.) are set on
    // ModuleDescriptor when registering the module with the registry.

    async fn execute(
        &self,
        input: Value,
        _ctx: &Context<Value>,
    ) -> Result<Value, apcore::errors::ModuleError> {
        let req: GetUserInput = serde_json::from_value(input)?;
        let user = match req.user_id.as_str() {
            "user-1" => GetUserOutput { id: "user-1".into(), name: "Alice".into(), email: "[email protected]".into() },
            "user-2" => GetUserOutput { id: "user-2".into(), name: "Bob".into(),   email: "[email protected]".into() },
            id       => GetUserOutput { id: id.into(),       name: "Unknown".into(), email: "[email protected]".into() },
        };
        Ok(serde_json::to_value(user)?)
    }
}

Add middleware

Rust reserves use as a keyword, so the middleware-attachment method is named use_middleware() rather than use() as in apcore-python and apcore-typescript. Functionally equivalent.

use apcore::observability::{ContextLogger, ObsLoggingMiddleware};

client.use_middleware(Box::new(ObsLoggingMiddleware::new(ContextLogger::new("app"))));
// TracingMiddleware requires a SpanExporter — see observability docs

TracingMiddleware — there is exactly one, apcore::TracingMiddleware (re-exported from observability::tracing_middleware). It opens the apcore.module.execute span the protocol specifies, keeps a span stack so nested module-to-module calls get real parent_span_id links, and exports through a pluggable SpanExporter with sampling controls and zero external dependencies. Point it at an OpenTelemetry collector with OTLPExporter.

Access control

ACLRule is #[non_exhaustive], so a rule is built through ACLRule::new and its optional fields assigned afterwards — the form that compiles from outside the crate, and the one that stays source-compatible when the spec adds a field.

use apcore::acl::{ACL, ACLRule};

let mut admins = ACLRule::new(vec!["admin.*".into()], vec!["*".into()], "allow");
admins.description = Some("Admins can call anything".into());

let mut others = ACLRule::new(vec!["*".into()], vec!["admin.*".into()], "deny");
others.description = Some("Others cannot call admin modules".into());

let acl = ACL::new(vec![admins, others], "deny", None);

A call that arrives with no caller_id is matched as apcore::EXTERNAL_CALLER ("@external"), an exact literal that no wildcard reaches — grant it explicitly with callers: ["@external"].

Execution policy (external governance overrides)

ExecutionPolicy lets a platform operator override a module's governance annotations (requires_approval, destructive) at execution time, without touching the module's source or its registration. It attaches to the Executor and is consulted by the approval gate (pipeline step 5). Rules use the same wildcard matching and specificity scoring as ACL rules; on a specificity tie the more restrictive rule wins.

use std::sync::Arc;

use apcore::approval::AutoApproveHandler;
use apcore::config::Config;
use apcore::executor::Executor;
use apcore::registry::registry::Registry;
use apcore::{ExecutionPolicy, PolicyRule};

fn configure(registry: Arc<Registry>) -> Result<Executor, apcore::errors::ModuleError> {
    let mut executor = Executor::new(registry, Config::from_defaults());

    let policy = ExecutionPolicy::new(vec![
        // Force approval for every module under `executor.payments.*`,
        // whatever the module itself declares.
        PolicyRule::new("executor.payments.*")?
            .with_requires_approval(true)
            .with_reason("PCI scope — platform requires human sign-off"),
        // Exempt a known-safe read path from the broader rule above; the more
        // specific pattern wins.
        PolicyRule::new("executor.payments.read_balance")?
            .with_requires_approval(false)
            .with_reason("read-only balance lookup"),
    ])
    // Defaults to true: gates anything annotated `destructive: true`.
    .with_gate_destructive(true)
    // Defaults to true: fails CLOSED when approval is required and no
    // ApprovalHandler is configured. Set `false` to opt out during migration.
    .with_strict(true);

    executor.set_policy(Some(policy));
    executor.set_approval_handler(Box::new(AutoApproveHandler));
    Ok(executor)
}

A matched rule overrides the module's own annotations — external governance is the platform's word against the module author's. Policy decisions are carried into ApprovalRequest and emitted as apcore.policy.override / apcore.approval.decision events. See examples/execution_policy.rs for a runnable end-to-end version.

Rust-specific quirks: two RetryConfig types

The Rust SDK ships two distinct RetryConfig structs that cannot share a crate-root alias because they collide on name. Pick the import path that matches the subsystem you are configuring:

// Middleware-level retry (used by `RetryMiddleware`). This one IS
// re-exported at the crate root for convenience.
use apcore::RetryConfig as MiddlewareRetryConfig;
// equivalent to: use apcore::middleware::RetryConfig;

// AsyncTaskManager-level retry (used by background task scheduling).
// Re-exported at the crate root under the non-colliding name
// `AsyncRetryConfig`, mirroring apcore-python and apcore-typescript which
// both rename-export the same type. The nested path also still works.
use apcore::AsyncRetryConfig as TaskRetryConfig;
// equivalent to: use apcore::async_task::RetryConfig;

YAML bindings

Register modules without touching Rust source — define a binding.yaml:

bindings:
  - module_id: "utils.format_date"
    target: "format_date::format_date_string"
    description: "Format a date string into a specified format"
    tags: ["utility", "date"]
    version: "1.0.0"
    input_schema:
      type: object
      properties:
        date_string:   { type: string }
        output_format: { type: string }
      required: [date_string, output_format]
    output_schema:
      type: object
      properties:
        formatted: { type: string }
      required: [formatted]

Load it at runtime:

use apcore::bindings::BindingLoader;

let mut loader = BindingLoader::new();
loader.load_from_yaml(std::path::Path::new("binding.yaml")).unwrap();

Discovery metadata and programmatic registration

The default discoverer reads a module's <stem>_meta.yaml companion file. It merges the file's annotations with the annotations returned by the module. YAML values override matching fields, and other fields keep their code-defined values.

For programmatic registration, use register_module(module_id, module) to derive the descriptor from the module, or register(module_id, module, descriptor) to supply a descriptor explicitly.

Examples

The examples/ directory contains runnable demos. Run any example with:

cargo run --example simple_client
cargo run --example greet
cargo run --example get_user
cargo run --example send_email
cargo run --example cancel_token
cargo run --example execution_policy   # external governance overrides (#76)
cargo run --example format_date        # YAML binding loader

simple_client — Implement Module and execute directly

Defines two modules (AddModule, GreetModule), builds an Identity + Context, and calls them directly without a registry.

use apcore::context::{Context, Identity};
use apcore::errors::ModuleError;
use apcore::module::Module;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::collections::HashMap;

struct AddModule;

#[async_trait]
impl Module for AddModule {
    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "a": { "type": "integer" },
                "b": { "type": "integer" }
            },
            "required": ["a", "b"]
        })
    }
    fn output_schema(&self) -> Value {
        json!({ "type": "object", "properties": { "result": { "type": "integer" } } })
    }
    fn description(&self) -> &str { "Add two integers" }

    async fn execute(&self, input: Value, _ctx: &Context<Value>) -> Result<Value, ModuleError> {
        let a = input["a"].as_i64().unwrap_or(0);
        let b = input["b"].as_i64().unwrap_or(0);
        Ok(json!({ "result": a + b }))
    }
}

#[tokio::main]
async fn main() {
    let identity = Identity::new(
        "user-1".to_string(),
        "user".to_string(),
        vec!["user".to_string()],
        HashMap::new(),
    );
    let ctx: Context<Value> = Context::new(identity);
    let module = AddModule;

    let result = module.execute(json!({"a": 10, "b": 5}), &ctx).await.unwrap();
    println!("{result}"); // {"result":15}
}

greet — Typed input/output with serde and default field values

Uses #[serde(default)] for optional fields and shows schema introspection and validation error handling.

use apcore::context::{Context, Identity};
use apcore::errors::ModuleError;
use apcore::module::Module;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize)]
struct GreetInput {
    name: String,
    #[serde(default = "default_greeting")]
    greeting: String,
}
fn default_greeting() -> String { "Hello".to_string() }

#[derive(Debug, Serialize, Deserialize)]
struct GreetOutput { message: String }

struct GreetModule;

#[async_trait]
impl Module for GreetModule {
    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "name":     { "type": "string", "description": "Name of the person to greet" },
                "greeting": { "type": "string", "description": "Custom greeting prefix", "default": "Hello" }
            },
            "required": ["name"]
        })
    }
    fn output_schema(&self) -> Value {
        json!({ "type": "object", "properties": { "message": { "type": "string" } }, "required": ["message"] })
    }
    fn description(&self) -> &str { "Greet a user by name" }

    async fn execute(&self, input: Value, _ctx: &Context<Value>) -> Result<Value, ModuleError> {
        let req: GreetInput = serde_json::from_value(input)
            .map_err(|e| ModuleError::new(apcore::errors::ErrorCode::GeneralInvalidInput, e.to_string()))?;
        Ok(serde_json::to_value(GreetOutput { message: format!("{}, {}!", req.greeting, req.name) }).unwrap())
    }
}

#[tokio::main]
async fn main() {
    let identity = Identity::new("agent-1".to_string(), "agent".to_string(), vec![], HashMap::new());
    let ctx: Context<Value> = Context::new(identity);
    let module = GreetModule;

    let out = module.execute(json!({"name": "Alice", "greeting": "Good morning"}), &ctx).await.unwrap();
    println!("{out}"); // {"message":"Good morning, Alice!"}

    let out = module.execute(json!({"name": "Bob"}), &ctx).await.unwrap();
    println!("{out}"); // {"message":"Hello, Bob!"}  ← default greeting applied

    // Schema introspection
    println!("{}", serde_json::to_string_pretty(&module.input_schema()).unwrap());

    // Missing required field → validation error
    let err = module.execute(json!({"greeting": "Hi"}), &ctx).await.unwrap_err();
    println!("Error: {err}");
}

get_user — Readonly module with ModuleAnnotations

Demonstrates behavioral annotations (readonly, idempotent, cacheable), typed input/output schemas, and looking up records by ID.

use apcore::module::{Module, ModuleAnnotations};
// ...

fn get_user_annotations() -> ModuleAnnotations {
    ModuleAnnotations {
        readonly: true,
        idempotent: true,
        cacheable: true,
        cache_ttl: 60,
        ..Default::default()
    }
}
user-1: {"email":"[email protected]","id":"user-1","name":"Alice"}
user-2: {"email":"[email protected]","id":"user-2","name":"Bob"}
user-999: {"email":"[email protected]","id":"user-999","name":"Unknown"}

send_email — Destructive module with sensitive fields

Schema-driven redaction follows local $ref definitions, escaped JSON Pointers, anchors and references within scoped embedded $id resources, including recursive object and array fields and composition branches. It uses a deep copy, retains configured redaction and _secret_ protection, and never retrieves external HTTP/file schemas. Object roots retain their object shape; whole-value sensitivity applies to nested fields. Schema indexing and positional array rules follow the declared dialect (default 2020-12), so unknown keywords cannot shadow local sensitivity anchors.

Shows x-sensitive: true on schema fields (for log redaction), ModuleAnnotations with metadata, and behavioral annotation for destructive operations.

fn input_schema(&self) -> Value {
    json!({
        "type": "object",
        "properties": {
            "to":      { "type": "string" },
            "subject": { "type": "string" },
            "body":    { "type": "string" },
            "api_key": { "type": "string", "x-sensitive": true }  // redacted in logs
        },
        "required": ["to", "subject", "body", "api_key"]
    })
}
fn send_email_annotations() -> ModuleAnnotations {
    ModuleAnnotations {
        destructive: true,
        requires_approval: true,
        ..Default::default()
    }
}

fn send_email_examples() -> Vec<ModuleExample> {
    vec![ModuleExample {
        title: "Send a welcome email".to_string(),
        inputs: json!({ "to": "[email protected]", "subject": "Welcome!", "body": "...", "api_key": "sk-xxx" }),
        output: json!({ "status": "sent", "message_id": "msg-12345" }),
        description: None,
    }]
}

cancel_token — Cooperative cancellation during long-running execution

CancelToken::drain().await waits for actual execution in that token's scope and its descendants, including cleanup continuing after a timeout response. It does not request cancellation or force termination. Call cancel() to signal cooperative cancellation separately. has_active_executions() reports whether the scope still owns execution; completed scopes retain no invocation handles. A deadline continues to return MODULE_TIMEOUT immediately, while successful active-task cancellation joins its owned background work, and AsyncTaskManager::shutdown drains remaining local work. Cancelling an already terminal task still returns false without interrupting its late cleanup.

CancelToken is a cloneable, shared cancellation signal. Modules poll token.is_cancelled() between steps to stop early.

use apcore::cancel::CancelToken;

// Attach a token to the context
let mut ctx: Context<Value> = Context::new(identity);
let token = CancelToken::new();
ctx.cancel_token = Some(token.clone());

// Cancel from another task after 80 ms
tokio::spawn(async move {
    tokio::time::sleep(Duration::from_millis(80)).await;
    token.cancel();
});

// Module checks the token between steps
async fn execute(&self, input: Value, ctx: &Context<Value>) -> Result<Value, ModuleError> {
    for i in 0..steps {
        if let Some(t) = &ctx.cancel_token {
            if t.is_cancelled() {
                return Err(ModuleError::new(ErrorCode::ExecutionCancelled, format!("cancelled at step {i}")));
            }
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    Ok(json!({ "completed_steps": steps }))
}
=== Run 1: normal execution ===
  [SlowModule] Executing step 0...
  [SlowModule] Executing step 1...
  [SlowModule] Executing step 2...
Result: {"completed_steps":3}

=== Run 2: cancelled mid-flight ===
  [SlowModule] Executing step 0...
  [SlowModule] Executing step 1...
  [main] Sending cancel signal…
  [SlowModule] Cancelled at step 2
Error (expected): Execution cancelled after 2 steps

Tests

Run all tests:

cargo test

Most integration tests compile into one binary (tests/it.rs, autotests = false) for fast builds; the few files that touch process-global Config/env state stay as their own binaries (see the [[test]] entries in Cargo.toml). To add a new test file, add a mod line to tests/it.rs — or, if it registers Config namespaces / mutates env, a [[test]] entry instead.

Run a specific consolidated test file (now a module of the it binary):

cargo test --test it test_cancel
cargo test --test it test_errors

Run a specific test by name:

cargo test test_cancel_token

Run with output visible:

cargo test -- --nocapture

Development

Prerequisites

Install Rust via rustup:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Clone and build

git clone https://github.com/apstack/apcore.git
cd apcore/rust
cargo build

Run tests

cargo test

Run tests with output

cargo test -- --nocapture

Run a specific test

cargo test test_cancel_token

Lint and format

cargo fmt           # auto-format code
cargo clippy        # lint

Build documentation

cargo doc --open

Check without building

cargo check

License

Apache-2.0

Links