Skip to main content

Crate toolkit

Crate toolkit 

Source
Expand description

§ToolKit - Declarative Gear System

A unified crate for building modular applications with declarative gear definitions.

§Features

  • Declarative: Use #[gear(...)] attribute to declare gears
  • Auto-discovery: Gears are automatically discovered via inventory
  • Type-safe: Compile-time validation of capabilities
  • Phase-based lifecycle: executed by HostRuntime (see runtime/host_runtime.rs docs)

§Golden Path: Stateless Handlers

For optimal performance and readability, prefer stateless handlers that receive Extension<T> and other extractors rather than closures that capture environment.

ⓘ
use axum::{Extension, Json};
use toolkit::api::{OperationBuilder, Problem};
use std::sync::Arc;

async fn list_users(
    Extension(svc): Extension<Arc<UserService>>,
) -> Result<Json<Vec<UserDto>>, Problem> {
    let users = svc.list_users().await.map_err(Problem::from)?;
    Ok(Json(users))
}

pub fn router(service: Arc<UserService>) -> axum::Router {
    let op = OperationBuilder::get("/users-info/v1/users")
        .summary("List users")
        .handler(list_users)
        .json_response(200, "List of users")
        .standard_errors(&registry);

    axum::Router::new()
        .route("/users-info/v1/users", axum::routing::get(list_users))
        .layer(Extension(service))
        .layer(op.to_layer())
}

§Benefits

  • Performance: No closure captures or cloning on each request
  • Readability: Clear function signatures show exactly what data is needed
  • Testability: Easy to unit test handlers with mock state
  • Type Safety: Compile-time verification of dependencies
  • Flexibility: Individual service injection without coupling

§Basic Gear Example

ⓘ
use toolkit::{gear, Gear, DbGear, RestfulGear, StatefulGear};

#[derive(Default)]
#[gear(name = "user", deps = [database], capabilities = [db, rest, stateful])]
pub struct UserGear;

// Implement the declared capabilities...

Re-exports§

pub use crate::contracts::GrpcServiceCapability;
pub use crate::contracts::RegisterGrpcServiceFn;
pub use config::ConfigError;
pub use config::ConfigProvider;
pub use config::gear_config_or_default;
pub use config::gear_config_required;
pub use context::GearContextBuilder;
pub use context::GearCtx;
pub use client_hub::ClientHub;
pub use registry::GearRegistry;
pub use api::IntoCanonical;
pub use api::OpenApiInfo;
pub use api::OpenApiRegistry;
pub use api::OpenApiRegistryImpl;
pub use api::OperationBuilder;
pub use api::error_mapping_middleware;
pub use http::sse::SseBroadcaster;
pub use runtime::DependencyChecker;
pub use runtime::ReadinessHealthcheck;
pub use domain::DomainErrorMarker;
pub use domain::DomainModel;
pub use directory::LocalDirectoryClient;
pub use discovery::ConsumerRegistration;
pub use discovery::DirectoryEndpointResolver;
pub use backends::BackendKind;
pub use backends::GearRuntimeBackend;
pub use backends::InstanceHandle;
pub use backends::LocalProcessBackend;
pub use backends::OopBackend;
pub use backends::OopGearConfig;
pub use backends::OopSpawnConfig;
pub use lifecycle::Lifecycle;
pub use lifecycle::Runnable;
pub use lifecycle::Status;
pub use lifecycle::StopReason;
pub use lifecycle::WithLifecycle;
pub use plugins::GtsPluginSelector;
pub use runtime::DEFAULT_SHUTDOWN_DEADLINE;
pub use runtime::DbOptions;
pub use runtime::Endpoint;
pub use runtime::GearInstance;
pub use runtime::GearManager;
pub use runtime::OopGearSpawnConfig;
pub use runtime::OopSpawnOptions;
pub use runtime::RunOptions;
pub use runtime::ShutdownOptions;
pub use runtime::run;
pub use tokio;
pub use inventory;
pub use crate::contracts::*;

Modules§

api
Type-safe API operation builder with compile-time guarantees
backends
Backend abstraction for out-of-process gear management
bootstrap
Unified bootstrap library for Gears Toolkit gears
client_hub
Minimalistic, type-safe ClientHub.
config
Configuration gear for typed gear configuration access.
context
contract
contract_support
contracts
directory
Directory API - contract for service discovery and instance resolution
discovery
Consumer-side discovery wiring for eventual readiness.
domain
Domain Layer Marker Traits
gts
GTS re-exports from toolkit-gts.
http
HTTP utilities for toolkit
lifecycle
plugins
registry
runtime
telemetry
Telemetry utilities for OpenTelemetry integration
var_expand
Single-pass expansion of ${VAR} and ${VAR:-default} placeholders from environment variables.
wiring
Runtime helpers consumed by #[toolkit::provides].

Structs§

GrpcServiceInfo
A resolved gRPC service and the endpoint it is reachable at.
HealthcheckComponentReport
One gear’s healthcheck result. All fields are part of the stable /health JSON contract.
HealthcheckReport
Aggregate report from RestHealthcheckRegistry::report; stable /health//readyz JSON contract.
HealthcheckResult
Result of one Healthcheck::check; fields are part of the stable /health JSON contract.
Page
PageInfo
RegisterInstanceInfo
Information for registering a new gear instance
RestHealthcheckRegistry
Holds the REST healthchecks registered during REST wiring; the gateway calls report on every /readyz and /health request.
Secured
A wrapper that binds a SecurityContext to a client reference.
ServiceEndpoint
Represents an endpoint where a service can be reached
ServiceInstanceInfo
Information about a service instance

Enums§

ContractError
Errors that can occur during contract support operations.
HealthcheckStatus
Single-check and aggregate readiness status. Serialized lowercase into /health//readyz; variants are a stable API contract.

Traits§

DirectoryClient
Directory API trait for service discovery and instance management
GrpcRepr
Marker for “any type that can appear in a gRPC method signature, either as a parameter or as the success type of Result<T, E> returned from a method.” Composite shapes (Vec<T>, Option<T>, maps) are GrpcRepr when their inner type is GrpcReprScalar.
GrpcReprScalar
Marker for “scalar” types — anything that can sit inside a Vec<>, Option<>, or as the value type of a HashMap<String, V>.
Healthcheck
Readiness probe implemented by a gear.
QueryParams
A struct usable as a REST query parameter.
WithSecurityContext
Extension trait that adds the security_ctx method to any type.

Type Aliases§

Result
Result<T, Error>

Attribute Macros§

async_trait
consumes
#[toolkit::consumes(contract = ..., from = "gear")] — declare a contract dependency wired via eventual-readiness directory discovery.
contract
domain_model
Marks a struct or enum as a domain model, enforcing DDD boundaries at compile time.
gear
Main #[gear] attribute macro
grpc_contract
lifecycle
provides
#[toolkit::provides(contract = ..., local = ..., transports = [...])] — auto-wire a generated contract client into the host ClientHub.
rest_contract

Derive Macros§

ContractError
#[derive(ContractError)] — wire a typed Rust error enum into the PRD #1536 RFC 9457 envelope.
ExpandVars
Derive macro that implements [toolkit::var_expand::ExpandVars].
ProtoBridge
QueryParams
#[derive(QueryParams)] — mark a struct as a REST query parameter.