relay clients: keep rate-limit retry out of oversized session files

Review follow-up for the first-send-after-community-switch fix.

Desktop: move the OK-frame settle/retry logic from relayClientSession.ts
(already over the file-size ratchet; grew 1084 -> 1129) into a pure
`handlePublishOk` in relayPublishRecovery.ts, taking the pending map and
a send callback. The session file now shrinks to 1078.

Drop the uncorrelated NOTICE retry-all. A `NOTICE rate-limited:` may have
been triggered by a REQ or COUNT, and an ephemeral event (e.g. presence,
kind 20001) the relay already fanned out has no id dedup, so resending
every in-flight publish could double-deliver. Only the correlated
`OK false rate-limited:` is retried; the NOTICE still arms the gate.
The test now asserts NOTICE never resends, and the reset test stubs the
Tauri websocket disconnect so it runs without a stderr TypeError.

Mobile: relay_session.dart tripped the same ratchet (1000 -> 1005). The
classify-then-arm sequence appeared three times, so it becomes
`RelayRateLimitGate.activateIfRateLimited(message)`; the session file
drops to 995. Gate unit test added.

Co-authored-by: Meli <5aaa86bce934fc3445fc254aab560a40923f10252f92107e665073dede0e04d3@buzz.block.builderlab.xyz>
Signed-off-by: Meli <5aaa86bce934fc3445fc254aab560a40923f10252f92107e665073dede0e04d3@buzz.block.builderlab.xyz>
This commit is contained in:
Meli
2026-08-22 21:14:11 -04:00
parent e3a3247b13
commit 43c5dc8d2c
6 changed files with 129 additions and 79 deletions

View File

@@ -34,6 +34,14 @@ Date.now = () => fakeNow;
globalThis.window = {
setTimeout: fakeSetTimeout,
clearTimeout: fakeClearTimeout,
// resetConnection() closes the socket through the Tauri bridge; answer it
// so the test stays quiet and a real warning cannot hide in the noise.
__TAURI_INTERNALS__: {
invoke: async (command) => {
if (command === "plugin:websocket|disconnect") return;
throw new Error(`Unexpected Tauri command: ${command}`);
},
},
};
// Import after the window shim is installed.
@@ -130,22 +138,20 @@ test("a non-rate-limit OK=false still rejects immediately", async () => {
assert.equal(publish.error?.message, "restricted: not a channel member");
});
test("legacy NOTICE rate-limited gives pending publishes the same single retry", async () => {
test("an uncorrelated NOTICE rate-limited arms the gate but never re-sends", async () => {
const { client, sent } = makeClient();
const publish = watch(client.publishEvent(event, "timeout", "send failed"));
await tickTo(0);
// The NOTICE may have been triggered by a REQ or COUNT, and an ephemeral
// event the relay already fanned out would be delivered twice on resend.
await deliver(client, ["NOTICE", RATE_LIMITED]);
await tickTo(0);
assert.equal(publish.settled, false);
assert.equal(sent.length, 1);
assert.equal(isRateLimited(), true, "gate armed from the NOTICE");
assert.equal(publish.settled, false, "NOTICE cannot be attributed; no fail");
// A second uncorrelated NOTICE cannot be attributed to this publish; it must
// neither fail it nor grant a second retry.
await deliver(client, ["NOTICE", RATE_LIMITED]);
await tickTo(3_000);
assert.equal(publish.settled, false);
assert.equal(sent.length, 2, "exactly one resend");
assert.equal(sent.length, 1, "no resend from an uncorrelated NOTICE");
await deliver(client, ["OK", "e1", true, ""]);
await tickTo(3_000);

View File

@@ -38,10 +38,10 @@ import {
} from "@/shared/api/relayClosedRecovery";
import { getChannelReconnectRepairEvents } from "@/shared/api/channelReconnectRepair";
import { replayLiveSubscriptions } from "@/shared/api/relayReconnectReplay";
import { handlePublishOk } from "@/shared/api/relayPublishRecovery";
import {
activateRateLimit,
parseRateLimitHint,
rateLimitRemainingMs,
waitForRateLimit,
} from "@/shared/api/relayRateLimitGate";
import {
@@ -834,49 +834,10 @@ export class RelayClient {
// Relay back-pressure — arm the gate until the window expires.
if (notice.startsWith("rate-limited:")) {
activateRateLimit(parseRateLimitHint(notice));
// Older relays answer an over-quota EVENT with this uncorrelated
// NOTICE instead of `OK false`; the publish would otherwise sit until
// PUBLISH_TIMEOUT_MS. Give every in-flight publish its one retry.
for (const pendingEvent of this.pendingEvents.values()) {
this.retryPublishAfterRateLimit(pendingEvent);
}
}
}
}
/**
* The relay refused an EVENT for back-pressure. Re-send it once the gate
* clears instead of failing the user's send — the burst that tripped the
* limit is typically our own post-(re)connect REQ fan-out, and the relay
* dedups by id so a resend can never double-post. One retry only; a second
* refusal is reported. Returns `false` when no retry is available.
*/
private retryPublishAfterRateLimit(pendingEvent: PendingEvent): boolean {
if (
pendingEvent.retriedAfterRateLimit ||
rateLimitRemainingMs() >= PUBLISH_TIMEOUT_MS
) {
return false;
}
pendingEvent.retriedAfterRateLimit = true;
const { event } = pendingEvent;
void waitForRateLimit().then(async () => {
// Settled meanwhile (timeout, reset, community switch) — nothing to do.
if (this.pendingEvents.get(event.id) !== pendingEvent) return;
try {
await this.sendRaw(["EVENT", event]);
} catch (error) {
if (this.pendingEvents.get(event.id) !== pendingEvent) return;
window.clearTimeout(pendingEvent.timeout);
this.pendingEvents.delete(event.id);
pendingEvent.reject(
this.normalizeRelayError(error, "Failed to re-send event to relay."),
);
}
});
return true;
}
private async handleAuthChallenge(challenge: string, generation: number) {
if (!this.relayUrl) {
this.relayUrl = await getRelayWsUrl();
@@ -951,24 +912,13 @@ export class RelayClient {
return;
}
const pendingEvent = this.pendingEvents.get(eventId);
if (!pendingEvent) {
return;
}
if (!success && message.startsWith("rate-limited:")) {
activateRateLimit(parseRateLimitHint(message));
if (this.retryPublishAfterRateLimit(pendingEvent)) return;
}
window.clearTimeout(pendingEvent.timeout);
this.pendingEvents.delete(eventId);
if (success) {
pendingEvent.resolve(pendingEvent.event);
} else {
pendingEvent.reject(new Error(message || "Relay rejected the event."));
}
handlePublishOk({
pendingEvents: this.pendingEvents,
eventId,
success,
message,
sendEvent: (event) => this.sendRaw(["EVENT", event]),
});
}
private hasLiveSubscriptions() {

View File

@@ -0,0 +1,81 @@
import type { PendingEvent } from "@/shared/api/relayClientShared";
import { PUBLISH_TIMEOUT_MS } from "@/shared/api/relayClientTimings";
import {
activateRateLimit,
parseRateLimitHint,
rateLimitRemainingMs,
waitForRateLimit,
} from "@/shared/api/relayRateLimitGate";
/**
* Settle a pending publish from the relay's `OK` frame.
*
* An `OK false "rate-limited: …"` is not a verdict on the event, only on
* timing: the burst that tripped the limit is typically our own
* post-(re)connect REQ fan-out. Arm the gate and re-send the EVENT once it
* clears instead of failing the user's send. Because the refusal is
* correlated, the relay has not applied the event, so the resend cannot
* double-deliver — unlike an uncorrelated `NOTICE`, which is never retried.
* One retry per publish; a second refusal, or a gate longer than the publish
* timeout, rejects with the relay's reason.
*/
export function handlePublishOk({
pendingEvents,
eventId,
success,
message,
sendEvent,
}: {
pendingEvents: Map<string, PendingEvent>;
eventId: string;
success: boolean;
message: string;
sendEvent: (event: PendingEvent["event"]) => Promise<void>;
}) {
const pendingEvent = pendingEvents.get(eventId);
if (!pendingEvent) return;
if (!success && message.startsWith("rate-limited:")) {
activateRateLimit(parseRateLimitHint(message));
if (
!pendingEvent.retriedAfterRateLimit &&
rateLimitRemainingMs() < PUBLISH_TIMEOUT_MS
) {
pendingEvent.retriedAfterRateLimit = true;
void waitForRateLimit().then(async () => {
// Settled meanwhile (timeout, reset, community switch) — nothing to do.
if (pendingEvents.get(eventId) !== pendingEvent) return;
try {
await sendEvent(pendingEvent.event);
} catch (error) {
if (pendingEvents.get(eventId) !== pendingEvent) return;
settle(pendingEvents, eventId, pendingEvent, () =>
pendingEvent.reject(
error instanceof Error
? error
: new Error("Failed to re-send event to relay."),
),
);
}
});
return;
}
}
settle(pendingEvents, eventId, pendingEvent, () =>
success
? pendingEvent.resolve(pendingEvent.event)
: pendingEvent.reject(new Error(message || "Relay rejected the event.")),
);
}
function settle(
pendingEvents: Map<string, PendingEvent>,
eventId: string,
pendingEvent: PendingEvent,
finish: () => void,
) {
window.clearTimeout(pendingEvent.timeout);
pendingEvents.delete(eventId);
finish();
}

View File

@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:math';
import 'relay_closed_policy.dart';
/// Creates a timer used by [RelayRateLimitGate].
typedef RelayTimerFactory =
Timer Function(Duration duration, void Function() callback);
@@ -47,6 +49,13 @@ class RelayRateLimitGate {
_timer = _timerFactory(duration, _expire);
}
/// Arms the gate from any relay refusal (`CLOSED`, `OK false`, HTTP error)
/// whose message classifies as back-pressure; a no-op otherwise.
void activateIfRateLimited(String message) {
if (classifyRelayClosed(message) != RelayClosedClass.rateLimited) return;
activate(parseRateLimitRetrySeconds(message));
}
/// Resolves when the active rate-limit window expires.
Future<void> wait() {
if (!isActive) return Future.value();

View File

@@ -220,11 +220,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
}
if (decoded is! Map<String, dynamic>) return;
final message = decoded['error'];
if (message is! String ||
classifyRelayClosed(message) != RelayClosedClass.rateLimited) {
return;
}
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
if (message is String) _rateLimitGate.activateIfRateLimited(message);
}
/// Fetch historical events matching [filter]. Sends REQ, collects events
@@ -692,9 +688,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
final historySub = _historySubscriptions.remove(subId);
if (historySub != null) {
if (closedClass == RelayClosedClass.rateLimited) {
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
}
_rateLimitGate.activateIfRateLimited(message);
historySub.timeout.cancel();
if (!historySub.completer.isCompleted) {
historySub.completer.completeError(Exception(message));
@@ -815,11 +809,8 @@ class RelaySessionNotifier extends Notifier<SessionState> {
);
}
} else {
// The relay refused the EVENT for back-pressure: arm the gate so
// concurrent subscribes/publishes back off instead of piling on.
if (classifyRelayClosed(message) == RelayClosedClass.rateLimited) {
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
}
// Back-pressure refusal: arm the gate so concurrent requests back off.
_rateLimitGate.activateIfRateLimited(message);
if (!pending.completer.isCompleted) {
pending.completer.completeError(
Exception(message.isNotEmpty ? message : 'Event rejected'),

View File

@@ -92,6 +92,19 @@ void main() {
expect(timers.single.isActive, isFalse);
expect(gate.isActive, isFalse);
});
test('activateIfRateLimited arms only on a back-pressure message', () {
final gate = RelayRateLimitGate(
now: () => DateTime.utc(2026),
timerFactory: (duration, callback) => _ManualTimer(duration, callback),
);
gate.activateIfRateLimited('restricted: not a channel member');
expect(gate.isActive, isFalse);
gate.activateIfRateLimited('rate-limited: quota exceeded; retry in 3s');
expect(gate.remainingMs(), 3000);
});
}
class _ManualTimer implements Timer {