Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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", <id>]` 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,9 @@ private void reportRelayFailure(String relayUri, Throwable failure) {
/**
* Stop this subscription, dropping its listener on every relay.
*
* <p>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.
* <p>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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -134,6 +137,11 @@ public class NostrRelayClient extends TextWebSocketHandler
private final ReentrantReadWriteLock sessionGate = new ReentrantReadWriteLock();
private PendingRequest pendingRequest;
private final Map<String, ListenerRegistration> 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<String> subscriptionsClosedByClient = ConcurrentHashMap.newKeySet();
private final AtomicReference<ConnectionState> connectionState =
new AtomicReference<>(ConnectionState.CONNECTING);

Expand Down Expand Up @@ -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()) {
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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).
*
* <p>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.
*
* <p>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());
}
}

/**
Expand Down Expand Up @@ -931,6 +988,7 @@ private void notifyClose() {
listener ->
LISTENER_EXECUTOR.execute(() -> safelyInvoke(listener.closeListener(), listener)));
listeners.clear();
subscriptionsClosedByClient.clear();
}

private void safelyInvoke(Consumer<String> consumer, String payload, ListenerRegistration listener) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> sentFrames(WebSocketSession session) throws IOException {
@SuppressWarnings("unchecked")
ArgumentCaptor<WebSocketMessage<?>> 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<String> 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<String> seenByFirst = new CopyOnWriteArrayList<>();
List<String> 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));
}
}
}