A TCP stream or connected UDP flow between a TailcatClient and a TailcatServer. Connections are created by TailcatClient$dial() and TailcatListener$accept(), not directly.
For TCP, reads may return fewer bytes than requested and $read() returns NULL at end of stream. For UDP, each read returns one datagram (possibly raw(0)) and each write sends one datagram of at most 1232 bytes (tailcat_udp_max_payload()). $write_message() and $read_message() send and receive delimited messages over TCP (see the section on messages), and $read_loop() reads continuously from the event loop (see the section on read loops).
One read and one write may be in flight at the same time (for example a pending $read_async() while writing). Further operations in the same direction wait their turn and run in the order they were started, for synchronous and asynchronous calls alike, so several $write_async() calls send their data in call order and several $read_async() calls receive consecutive chunks of the stream in call order. The wait counts toward each operation's timeout, and canceling or timing out an operation that is still waiting ends it without affecting the others.
$client or $server (the other is NULL) gives the object that owns the connection, the client that dialed it or the server whose listener accepted it.
Once the connection, or the client or server that owns it, is closed, every method other than $close(), $format(), and $print(), and every field other than $is_closed, $is_reading, $client, and $server, raises a tailcat_closed error; nothing is kept from before. Timeouts (including timeout = 0, a poll) and errors are described in TailcatServer.
Messages
TCP is a stream of bytes with no boundaries: one $write() may arrive as several reads, and several writes as one. $write_message() and $read_message() add boundaries, so that each $read_message() returns exactly what one $write_message() sent. On the wire a message is its length as 4 bytes (unsigned, big-endian, so a peer in another language can implement it in a few lines) followed by that many bytes. The protocol allows messages up to 4 GiB; rtailcat sends and accepts at most 2147483647 bytes (just under 2 GiB) per message.
Give $read_message() a max_bytes that fits your protocol whenever the peer is not fully trusted: the length is checked before the message is read, so an oversized message is refused without reading it into memory.
To send R objects, serialize them: conn$write_message(serialize(x, NULL)) and unserialize(conn$read_message(max_bytes = 1e8)). Only do this with peers you trust completely: unserialize() on data from an untrusted peer can run arbitrary code. Use a data format such as JSON otherwise.
Read loops
$read_loop(callback) reads continuously, driven by the later event loop, and calls callback(data) on the main R thread with each chunk (TCP), each datagram (UDP), or with messages = TRUE each message. It is the reading counterpart of TailcatListener$serve() and makes progress under the same conditions: while R is idle at the console, inside Shiny or httpuv, or while a script runs the event loop (see tailcat_run()). If callback returns a promise, the next read starts after it settles, so data is handled in order and a slow callback slows down reading rather than piling up work.
The loop ends when the peer ends a TCP stream (on_end is then called), when the connection or its owner is closed, or when $stop_reading() is called; the last two end it quietly. $is_reading tells whether a loop is running. If a read fails or the callback fails, on_error is called, the loop stops, and the connection is closed. While a read loop runs, other reads on the connection would interleave with it, so only write.
Active bindings
local_addressThe local endpoint as
"host:port"on the tailcat network. It is fetched from tailcat on each access.remote_addressThe peer's endpoint as
"host:port"on the tailcat network. It is fetched from tailcat on each access.network"tcp"or"udp".clientThe TailcatClient that dialed the connection, or
NULLfor an accepted connection. Like$server, it keeps working after the connection is closed.serverThe TailcatServer whose listener accepted the connection, or
NULLfor a dialed connection. It keeps working after the connection is closed.is_readingTRUEwhile a read loop started by$read_loop()is running,FALSEotherwise, including once the connection is closed.is_closedTRUEonce the connection, or the client or server that owns it, has been closed.
Methods
TailcatConnection$new()
Internal constructor; use TailcatClient$dial() or TailcatListener$accept().
Usage
TailcatConnection$new(handle, owner, network)Arguments
handleNative connection handle.
ownerThe owning TailcatClient or TailcatServer.
networkInteger network code.
TailcatConnection$read()
Read up to n bytes (TCP) or one datagram (UDP, truncated to n bytes). One call returns at most 65536 bytes whatever the value of n (TCP reads may return less than requested anyway, and UDP datagrams are much smaller), so loop, or use $read_all(), to read more. A timeout ends only this read; the connection stays usable. With timeout = 0 the read returns data (or the end of stream) that has already arrived, and otherwise raises tailcat_timeout at once. A TCP read returns whatever has arrived, so with as = "text" a multibyte UTF-8 character can be split across two reads; for multibyte text use $read_all(), or read raw bytes and convert them once. On UDP, n = 0 consumes one datagram and returns no bytes; on TCP it returns at once without reading.
Usage
TailcatConnection$read(n = 65536L, timeout = Inf, as = c("raw", "text"))Arguments
nMaximum number of bytes to return (at most 65536 are returned).
timeoutSeconds to wait;
Infwaits indefinitely and0polls.asExactly
"raw"(the default) to return a raw vector, or"text"to return a single string marked as UTF-8 (the bytes are not checked for valid UTF-8). Data containing NUL bytes cannot be returned as text and raises atailcat_invalid_argumenterror; the data is consumed, so read binary data withas = "raw".
TailcatConnection$read_async()
Asynchronous version of $read().
Usage
TailcatConnection$read_async(n = 65536L, timeout = Inf, as = c("raw", "text"))TailcatConnection$read_all()
Read until the peer ends the stream (TCP only). On timeout or error the condition's bytes field gives the number of bytes read before it; those bytes are discarded. With timeout = 0 it returns only if the whole stream, including its end, has already arrived.
Usage
TailcatConnection$read_all(
timeout = Inf,
as = c("raw", "text"),
max_bytes = Inf
)Arguments
timeoutOverall seconds to wait;
Infwaits indefinitely and0polls.asExactly
"raw"(the default) to return a raw vector, or"text"to return a single string marked as UTF-8 (""for an empty stream). See$read()for NUL bytes.max_bytesThe most bytes to accept, a single non-negative whole number or
Inf(the default) for no limit. If the stream is longer, reading stops aftermax_bytes + 1bytes and atailcat_failureerror is raised whosebytesfield is the number of bytes read (max_bytes + 1). Those bytes are discarded, but the connection stays open and usable: the rest of the stream can still be read, or the connection closed.
TailcatConnection$read_all_async()
Asynchronous version of $read_all(). Canceling the promise with tailcat_cancel() ends the read in flight and starts no further reads.
Usage
TailcatConnection$read_all_async(
timeout = Inf,
as = c("raw", "text"),
max_bytes = Inf
)TailcatConnection$read_exact()
Read exactly n bytes (TCP only), waiting for as many reads as that takes. Use it to read fixed-size fields of a binary protocol; for messages of varying length see $read_message().
If the stream ends before the first byte, $read_exact() returns NULL, so a peer that closes the connection between records is not an error. If it ends part way, or on timeout or error, the condition's bytes field gives the number of bytes read before it; those bytes are discarded. The timeout covers all the reads together. With timeout = 0 it returns only if all n bytes have already arrived.
Usage
TailcatConnection$read_exact(n, timeout = Inf, as = c("raw", "text"))TailcatConnection$read_exact_async()
Asynchronous version of $read_exact(). Canceling the promise with tailcat_cancel() ends the read in flight and starts no further reads.
Usage
TailcatConnection$read_exact_async(n, timeout = Inf, as = c("raw", "text"))TailcatConnection$write_message()
Send data as one message (TCP only), for the peer to read with $read_message(). See the section on messages.
Arguments
dataA raw vector, or a character vector which is pasted together without separators and sent as UTF-8. At most 2147483647 bytes.
timeoutSeconds to wait;
Infwaits indefinitely and0polls. On timeout or error the condition'sbytesfield gives the number of bytes already sent, counting the 4-byte length; the peer then sees a partial message, so close the connection.
TailcatConnection$write_message_async()
Asynchronous version of $write_message().
TailcatConnection$read_message()
Read one message sent with $write_message() (TCP only). See the section on messages.
If the stream ends cleanly between messages, $read_message() returns NULL. If it ends part way through a message, or on timeout or error, the condition's bytes field gives the number of bytes read, counting the 4-byte length; those bytes are discarded and the connection should be closed, since the rest of the stream no longer starts at a message boundary. The timeout covers the whole message.
Usage
TailcatConnection$read_message(
timeout = Inf,
as = c("raw", "text"),
max_bytes = Inf
)Arguments
timeoutOverall seconds to wait;
Infwaits indefinitely and0polls.as"raw"or"text", as for$read().max_bytesThe largest message to accept, a single non-negative whole number or
Inf(the default; messages are limited to 2147483647 bytes in any case). The length is checked before the message is read: a longer message raises atailcat_failureerror withbytesset to 4, and its body is left unread, so close the connection.
TailcatConnection$read_message_async()
Asynchronous version of $read_message(). Canceling the promise with tailcat_cancel() ends the read in flight and starts no further reads; a message read part way is lost.
Usage
TailcatConnection$read_message_async(
timeout = Inf,
as = c("raw", "text"),
max_bytes = Inf
)TailcatConnection$read_loop()
Start an asynchronous read loop that calls callback(data) with every chunk (TCP), datagram (UDP), or message (with messages = TRUE) as it arrives, and returns immediately. See the section on read loops.
Usage
TailcatConnection$read_loop(
callback,
on_error = NULL,
on_end = NULL,
as = c("raw", "text"),
messages = FALSE,
max_bytes = Inf
)Arguments
callbackA function of one argument, the data read. It may return a promise, in which case the next read starts once the promise settles.
on_errorA function
function(cond)called when a read fails, the data is not acceptable (such as a message longer thanmax_bytes),callbacksignals an error, or the promise it returned rejects; orNULLto turn such errors into warnings (signaled from the later event loop). The loop then stops and the connection is closed. An error signaled byon_erroritself is turned into a warning.on_endA function of no arguments called when the peer ends a TCP stream, after the last data, or
NULL. An error it signals is turned into a warning.as"raw"or"text", as for$read().messagesFALSE(the default) to deliver data as it arrives, orTRUEto deliver whole messages sent with$write_message()(TCP only).max_bytesThe largest message to accept with
messages = TRUE, as for$read_message().
TailcatConnection$stop_reading()
Stop the read loop started by $read_loop() without closing the connection. The pending read is canceled; data whose read completed at the same moment is still passed to the callback, but a message read part way is lost, so with messages = TRUE stop only between messages or then close the connection. Calling it when no read loop is running does nothing.
TailcatConnection$write()
Write all of data: the call returns once everything has been sent, or raises. On timeout or error the condition's bytes field gives the number of bytes already sent.
TailcatConnection$write_async()
Asynchronous version of $write().
TailcatConnection$close_write()
Half-close a TCP connection: tell the peer there is nothing more to send, while still being able to read its reply.
TailcatConnection$is_readable()
Check without waiting whether a TCP read would return immediately (buffered data, end of stream, or a pending error). Intended for checking idle connections, not as a readiness loop.
TailcatConnection$close()
Close the connection. Pending reads and writes end with a tailcat_closed error. Closing twice is harmless.
TailcatConnection$format()
Format a summary, the lines that $print() shows. An open connection shows its local and remote endpoints on the tailcat network (not secrets); they are left out when the connection is closed, when tailcat cannot report them, and once $close_write() has succeeded on it.
Examples
if (FALSE) { # \dontrun{
conn = TailcatClient$new(address)$dial(8080)
conn$write("ping")$close_write()
conn$read_all(timeout = 10, as = "text")
} # }