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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ The format is inspired by Keep a Changelog, and this project adheres to semantic

## [Unreleased]

## [2.4.3] - 2026-11-25

### 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
2 changes: 1 addition & 1 deletion docs/howto/multi-relay-publishing.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ send a private direct message.
<dependency>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java-api</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
</dependency>
```

Expand Down
2 changes: 1 addition & 1 deletion nostr-java-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<parent>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion nostr-java-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<parent>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
this.deliveredEvents = new DeliveredEventWindow(deduplicationWindowSize);
}

/**

Check warning on line 58 in nostr-java-client/src/main/java/nostr/client/relay/RelaySubscription.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Lombok @Getter may be used

Field 'subscriptionId' may have Lombok @Getter
* The identifier relays see for this subscription.
*
* @return the subscription identifier
Expand Down Expand Up @@ -188,7 +188,7 @@
if (closed.get()) {
return;
}
handlesByRelay.remove(relayUri);

Check warning on line 191 in nostr-java-client/src/main/java/nostr/client/relay/RelaySubscription.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

AutoCloseable used without 'try'-with-resources

'AutoCloseable' used without 'try'-with-resources statement
relaysAwaitingBacklog.remove(relayUri);
listener.onRelayFailure(relayUri, failure);
announceEndOfStoredEventsIfComplete();
Expand All @@ -197,10 +197,9 @@
/**
* 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 @@ -95,7 +98,7 @@
private long maxIdleTimeoutMs;

@Value("${nostr.websocket.max-events-per-request:10000}")
private int maxEventsPerRequest = DEFAULT_MAX_EVENTS_PER_REQUEST;

Check warning on line 101 in nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Field can be local variable

Field can be converted to a local variable

Check warning on line 101 in nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Field may be 'final'

Field `maxEventsPerRequest` may be 'final'

/**
* Decorator buffer-size limit captured at construction. Exposed as a
Expand Down Expand Up @@ -134,6 +137,11 @@
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 @@
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 @@
}
}

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 @@
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 @@
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 @@ -844,7 +901,7 @@
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
log.warn("Invalid value for property {}: {}, using default: {}", key, value, defaultValue);

Check notice on line 904 in nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Non-distinguishable logging calls

Similar log messages
}
}
return defaultValue;
Expand All @@ -856,7 +913,7 @@
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
log.warn("Invalid value for property {}: {}, using default: {}", key, value, defaultValue);

Check notice on line 916 in nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Non-distinguishable logging calls

Similar log messages
}
}
return defaultValue;
Expand Down Expand Up @@ -931,6 +988,7 @@
listener ->
LISTENER_EXECUTOR.execute(() -> safelyInvoke(listener.closeListener(), listener)));
listeners.clear();
subscriptionsClosedByClient.clear();
}

private void safelyInvoke(Consumer<String> consumer, String payload, ListenerRegistration listener) {
Expand Down Expand Up @@ -978,7 +1036,7 @@
long retryDelayMs = NostrRetryable.DELAY;
IOException lastFailure = null;

for (int attempt = 1; attempt <= NostrRetryable.MAX_ATTEMPTS; attempt++) {

Check warning on line 1039 in nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Constant values

Condition `attempt <= NostrRetryable.MAX_ATTEMPTS` is always `true`
try {
return operation.get();
} catch (IOException ex) {
Expand All @@ -991,7 +1049,7 @@
}
}

throw lastFailure == null

Check warning on line 1052 in nostr-java-client/src/main/java/nostr/client/springwebsocket/NostrRelayClient.java

View workflow job for this annotation

GitHub Actions / Qodana Community for JVM

Constant values

Condition `lastFailure == null` is always `false`
? new IOException("Relay operation failed without exception details")
: lastFailure;
}
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));
}
}
}
2 changes: 1 addition & 1 deletion nostr-java-core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<parent>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion nostr-java-event/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<parent>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion nostr-java-identity/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<parent>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion nostr-java-mcp/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<parent>
<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

<groupId>xyz.tcheeric</groupId>
<artifactId>nostr-java</artifactId>
<version>2.4.2</version>
<version>2.4.3</version>
<packaging>pom</packaging>

<name>nostr-java</name>
Expand Down
Loading