Qué hace
- Negociación de la tabla de métodos: el nombre nunca viaja por la red
- Metadatos, plazo relativo y cancelación
- Interceptores en un orden definido
- Streams con créditos de bytes, multiplexación y ping automático
- Bus de topics con comodines y colas por suscriptor
- Entrega at-most-once o at-least-once
Medido
- MSVC 19.51, x64, Release, transporte nulo. Coste de una llamada unaria: 617 a 714 ns (objetivo 1000 ns)
- Despacho en el servidor: 318 a 343 ns. Petición en la red: 41 bytes
- Ida y vuelta de un ping: 1 a 2 µs
- Asignaciones por llamada: 1. Objetivo de cero no cumplido
Límites conocidos
- Sin compresión del cuerpo y sin streams bidireccionales simultáneos
- El servidor atiende una petición a la vez por conexión
The surface of spec 09 is covered. Wire format, dispatch by number, negotiation, closing with a message, liveness signal, metadata, deadline and cancellation, interceptors, streams in both directions with window control, multiplexing, topic bus and C ABI layer. What is left out is left out by decision or by measurement, and it is in "What is missing". The section is short, and should be read before counting on what is not there.
---
What this step did, and why
frame.hpp and frame.cpp (the 24-byte format that the spec says to define explicitly) were written and orphaned: they were not in the source list of CMakeLists.txt, they were not included by rpc_inc.hpp, nobody included them, and no test touched them.
They had never been compiled a single time. Hooking them into the target revealed two macros that do not exist in this tree (ETL_INLINE_VAR and ETL_FORCEINLINE, the latter with one underscore too few). Code that has never been through a compiler simply has not been contradicted yet. That does not prove it works.
The protocol, meanwhile, was still on the previous design:
[ 1 byte : type ]
[ 4 bytes : identifier ]
[ LEB128 : name length ][ name ]
[ rest : body ]The method name traveled on every call, and the server dispatched by comparing text against each registered method. There was no integrity check at all: a flipped bit in the identifier delivered the response to another call. That is exactly the damage the module's rule 1 exists to prevent, coming in through the back door.
---
The design, and what each choice buys
Twenty-four bytes, and none of them padding
uint32 uMagic 'ETLR'
uint8 uVersion
uint8 uType EFrameType
uint16 uFlags EFrameFlag + 3 priority bits
uint32 uCorrelationId
uint32 uMethodId
uint32 uPayloadLength
uint32 uHeaderCrc covers the first TWENTY bytesFixed size, so that the read loop is read 24, check, read the body, with no state machine for the header, which is where framing defects live. Little-endian written byte by byte, with no memcpy over the struct: copying 24 bytes from the wire works on a little-endian machine and gives swapped numbers on a big-endian one, with no warning at all.
The whole table comes in the negotiation
*"
Settingsframe exchanged on connect: protocol version, max frame size, max concurrent streams, compression support, service and method ID table. Method IDs are negotiated once so the wire never carries names."*
Register gives each method a slot in registration order, starting at 1. Zero belongs to no method, and that is what makes it useful: uMethodId == 0 means "the name comes in the body".
Before the first call the client sends an eSettings and the server responds with the version, the limits, the generation and all the name/number pairs. One round trip, once per connection. From then on the name of a registered method never goes on the wire again. That is the spec's sentence, and a test that reads the bytes that went out requires it.
The slow path (number zero, name in the body) still exists, and it has a purpose: it is the path taken by a method registered after the negotiation, which the client could not have had in its table. That method's response carries the number, and the client learns it. Without this, registering late would be registering in vain.
A rejected negotiation breaks nothing. If the other side responds with an error, the client continues on the slow path (which is how the module worked before there was negotiation) and does not try again: retrying on every call would double the traffic and the time of all of them, forever, because of an answer already received. What is not tolerated is the negotiation going unanswered: then the channel is not healthy, and that comes back as eTimeout or eDisconnected.
The body is the same in both directions, and the client's goes with an empty table:
[ LEB128 : size of the fixed block ]
[ fixed block, which in version 1 is ]
[ 1 byte : the highest version this side speaks ]
[ 4 bytes : the limit this side accepts to RECEIVE ]
[ 2 bytes : simultaneous streams it can handle ]
[ 1 byte : compression mask ]
[ 2 bytes : table generation ]
[ LEB128 : how many methods ]
[ LEB128 name length ][ name ][ 4 bytes : the number ]The fixed block carries its own size up front, and that is what allows adding fields in a version 2 without breaking a version 1 reader: it consumes what it knows and skips the rest up to the announced end. Without that size, a new field would make the old reader start reading the table two bytes before the right place. A table read from the wrong place does not produce an error: it produces names with garbage and plausible numbers. That is the worst kind of format defect, the kind that looks like data.
The generation, for the case the negotiation does not solve
The table comes once per connection. The problem is that this module does not know when the connection changes: IMessageTransport has no reconnection signal, and a transport that reconnects internally (because the server went down and came back) still looks like the same object.
With no defense at all, the client would send slot 3 to the new server, which has something else in slot 3, and the call would hit the wrong method successfully. That is the rule 1 damage coming in through another door, and just as silent.
That is why the method number is split in two: sixteen bits of generation (drawn once per CRpcServer) and sixteen of slot. The new server sees a generation that is not its own, rejects with eStaleMethodId, and the client forgets, negotiates again and repeats the call once. The caller notices nothing. What remains is the Retries() counter going up.
It is a detection, not a proof. Two generations that match by chance happen once in 65,536, and then the old number gets through. Saying the hole is closed would be a lie. What can be said is that it went from "happens whenever the registration order changes" to "happens once in 65,536 reconnections with the order changed". Closing it for good requires the transport to say that it reconnected.
The generation draw is a counter multiplied by an odd number, plus a per-process seed: the first 65,536 servers of a process get guaranteed different generations. An arbitrary mixing function would not give that guarantee, and two servers with the same tag would make the defense fail with nothing to give it away.
The error code is its own byte
The previous design told "unknown method" apart from "method failed" by looking at the start of the message:
const bool bUnknown = ( sError.rfind( "unknown method", 0 ) == 0 );Translating the message (something that is done with messages) broke the distinction, silently, and the caller would then treat a wrong protocol version as an invalid argument. The body of the error frame is now [ 1 byte of ERpcError ][ message ], which is the spec's "typed status code plus an optional message".
**The ERpcError values now cross the wire.** Appending at the end is safe. Reordering changes the protocol, not just the code.
Whoever rejects a frame closes the connection, and says why
The line is drawn by the decoder, independently of meaning:
- a frame it rejects (wrong magic, a version it does not speak, corrupted CRC, length that does not match, body above the limit) gets an
eGoAwaywith the reason, and the connection closes. - a valid frame with a problem of meaning (method that does not exist, method that failed, number from another table) gets an
eError, and the connection stays.
The spec puts both halves in writing. On the closing side: "A payload length beyond the limit closes the connection with GoAway." On the staying side: "Server handler failures never close the connection unless the failure is a protocol violation."
Why not ignore it and move on. With a message transport, skipping a corrupted message and continuing is technically possible, because the framing does not lose sync. But whoever sends a frame that fails the check is either defective or not who it claims to be, and in both cases the next frame comes from the same place. Continuing to serve is accepting a queue of garbage, for free, forever.
And why state the reason. Closing without a message makes the other side see the same thing it would see if the cable had been pulled, and the reaction to a pulled cable is to reconnect. A client that sends a frame the server rejects and gets only silence enters a loop: it reconnects, sends the same thing, is closed again. The message is what turns that loop into a readable error, and that is why eGoAway is its own code, not an eDisconnected.
The rule belongs to the protocol, and applies to both sides. The client does the same when it is the one receiving bytes that are not a frame: it sends the goodbye and closes. A client that knows how to send a goodbye and does not know how to read one ends up exactly in the loop this exists to avoid.
The goodbye always goes with identifier zero. Almost always what caused it was a header that failed the check, and a header that failed has no trustworthy identifier. Returning it would be answering a call that may never have existed.
And there is the other use, which is nobody's fault: CRpcServer::GoAway( …, eShutdown, "shutting down" ), for whoever is shutting down on purpose and wants the other side to know it was not the cable.
The liveness signal
ePing / ePong, for the question an idle connection cannot answer any other way: are you still there? The ping carries an identifier, like any request that expects a response, and the pong returns the same one. Rule 1 applies here in the same way.
The pong returns the ping's body intact. It is what ICMP does and what WebSocket requires, for the same reason: without the echo, the responder does not need to have read the ping. Seeing the frame type and sending an empty pong would be enough. The client puts in an eight-byte token and rejects a pong that does not return it.
A ping does not negotiate. Forcing an eSettings round trip to ask whether the other side is alive would make the cheapest question the most expensive one. Worse, there would no longer be a way to ask when it is the negotiation that is failing.
And the response is automatic, on both sides, inside any wait: a call, a Pump, a negotiation. A liveness signal that only works when whoever is on the other side remembers to handle it becomes just one more thing to forget.
The asymmetry that remains is deliberate: CRpcClient::Ping waits for the pong and returns the round-trip time. CRpcServer::Ping does not wait. The server is inside ServeOne when it wants to ask, and waiting there would mean no longer serving whoever has already sent a request. The pong shows up on a later pass and is counted in PongsReceived(). It is asynchronous, and the API says so instead of pretending it is not.
What a pong says, and what it does not. It says that bytes go back and forth and that the other side is servicing its loop. It does not say that the methods respond, that the database is up, or that the process is not on its way to running out of memory. A service that responds to pings and fails at everything else is a common case, and a ping does not catch it. This is written in the header, next to the function.
Metadata goes at the end, and the deadline is part of it
The spec calls this data "an optional trailing header block", and trailing has a consequence: the message body has no size of its own, it is what is left of the frame. If the metadata came after it, nothing would say where one ends and the other begins. So:
[ body ][ metadata block ][ 4 bytes : block size ]Reading goes from end to start. Putting the metadata in front would have been simpler and would have cost a copy: whoever writes the body writes directly into the send buffer, and a block of unknown size in front would force leaving room and pushing everything afterward.
Two limits (count and size), checked when setting and when reading. Checking only when reading is trusting that the sender stays within the limits, and the sender may be another implementation.
The deadline is a metadata entry with a reserved key, and it travels as the time remaining. An instant would require the two clocks to agree, and they do not: a server with a fast clock would reject everything, a slow one would reject nothing. What is lost with the relative form is the transit time: the server's deadline ends a little after the caller's, which is the safe side of the error.
The wait time and the deadline are the same number. Two knobs would give the pair "I wait 100 ms but give you 5 s", which means nothing useful: at 100 ms the caller gives up and the server keeps working for the trash can.
Cancellation says what it can, without pretending the rest
When a call times out, the client sends an eCancel. It is only a notice that nobody is listening. Rule 4 still holds in full, and the method is not interrupted in the middle.
The gain is real: the server finds this out before responding and does not spend the network on a response nobody will read. And there are two paths to the same conclusion, because the notice can get lost: the cancellation, and the deadline the server checks on its own when it finishes.
Peeking at the transport costs a millisecond, and so it is only done when already late. Paying that on every call would mean trading seven hundred nanoseconds of overhead for more than a thousand times that.
SCallContext::IsCancelled() is only true when the cancellation arrived before the method started. With a single thread, nobody reads from the transport while it runs. This is stated next to the function, in plain sight.
Interceptors are crossed twice, and never per byte
They enter in registration order and exit in reverse, with the method in the middle: A>B>*<B<A. One that rejects on entry stops the call (that is how authentication is written once, instead of at the start of each method), and then only those that had already entered exit, because one that never entered has nothing to close.
With none registered, the cost is a comparison with zero.
Streams, and the window
The window is a credit in bytes: the receiver announces how much it accepts to have pending to read, the sender deducts, and when the credit runs out it waits. Without this, a fast producer against a slow consumer produces no error at all. It produces a queue growing somewhere until someone runs out of memory, and the place where it blows up is rarely the place where the cause is.
Backpressure shows up as waiting, never as a queue: that is what the spec requires when it says "never as an unbounded internal queue".
A chunk is only split by the frame limit, never by the window. Splitting by the window would make someone who writes a hundred bytes at a time see the consumer receive a hundred, then fifty, then fifty. A message stream would stop having messages, and nobody asked for that by narrowing the window.
A stream that fails midway says it failed. eStreamEnd carries the error inside when there was one. Without this, an interrupted stream is indistinguishable from one that finished, and the consumer is left with half the data thinking it has all of it.
In both directions: the server writes with CStreamWriter and the client consumes with a sink. In the opposite direction, the client writes with CStreamSender and the method pulls with CStreamReader. The method pulls the chunks. A method that received the chunks through a callback would have to keep state between calls. This way its state is that of its local variables.
Multiplexing: the slot and the identifier are the same thing
Without it, a client belongs to one thread: the caller stays inside the read loop until its response arrives, and another thread's call waits for the first one without having anything to do with it.
With the mode on, an I/O thread reads the transport and dispatches by identifier. The spec says how: "a dense array indexed by a slot number with a generation, not a hash map". The identifier is split like the method number: generation on top, slot at the bottom. The generation advances when the slot is released, and that is what prevents the late response of an already abandoned call from waking whoever took the slot next. It is rule 1 again, now with the slot reused.
One lock on send, none on receive, as the spec asks.
The callback of an asynchronous call runs on the I/O thread, and that is stated prominently in the header: putting application work there stops transport reads for as long as it lasts, and with that the responses of all the other calls are left waiting.
It is multiplexing that gives the ping what it was missing: an automatic liveness signal. A ping that depends on someone remembering to send it does not discover a dead connection. What discovers it is the next call, when it is already too late. After N pings without a response the connection is declared dead and is closed, which is the part that matters: a connection that only looks alive is worse than one known to be dead.
The topic bus
Matching by prefix tree, with no text comparison per message. With a hundred subscriptions and one comparison for each, publishing costs a hundred comparisons, and a bus where publishing gets more expensive with each new subscriber degrades with use. Here the cost is the number of segments in the topic: three or four.
* matches one segment, # matches the rest and is only valid at the end. The queues are per subscriber and bounded, with the overflow policy chosen by the publisher: only it knows whether the old message or the new one is what matters. Delivery at most once or at least once, by choice. Exactly once is not offered, for a concrete reason: it would require the delivery and the effect to be the same transaction, and this module knows nothing about the effect.
The C layer
Opaque handles, methods as a function pointer plus context, caller-owned buffers. The question "who frees this" has no good answer across an ABI boundary where the two sides may have different allocators, so no function in that header allocates memory the other side has to free.
A response that does not fit is an error, never a truncated response. Truncating would give the caller half a message with a success code.
And there is the embedded transport: it serves the server within the call itself, which allows embedding a server in the same process without bringing a thread into the program of whoever uses the library. The code path is the same as in the distributed case, and that is what prevents the defect that only shows up when the embedded transport is swapped for the network.
A single limit
DEFAULT_MAX_MESSAGE was 16 MB and kDefaultMaxPayload is 4 MB: two limits for the same thing, waiting to disagree. Only one remains, and the old name still compiles.
It is now checked on the sender's side too. Rule 6 is usually read as a defense against the other side. It is both, because a frame that only the destination rejects has already spent the network and delivers the news by the most expensive path there is.
---
What was measured
MSVC 19.51, x64, Release, over the test suite's null transport (the server runs on the same thread, with no context switch adding to the number).
| measured | spec target | |
|---|---|---|
| overhead per unary call | 617 to 714 ns | < 1000 ns ✓ |
| allocations per call | 1 | zero ✗ |
| request on the wire, with number | 41 bytes | n/a |
| request on the wire, with name | 46 bytes | n/a |
| server dispatch, with number | 318 to 343 ns | n/a |
| server dispatch, with name | 339 to 366 ns | n/a |
| negotiations per connection | 1 | n/a |
| name lookups on the server, in steady state | zero | n/a |
| goodbye sent per rejected frame | 1, and the connection closes | n/a |
| ping round trip, null transport | 1 to 2 µs | n/a |
| requests in flight at the same time (multiplexed) | 8 | > 1 ✓ |
| automatic pings in 300 ms idle | 5 | n/a |
The remaining allocation is not from framing, and that was measured. The frame's two buffers belong to the connection and already have capacity: clear plus resize reuses the block. The allocation comes from the Serialization::CWriter the server constructs per request: its constructor writes the stream header, and that is the first write into an empty vector. The test suite measures a CWriter on its own, separately, and gets exactly 1: the numbers add up. Removing that allocation is work for the Serialization module.
The time difference between the two dispatches cannot be measured here, and that is stated. What is measured is the dispatch, without the whole call. The call by name only happens once per connection, and forcing it would require reconnecting, which brings a negotiation into the measurement. So the request is built both ways, once, and the same frame is given to the server twenty thousand times. Everything else is equal.
Even so, the result swings from +13% to −1% between runs, on the same machine and the same build: looking up a name in a table of ten costs less than this machine's noise can separate. Picking the run that gives 13% would be picking the number that pleases.
That is why the test suite prints the comparison, says when it falls below the noise, and does not require it. What is required is what can be measured without a stopwatch: the request shrinks by five bytes, and the server stops comparing text on every call (NamedLookups() stays at zero in steady state).
The time target is only required with NDEBUG. In Debug the same call costs more than ten microseconds, and that comes from the build mode. Failing with that number would be accusing the module of a cost that is not its own.
---
How this was verified
tests/rpc_bus.cpp (262 checks), the rpc section of smoke (149) and tests/rpc_c_abi.c (28, compiled as C11 and as C17, without extensions). All pass in Debug and in Release.
The whole test suite stays at 60/60 in both modes, with plugin.manifest left out. That test is intermittent for its own reasons: it measures concurrency with busy waiting and takes anywhere from 4 s to more than 5 min between runs. It has nothing to do with this module (its executable does not even link rpc.obj), and it is recorded separately.
The byte table written by hand
A round trip proves no format at all: encoding and decoding with the same code passes with any format, including one that changes on its own in the next build. What pins down the surface is a literal table, field by field, with the CRC recorded:
45 54 4C 52 01 01 02 05 44 33 22 11 07 00 00 00 03 00 00 00 1D EB 86 1FAnd the proof that the CRC covers twenty bytes, not twenty-four: changing the four bytes of the field itself does not change the computation.
The rejection reasons, one by one
eShort at all twenty-four possible sizes, eBadMagic, eBadVersion, eBadType at zero and above the highest, eBadFlags, eBadCrc with a bit flipped in each of the twenty covered bytes, and eTooLarge one byte below the limit and exactly at the limit.
eLengthMismatch is the only one that does not fit here, and the reason is its own: the decoder never produces it. It looks at twenty-four bytes and does not know how many came after them. The layer that joins header and body is what knows. That is why it is required through the server, in the rpc section of smoke, with a valid header that promises a body and does not deliver it.
Two more properties that are not cases, but orderings:
- the magic before the CRC: a desynchronized stream has to declare itself desynchronized, not "bad CRC", which sends people looking in the network for a defect that is in the framing.
- the CRC before the length: a corrupted header has a length field with no meaning at all, and rejecting it as "too large" sends the caller off to raise the limit instead of finding out who is corrupting bytes.
And that nothing is written to the output when there is a rejection: the struct goes in with sentinels in its eight fields and comes out with all eight intact.
The bytes the module actually put on the wire
Section 2 checks the encoder. This one checks the protocol. The null transport keeps the last frame in each direction, and the test suite decodes it: the first call goes out without a number and with the name in the body, the response carries the number, the second call goes out with only the number and with the body being exactly the arguments, the notification goes out with identifier zero, and the error frame carries the code in the first byte.
These are two different claims ("the encoder knows how to write a header" and "the module uses the header it says it uses"), and the second is the one that matters to whoever reads this from the other end of the wire, in another language.
The negotiation
The outgoing frame is read byte by byte: type eSettings, nonzero identifier (a negotiation without a response negotiates nothing), method number zero, fixed block announcing ten bytes, version, generation, and the table (empty in the client's request, with the name/number pairs in the server's response).
After that, three properties that are the whole point:
- one per connection: twenty calls, one
Handshakes(), oneSettingsServed(). - a field this code does not know does not break it: a fake server responds with a twelve-byte fixed block, two bytes of which belong to a version that does not exist. The table is still read after what is unknown, not on top of it.
- a rejection breaks nothing: another fake server responds to the negotiation with an error. The next five calls work through the slow path, and the transport saw one negotiation attempt, not five.
The generation, with the trap set
Two servers with the same two methods in swapped order: in the first, alpha is in slot 1. In the second, slot 1 is beta. The client calls alpha on the first, keeps the number, and then the transport switches servers underneath, **without anyone calling Attach**, which is exactly what an internal reconnection does.
The next call to alpha answers alpha. Without the generation it would answer beta, successfully, and nothing in the program would notice. The test also requires the price: one StaleMethodIds() on the new server, one Retries() on the client, a second negotiation, and none of that repeating in the next ten calls.
The goodbye, on both sides
On the server side, in the rpc section of smoke: five frames the decoder rejects (short garbage, header cut one byte short, a flipped bit, a four-gigabyte length, a length that does not match), and each one requires both halves of the rule. That the goodbye went out, with identifier zero and the reason in the first byte of the body, and that the connection closed.
Right after come the two cases that prove the other half: a lying name inside a small body and a server receiving a response. These are valid frames. The problem is in what they say. They are counted, there is no goodbye at all, and the connection stays up. Without these two the rule is not measured: a server that closed the connection for everything it does not understand would pass the five above.
On the client side, in rpc_bus: it receives a goodbye in the middle of a call and returns eGoAway with the reason and the message, instead of a drop. And, when it is the one receiving bytes that are not a frame, it is the one that sends the goodbye and closes.
These cases can no longer share a connection. Seven in a row on the same pair measured, from the second one on, a server serving over an already closed transport, and what they claimed to measure stopped happening. Each one now has its own pair.
Two defects the goodbye revealed
Identifier zero was taken for a late response. A goodbye is not a response to any call, and it comes with identifier zero. The rule 1 check (if the identifier is not mine, it is a late response, count it and move on) swallowed the goodbye: the call kept waiting for a response that never comes, until the deadline, and the reason was lost. The goodbye check has to come before the identifier check, and there is a test that requires StaleResponses() == 0 on that path.
**Pump refused to read the last message.** It started by asking IsConnected(), and a transport whose peer has already closed answers no, even while still having the last message in the queue. That last message is precisely the goodbye that explains the closing. Measured: with the question there, the case of the voluntary goodbye returned eNotConnected and the reason never reached anyone. The sender still asks, and should: without a connection there is nowhere to send the request.
The liveness signal, in both directions
In rpc_bus: the outgoing frame is an ePing with an identifier, no method number and an eight-byte token. The pong comes back with the same identifier and the body byte for byte. Two consecutive pings do not carry the same token. And none of this negotiates: Handshakes() and SettingsServed() stay at zero. There is also a fake server that responds with an empty pong, and it is rejected.
And the case that proves the response is automatic: another fake server answers a call with a ping instead of the response. The call has to survive that: the client answers the ping, keeps waiting and receives its response. PingsAnswered() goes up, StaleResponses() stays at zero.
In smoke, over the loopback pair: the server asks, the client answers during a Pump, and the server sees the pong on a later pass through ServeOne, and none of that counts as a request served. Then the reverse, with a thread serving, so that the round trip is real.
Four tests that passed for the wrong reason
The malformed message cases in smoke were written for the old format. With the new frame they all kept passing: the decoder's first check is the magic, and none of those bytes start with ETLR. The test suite stayed green asserting things it was no longer measuring: "rejected before reading the identifier", when what was happening was "this is not even ours".
They were rewritten on the new format, and gained the case the previous design could not have: a flipped bit inside the header, caught by the CRC.
Three defects the tests of these steps caught
The zero that meant the opposite. The cancellation drain was written with ReceiveMessage( …, 0 ) intending to mean "look and come right back". In this interface zero means no limit: the server stood still forever after each method, and the whole test suite hung. There is no value that means "do not wait", and so the drain now waits one millisecond, and only when already late.
The count that did not advance. In the bus, the attempt count lived in the pending record. Each round erased that record and put the message back in the queue, and the next delivery was born with zero. The message retried forever and never reached the dead letter. The count now travels with the delivery.
The test that measured something else. The rule 1 late response case stopped working when deadlines arrived. With a deadline, the server finds out when it finishes that the request is no longer valid and does not send the response, so there is no late response at all to discard. The case was split in two: one with a deadline, which measures the suppression, and another without, which still measures rule 1.
The literal that hung the test suite
When building the slow path request by hand, the measurement kept running forever, only in Debug. The line was this:
BodyWithName.insert( BodyWithName.end(), "soma", "soma" + 4 );Two occurrences of the same literal are not necessarily the same array. String pooling merges the two, and it is on in Release and off in Debug. In Release both pointers were from the same array and the range was valid. In Debug they were from different arrays, the distance between them meant nothing, and insert kept copying until the end of the world.
It is on record because the way it went unnoticed is the interesting part: it passed in Release, which is where the measurements run and therefore where one looks first.
---
---
A deadline expired against a response already arrived: which one wins?
It was not written anywhere, and it was an intermittent failure that forced an answer.
What was seen
A call with a deadline of 1 ms, against a method that sleeps 20 ms, returned eNone: success. Once, in a Debug run with --parallel 8.
At one point it was written in this batch's log that "if confirmed, it is a defect". Raising the test's deadline to 5 ms made it reproducible: three failures in twenty-six runs.
Here the temptation was to run it more times
What answered the question was timing the call, sixty times, with the test suite alongside:
| result | call time |
|---|---|
eTimeout (56 times) | 5.6 to 40.9 ms |
eNone (4 times) | 21.7 / 33.3 / 37.2 / 37.7 ms |
There was never a success below the twenty milliseconds the method sleeps. That rules out the hypothesis that needed ruling out: the deadline is respected in time.
What happens, and why it is not a defect
If the calling thread is starved of processor time, it wakes up with both things true at the same time: the deadline expired and the response in the channel. And the client prefers the response it has in hand.
Throwing away work already done to honor a clock serves no one. Above twenty, one or the other comes out, depending on the order in which the client notices the two things. Below, only the deadline can come out. That is exactly what a race between two observations produces.
What remains
- The policy is written down, in the documentation block of
Call, with the numbers that revealed it. - Anyone who needs the opposite has to enforce it on the other side: with
bSendDeadline, the server finds out when it finishes that it is already past time, and the response never even goes out. That was the way out, and it already existed. - The test now requires the whole policy (either the deadline expires, or it comes back with the response that had already arrived), not just half of it. When the response wins, the released slot case does not apply, and the test says so instead of failing.
- The error code is now always printed, with the call time next to it. The absence of those two pieces of data is what made this question take three rounds to answer.
What is missing
Little, and each item for an explicit reason:
By decision, and with the field already on the wire:
- body compression. The mask travels in the negotiation, goes zeroed on both sides, and the
eCompressedflag is set by no one. TheCompressionmodule is right next to it, still not hooked up. What is missing is deciding from what size it pays off, and that is measured, not guessed. - simultaneous bidirectional streams. There is the downstream one and the upstream one, each complete with a window. True duplex (both running at the same time on the same call) requires the producing side and the consuming side not to be the same thread, and the piece that gives that is multiplexing reaching streams too. That is why
uMaxStreamstravels zeroed.
Because the server can be shared between connections and there is no connection object in which to keep state:
- the limit announced by the client is read and not respected. The server respects its own when responding, which is the same number, but a client that announces a smaller limit is not accommodated.
- the server serves one request at a time per connection. The client's multiplexing puts eight requests in flight, and whoever answers them still answers serially. For the server to overlap requests it needs a reader and a thread pool, and with them
IsCancelledbecomes true in the middle of a method, which is the other half of cancellation.
Because it is the price of a chosen API:
- the client-side lookup of the number by name still compares text. It is the cost of calling the method by
std::stringon every call. It does not leave the process and does not allocate memory. The spec's typed handle (CCall<Req, Resp>) would end this for good, and would bring along code generation this module does not have.
And one allocation per call, from the CWriter the server constructs per request. It is measured, attributed, and belongs to the Serialization module.