From 7d21b74d517c34aeb8a362839ecea132c3366669 Mon Sep 17 00:00:00 2001 From: tcheeric Date: Wed, 25 Nov 2026 19:49:01 +0000 Subject: [PATCH] fix(client): send CLOSE when a subscription handle is closed Closing the handle from NostrRelayClient.subscribe(ReqMessage, ...) now drops the listener and sends ["CLOSE", id] once, fire-and-forget. Relays no longer accumulate open REQs until they refuse new ones. The relay's CLOSED reply to a client-initiated CLOSE does not complete an in-flight send(). Raw-JSON subscriptions are unchanged (no parsed id). --- CHANGELOG.md | 7 ++ .../nostr/client/relay/RelaySubscription.java | 7 +- .../springwebsocket/NostrRelayClient.java | 60 +++++++++- ...NostrRelayClientSubscriptionCloseTest.java | 113 ++++++++++++++++++ 4 files changed, 182 insertions(+), 5 deletions(-) create mode 100644 nostr-java-client/src/test/java/nostr/client/springwebsocket/NostrRelayClientSubscriptionCloseTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index f4d20ac5..d8c28972 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ The format is inspired by Keep a Changelog, and this project adheres to semantic ## [Unreleased] +### Fixed +- Closing a subscription handle from `NostrRelayClient.subscribe(ReqMessage, ...)` (and so + `RelaySubscription.close()`) now sends `["CLOSE", ]` to the relay, once, fire-and-forget. + Previously only the local listener was dropped, so relays accumulated open REQs until they + refused new ones (`too many concurrent REQs`). The relay's `CLOSED` reply no longer ends an + in-flight `send()`. Raw-JSON subscriptions still send no CLOSE, since their id is not parsed. + ## [2.4.2] - 2026-10-04 ### Fixed diff --git a/nostr-java-client/src/main/java/nostr/client/relay/RelaySubscription.java b/nostr-java-client/src/main/java/nostr/client/relay/RelaySubscription.java index cb17fba2..9d9a1d5c 100644 --- a/nostr-java-client/src/main/java/nostr/client/relay/RelaySubscription.java +++ b/nostr-java-client/src/main/java/nostr/client/relay/RelaySubscription.java @@ -197,10 +197,9 @@ private void reportRelayFailure(String relayUri, Throwable failure) { /** * Stop this subscription, dropping its listener on every relay. * - *

No {@code CLOSE} is sent to the relays. A connection serves one request at a time, so - * sending one would consume the slot the next subscription needs and leave that subscription - * receiving nothing. The relay stops streaming when the connection closes, and an unread - * subscription on a still-open connection is the lesser cost. + *

Each relay handle sends {@code ["CLOSE", id]} when closed, so the relay frees the REQ. + * The CLOSE is written fire-and-forget, outside the connection's single request slot, so it + * does not take the slot the next subscription or request on that connection needs. */ @Override public void close() { diff --git a/nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java b/nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java index a4f80a11..0758013d 100644 --- a/nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java +++ b/nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java @@ -4,6 +4,7 @@ import lombok.extern.slf4j.Slf4j; import nostr.client.relay.RelayConnection; import nostr.event.BaseMessage; +import nostr.event.message.CloseMessage; import nostr.event.message.ReqMessage; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.BeanDefinition; @@ -29,6 +30,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -38,6 +40,7 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -134,6 +137,11 @@ public class NostrRelayClient extends TextWebSocketHandler private final ReentrantReadWriteLock sessionGate = new ReentrantReadWriteLock(); private PendingRequest pendingRequest; private final Map listeners = new ConcurrentHashMap<>(); + /** + * Subscription ids this client sent a CLOSE for and whose CLOSED reply has not arrived yet. + * That reply must not end an unrelated in-flight {@link #send(String)}. + */ + private final Set subscriptionsClosedByClient = ConcurrentHashMap.newKeySet(); private final AtomicReference connectionState = new AtomicReference<>(ConnectionState.CONNECTING); @@ -423,6 +431,9 @@ public ConnectionState getConnectionState() { protected void handleTextMessage(@NonNull WebSocketSession session, TextMessage message) { log.debug("Relay payload received: {}", message.getPayload()); dispatchMessage(message.getPayload()); + if (isReplyToClientClose(message.getPayload())) { + return; + } sendLock.lock(); try { if (pendingRequest != null && !pendingRequest.isDone()) { @@ -437,6 +448,14 @@ protected void handleTextMessage(@NonNull WebSocketSession session, TextMessage } } + private boolean isReplyToClientClose(String payload) { + if (payload == null || !payload.startsWith("[\"CLOSED\"")) { + return false; + } + String subscriptionId = subscriptionIdOf(payload); + return subscriptionId != null && subscriptionsClosedByClient.remove(subscriptionId); + } + private boolean isTerminationMessage(String payload) { if (payload == null || payload.length() < 2) { return false; @@ -609,6 +628,8 @@ public AutoCloseable subscribe( throws IOException { // No subscription id to route on: the raw JSON is not parsed here, so this // listener keeps receiving every payload on the connection, as before. + // For the same reason its handle sends no CLOSE: guessing the id from + // unvalidated JSON could close somebody else's subscription. return subscribe(requestJson, null, messageListener, errorListener, closeListener); } @@ -647,7 +668,43 @@ private AutoCloseable subscribe( throw new IOException("Failed to send subscription payload", e); } - return () -> listeners.remove(listenerId); + return subscriptionHandle(listenerId, subscriptionId); + } + + /** + * The handle returned by {@code subscribe}. Closing it drops the listener and, when the + * subscription id is known, sends {@code ["CLOSE", id]} so the relay frees the REQ (NIP-01). + * + *

The CLOSE is fire-and-forget: it is written straight to the session and never claims the + * single in-flight {@link #send(String)} slot, so it cannot block or consume the slot the next + * request on this connection needs. The relay's {@code CLOSED} reply is routed by id to the + * already-removed listener and is kept from completing an in-flight request. + * + *

Raw-JSON subscriptions have no parsed id, so their handle only drops the listener. + * Closing twice sends a single CLOSE. + */ + private AutoCloseable subscriptionHandle(String listenerId, String subscriptionId) { + AtomicBoolean closed = new AtomicBoolean(); + return () -> { + if (!closed.compareAndSet(false, true)) { + return; + } + listeners.remove(listenerId); + if (subscriptionId != null) { + sendCloseQuietly(subscriptionId); + } + }; + } + + private void sendCloseQuietly(String subscriptionId) { + subscriptionsClosedByClient.add(subscriptionId); + try { + sendFrameGated(new CloseMessage(subscriptionId).encode()); + } catch (IOException | RuntimeException e) { + subscriptionsClosedByClient.remove(subscriptionId); + log.debug("Could not send CLOSE for subscription {} on relay {}: {}", + subscriptionId, relayUri, e.getMessage()); + } } /** @@ -931,6 +988,7 @@ private void notifyClose() { listener -> LISTENER_EXECUTOR.execute(() -> safelyInvoke(listener.closeListener(), listener))); listeners.clear(); + subscriptionsClosedByClient.clear(); } private void safelyInvoke(Consumer consumer, String payload, ListenerRegistration listener) { diff --git a/nostr-java-client/src/test/java/nostr/client/springwebsocket/NostrRelayClientSubscriptionCloseTest.java b/nostr-java-client/src/test/java/nostr/client/springwebsocket/NostrRelayClientSubscriptionCloseTest.java new file mode 100644 index 00000000..53ac7b53 --- /dev/null +++ b/nostr-java-client/src/test/java/nostr/client/springwebsocket/NostrRelayClientSubscriptionCloseTest.java @@ -0,0 +1,113 @@ +package nostr.client.springwebsocket; + +import nostr.event.message.ReqMessage; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketMessage; +import org.springframework.web.socket.WebSocketSession; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Closing a subscription handle must tell the relay, or relays accumulate open REQs until they + * refuse new ones ("too many concurrent REQs"). + */ +class NostrRelayClientSubscriptionCloseTest { + + private static WebSocketSession openSession() { + WebSocketSession session = Mockito.mock(WebSocketSession.class); + Mockito.when(session.isOpen()).thenReturn(true); + return session; + } + + private static List sentFrames(WebSocketSession session) throws IOException { + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(WebSocketMessage.class); + Mockito.verify(session, Mockito.atLeastOnce()).sendMessage(captor.capture()); + return captor.getAllValues().stream().map(m -> ((TextMessage) m).getPayload()).toList(); + } + + // Closing a typed subscription handle twice sends exactly one CLOSE for its id. + @Test + void closingTheHandleSendsExactlyOneClose() throws Exception { + WebSocketSession session = openSession(); + try (NostrRelayClient client = new NostrRelayClient(session, 1_000)) { + AutoCloseable handle = client.subscribe(new ReqMessage("sub-1"), p -> {}, t -> {}, null); + + handle.close(); + handle.close(); + + List closes = + sentFrames(session).stream().filter(f -> f.startsWith("[\"CLOSE\"")).toList(); + assertEquals(List.of("[\"CLOSE\",\"sub-1\"]"), closes); + } + } + + // A raw-JSON subscription has no parsed id, so closing its handle sends no CLOSE. + @Test + void closingARawJsonSubscriptionSendsNoClose() throws Exception { + WebSocketSession session = openSession(); + try (NostrRelayClient client = new NostrRelayClient(session, 1_000)) { + AutoCloseable handle = client.subscribe("[\"REQ\",\"raw\",{}]", p -> {}, t -> {}, null); + + handle.close(); + + assertTrue(sentFrames(session).stream().noneMatch(f -> f.startsWith("[\"CLOSE\""))); + } + } + + // Closing a handle after the session closed only logs, it never throws. + @Test + void closingAfterTheSessionClosedDoesNotThrow() throws Exception { + WebSocketSession session = openSession(); + try (NostrRelayClient client = new NostrRelayClient(session, 1_000)) { + AutoCloseable handle = client.subscribe(new ReqMessage("sub-1"), p -> {}, t -> {}, null); + Mockito.when(session.isOpen()).thenReturn(false); + + assertDoesNotThrow(handle::close); + } + } + + // Subscribe, close, subscribe again on one connection: the second subscription still gets + // its events, and the relay's CLOSED reply to the first does not end a following request. + @Test + void backToBackSubscriptionsOnOneConnectionStillDeliverEvents() throws Exception { + WebSocketSession session = openSession(); + try (NostrRelayClient client = new NostrRelayClient(session, 1_000)) { + List seenByFirst = new CopyOnWriteArrayList<>(); + List seenBySecond = new CopyOnWriteArrayList<>(); + + AutoCloseable first = + client.subscribe(new ReqMessage("sub-1"), seenByFirst::add, t -> {}, null); + first.close(); + AutoCloseable second = + client.subscribe(new ReqMessage("sub-2"), seenBySecond::add, t -> {}, null); + + client.handleTextMessage(session, new TextMessage("[\"CLOSED\",\"sub-1\",\"\"]")); + String event = "[\"EVENT\",\"sub-2\",{\"id\":\"e1\",\"kind\":1,\"content\":\"hi\"}]"; + client.handleTextMessage(session, new TextMessage(event)); + client.handleTextMessage(session, new TextMessage("[\"EOSE\",\"sub-2\"]")); + + await().atMost(2, TimeUnit.SECONDS).until(() -> seenBySecond.size() >= 2); + assertEquals(List.of(event, "[\"EOSE\",\"sub-2\"]"), seenBySecond); + assertTrue(seenByFirst.isEmpty(), "a closed subscription must receive nothing"); + second.close(); + + assertEquals( + List.of( + "[\"REQ\",\"sub-1\"]", "[\"CLOSE\",\"sub-1\"]", + "[\"REQ\",\"sub-2\"]", "[\"CLOSE\",\"sub-2\"]"), + sentFrames(session)); + } + } +}