Tripwire
Tripwire is an opt-in experimental performance format. Use IC Wire for ordinary application and peer protocols. A Tripwire endpoint loads a small compiled fixed area and accesses named fields; large payloads stay in the IC's argument storage until requested. It uses fixed-width values and cumulative payload boundaries, without Serde, Rust pointers or a full-message decode. Producers and consumers must use the same compiled contract.
use cdk_rsx::tripwire::message;
#[message]
pub struct Submit {
user_id: u64,
nonce: u64,
body: Bytes<1048576>,
}
#[cdk_rsx::update(tripwire, max_arg_bytes = 2 * 1024 * 1024)]
fn check_fields(request: Submit<'_>) -> [u8; 8] {
if request.user_id() == 0 {
return 0u64.to_le_bytes();
}
request.nonce().to_le_bytes()
}
This example checks the scalar fields and replies without fetching body,
regardless of its supplied size. Integer and inline-byte-array getters read the
already loaded fixed area. Boolean getters check their value representation.
Selective reads
Selecting a variable field checks its declared byte bound and source range, without reading its contents. Fetch a complete field, a range, or one chunk into caller-owned storage:
let body = request.body()?;
let mut workspace = [0u8; 4096];
let first = body.read_chunk_into(0, &mut workspace)?;
// Process first before reusing workspace for another range or field.
Bytes<MAX> and Text<MAX> bounds are byte counts. Text is checked for UTF-8
when fetched; splitting a code point in a text range returns an error. Unselected
payload contents are neither copied nor validated. Invalid selected ranges and
short destination buffers fail before an IC copy. Previously fetched bytes may
be kept in ordinary owned buffers.
For a message already in caller-owned bytes, use the generated
Submit::with_slice(&bytes, limit, ...) entry or an existing SliceSource.
Byte fields expose field.as_slice() to borrow the validated original range
without a payload copy. Sources opt into this through Source::borrow_range;
current IC arguments and default custom sources return None without fetching
data. The borrowed range keeps the request's scoped lifetime. Typed child
getters preserve that access through the original source window.
Payload reads are explicit: reading the same field twice copies it twice. Fetch
once into caller storage and reuse that slice when the same bytes are needed
again. Declare known child fields as Nested<Child> and select them with their
typed getter, such as request.address()?. This copies only the child's fixed
area and keeps its payload on the original source; see
typed children and lists.
body.slice(start..end)? creates a checked child view without fetching bytes or
allocating. Its offsets are relative to the selected field, and it keeps the
same source lifetime. A packed batch can select one item's span and call
read_in(allocator) on that child to copy only that item into its final buffer.
Exact source windows
BytesView::window() returns an exact SourceWindow by value, retaining the
original source reference and absolute frame range. window.slice(start..end)
checks a child range without copying. This supports typed child factories that
return a view after the temporary byte-field handle has been dropped; the child
still borrows the original call source, and owns only its fixed header.
An explicit tag may select a known child contract inside an opaque byte field. Within that tag's branch, open the selected frame through its original-source window:
let child = {
let field = request.child_frame()?;
<Child<'static> as cdk_rsx::tripwire::Message>::open_window(
field.window(), CHILD_BYTE_LIMIT,
)?
};
// child keeps the original source lifetime after the local field handle drops.
The tag and compiled route determine the child contract; the window supplies
its exact frame and the byte cap is checked before its fixed-area copy.
BytesView also implements Source for low-level scoped readers that consume
the child entirely within a borrowed adapter's callback.
Message associates each compiled contract with its source-backed View,
borrowed client Args, finite MAX_ENCODED_LEN, and optional exact canonical
FIXED_ENCODED_LEN. Its static encoders write into caller storage. Bounds stay
inside the existing u32 frame-length domain; a sum of declared maxima beyond
that domain does not reject an existing declaration. Native-only schema metadata
is independent of the source window and is never transmitted. Scoped views and
windows still cannot escape the higher-ranked entry callback or enter a returned
future. Ordinary owned payload reads remain the way to retain data for later
work.
Typed children and lists
Declare typed children with Nested<Child> and bounded child collections with
List<Child, MAX_COUNT>:
#[message]
pub struct Address { postal_code: u32, city: Text<64> }
#[message]
pub struct Item { sku: u64, quantity: u32 }
#[message]
pub struct Order {
request_id: u64,
address: Nested<Address>,
items: List<Item, 128>,
}
let items = [ItemArgs { sku: 7, quantity: 2 }];
let bytes = OrderArgs {
request_id: 19,
address: AddressArgs { postal_code: 1234, city: "Oslo" },
items: &items,
}.encode()?;
Order::with_slice(&bytes, 4096, |order| {
let address = order.address()?;
let mut city = [0; 64];
let city = address.city()?.read_into(&mut city)?;
let items = order.items()?;
if let Some(item) = items.get(0)? {
assert_eq!(item.quantity(), 2);
}
for item in items.iter() {
let item = item?;
// Consume item.sku() and item.quantity() without materializing a DTO.
}
Ok::<_, cdk_rsx::tripwire::Error>(city.len())
})??;
Child paths may be module-qualified, for example Nested<contacts::Address>.
They must name a generated #[message] record without lifetime or type
arguments. A plain address: Address, primitive type aliases, arbitrary Rust
containers, Option and enums are not inferred or automatically encoded. Every
declared fixed field is transmitted, including fields an application case does
not use; empty bytes occupy no payload bytes.
Use distinct message carriers for distinct application cases while sharing
typed child records where useful. Cyclic unbounded contracts fail compilation.
Nested<Child, MAX_BYTES> optionally narrows the parent field's byte cap to the
smaller of the literal and the child's compiled maximum. Omit the literal to use
the child's maximum. This preserves a narrow parent admission budget even when
the reusable child contract permits larger values. The cap is checked before
child fixed-area copies and encoder writes. A fixed child wider than its cap
fails compilation; a zero cap can hold a zero-width child.
Nested and list fields occupy ordinary variable payload spans in their parent. Selecting a nested field first checks its finite byte cap, then opens the exact child source window and copies only the child's fixed area. The returned child owns that fixed area and borrows the original source; it can outlive a temporary parent or byte-field handle inside the call. It cannot escape the entry callback or enter a returned future. No intermediate child byte buffer, allocation, pointer cast or lifetime extension is needed. Nested client Args are typed child Args; their encoder writes directly into the final parent destination.
A list starts with a little-endian u32 element count. Children with a proven
exact canonical width follow contiguously without a directory; selection uses
that stride. Variable-width children use count - 1 cumulative u32 ends
followed by packed exact child frames. Ends are relative to the packed child
payload, and the exact list span supplies the final end. Count zero is exactly
four bytes, with no directory or payload. Zero-width children also need only the
count, even when that count is nonzero.
Selecting a list checks the count before directory arithmetic, requires exact
container geometry, and validates monotone ends, source ranges and each child
byte cap using bounded stack scratch. It does not open every child header or
fetch child payloads. len, is_empty, get(index) and iter() expose
source-backed access: get returns Result<Option<Child>, Error>, and iteration
returns Result<Child, Error> per item. A selected child then validates its own
fixed-area structure. Boolean values, per-field bounds and fetched text remain
lazy. No decoded collection or index cache is built; repeated variable-item
selection may reread its directory words. Encode list Args from a borrowed slice
of child Args; every child writes directly into its final destination span.
Message is the compiled contract interface used by generated records and
lists. A marker such as Item<'static> identifies the schema at compile time;
its View<'msg> still borrows the actual source for 'msg. The marker stores no
source. FIXED_ENCODED_LEN describes canonical encodings, not a new rule
rejecting trailing bytes in scalar-only record opens.
Owned reads and persistent destinations
BytesView::read_in(allocator) copies a complete selected byte field into a
buffer owned by the chosen allocator. With the pinned compiler, enable
#![feature(allocator_ext)] in the consuming crate. Ordinary computation can
use body.read_in(std::alloc::Global)?; the returned Vec does not borrow the
request and can outlive its scope.
For a Nyxus owner, select its allocator before the copy and adopt that exact buffer through the native collection wrapper:
use cdk_rsx_collections::nyxus;
let body = request.body()?;
let bytes = body.read_in(nyxus::Nyxus)?;
let retained = nyxus::Vec::from_std(bytes);
The IC copy writes directly into the final retained allocation. from_std
moves its ownership without copying the payload; inserting that carrier into
the owner's Data also moves its ownership. Perform authentication, capacity and
other expected business checks first, then publish through the owner's service
inside its existing root::with frame. Ordinary Global buffers cannot become
retained by moving their headers into Data or relabeling their allocator.
IC and slice sources initialize the final allocation directly, without a
preceding zeroing pass. Before publishing the Vec length, read_in checks that
the returned initialized slice covers exactly the requested allocation span.
Custom Source implementations can use the zero-initializing default instead.
Allocation refusal returns Error::Allocation; a failed source copy drops the
unpublished output. Native Rust object construction
is still application work: bytes are not automatically reconstructed as a Rust
record, pointer graph or arbitrary container. For byte fields explicitly holding
UTF-8, nyxus::String::from_utf8(retained) validates and adopts the same buffer.
For immutable shared bytes, fill the combined owner-and-payload allocation directly after admission checks:
use cdk_rsx::tripwire::Source;
let retained = nyxus::SharedSlice::<u8>::from_reader(body.len(), |destination| {
body.copy_range_uninit(0, destination).expect("request body copy")
});
The constructor checks the returned initialized span before publishing an owner;
copy failure traps and releases the unpublished allocation during native unwind.
nyxus::SharedString::from_utf8(retained) validates UTF-8 and adopts those same
immutable bytes without another allocation or payload copy.
When several queued fields belong to one retained packet, use
nyxus::SharedBytes and SharedText to keep checked nested ranges on that owner.
For sequential admission, SharedBytesBuilder copies each accepted field
directly into one bounded chunk's unused tail and returns its immutable span
immediately. Nested generated messages can open transiently with
Inner::with_slice(span.as_slice(), limit, ...); their scoped views still cannot
escape. No message-relative offset becomes a native pointer. See the
collection ownership rules for exact initialization,
capacity and Drop behavior. A retained span pins its whole packet, so explicitly
copy a small subset that must outlive packet processing.
IC argument storage is a read-only source outside the canister's Rust memory. A field's message-relative offset is not a native pointer or a borrowed Rust slice. Reads always copy selected bytes into the chosen destination.
Stable blobs
Stable memory cannot be the destination of an IC argument-copy call. Stream
through one reusable linear-memory buffer. Within the owner's Hylix write frame,
hylix::Blob::from_reader allocates one stable blob, fills each requested span
and writes it before reusing scratch. Here hylix is
cdk_rsx_collections::hylix, and HylixError is
cdk_rsx_engine_hylix::Error:
let mut scratch = [0; 4096];
let blob = hylix::Blob::from_reader(body.len(), &mut scratch, |at, dst| {
body.read_range_into(at..at + dst.len(), dst).map(|_| ())
.map_err(|_| HylixError::InvalidInput("Tripwire body read"))
});
Validate expected business rejection before calling this constructor. After allocation, fill, storage and publication failures must trap so the IC rolls back the update; returning an ordinary error does not undo persistent writes. The constructor returns a completed Blob only after every span succeeds. Move it into the owner's record using its normal Hylix ownership rules, including retiring a displaced owner. The stable engine may use further bounded heap cache space in addition to this 4 KiB scratch. No complete transient payload is assembled by this path.
Layout and generated code
Only declared values and necessary payload boundaries appear on the wire.
Fixed scalars and inline byte arrays occupy their declared widths in declaration
order, without padding. Integers are little-endian. Each variable field except
the final variable field occupies one little-endian u32 cumulative payload-end
boundary at its declaration position. Variable payloads append in declaration
order after the complete fixed area, including any scalars declared after a
variable field. Boundaries are relative to that payload start. The final end is
source.len() - Name::FIXED_LEN, so a single variable field needs no boundary.
For F bytes of scalars/inline arrays and V variable fields, FIXED_LEN is
F + 4 * max(V - 1, 0).
For example, Submit above has FIXED_LEN = 16: two eight-byte scalars, followed
directly by body. A declaration id: u64, title: Text<128>, body: Bytes<1024>
has FIXED_LEN = 12: the scalar followed by the four-byte title end. Its body
starts at the title end and ends at the exact source length. A bytes-only record
has FIXED_LEN = 0 and opens without any source read. An empty record encodes as
zero bytes and also opens without a read. Scalar-only records read their fixed
area; any trailing source bytes remain unselected.
There is no magic, encoded fixed-area length, transmitted schema identity, pointer fixup or runtime field lookup. No wire schema check can detect a mismatched declaration. The compiled producer and consumer must agree on field order, kinds, widths, bounds and nesting; coordinate their deployment and keep the contract fixed while saved bytes or unresolved work remain live. Root persistence admission checks the retained representation independently and does not prove a message producer used the matching protocol. There is one compact format and no fallback decoder.
The source supplied to a variable-bearing record must describe its exact frame, without an unrelated trailer. Outer containers must select the exact child span before opening a nested record. Generated entry points validate every stored cumulative end in the already-loaded fixed area before invoking the handler: ends must be nondecreasing, and the last stored end must not exceed the exact payload length. This proves that the variable fields of a variable-bearing record partition its payload without cross-field overlap, including intervals the handler never selects. It adds no payload copy, heap allocation or runtime layout table. Zero/one-variable records have no stored boundaries to check. Full-message byte admission and fixed-area truncation checks still precede the fixed copy; a nonempty fixed area needs one source copy.
Getters remain constant-time and return their existing Result types. Declared
field byte limits, boolean representation and fetched text's UTF-8 remain lazy;
structural admission does not assert that every field is semantically valid.
Authentication, business limits and the shared producer/consumer codec contract
remain the caller's responsibility. The low-level Request API knows only its
fixed length, not the complete directory, so its callers must supply/validate
their own layout contract. Its selected-range checks remain in place; ordinary
endpoints should use generated entry points for whole-directory admission.
The macro rejects unsupported fields and fixed areas larger than 2 KiB during
compilation. Supported declarations are fixed-width signed/unsigned integers,
bool, inline [u8; N], Bytes<MAX>, Text<MAX>, Nested<Child> and
List<Child, MAX_COUNT> with literal bounds. All
declared integer bit patterns remain available; compacting the frame does not
narrow scalar domains or introduce varints. Generated field types and internal
primitive types use ::core::primitive paths, so a caller's same-named aliases
cannot change the selected wire kind, width or boolean validation.
SubmitArgs is the generated client builder. It borrows variable data and offers
encoded_len, encode_into for reusable storage, and fallible encode for owned
output. Submit::SCHEMA, DESCRIPTOR and FIELDS are native-only build/client
metadata, absent from Wasm and never transmitted. The descriptor uses
format: "tripwire-compact-1", fixed_len, and named fields with kind and
bound. Scalars carry offset; variable fields carry boundary_offset, which
is null for the final variable field. FIELDS contains
(name, kind, scalar_offset, boundary_offset, bound) with optional u32
locations. Standalone users import message from cdk_rsx_tripwire; SDK
applications use cdk_rsx::tripwire::message.
Submit::SCALAR_OFFSETS is available on every target for compiled adapters. Its
declaration-ordered entries are Some(offset) for scalars and None for payload
fields. Bind positions in constant evaluation to avoid runtime metadata access.
Typed fields add a flat native-only child schema reference; child descriptors
are not recursively embedded. List schema identities include their child
contract and count cap. Existing scalar/bytes/text descriptors and identities
retain their exact bytes. These references remain build/client metadata and add
no transmitted field or runtime schema lookup.
List field descriptors also expose item_schema, max_count and
item_fixed_len: the last is the compiler-proven canonical child width or
null for variable children. With count cap zero, item_schema and
item_fixed_len are null because no child can occur. Native
Name::visit_schemas(&mut visitor) visits (schema, descriptor) pairs for the
record and reachable typed child records. A client may collect these into its
own deduplicated schema map for a generic codec. The visitor stores no registry,
performs no runtime hashing, and does not recursively embed descriptor strings.
Return true to visit descendants, or false to prune a record already present
in the client's map; this avoids repeated traversal of shared children. Compiled message
schemas must be acyclic; custom Message contracts provide native descriptors
only if their clients require them. A generic client must report missing
descriptors rather than guessing an unknown encoding.
Execution boundary
Tripwire endpoints use the ordinary SDK guards and executor context. They must
be synchronous: scoped source and field handles cannot escape into a later
execution. Higher-ranked callbacks and Rust lifetimes enforce this, without an
epoch table or per-access ownership registry. Copy selected data into owned
storage before queuing work that needs it later. A source handle, field handle,
Store scope, data guard or streaming scratch loan must never cross await.
Replies implement AsRef<[u8]>, allowing fixed arrays without a reply allocation.
Generated Args offer args.encode_stack::<CAPACITY>(), returning an owned
StackEncoded<CAPACITY> that a Tripwire handler can return directly. It writes
through the existing checked encoder into a fully initialized inline buffer,
with no heap output allocation. Only its completed prefix is sent; unused
capacity is private. Choose capacity for the fixed area and desired payload
budget. Capacity below the compiled fixed area fails compilation, and a dynamic
payload exceeding capacity returns Error::BufferTooSmall. Field and child
bounds retain their ordinary checks. The scoped examples
show owned output leaving its borrowed Args.
Their bytes are explicit application protocol output, without an automatic
Wire wrapper. The canonical builder records these endpoints as raw methods,
separately from typed Wire methods. Use the matching Tripwire schema/builder on
the client; automatic Wire client generation does not encode Tripwire messages.
Root initialization remains the existing bounded Wire constructor.
The crate contains copy-bound tests and compile-fail lifetime examples. See the entry path for SDK work and measurement guide for complete-call instruction/page costs.