Say when a vault has moved, so nobody waits out the minute

The delta pull was cheap enough to run on a timer and the client did, once a
minute. That is fine for a machine and wrong for two people: an edit a colleague
makes is up to a minute stale, which is long enough for both of them to make it
and produce a conflict neither needed to have. Shortening the interval is the
obvious answer and the wrong one — it costs a request per client per interval
whether or not anything happened, and it converges on a busier server that is
still late.

So the server now says so. A client holds a WebSocket open at GET /api/v1/events,
subprotocol dodossh.events.v1, and gets a line down it when something it can read
has changed. ADR 0012 has the reasoning; three parts of it are worth repeating
here, because they are what everything else rests on.

**What crosses the socket is a notice, never data.** A frame names a vault and
how far its change log has got. No item, no ciphertext, not even which item it
was. The client's answer is the delta pull it would have run anyway, so there is
still exactly one code path that applies a change to a keychain, and it is not
this one. Pushing the items themselves would save a round trip and fork that path
in two, with the cursor, the merge and the tombstone rules duplicated across both
— ADR 0003 put every mutation through one write path for that reason, and this
keeps every read on one for the same one. It also makes a dropped notice
harmless, which is what lets the fan-out below be as simple as it is.

**Polling stays, and is what guarantees a pass.** The minute timer is unchanged.
A network that eats WebSockets, a server with Events:Enabled off, an older
server, a proxy that will not upgrade, a notice dropped under backpressure —
every one of those leaves a client behaving exactly as it did before this commit.
Nothing is reachable only over the socket and nothing is meant to become so;
VaultViewModel's AutoSyncInterval remark now says that where somebody changing it
will read it.

**The bearer token authorises the upgrade, unlike the relay's ticket.** Not an
inconsistency with ADR 0004: the relay's socket is a byte pipe whose whole
authorization decision — which host, which IPs, which port — is made before it
opens and never revisited, and it is the extraction seam for a process that must
hold no ACL code. This one is a view of the caller's own vault list and has to
keep answering "what may this account read" for as long as it is held. A ticket
would carry that answer in a token and be wrong the moment the account's access
changed. The two bounds that arrangement needs are met rather than waved at: the
socket is closed at the token's exp with close code 4401 and the client comes
straight back with a fresh one, and the vault set is re-resolved every few
minutes as well as on the changes known to affect it. Both bound *metadata*,
because a notice contains nothing else and reading a vault still needs a key this
server has never held.

**The fan-out.** VaultEventHub is a singleton holding the sockets this node
accepted; publishing walks them and asks each whether it cares, rather than
keeping a vault-to-subscriber index that every re-subscription would have to move
entries between under a lock publishing also takes. At a few hundred sockets per
node and an event rate bounded by how often people edit keychains, the walk is
not measurable and its races are obvious. Per-connection queues are bounded and
drop the *oldest*: a notice means "pull vault X, which is at least at sequence
N", so the newest subsumes what it displaces and the client's answer is identical
either way — which is what lets the publish path be void, never block, and never
fail.

Announced from the endpoint rather than from SyncService, and that placement is
the point: by then the push has committed and released the per-vault advisory
lock. From inside it would name a sequence no reader can see yet and would hold
the lock that serialises writers across a socket write. Only the highest
*applied* sequence, so a batch of pure conflicts announces nothing, and a
duplicate — already announced when it first landed — announces nothing either.

Grants and membership publish too, and those take the *recipient* rather than the
actor. This is what AdmitNewVaultsAsync has been apologising for since sharing
shipped — "the recipient is handed nothing, there is no push channel" — and the
README with it. A vault shared with somebody now turns up as it is shared. The
comment and the README paragraph both say what is true now, and both keep saying
that the pass is what *discovers* the vault, because a client with no socket has
to arrive at the same place.

**On the client**, VaultEventStream is really a reconnection policy wrapped round
a ClientWebSocket: a dropped socket is the ordinary case here — laptops sleep,
proxies time out, tokens expire, servers are redeployed — so nothing in it treats
a failure as exceptional, and every path ends in "wait, then dial again". A
connection that lived long enough to say hello resets the backoff, so a laptop
that woke, worked, and lost its network an hour later does not inherit a
minute-long wait it has already proved it need not take. A 4401 close skips the
backoff entirely and asks the token provider again, which is the whole reason
that close code is distinct. A server that does not advertise the events feature
gets IdleVaultEventStream, which never delivers — so IVaultServer.Events is never
null and every caller stays on one shape, because the correct behaviour without a
socket is the behaviour with a silent one.

The shell's background loop now selects between the timer and a notice, and both
waits are held across iterations. That is load-bearing rather than tidy:
PeriodicTimer permits one outstanding WaitForNextTickAsync and throws on a
second, and an abandoned channel read stays registered and consumes the next
notice written. Either defect leaves the first notice working and every one after
it silently lost, which is why NoticesKeepWakingTheLoop_NotJustTheFirst pushes
three and not one. Notices are coalesced over a quarter of a second, so one
person's save — a host and its log entry are two items — and a colleague clearing
a folder each cost one pass rather than a dozen.

**The kind is a string, not an enum**, and that is a compatibility decision.
UseStringEnumConverter throws on a value it does not know, so a newer server
sending a kind an older client had never heard of would not add an unreadable
frame — it would break that client's socket outright. A string is ignored
instead. ProblemCodes is the same shape for the same reason.

**Tested on both sides, through the real pipeline.** The endpoint suite opens a
genuine socket against TestServer and proves a push produces a notice, that
another account's push does not reach it, that a ping is answered, and that a
frame this server cannot parse does not end the connection. Two of those assert
on *ordering* rather than on absence within a timeout — the stranger's write goes
first, so a socket that leaked would have announced it before the one the test
waits for — because "nothing arrived in two seconds" is a test that passes on a
slow machine for the wrong reason. And ANoticeCarriesNoCiphertext asserts on the
bytes that crossed the wire rather than on the record's fields, since the latter
would only prove that this type has no payload member, which is a tautology; the
former is what catches a field added later without anybody thinking about
disclosure.

The client suite drives VaultEventStream through an injected connector, because
the one thing a test cannot do to a real network is make it fail on cue — and
failure is the entire subject. The shell suite proves a notice produces a pull
inside ten seconds against a sixty-second timer, so the timer cannot be what
caused it.

**Two limits, stated rather than left to be discovered.** Fan-out is in-process,
so a deployment running more than one API replica only pushes for writes its own
replica handled and the rest arrive on the timer. IVaultEventPublisher is the
seam a PostgreSQL LISTEN/NOTIFY backplane implements and it is deliberately not
implemented: an untested backplane is worse than a documented gap, and multiple
replicas degrade to the behaviour before this commit rather than breaking. And a
client is notified of its own writes; it pushed, so it already pulled, and the
extra pass finds nothing. Suppressing that echo correctly needs a per-device
identity on the socket, and the same user's other machines must still be told.

Manual checks phase 15 covers what no test here can reach, which is the network
in between: a proxy that will not upgrade, one that drops an idle socket without
telling either end, a laptop lid, a token expiring. Every one of those is
invisible inside a test host, and every check there passes only if the change
arrives quickly *and* still arrives with the socket taken away.

ADR 0012 also fixes one thing about the shared terminal session this is the
transport for, so it need not be renegotiated later: session data will be binary
frames on this same socket, because base64 in a JSON envelope is the wrong shape
for the one payload here that is continuous rather than occasional. Two questions
it explicitly does not answer by implication — whether those bytes go through the
API at all, and what end-to-end encryption means when the second party watches a
stream rather than holding a key — are ADR 0001 questions and get their own
decision.

1512 tests pass. DodoSSH.SystemTests was not run — it needs the whole compose
stack — so the end-to-end path is unverified for this change beyond what the
manual checks describe.
This commit is contained in:
2026-08-04 16:37:41 +02:00
parent 176df67861
commit 4b706bc3c3
31 changed files with 3285 additions and 13 deletions
@@ -66,6 +66,11 @@ namespace DodoSSH.Contracts;
// Registered in its own right, not only as a member of the sync DTOs: the client's local
// cache seals this record under the LocalCacheKey and needs its type info directly.
[JsonSerializable(typeof(SyncPlaintextFields))]
// The event socket's only frame type. Registered although nothing else references it: frames are
// written straight onto a WebSocket rather than through a response body, so the resolver never
// infers it from an endpoint's signature the way it does for every DTO above.
[JsonSerializable(typeof(VaultEvent))]
[JsonSerializable(typeof(RelayTicketRequest))]
[JsonSerializable(typeof(RelayTicketResponse))]
[JsonSerializable(typeof(RelaySessionSummary))]
+134
View File
@@ -0,0 +1,134 @@
namespace DodoSSH.Contracts;
/// <summary>
/// The event socket's protocol constants.
/// </summary>
/// <remarks>
/// The version lives in the subprotocol name rather than in the URL, for the reason ADR 0002 gives
/// about the rest of this API: a client and a server that upgrade independently have to agree by
/// negotiating rather than by assuming, and a WebSocket handshake already has a field for exactly
/// that. A server that does not offer <see cref="SubProtocol"/> fails the handshake, which a client
/// can act on — rather than opening a socket that then speaks a dialect it cannot read.
/// </remarks>
public static class VaultEvents
{
/// <summary>The path the event socket is served from.</summary>
public const string Path = "/api/v1/events";
/// <summary>The only subprotocol this version speaks.</summary>
public const string SubProtocol = "dodossh.events.v1";
/// <summary>The <c>/api/v1/meta</c> feature flag advertising that this server pushes at all.</summary>
public const string Feature = "events";
/// <summary>
/// Close code for a socket whose access token has expired.
/// </summary>
/// <remarks>
/// In the 40004999 range, which the WebSocket specification reserves for applications. Its own
/// code because it is the one close a client should answer by reconnecting immediately with a
/// fresh token, rather than by backing off as it would for a server that went away.
/// </remarks>
public const int TokenExpiredCloseCode = 4401;
/// <summary>
/// Close code for a caller already holding as many sockets as it may.
/// </summary>
/// <remarks>
/// Distinguished from <see cref="TokenExpiredCloseCode"/> because the remedy is the opposite:
/// reconnecting at once is what caused it. A client that meets this backs off and keeps polling.
/// </remarks>
public const int TooManyConnectionsCloseCode = 4429;
}
/// <summary>
/// The kinds of event this socket carries.
/// </summary>
/// <remarks>
/// <para>
/// Constants rather than an <c>enum</c>, and that is a compatibility decision rather than a style
/// one. <c>DodoSshJsonContext</c> sets <c>UseStringEnumConverter</c>, which <em>throws</em> on a
/// value it does not know — so a newer server sending a kind an older client has never heard of
/// would not merely add an unreadable frame, it would break that client's socket. A string is
/// ignored instead, which is what makes this list extensible. <see cref="ProblemCodes"/> is the same
/// shape for the same reason.
/// </para>
/// <para>
/// <b>Anything a client cannot parse must be skipped, not treated as an error.</b> That rule is what
/// the shared-session frames of ADR 0012 will rely on when they arrive.
/// </para>
/// </remarks>
public static class VaultEventKinds
{
/// <summary>The server accepted the socket. Always the first frame.</summary>
public const string Hello = "hello";
/// <summary>
/// A vault has changes at or before <see cref="VaultEvent.Sequence"/>.
/// </summary>
/// <remarks>
/// Carries no ciphertext and no item identity — the client's answer is the delta pull it would
/// have run on its timer anyway. See ADR 0012 for why pushing the items themselves is refused.
/// </remarks>
public const string VaultChanged = "vault.changed";
/// <summary>
/// The set of vaults this account can reach is no longer what it was.
/// </summary>
/// <remarks>
/// A vault shared with the caller, or a grant withdrawn. Deliberately says nothing about
/// <em>which</em>: the client re-reads the list, which is the same call it already makes at the
/// start of every synchronisation pass.
/// </remarks>
public const string VaultsChanged = "vaults.changed";
/// <summary>Heartbeat. Whichever side receives one answers <see cref="Pong"/>.</summary>
public const string Ping = "ping";
/// <summary>The answer to a <see cref="Ping"/>.</summary>
public const string Pong = "pong";
}
/// <summary>
/// One frame on the event socket.
/// </summary>
/// <remarks>
/// <para>
/// One flat record for every kind, with the fields a given kind does not use left null, rather than
/// a polymorphic hierarchy. The set is small, the frames are tiny, and <c>System.Text.Json</c>
/// polymorphism would put a second discriminator mechanism next to the <see cref="Kind"/> string
/// that is already the discriminator. Nothing else in <c>DodoSSH.Contracts</c> is polymorphic.
/// </para>
/// <para>
/// <b>Nothing here is secret, by construction.</b> The server cannot read a vault's contents, so a
/// notice cannot describe them; what it does disclose — that a vault changed, and when — is the same
/// metadata ADR 0001 already accepts the server holding.
/// </para>
/// </remarks>
/// <param name="Kind">One of <see cref="VaultEventKinds"/>. An unrecognised kind must be ignored.</param>
/// <param name="VaultId">The vault a <see cref="VaultEventKinds.VaultChanged"/> is about.</param>
/// <param name="Sequence">
/// The change-log position that vault has reached. A hint for logging and for coalescing, not a
/// cursor: cursors are opaque and HMAC-tagged, and this is neither.
/// </param>
/// <param name="ServerTime">
/// The server's clock when the frame was written. The client already measures skew against
/// <c>SyncPullResponse.ServerTime</c>; this lets a socket that is quiet for other reasons keep that
/// measurement current.
/// </param>
/// <param name="HeartbeatSeconds">
/// How often the server will ping, sent with <see cref="VaultEventKinds.Hello"/>. The client uses it
/// to decide when silence means the connection is dead rather than idle.
/// </param>
/// <param name="VaultCount">
/// How many vaults this socket is subscribed to, sent with <see cref="VaultEventKinds.Hello"/>.
/// Diagnostic: a socket subscribed to nothing is a real state — an account with no vaults yet — and
/// is otherwise indistinguishable from one that is quietly broken.
/// </param>
public sealed record VaultEvent(
string Kind,
Guid? VaultId = null,
long? Sequence = null,
DateTimeOffset? ServerTime = null,
int? HeartbeatSeconds = null,
int? VaultCount = null);
+10
View File
@@ -66,6 +66,16 @@ public static class ProblemCodes
/// </remarks>
public const string MalformedRequest = "malformed-request";
/// <summary>
/// This deployment does not push vault changes over a socket.
/// </summary>
/// <remarks>
/// Not a failure to recover from: synchronising on a timer is the supported behaviour and the
/// socket only ever made it early. A client that meets this stops dialling and keeps polling. See
/// ADR 0012.
/// </remarks>
public const string EventsUnavailable = "events-unavailable";
/// <summary>The relay refused the requested target. Never states why, to avoid a probe oracle.</summary>
public const string RelayTargetRejected = "relay-target-rejected";
@@ -2,6 +2,7 @@
const DodoSSH.Contracts.ProblemCodes.AlreadyEnrolled = "already-enrolled" -> string!
const DodoSSH.Contracts.ProblemCodes.ClientTooOld = "client-too-old" -> string!
const DodoSSH.Contracts.ProblemCodes.EnrollmentRequired = "enrollment-required" -> string!
const DodoSSH.Contracts.ProblemCodes.EventsUnavailable = "events-unavailable" -> string!
const DodoSSH.Contracts.ProblemCodes.Forbidden = "forbidden" -> string!
const DodoSSH.Contracts.ProblemCodes.IdempotencyKeyReuse = "idempotency-key-reuse" -> string!
const DodoSSH.Contracts.ProblemCodes.IdentityBindingInvalid = "identity-binding-invalid" -> string!
@@ -22,6 +23,16 @@ const DodoSSH.Contracts.ProblemCodes.TeamNotEmpty = "team-not-empty" -> string!
const DodoSSH.Contracts.ProblemCodes.TeamSlugTaken = "team-slug-taken" -> string!
const DodoSSH.Contracts.ProblemCodes.TypeBaseUri = "https://dodossh.dev/problems/" -> string!
const DodoSSH.Contracts.ProblemCodes.VaultConflict = "vault-conflict" -> string!
const DodoSSH.Contracts.VaultEventKinds.Hello = "hello" -> string!
const DodoSSH.Contracts.VaultEventKinds.Ping = "ping" -> string!
const DodoSSH.Contracts.VaultEventKinds.Pong = "pong" -> string!
const DodoSSH.Contracts.VaultEventKinds.VaultChanged = "vault.changed" -> string!
const DodoSSH.Contracts.VaultEventKinds.VaultsChanged = "vaults.changed" -> string!
const DodoSSH.Contracts.VaultEvents.Feature = "events" -> string!
const DodoSSH.Contracts.VaultEvents.Path = "/api/v1/events" -> string!
const DodoSSH.Contracts.VaultEvents.SubProtocol = "dodossh.events.v1" -> string!
const DodoSSH.Contracts.VaultEvents.TokenExpiredCloseCode = 4401 -> int
const DodoSSH.Contracts.VaultEvents.TooManyConnectionsCloseCode = 4429 -> int
DodoSSH.Contracts.AddTeamMemberRequest
DodoSSH.Contracts.AddTeamMemberRequest.<Clone>$() -> DodoSSH.Contracts.AddTeamMemberRequest!
DodoSSH.Contracts.AddTeamMemberRequest.AddTeamMemberRequest(System.Guid UserId, DodoSSH.Contracts.TeamMemberRole Role, string? Email = null) -> void
@@ -686,6 +697,25 @@ DodoSSH.Contracts.UpdateVaultRequest.Equals(DodoSSH.Contracts.UpdateVaultRequest
DodoSSH.Contracts.UpdateVaultRequest.Name.get -> string!
DodoSSH.Contracts.UpdateVaultRequest.Name.init -> void
DodoSSH.Contracts.UpdateVaultRequest.UpdateVaultRequest(string! Name) -> void
DodoSSH.Contracts.VaultEvent
DodoSSH.Contracts.VaultEvent.<Clone>$() -> DodoSSH.Contracts.VaultEvent!
DodoSSH.Contracts.VaultEvent.Deconstruct(out string! Kind, out System.Guid? VaultId, out long? Sequence, out System.DateTimeOffset? ServerTime, out int? HeartbeatSeconds, out int? VaultCount) -> void
DodoSSH.Contracts.VaultEvent.Equals(DodoSSH.Contracts.VaultEvent? other) -> bool
DodoSSH.Contracts.VaultEvent.HeartbeatSeconds.get -> int?
DodoSSH.Contracts.VaultEvent.HeartbeatSeconds.init -> void
DodoSSH.Contracts.VaultEvent.Kind.get -> string!
DodoSSH.Contracts.VaultEvent.Kind.init -> void
DodoSSH.Contracts.VaultEvent.Sequence.get -> long?
DodoSSH.Contracts.VaultEvent.Sequence.init -> void
DodoSSH.Contracts.VaultEvent.ServerTime.get -> System.DateTimeOffset?
DodoSSH.Contracts.VaultEvent.ServerTime.init -> void
DodoSSH.Contracts.VaultEvent.VaultCount.get -> int?
DodoSSH.Contracts.VaultEvent.VaultCount.init -> void
DodoSSH.Contracts.VaultEvent.VaultEvent(string! Kind, System.Guid? VaultId = null, long? Sequence = null, System.DateTimeOffset? ServerTime = null, int? HeartbeatSeconds = null, int? VaultCount = null) -> void
DodoSSH.Contracts.VaultEvent.VaultId.get -> System.Guid?
DodoSSH.Contracts.VaultEvent.VaultId.init -> void
DodoSSH.Contracts.VaultEventKinds
DodoSSH.Contracts.VaultEvents
DodoSSH.Contracts.VaultGrantsResponse
DodoSSH.Contracts.VaultGrantsResponse.<Clone>$() -> DodoSSH.Contracts.VaultGrantsResponse!
DodoSSH.Contracts.VaultGrantsResponse.Deconstruct(out System.Guid VaultId, out uint KeyGeneration, out bool RekeyRequired, out System.Collections.Generic.IReadOnlyList<DodoSSH.Contracts.VaultGrantSummary!>! Grants) -> void
@@ -877,6 +907,9 @@ override DodoSSH.Contracts.UpdateTeamRequest.ToString() -> string!
override DodoSSH.Contracts.UpdateVaultRequest.Equals(object? obj) -> bool
override DodoSSH.Contracts.UpdateVaultRequest.GetHashCode() -> int
override DodoSSH.Contracts.UpdateVaultRequest.ToString() -> string!
override DodoSSH.Contracts.VaultEvent.Equals(object? obj) -> bool
override DodoSSH.Contracts.VaultEvent.GetHashCode() -> int
override DodoSSH.Contracts.VaultEvent.ToString() -> string!
override DodoSSH.Contracts.VaultGrantsResponse.Equals(object? obj) -> bool
override DodoSSH.Contracts.VaultGrantsResponse.GetHashCode() -> int
override DodoSSH.Contracts.VaultGrantsResponse.ToString() -> string!
@@ -972,6 +1005,8 @@ static DodoSSH.Contracts.UpdateTeamRequest.operator !=(DodoSSH.Contracts.UpdateT
static DodoSSH.Contracts.UpdateTeamRequest.operator ==(DodoSSH.Contracts.UpdateTeamRequest? left, DodoSSH.Contracts.UpdateTeamRequest? right) -> bool
static DodoSSH.Contracts.UpdateVaultRequest.operator !=(DodoSSH.Contracts.UpdateVaultRequest? left, DodoSSH.Contracts.UpdateVaultRequest? right) -> bool
static DodoSSH.Contracts.UpdateVaultRequest.operator ==(DodoSSH.Contracts.UpdateVaultRequest? left, DodoSSH.Contracts.UpdateVaultRequest? right) -> bool
static DodoSSH.Contracts.VaultEvent.operator !=(DodoSSH.Contracts.VaultEvent? left, DodoSSH.Contracts.VaultEvent? right) -> bool
static DodoSSH.Contracts.VaultEvent.operator ==(DodoSSH.Contracts.VaultEvent? left, DodoSSH.Contracts.VaultEvent? right) -> bool
static DodoSSH.Contracts.VaultGrantsResponse.operator !=(DodoSSH.Contracts.VaultGrantsResponse? left, DodoSSH.Contracts.VaultGrantsResponse? right) -> bool
static DodoSSH.Contracts.VaultGrantsResponse.operator ==(DodoSSH.Contracts.VaultGrantsResponse? left, DodoSSH.Contracts.VaultGrantsResponse? right) -> bool
static DodoSSH.Contracts.VaultGrantSummary.operator !=(DodoSSH.Contracts.VaultGrantSummary? left, DodoSSH.Contracts.VaultGrantSummary? right) -> bool