Skip to content

QUIC

简体中文 · Reference

Overview

pace::quic provides QUIC connections with independent, multiplexed streams, secured by TLS 1.3 with mandatory peer verification on the client.

Header Package config
<pace/quic.hpp> quic = true (also enabled by http3 = true)

Choose the backend with the quic_backend config. All three implement the stream API in pace/quic/connection.hpp, define PACE_HAS_QUIC and support HTTP/3.

quic_backend Packet processing, loss recovery, congestion and flow control TLS and cryptography Extra define
ngtcp2 (default) ngtcp2 1.26.0 OpenSSL 3.5.7 PACE_QUIC_NGTCP2
openssl OpenSSL 3.5.7 native QUIC OpenSSL 3.5.7 none
native PACE QUIC v1 and v2 PACE TLS 1.3 with the selected crypto provider PACE_QUIC_NATIVE

The table describes role-only quic::context instances. With native_tls = true, supplying a tls::config to a listener or connection selects PACE TLS 1.3 and ngtcp2 packet processing in the ngtcp2 and OpenSSL builds. This path supports ECH, PACE session tickets and 0-RTT. Both peers must enable early data. Use connection::connect_early for a replay-safe first request and stream::received_early_data() to inspect its delivery on the server. Native TLS configuration

The native backend uses PACE UDP sockets. The ngtcp2 and OpenSSL drivers require POSIX. All backends accept numeric IPv4 and IPv6 endpoints. The C++ named module is pace.quic. DNS resolution

Native transport

Enable quic = true with quic_backend = "native". This builds PACE TLS 1.3 automatically. Supply a tls::config for ECH, tickets or early data. Share a client quic::context across connections to reuse address validation tokens. context::set_versions({0x6b3343cf, 1}) prefers v2 and allows v1. Use set_versions({0x6b3343cf, 1}, 1) to send a v1 Initial and advertise a preference for upgrading to v2. context::require_retry(true) requires address validation before the server allocates connection state. After the handshake, negotiated_version() reports the wire version. update_keys() requires handshake confirmation and acknowledgment of the current sending keys. Wait for transport events until can_update_keys() returns true before starting an update. rotate_connection_id() uses a spare CID supplied by the peer. Both operations throw std::logic_error if their prerequisites are missing.

basic_endpoint<Policies> owns the listening socket. Each accepted basic_connection<Policies> has its own congestion controller. The listener and connection aliases use default_policies and link the default instantiations from pace_quic. Include pace/quic/engine_impl.hpp to instantiate a custom policy.

#include <pace/quic/engine_impl.hpp>

struct policies : pace::quic::default_policies
{
    using congestion_control = pace::quic::cc::select<pace::quic::cc::cubic, pace::quic::cc::bbr_v1>;
};

void authenticated(pace::quic::basic_connection<policies>& connection)
{
    connection.congestion().use<pace::quic::cc::bbr_v1>();
}

The defaults are CUBIC, an identity packet transform, a PACE UDP socket, random fixed-length CIDs, endpoint validation, minimum-RTT multipath scheduling, and disabled tracing. A custom congestion controller satisfies cc::controller. Its callbacks receive a cc::sample with byte counts, transmission and feedback times, RTTs, delivery rate in bytes per second, ECN counters and the application-limited flag. congestion_window() returns bytes and pacing_rate() returns bytes per second. NewReno is available as cc::new_reno. For deterministic transport tests, testing::simulator::send takes a logical time, an owned packet and an optional transit delay. Pass std::nullopt to drop a packet and call receive(now) to collect due packets in delivery order.

Configure a packet transform per endpoint by passing its value after the client context, or after the server context and CID issuer. For an injected socket pass the transform after the port adapter. Each newly bound socket copies the configured value. Store shared state in the policy when several ports should share a counter or other mutable data. The encode and decode hooks may resize the UDP payload or return false to discard it.

Native connections negotiate RFC 9221 DATAGRAM in each direction. Before connecting or listening, context::set_max_datagram_frame_size(n) sets the receive limit including framing (default 1200, zero disables reception). After connecting, max_datagram_size() returns the send payload budget. send_datagram(bytes) queues one message and co_await receive_datagram() returns one owned message. The sender applies congestion control and pacing. Loss is final. Each queue holds up to 128 messages. A full send queue reports no_buffer_space. A full receive queue drops new arrivals. Oversized sends throw std::length_error. A peer that disables reception causes sends to report operation_not_supported.

connection::statistics() returns RTTs, congestion window and bytes in flight, pacing rate in bytes per second, sent and authenticated received protected packet and byte counts, and packets declared lost.

Connection migration and NAT rebinding

A native client can change its UDP binding while streams on the connection stay open. Supply a numeric local address and use port zero to let the OS choose an available port.

co_await connection.rebind({"127.0.0.1", 0});
auto bound = connection.local_endpoint();

Use co_await connection.migrate(bound, alternate_peer) to probe another numeric address or port that routes to the same QUIC server. Both calls wait for handshake confirmation and, when the peer uses connection IDs, an unused peer CID. The optional timeout defaults to five seconds and includes this wait. The client continues using the old path while validating the new one. A timeout reports std::errc::timed_out and the old path remains available. After success, local_endpoint() and peer_endpoint() report the selected endpoints.

Native servers automatically validate changes to a client's observed UDP address, including NAT port changes. A server can advertise disable_active_migration() before listening. Native clients then report operation_not_supported for explicit migration, while a NAT port change using the existing CID can still be validated. An IP address change resets RTT and congestion estimates. A port-only change preserves them.

With qlog enabled, quic:tuple_assigned identifies the local and remote endpoints. quic:migration_state_updated records probing, validation, completion or abandonment on that tuple. Match the eight-byte data values of PATH_CHALLENGE and PATH_RESPONSE frames to follow a probe.

Multipath negotiation and validation

Call set_initial_max_path_id(2) on both native contexts before connecting or listening to allow paths 0, 1 and 2. The default is std::nullopt. One-sided offers use ordinary single-path QUIC. Zero negotiates the extension with only path 0. Either endpoint can subsequently call connection.increase_max_path_id(n) to raise its advertised limit. PACE accepts local limits from 0 to 8. Each connection negotiates fresh limits, including when resuming a session.

if (connection.multipath_negotiated())
{
    auto id = co_await connection.add_path({"127.0.0.1", 0}, connection.peer_endpoint());
    auto paths = connection.validated_paths(); // Includes path 0 and the new ID.
}

Only clients initiate paths. The call waits for handshake confirmation, a CID for the same path ID from each endpoint, acknowledgment of the client CID, and a matching response to a padded challenge. The timeout defaults to five seconds. Servers independently validate the return route and enforce its amplification limit. Paths may share a UDP four-tuple. Each has its own CIDs, 1-RTT packet numbers and nonce domain. A failed probe consumes its path ID. Exhausting the allowed IDs reports no_space_on_device.

Pass an OS interface index as the third argument of add_path(local, peer, index) to bind a new UDP socket to that interface. An unavailable interface reports a socket error. A path policy can implement initially_backup(id, local, peer) for newly validated additional paths and abandon_after_pto(id, consecutive) to retire a silent route when an alternative is available. The default announces new paths as available and waits for three consecutive probe timeouts. Path statistics expose both the locally advertised and peer-advertised backup status.

Data scheduling and failover

The default sched::min_rtt sends STREAM, DATAGRAM and queued 1-RTT control frames on the writable available path with the lowest smoothed RTT. Each validated path tracks its own packet numbers, RTT, congestion window, pacing and loss timer. A matching challenge response supplies its first RTT sample. After validation, PACE returns PATH_ACK on the incoming path. Cross-path ACKs acknowledge delivery without contributing a same-path RTT sample.

Each endpoint chooses its own scheduler. To use primary/backup for both directions, instantiate the client and listener with the same policy.

struct standby : pace::quic::default_policies
{
    using scheduler = pace::quic::sched::primary_backup;
};
using client_type = pace::quic::basic_connection<standby>;
using listener_type = pace::quic::basic_endpoint<standby>;

primary_backup uses the lowest available path ID, initially 0, and waits through pacing or window limits on that path. Either policy gives available paths priority over paths the peer marks as backup. Call connection.set_path_backup(id, true) to request backup treatment at the peer and pass false to advertise availability again. A custom scheduler takes a nonempty std::span<const sched::path_candidate> and returns a candidate ID.

With a validated alternative, three consecutive probe timeouts without acknowledgment, a local socket failure, or a peer PATH_ABANDON can move traffic off the failed path. Outstanding reliable frames can be retransmitted on the survivor. A DATAGRAM already sent is never retransmitted. Path IDs in validated_paths() reflect the change. Packet and byte counters cover the connection, while RTT and congestion statistics and path_mtu refer to the selected sending path. Each validated path runs its own MTU discovery and ECN validation. The sender splits STREAM frames to fit the selected path, including after failover. For a DATAGRAM, the scheduler chooses among paths that can carry the whole frame. If every eligible path shrinks below the queued frame size, the sender drops the datagram.

On an established connection, connection.statistics(path_id) returns a std::optional<pace::quic::path_statistics> snapshot on the owning IO context. Use IDs from validated_paths(), including ID 0 on a single-path connection. Unknown, validating and abandoned IDs return std::nullopt. A snapshot contains the smoothed, minimum and latest RTT in microseconds, congestion window and bytes in flight, pacing rate in bytes per second, path MTU in UDP payload bytes, and ECN state. A zero min_rtt indicates that the path has no RTT sample yet. The ecn field takes one of the pace::quic::ecn_state values idle, testing, unknown, capable or failed.

Each snapshot reports cumulative packets_sent, packets_received, bytes_sent, bytes_received and packets_lost for that path ID. The sender counts protected packets before the outbound transform. The receiver counts authenticated packets that pass header checks, including duplicate arrivals. Byte totals include the QUIC header and authentication tag. Handshake traffic belongs to path 0. ACK-only packets, probes and retransmissions count on the path carrying them. A loss reported through cross-path feedback belongs to the original sending path. Connection totals include retired paths.

After multipath negotiation, quic:recovery_metrics_updated identifies each sample by data.path_id and tuple. It records RTT in milliseconds, congestion window and bytes in flight, pacing rate in bits per second, PTO count and the five cumulative traffic counters. When only traffic changes, the transport coalesces counter updates and flushes outstanding changes before closing the trace. Each quic:congestion_state_updated transition belongs to the same path as its controller. Custom controllers can supply state names through state_name.

With qlog enabled, pace:path_selected records the scheduled 1-RTT packet number, path ID, scheduler, smoothed RTT in microseconds and tuple. pace:path_switched records the old and new IDs and the trigger. pace:path_state_updated records negotiation on path 0 and validation start, success and abandonment on additional paths. Correlate header.path_id with the event's tuple and the path ID in path_ack frames. The trace declares the PACE multipath schema alongside the IETF QUIC event schema. PACE multipath CDDL · RFC 10069

Path MTU discovery

After handshake confirmation, the native transport probes each validated path with an encrypted PING padded to an exact UDP payload size. Only an ACK covering that packet number in the probed path’s number space confirms the size. connection.statistics().path_mtu reports the current UDP payload limit in bytes, excluding IP and UDP headers. connection.max_datagram_size() uses the largest eligible path MTU and accounts for QUIC framing and the peer's DATAGRAM limit. Set context::set_max_datagram_frame_size(4096) on the receiver before connecting or listening to allow the sender to use payloads larger than the default frame limit of 1200.

Each new path starts at 1200 bytes. PACE caps its search at 1472 bytes on IPv4 and 1452 on IPv6, subject to the peer's UDP payload limit. Three missed probes narrow the search. A result below the ceiling is revisited after ten minutes. Repeated loss of large data packets returns the sender to 1200 bytes and restarts discovery. Reliable stream data is split to fit, and queued unreliable DATAGRAM frames that exceed the new limit are dropped. Probe loss alone leaves the congestion window intact. With a custom packet transform or a socket without DF support, the limit stays at 1200.

In qlog, quic:mtu_updated carries the tuple, the new estimate, the previous estimate when available, and done when the search settles. Multipath traces include data.path_id even when paths share a tuple. Sent and lost probe packets carry is_mtu_probe_packet. RFC 8899 and QUIC path MTU discovery.

Explicit Congestion Notification (ECN)

The native backend tests each active IPv4 or IPv6 path by marking ordinary ack-eliciting 1-RTT packets with ECT(0). The trial marks up to ten packets and runs for at most three probe timeouts (PTOs). ACK-only traffic, path-validation packets, MTU probes and PTO probes stay unmarked. On receive, each successfully processed packet contributes its IP codepoint once to that packet number space's ACK_ECN counters, including when several QUIC packets share one UDP datagram.

An advancing ACK with consistent counters validates the path. An increase in validated CE feedback signals congestion to the controller of the path identified by the ACK. A PATH_ACK can return on a different path. Custom controllers can implement on_ecn_ce(const cc::sample&) to handle CE separately. Controllers with the existing interface receive a congestion notification through on_loss with zero lost bytes. An invalid report or a path that drops the marked traffic disables outgoing marking. Streams continue, and the receiver still reports marks from the peer. Active migration and NAT rebinding start a fresh trial when the new path becomes active.

With qlog enabled, quic:ecn_state_updated identifies the tuple and records the new state, previous state when available, and trigger. In multipath traces it also records data.path_id. A successful trial reaches capable. A trial that exhausts its marking budget enters unknown while waiting for feedback. A failed event explains why marking stopped. Received and sent ACK frame records expose the ect0, ect1 and ce counters. RFC 9000 §13.4.

Routable connection IDs

Use one shared issuer per server ID and configuration across workers. The server generates a fresh nonce for each CID. Configure the load balancer with the same rotation slot, server ID width, nonce width and optional 16-byte AES key. Pass the complete destination CID to config.decode(cid) and look up the returned server ID in your routing table. An unknown slot or malformed length yields std::nullopt. Clients can choose their initial destination CID, so the router also needs a fallback for unknown servers. QUIC-LB draft 22

#include <pace/quic/engine_impl.hpp>
#include <pace/quic/load_balancer.hpp>

struct routed : pace::quic::default_policies
{
    using connection_id = pace::quic::cid::quic_lb;
};

pace::quic::basic_endpoint<routed> listen_routed(
    pace::io_context& io, const pace::quic::context& tls, pace::udp::endpoint local,
    pace::quic::cid::quic_lb issuer)
{
    return {io, local, tls, issuer};
}

Construct the issuer with a routing configuration and a server ID, for example pace::quic::cid::quic_lb issuer({0, 3, 8, key}, {0, 0, 7});. Install the next slot on the load balancer first, then call issuer.rotate(next, server_id). All copies of the issuer use the new slot for future CIDs. Continue decoding the old slot while connections using it remain active. Live rotation preserves the total CID length and uses a fresh encryption key. If the nonce space is exhausted, the issuer switches to random CIDs with reserved slot 7 for fallback routing. Use a fresh key and slot when starting a new issuer after a restart, or supply unique nonces from persistent storage to lb_config::encode(server_id, nonce). A plaintext configuration requires unlinkable nonces.

qlog

Select trace::qlog on the native client or listener. Each connection writes a separate RFC 7464 JSON text sequence, with the original destination CID as the group ID shared by both endpoints. Create the output directory before starting the endpoint.

#include <pace/quic/engine_impl.hpp>

struct traced : pace::quic::default_policies
{
    using trace = pace::quic::trace::qlog;
};

pace::quic::basic_endpoint<traced> listen_traced(
    pace::io_context& io, pace::udp::endpoint bind, pace::quic::context& server)
{
    server.set_qlog(pace::quic::trace::qlog::directory("traces"));
    return {io, bind, server};
}

Clients use basic_connection<traced> with the same context option. Omitting set_qlog on a traced endpoint selects the directory named by QLOGDIR; an unset or empty value disables output. The default policy is trace::none. Configure the context before opening connections.

For a callback sink, pass trace::qlog(factory). The factory receives a suggested filename once per connection and returns a callable accepting one complete record as a std::string_view. For in-memory output, use trace::qlog::streams(factory) and retain a fresh std::shared_ptr<std::ostringstream> for each filename. Callbacks run synchronously on the owning IO context. A factory can decline a connection by returning an empty writer. A writer that throws is disabled for the rest of that trace.

Events cover connection start/close, address tuples, packet send/receive/drop/loss, frame headers, transport parameters, RTT and congestion metrics, controller state changes, and TLS key generations. Packet records carry lengths and frame metadata. Payload bytes, traffic secrets and token contents are omitted. The current transport supports one active path.

The native format follows qlog main schema 15 and QUIC events 14. For qvis releases using its 0.3 importer, run the following command from the repository root and open view.sqlog in qvis.

python3 scripts/qlog_to_qvis.py connection.sqlog > view.sqlog

Synopsis

#include <pace/quic.hpp>
#include <pace/runtime.hpp>

#include <array>
#include <iostream>
#include <string>

pace::task<std::string> read_to_fin(pace::quic::stream& stream)
{
    std::array<char, 4096> buffer{};
    std::string bytes;
    while (auto count = co_await stream.read_some(pace::as_writable_bytes(buffer)))
    {
        bytes.append(buffer.data(), count);
    }
    co_return bytes;
}

pace::task<void> echo_once(pace::quic::listener& listener)
{
    auto connection = co_await listener.accept();
    auto stream = co_await connection.accept_stream();
    co_await pace::write(stream, "echo: " + co_await read_to_fin(stream));
    stream.finish_write();
    co_await stream.drain();
}

pace::task<void> ask(pace::quic::listener& listener, const pace::quic::context& client_config)
{
    co_await pace::with_task_group(
        [&](pace::task_group& group) -> pace::task<void>
        {
            auto server = group.spawn(echo_once(listener));
            auto connection = co_await pace::quic::connect(client_config, listener.local_endpoint(), "localhost");
            auto stream = co_await connection.open_stream();
            co_await stream.write_all(pace::as_bytes("hello"));
            stream.finish_write(); // FIN on our direction; the reply still arrives.
            std::cout << co_await read_to_fin(stream) << '\n';
            co_await server; // Keep the connection open until the server has its acknowledgement.
        }
    );
}

int main()
{
    pace::quic::context server_config(pace::quic::role::server);
    server_config.use_certificate_chain("localhost.pem", "localhost-key.pem");
    server_config.set_alpn_protocols({"example"});

    pace::quic::context client_config; // role::client, system trust store
    client_config.load_verify_file("ca.pem");
    client_config.set_alpn_protocols({"example"});

    pace::run(
        [&](pace::io_context& io) -> pace::task<void>
        {
            auto listener = pace::quic::listen(io, {"127.0.0.1", 0}, server_config);
            co_await ask(listener, client_config);
        }
    );
}

Types

role and stream_type

enum class role { client, server };
enum class stream_type { bidirectional, unidirectional };

role selects which side of the handshake a context configures. stream_type selects the direction of a stream opened with connection::open_stream().

context

class context
{
public:
    explicit context(role mode = role::client);
    void load_verify_file(const std::string& path);
    void use_certificate_chain(const std::string& chain, const std::string& key);
    void set_alpn_protocols(const std::vector<std::string>& protocols);
};

The shared QUIC/TLS 1.3 configuration of one side. Copies are cheap and share one state.

  • context(mode) creates a configuration for mode. TLS is fixed to version 1.3. A client loads the system trust store and always verifies the server; there is no insecure client mode and no client certificate (mutual TLS) in this API. The initial ALPN list is {"pace-quic"}.
  • load_verify_file(path) adds the PEM certificates in path to the trusted roots, in addition to the system store.
  • use_certificate_chain(chain, key) loads a PEM certificate chain and its private key for a server. The key must be an unencrypted PEM file; loading never prompts for a passphrase. A key that does not match the certificate is rejected.
  • set_alpn_protocols(protocols) replaces the ALPN list. Each identifier is 1–255 bytes and the encoded list at most 65535 bytes; an empty list is rejected. The server selects the first protocol in its own list that the client also offers; no overlap fails the handshake. Read the result with connection::selected_protocol().

Configure a context completely before the first connection or listener uses it, and do not change it while any of them is alive.

connection

class connection
{
public:
    connection(io_context& io, const quic::context& config);
    connection(connection&&) noexcept;
    connection& operator=(connection&&) noexcept;
    ~connection();

    task<void> connect(udp::endpoint peer, std::string expected_name,
                       std::chrono::milliseconds timeout = std::chrono::seconds(10));
    task<stream> open_stream(stream_type type = stream_type::bidirectional);
    task<stream> accept_stream();
    io_context& context() const noexcept;
    std::string selected_protocol() const;
    bool is_open() const noexcept;
    void close(std::uint64_t application_error = 0) noexcept;
};

A client connection, or a connection returned by listener::accept(). Move-only.

  • connection(io, config) creates an unconnected client on io, bound to an ephemeral UDP port. config must be a client context.
  • connect(peer, expected_name, timeout) performs the handshake with peer and verifies the server certificate against expected_name, which is independent of the network address. A DNS name is also sent as SNI and must match a DNS subject alternative name; an IPv4 or IPv6 literal must match an IP subject alternative name. An empty name, a name containing NUL and port 0 are rejected. timeout bounds the handshake; a nonpositive value allows one immediate attempt. A connection whose connect() failed is closed.
  • open_stream(type) opens a stream, waiting while the peer's stream limit is reached. Opening a stream sends nothing: the peer sees it when its first data or FIN arrives.
  • accept_stream() waits for the next stream the peer opened. A stream becomes visible when its first data or FIN arrives; arrival order across streams is not an ordering guarantee.
  • selected_protocol() returns the negotiated ALPN protocol, or an empty string before the handshake.
  • is_open() is false after close(), after a connection failure and once the owning context has stopped.
  • close(application_error) sends CONNECTION_CLOSE with application_error, best effort and immediately. It discards unacknowledged output, invalidates every stream of the connection and wakes their pending operations. There is no graceful drain. Closing one accepted connection leaves the listener's other connections running.

stream

class stream
{
public:
    stream(stream&&) noexcept;
    stream& operator=(stream&&) noexcept;
    ~stream();

    std::uint64_t id() const noexcept;
    bool is_unidirectional() const noexcept;
    bool is_local() const noexcept;
    io_context& context() const noexcept;
    task<std::size_t> read_some(std::span<std::byte> buffer);
    task<void> write_all(std::span<const std::byte> bytes);
    task<void> shutdown_write();
    task<void> drain();
    void close() noexcept;
    void finish_write();
    void reset(std::uint64_t application_error = 0) noexcept;
};

One stream of a connection. Move-only. A stream handle keeps its connection's state alive. A quic::stream is a pace::byte_stream: it reads and writes std::byte spans (text goes through pace::as_bytes and pace::as_writable_bytes), and tls::stream can run over a bidirectional one.

  • id() is the QUIC stream ID; is_unidirectional() and is_local() (this endpoint opened it) are derived from it. context() is the owning io_context.
  • read_some(buffer) waits for at least one byte and returns the number read. It returns 0 only at the peer's FIN, or immediately for an empty buffer. A reset stream or failed connection is an error, not 0.
  • write_all(bytes) completes when the transport has accepted every byte, applying flow-control backpressure. It does not mean the peer has received or acknowledged them. The bytes are borrowed: keep them alive until the task completes.
  • shutdown_write() is finish_write() in the form pace::byte_stream requires: it queues FIN and completes at once.
  • close() is reset() with application error 0, in the form pace::byte_stream requires: it abandons both directions at once and wakes pending operations.
  • drain() waits until the peer acknowledges queued payload bytes. FIN is tracked separately.
  • finish_write() queues FIN on the sending direction. The receive direction stays usable.
  • reset(application_error) abandons the stream with application_error and wakes its pending operations.

Reading the sending-only side of a unidirectional stream, writing its receive-only side, and writing after finish_write() are errors.

listener

class listener
{
public:
    listener(io_context& io, udp::endpoint local, const quic::context& config);
    ~listener();

    task<connection> accept(std::chrono::milliseconds handshake_timeout = std::chrono::seconds(10));
    udp::endpoint local_endpoint() const;
    io_context& context() const noexcept;
    bool is_open() const noexcept;
    void close() noexcept;
};

A bound UDP socket that accepts QUIC connections. Not copyable or movable.

  • listener(io, local, config) binds local immediately and starts receiving. config must be a server context with a certificate. An IPv6 endpoint is bound IPv6-only.
  • accept(handshake_timeout) takes the next connection from the accept queue and completes its handshake. The timeout starts when the connection leaves the queue; it does not bound the wait for a new peer. A failed handshake (certificate, ALPN or deadline) throws, but the listener keeps accepting while is_open() is true.
  • local_endpoint() returns the bound address, with the port the system chose for port 0.
  • is_open() is false after close(), after an engine failure and once the owning context has stopped.
  • close() cancels a pending accept() and invalidates every connection accepted on this listener. The destructor calls it.

Functions

listener listen(io_context& io, udp::endpoint local, const quic::context& configuration);
listener listen(udp::endpoint local, const quic::context& configuration);

Bind a listener, exactly like the listener constructor. The second form uses the current context and must be called inside a running io_context.

task<connection> connect(io_context& io, quic::context configuration, udp::endpoint peer,
                         std::string expected_name,
                         std::chrono::milliseconds timeout = std::chrono::seconds(10));
task<connection> connect(quic::context configuration, udp::endpoint peer, std::string expected_name,
                         std::chrono::milliseconds timeout = std::chrono::seconds(10));

Create a client connection and complete connection::connect(). The task holds its own copy of configuration (a shared handle), so the caller's object need not outlive it. The timeout bounds the handshake only, not later stream operations. The second form uses the current context. ALPN and the certificate identity stay explicit: nothing is chosen for you.

The stream helpers of <pace/net/stream_io.hpp> (pace::write, pace::read_exact) also accept a quic::stream.

Errors

Condition Exception
Invalid argument: role, empty or oversized ALPN, empty or NUL-containing name, port 0, wrong context role, stream type std::invalid_argument
Scoped IPv6 destination with the openssl backend std::invalid_argument
Overlapping operation of the same kind, call from another context, operation before the handshake, wrong stream direction, write after FIN std::logic_error
Handshake deadline std::system_error with std::errc::timed_out
Connection, listener or context closed or stopped; cancellation std::system_error with std::errc::operation_canceled
Peer closed the connection, idle timeout std::system_error with std::errc::connection_aborted
TLS or QUIC failure: untrusted or mismatched certificate, no common ALPN, key or trust file errors, protocol violation std::system_error with std::errc::protocol_error; the message carries the backend's diagnostics
UDP socket failure std::system_error with the system error

A failure inside the shared UDP engine closes it and is reported to every operation on it. A server should catch per-peer errors around accept() and the work on each connection so one peer cannot stop unrelated tasks.

Threads and concurrency

  • Every member runs on the thread running the owning io_context; a call from elsewhere throws std::logic_error. Construct and destroy handles on that thread too, or while the context is not running.
  • Per stream, one read and one write may be outstanding at a time. Per connection, one connect(), one open and one accept may be outstanding. Per listener, one accept(). A second operation of the same kind throws std::logic_error.
  • Distinct streams progress independently and concurrently. All connections of a listener, and all streams of a connection, share one UDP socket.
  • Both backends are driven by PACE UDP readiness and cancellable io_context timers, with no polling thread. Library callbacks never resume application code directly: continuations are queued on the context.

Lifetime and ownership

  • The io_context must outlive every listener, connection and stream on it.
  • A stream holds a shared reference to its connection's state, and a connection to its UDP engine. Destroying a connection object therefore does not invalidate its streams. The transport is released with the last handle; if delivery matters, use co_await stream.drain() before dropping it, and keep the connection open until the peer has finished.
  • connection::close() invalidates every stream of the connection. listener::close() and the listener's destructor invalidate every connection accepted on it, so keep the listener alive while its connections are in use.
  • write_all() and read_some() borrow their buffers until the task completes.
  • A context is shared by the connections and listeners created from it; they keep it alive.

Limits and defaults

Setting Value
Handshake timeout (connect, accept) 10 s; nonpositive allows one immediate attempt
Initial ALPN list {"pace-quic"}
ALPN identifier / encoded list 1–255 bytes / at most 65535 bytes
TLS version 1.3 only
Client trust System store plus load_verify_file()
IPv6 listener IPv6-only
Scoped IPv6 destinations Preserved (native, ngtcp2); rejected (openssl)

The ngtcp2 backend uses these transport settings. The openssl backend uses OpenSSL's defaults.

ngtcp2 setting Value
UDP payload size 1200 bytes; PMTU discovery off
Per-stream flow-control window 256 KiB
Connection flow-control window 4 MiB
Incoming streams exposed at once 64 per direction; credit returns as handles are released
Internal write chunk at most 16 KiB
Pending accept queue 128 connections
Incomplete server handshake expires after 10 s, even without an accept()
Idle timeout 30 s
Packets per receive or send batch 64
Active connection migration Disabled

The native backend starts with the same 256 KiB stream and 4 MiB connection windows and can grow each to four times its initial size. It accepts up to 256 pending connections. Set the idle timeout on the context before connecting or listening.

See also