Skip to main content

AgentCx

Struct AgentCx 

Source
pub struct AgentCx { /* private fields */ }
Expand description

A capability-scoped context for agent operations.

§Construction

  • Production: prefer constructing once per top-level request/run and passing &AgentCx through.
  • Tests: use Self::for_testing / Self::for_testing_with_io to avoid ambient dependencies and to keep runs deterministic.

Implementations§

Source§

impl AgentCx

Source

pub const fn from_cx(cx: Cx) -> Self

Wrap an existing asupersync::Cx.

Source

pub fn for_current_or_request() -> Self

Use the ambient context when available, otherwise fall back to a request-scoped context.

This is useful when helper code may run either inside an already-scoped async task (where inheriting the current cancellation/budget is desirable) or at a top-level entry point that needs to create a fresh request context.

Source

pub fn for_request() -> Self

Create a request-scoped context (infinite budget).

Source

pub fn for_request_with_budget(budget: Budget) -> Self

Create a request-scoped context with an explicit budget.

Source

pub fn for_testing() -> Self

Create a test-only context (infinite budget).

Source

pub fn for_testing_with_io() -> Self

Create a test-only context with lab I/O capability.

Source

pub const fn cx(&self) -> &Cx

Borrow the underlying asupersync context.

Source

pub const fn fs(&self) -> AgentFs<'_>

Filesystem capability accessor.

Source

pub const fn time(&self) -> AgentTime<'_>

Time capability accessor.

Source

pub const fn http(&self) -> AgentHttp<'_>

HTTP capability accessor.

Source

pub const fn process(&self) -> AgentProcess<'_>

Process capability accessor.

Methods from Deref<Target = Cx>§

Source

pub fn restrict<NewCaps>(&self) -> Cx<NewCaps>
where NewCaps: SubsetOf<Caps>,

Re-type this context to a narrower capability set.

This is a zero-cost type-level restriction. It does not change runtime behavior, but removes access to gated APIs at compile time.

Source

pub fn pressure(&self) -> Option<&SystemPressure>

Read the current system pressure, if attached.

Returns None if no pressure handle was attached to this context.

Source

pub fn registry_handle(&self) -> Option<RegistryHandle>

Returns the registry capability handle, if attached.

Source

pub fn has_registry(&self) -> bool

Returns true if a registry handle is attached.

Source

pub fn emit_evidence(&self, entry: &EvidenceLedger)

Emit an evidence entry to the attached sink, if any.

This is a no-op if no evidence sink is configured. Errors during emission are handled internally by the sink (logged and dropped).

Source

pub fn macaroon(&self) -> Option<&MacaroonToken>

Returns a reference to the attached Macaroon token, if any.

Source

pub fn attenuate(&self, predicate: CaveatPredicate) -> Option<Cx<Caps>>

Attenuate the capability token by adding a caveat.

Returns a new Cx with an attenuated macaroon. The original context is unchanged. This does not require the root key — any holder can add caveats (but nobody can remove them).

Returns None if no macaroon is attached.

Source

pub fn attenuate_time_limit(&self, deadline_ms: u64) -> Option<Cx<Caps>>

Attenuate with a time limit: the token expires at deadline_ms.

Convenience wrapper around attenuate with [CaveatPredicate::TimeBefore].

Returns None if no macaroon is attached.

Source

pub fn attenuate_scope(&self, pattern: impl Into<String>) -> Option<Cx<Caps>>

Attenuate with a resource scope restriction.

The pattern uses simple glob syntax: * matches any single segment, ** matches any number of segments.

Returns None if no macaroon is attached.

Source

pub fn attenuate_rate_limit( &self, max_count: u32, window_secs: u32, ) -> Option<Cx<Caps>>

Attenuate with a windowed rate limit.

Restricts the token to at most max_count uses per window_secs. The caller is responsible for tracking the sliding window and providing window_use_count in VerificationContext.

Returns None if no macaroon is attached.

Source

pub fn attenuate_from_budget(&self) -> Option<Cx<Caps>>

Attenuate with the Cx’s current budget deadline.

If the Cx has a finite deadline, adds a TimeBefore caveat using it. If no deadline is set, the macaroon is returned unchanged.

Returns None if no macaroon is attached.

Source

pub fn verify_capability( &self, root_key: &AuthKey, context: &VerificationContext, ) -> Result<(), VerificationError>

Verify the attached capability token against a root key and context.

Checks the HMAC chain integrity and evaluates all caveat predicates. Emits evidence to the attached sink on both success and failure.

Returns Ok(()) if the token is valid and all caveats pass.

§Errors

Returns VerificationError if verification fails (bad signature or failed caveat). Returns Err(VerificationError::InvalidSignature) if no macaroon is attached.

Source

pub fn logical_now(&self) -> LogicalTime

Returns the current logical time without ticking.

Source

pub fn logical_tick(&self) -> LogicalTime

Records a local logical event and returns the updated time.

Source

pub fn logical_receive(&self, sender_time: &LogicalTime) -> LogicalTime

Merges a received logical time and returns the updated time.

Source

pub fn timer_driver(&self) -> Option<TimerDriverHandle>
where Caps: HasTime,

Returns a cloned handle to the timer driver, if present.

The timer driver provides access to timer registration for async time operations like sleep, timeout, and interval. When present, these operations use the runtime’s timer wheel instead of spawning threads.

§Example
if let Some(timer) = Cx::current().and_then(|cx| cx.timer_driver()) {
    let deadline = timer.now() + Duration::from_secs(1);
    let handle = timer.register(deadline, waker);
}
Source

pub fn has_timer(&self) -> bool
where Caps: HasTime,

Returns true if a timer driver is available.

When true, time operations can use the runtime’s timer wheel. When false, time operations fall back to OS-level timing.

Source

pub fn io(&self) -> Option<&dyn IoCap>
where Caps: HasIo,

Returns the I/O capability, if one is configured.

The I/O capability provides access to async I/O operations. If no capability is configured, this returns None and I/O operations are not available.

§Capability Model

Asupersync uses explicit capability-based I/O:

  • Production runtime configures real I/O capability (via reactor)
  • Lab runtime can configure virtual I/O for deterministic testing
  • Code that needs I/O must explicitly check for and use this capability
§Example
async fn read_data(cx: &Cx) -> io::Result<Vec<u8>> {
    let io = cx.io().ok_or_else(|| {
        io::Error::new(io::ErrorKind::Unsupported, "I/O not available")
    })?;

    // Use io capability...
    Ok(vec![])
}
Source

pub fn has_io(&self) -> bool
where Caps: HasIo,

Returns true if I/O capability is available.

Convenience method to check if I/O operations can be performed.

Source

pub fn remote(&self) -> Option<&RemoteCap>
where Caps: HasRemote,

Returns the remote capability, if one is configured.

The remote capability authorizes spawning tasks on remote nodes. Without this capability, spawn_remote returns RemoteError::NoCapability.

§Capability Model

Remote execution is an explicit capability:

  • Production runtime configures remote capability with transport config
  • Lab runtime can configure it for deterministic distributed testing
  • Code that needs remote spawning must check for this capability
Source

pub fn has_remote(&self) -> bool
where Caps: HasRemote,

Returns true if the remote capability is available.

Convenience method to check if remote task operations can be performed.

Source

pub fn register_io<S>( &self, source: &S, interest: Interest, ) -> Result<IoRegistration, Error>
where S: Source, Caps: HasIo,

Registers an I/O source with the reactor for the given interest.

This method registers a source (such as a socket or file descriptor) with the reactor so that the task can be woken when I/O operations are ready.

§Arguments
  • source - The I/O source to register (must implement Source)
  • interest - The I/O operations to monitor for (read, write, or both)
§Returns

Returns a IoRegistration handle that represents the active registration. When dropped, the registration is automatically deregistered from the reactor.

§Errors

Returns an error if:

  • No reactor is available (reactor not initialized or not present)
  • The reactor fails to register the source
Source

pub fn region_id(&self) -> RegionId

Returns the current region ID.

The region ID identifies the structured concurrency scope that owns this task. Useful for debugging and for associating task-specific data with region boundaries.

§Example
fn log_context(cx: &Cx) {
    println!("Running in region: {:?}", cx.region_id());
}
Source

pub fn task_id(&self) -> TaskId

Returns the current task ID.

The task ID uniquely identifies this task within the runtime. Useful for debugging, tracing, and correlating log entries.

§Example
fn log_task(cx: &Cx) {
    println!("Task {:?} starting work", cx.task_id());
}
Source

pub fn task_type(&self) -> Option<String>

Returns the task type label, if one has been set.

Task types are optional metadata used by adaptive deadline monitoring and metrics to group similar work.

Source

pub fn set_task_type(&self, task_type: impl Into<String>)

Sets a task type label for adaptive monitoring and metrics.

This is intended to be called early in task execution to associate a stable label with the task’s behavior profile.

Source

pub fn budget(&self) -> Budget

Returns the current budget.

The budget defines resource limits for this task:

  • deadline: Absolute time limit
  • poll_quota: Maximum number of polls
  • cost_quota: Abstract cost units
  • priority: Scheduling priority

Frameworks can use the budget to implement request timeouts:

§Example
async fn check_timeout(cx: &Cx) -> Result<(), TimeoutError> {
    let budget = cx.budget();
    if budget.is_expired() {
        return Err(TimeoutError::DeadlineExceeded);
    }
    Ok(())
}
Source

pub fn is_cancel_requested(&self) -> bool

Returns true if cancellation has been requested.

This is a non-blocking check that queries whether a cancellation signal has been sent to this task. Unlike checkpoint(), this method does not return an error - it just reports the current state.

Frameworks should check this periodically during long-running operations to enable graceful shutdown.

§Example
async fn process_items(cx: &Cx, items: Vec<Item>) -> Result<(), Error> {
    for item in items {
        // Check for cancellation between items
        if cx.is_cancel_requested() {
            return Err(Error::Cancelled);
        }
        process(item).await?;
    }
    Ok(())
}
Source

pub fn checkpoint(&self) -> Result<(), Error>

Checks for cancellation and returns an error if cancelled.

This is a checkpoint where cancellation can be observed. It combines checking the cancellation flag with returning an error, making it convenient for use with the ? operator.

In addition to cancellation checking, this method records progress by updating the checkpoint state. This is useful for:

  • Detecting stuck/stalled tasks via checkpoint_state()
  • Work-stealing scheduler decisions
  • Observability and debugging

If the context is currently masked (via masked()), this method returns Ok(()) even when cancellation is pending, deferring the cancellation until the mask is released.

§Errors

Returns an Err with kind ErrorKind::Cancelled if cancellation is pending and the context is not masked.

§Example
async fn do_work(cx: &Cx) -> Result<(), Error> {
    // Use checkpoint with ? for concise cancellation handling
    cx.checkpoint()?;

    expensive_operation().await?;

    cx.checkpoint()?;

    another_operation().await?;

    Ok(())
}
Source

pub fn checkpoint_with(&self, msg: impl Into<String>) -> Result<(), Error>

Checks for cancellation with a progress message.

This is like checkpoint() but also records a human-readable message describing the current progress. The message is stored in the checkpoint state and can be retrieved via checkpoint_state().

§Errors

Returns an Err with kind ErrorKind::Cancelled if cancellation is pending and the context is not masked.

§Example
async fn process_batch(cx: &Cx, items: &[Item]) -> Result<(), Error> {
    for (i, item) in items.iter().enumerate() {
        cx.checkpoint_with(format!("Processing item {}/{}", i + 1, items.len()))?;
        process(item).await?;
    }
    Ok(())
}
Source

pub fn checkpoint_state(&self) -> CheckpointState

Returns a snapshot of the current checkpoint state.

The checkpoint state tracks progress reporting checkpoints:

  • last_checkpoint: When the last checkpoint was recorded
  • last_message: The message from the last checkpoint_with() call
  • checkpoint_count: Total number of checkpoints

This is useful for monitoring task progress and detecting stalled tasks.

§Example
fn check_task_health(cx: &Cx) -> bool {
    let state = cx.checkpoint_state();
    if let Some(last) = state.last_checkpoint {
        // Stalled if no checkpoint in 30 seconds
        last.elapsed() < Duration::from_secs(30)
    } else {
        // Never checkpointed, could be stuck
        false
    }
}
Source

pub fn masked<F, R>(&self, f: F) -> R
where F: FnOnce() -> R,

Executes a closure with cancellation masked.

While masked, checkpoint() will return Ok(()) even if cancellation has been requested. This is used for critical sections that must not be interrupted, such as:

  • Completing a two-phase commit
  • Flushing buffered data
  • Releasing resources in a specific order

Masking can be nested - each call to masked() increments a depth counter, and cancellation is only observable when depth returns to 0.

§Example
async fn commit_transaction(cx: &Cx, tx: Transaction) -> Result<(), Error> {
    // Critical section: must complete even if cancelled
    cx.masked(|| {
        tx.prepare()?;
        tx.commit()?;  // Cannot be interrupted here
        Ok(())
    })
}
§Note

Use masking sparingly. Long-masked sections defeat the purpose of responsive cancellation. Prefer short critical sections followed by a checkpoint.

Source

pub fn trace(&self, message: &str)

Traces an event for observability.

Trace events are associated with the current task and region, enabling structured observability. In the lab runtime, traces are captured deterministically for replay and debugging.

§Example
async fn process_request(cx: &Cx, request: &Request) -> Response {
    cx.trace("Request received");

    let result = handle(request).await;

    cx.trace("Request processed");

    result
}
§Note

This is currently a placeholder. The full implementation will write to the trace buffer maintained by the runtime.

Source

pub fn trace_with_fields(&self, message: &str, fields: &[(&str, &str)])

Logs a trace-level message with structured key-value fields.

Each field is attached to the resulting LogEntry, making it queryable in the log collector.

§Example
cx.trace_with_fields("request handled", &[
    ("method", "GET"),
    ("path", "/api/users"),
    ("status", "200"),
]);
Source

pub fn enter_span(&self, name: &str) -> SpanGuard<Caps>

Enters a named span, returning a guard that ends the span on drop.

The span forks the current DiagnosticContext, assigning a new SpanId with the previous span as parent. When the guard is dropped the original context is restored.

§Example
{
    let _guard = cx.enter_span("parse_request");
    // ... work inside the span ...
} // span ends here
Source

pub fn set_request_id(&self, id: impl Into<String>)

Sets a request correlation ID on the diagnostic context.

The ID propagates to all log entries and child spans created from this context, enabling end-to-end request tracing.

Source

pub fn request_id(&self) -> Option<String>

Returns the current request correlation ID, if set.

Source

pub fn log(&self, entry: LogEntry)

Logs a structured entry to the attached collector, if present.

Source

pub fn diagnostic_context(&self) -> DiagnosticContext

Returns a snapshot of the current diagnostic context.

Source

pub fn set_diagnostic_context(&self, ctx: DiagnosticContext)

Replaces the current diagnostic context.

Source

pub fn set_log_collector(&self, collector: LogCollector)

Attaches a log collector to this context.

Source

pub fn log_collector(&self) -> Option<LogCollector>

Returns the current log collector, if attached.

Source

pub fn set_trace_buffer(&self, trace: TraceBufferHandle)

Attaches a trace buffer to this context.

Source

pub fn trace_buffer(&self) -> Option<TraceBufferHandle>

Returns the current trace buffer handle, if attached.

Source

pub fn entropy(&self) -> &(dyn EntropySource + 'static)
where Caps: HasRandom,

Returns the entropy source for this context.

Source

pub fn random_u64(&self) -> u64
where Caps: HasRandom,

Generates a random u64 using the context entropy source.

Source

pub fn random_bytes(&self, dest: &mut [u8])
where Caps: HasRandom,

Fills a buffer with random bytes using the context entropy source.

Source

pub fn random_usize(&self, bound: usize) -> usize
where Caps: HasRandom,

Generates a random usize in [0, bound) with rejection sampling.

Source

pub fn random_bool(&self) -> bool
where Caps: HasRandom,

Generates a random boolean.

Source

pub fn random_f64(&self) -> f64
where Caps: HasRandom,

Generates a random f64 in [0, 1).

Source

pub fn shuffle<T>(&self, slice: &mut [T])
where Caps: HasRandom,

Shuffles a slice in place using Fisher-Yates.

Source

pub fn set_cancel_requested(&self, value: bool)

Sets the cancellation flag for testing purposes.

This method allows tests to simulate cancellation signals. It sets the cancel_requested flag, which will cause subsequent checkpoint() calls to return an error (unless masked).

§Example
use asupersync::Cx;

let cx = Cx::for_testing();
assert!(cx.checkpoint().is_ok());

cx.set_cancel_requested(true);
assert!(cx.checkpoint().is_err());
§Note

This API is intended for testing only. In production, cancellation signals are propagated by the runtime through the task tree.

Source

pub fn cancel_with(&self, kind: CancelKind, message: Option<&'static str>)

Cancels this context with a detailed reason.

This is the preferred method for initiating cancellation, as it provides complete attribution information. The reason includes:

  • The kind of cancellation (e.g., User, Timeout, Deadline)
  • An optional message explaining the cancellation
  • Origin region and task information (automatically set)
§Arguments
  • kind - The type of cancellation being initiated
  • message - An optional human-readable message explaining why
§Example
use asupersync::{Cx, types::CancelKind};

let cx = Cx::for_testing();
cx.cancel_with(CancelKind::User, Some("User pressed Ctrl+C"));
assert!(cx.is_cancel_requested());

if let Some(reason) = cx.cancel_reason() {
    assert_eq!(reason.kind, CancelKind::User);
}
§Note

This method only sets the local cancellation flag. In a real runtime, cancellation propagates through the region tree via cancel_request().

Source

pub fn cancel_fast(&self, kind: CancelKind)

Cancels without building a full attribution chain (performance-critical path).

Use this when attribution isn’t needed and minimizing allocations is important. The cancellation reason will have minimal attribution (kind + region only).

§Performance

This method avoids:

  • Message string allocation
  • Cause chain allocation
  • Timestamp lookup

Use cancel_with when you need full attribution for debugging.

§Example
use asupersync::{Cx, types::CancelKind};

let cx = Cx::for_testing();

// Fast cancellation - no allocation
cx.cancel_fast(CancelKind::RaceLost);
assert!(cx.is_cancel_requested());
Source

pub fn cancel_reason(&self) -> Option<CancelReason>

Gets the cancellation reason if this context is cancelled.

Returns None if the context is not cancelled, or Some(reason) if cancellation has been requested. The returned reason includes full attribution (kind, origin region, origin task, timestamp, cause chain).

§Example
use asupersync::{Cx, types::CancelKind};

let cx = Cx::for_testing();
assert!(cx.cancel_reason().is_none());

cx.cancel_with(CancelKind::Timeout, Some("request timeout"));
if let Some(reason) = cx.cancel_reason() {
    assert_eq!(reason.kind, CancelKind::Timeout);
    println!("Cancelled: {:?}", reason.kind);
}
Source

pub fn cancel_chain(&self) -> impl Iterator<Item = CancelReason>

Iterates through the full cancellation cause chain.

The first element is the immediate reason, followed by parent causes in order (immediate -> root). This is useful for understanding the full propagation path of a cancellation.

Returns an empty iterator if the context is not cancelled.

§Example
use asupersync::{Cx, types::{CancelKind, CancelReason}};

let cx = Cx::for_testing();

// Create a chained reason: ParentCancelled -> Deadline
let root_cause = CancelReason::deadline();
let chained = CancelReason::parent_cancelled().with_cause(root_cause);

// Set it via internal method for testing
cx.set_cancel_reason(chained);

let chain: Vec<_> = cx.cancel_chain().collect();
assert_eq!(chain.len(), 2);
assert_eq!(chain[0].kind, CancelKind::ParentCancelled);
assert_eq!(chain[1].kind, CancelKind::Deadline);
Source

pub fn root_cancel_cause(&self) -> Option<CancelReason>

Gets the root cause of cancellation.

This is the original trigger that initiated the cancellation, regardless of how many parent regions the cancellation propagated through. For example, if a grandchild task was cancelled due to a parent timeout, root_cancel_cause() returns the original Timeout reason, not the intermediate ParentCancelled reasons.

Returns None if the context is not cancelled.

§Example
use asupersync::{Cx, types::{CancelKind, CancelReason}};

let cx = Cx::for_testing();

// Simulate a deep cancellation chain
let deadline = CancelReason::deadline();
let parent1 = CancelReason::parent_cancelled().with_cause(deadline);
let parent2 = CancelReason::parent_cancelled().with_cause(parent1);

cx.set_cancel_reason(parent2);

// Root cause is the original Deadline, not ParentCancelled
if let Some(root) = cx.root_cancel_cause() {
    assert_eq!(root.kind, CancelKind::Deadline);
}
Source

pub fn cancelled_by(&self, kind: CancelKind) -> bool

Checks if cancellation was due to a specific kind.

This checks the immediate reason only, not the cause chain. For example, if a task was cancelled with ParentCancelled due to an upstream timeout, cancelled_by(CancelKind::ParentCancelled) returns true but cancelled_by(CancelKind::Timeout) returns false.

Use any_cause_is() to check the full cause chain.

§Example
use asupersync::{Cx, types::CancelKind};

let cx = Cx::for_testing();
cx.cancel_with(CancelKind::User, Some("manual cancel"));

assert!(cx.cancelled_by(CancelKind::User));
assert!(!cx.cancelled_by(CancelKind::Timeout));
Source

pub fn any_cause_is(&self, kind: CancelKind) -> bool

Checks if any cause in the chain is a specific kind.

This searches the entire cause chain, from the immediate reason to the root cause. This is useful for checking if a specific condition (like a timeout) anywhere in the hierarchy caused this cancellation.

§Example
use asupersync::{Cx, types::{CancelKind, CancelReason}};

let cx = Cx::for_testing();

// Grandchild cancelled due to parent timeout
let timeout = CancelReason::timeout();
let parent_cancelled = CancelReason::parent_cancelled().with_cause(timeout);

cx.set_cancel_reason(parent_cancelled);

// Immediate reason is ParentCancelled, but timeout is in the chain
assert!(cx.cancelled_by(CancelKind::ParentCancelled));
assert!(!cx.cancelled_by(CancelKind::Timeout));  // immediate only
assert!(cx.any_cause_is(CancelKind::Timeout));   // searches chain
assert!(cx.any_cause_is(CancelKind::ParentCancelled));  // also in chain
Source

pub fn set_cancel_reason(&self, reason: CancelReason)

Sets the cancellation reason (for testing purposes).

This method allows tests to set a specific cancellation reason, including complex cause chains. It sets both the cancel_requested flag and the cancel_reason.

§Example
use asupersync::{Cx, types::{CancelKind, CancelReason}};

let cx = Cx::for_testing();

// Create a chained reason for testing
let root = CancelReason::deadline();
let chained = CancelReason::parent_cancelled().with_cause(root);

cx.set_cancel_reason(chained);

assert!(cx.is_cancel_requested());
assert_eq!(cx.cancel_reason().unwrap().kind, CancelKind::ParentCancelled);
Source

pub async fn race<T>( &self, futures: Vec<Pin<Box<dyn Future<Output = T> + Send>>>, ) -> Result<T, JoinError>

Races multiple futures, waiting for the first to complete.

This method is used by the race! macro. It runs the provided futures concurrently (inline, not spawned) and returns the result of the first one to complete. Losers are dropped (cancelled).

§Cancellation vs Draining

This method drops the losing futures, which cancels them. However, unlike Scope::race, it does not await the losers to ensure they have fully cleaned up (“drained”).

If you are racing TaskHandles and require the “Losers are drained” invariant (parent waits for losers to terminate), use Scope::race or Scope::race_all instead.

Source

pub async fn race_named<T>( &self, futures: Vec<(&'static str, Pin<Box<dyn Future<Output = T> + Send>>)>, ) -> Result<T, JoinError>

Races multiple named futures.

Similar to race, but accepts names for tracing purposes.

§Cancellation vs Draining

This method drops the losing futures, which cancels them. However, unlike Scope::race, it does not await the losers to ensure they have fully cleaned up (“drained”).

Source

pub async fn race_timeout<T>( &self, duration: Duration, futures: Vec<Pin<Box<dyn Future<Output = T> + Send>>>, ) -> Result<T, JoinError>
where Caps: HasTime,

Races multiple futures with a timeout.

If the timeout expires before any future completes, returns a cancellation error.

§Cancellation vs Draining

This method drops the losing futures (or all futures on timeout), which cancels them. However, it does not await the losers to ensure they have fully cleaned up (“drained”).

Source

pub async fn race_timeout_named<T>( &self, duration: Duration, futures: Vec<(&'static str, Pin<Box<dyn Future<Output = T> + Send>>)>, ) -> Result<T, JoinError>
where Caps: HasTime,

Races multiple named futures with a timeout.

§Cancellation vs Draining

This method drops the losing futures (or all futures on timeout), which cancels them. However, it does not await the losers to ensure they have fully cleaned up (“drained”).

Source

pub fn scope(&self) -> Scope<'static>

Creates a Scope bound to this context’s region.

The returned Scope can be used to spawn tasks, create child regions, and register finalizers. All spawned tasks will be owned by this context’s region.

§Example
// Using the scope! macro (recommended):
scope!(cx, {
    let handle = scope.spawn(|cx| async { 42 });
    handle.await
});

// Manual scope creation:
let scope = cx.scope();
// Use scope for spawning...
§Note

In Phase 0, this creates a scope bound to the current region. In later phases, the scope! macro will create child regions with proper quiescence guarantees.

Source

pub fn scope_with_budget(&self, budget: Budget) -> Scope<'static>

Creates a Scope bound to this context’s region with a custom budget.

This is used by the scope! macro when a budget is specified:

scope!(cx, budget: Budget::deadline(Duration::from_secs(5)), {
    // body
})

Trait Implementations§

Source§

impl Clone for AgentCx

Source§

fn clone(&self) -> AgentCx

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AgentCx

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for AgentCx

Source§

type Target = Cx

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ParallelSend for T

Source§

impl<T> Send for T
where T: ?Sized,

Source§

impl<T> Sync for T
where T: ?Sized,