diff --git a/core/src/main/java/com/minekube/connect/module/CommonModule.java b/core/src/main/java/com/minekube/connect/module/CommonModule.java index a812f9041..5c35bd764 100644 --- a/core/src/main/java/com/minekube/connect/module/CommonModule.java +++ b/core/src/main/java/com/minekube/connect/module/CommonModule.java @@ -50,6 +50,7 @@ import com.minekube.connect.inject.CommonPlatformInjector; import com.minekube.connect.packet.PacketHandlersImpl; import com.minekube.connect.platform.util.PlatformUtils; +import com.minekube.connect.tunnel.SessionDialGuard; import com.minekube.connect.tunnel.TunnelClientTransport; import com.minekube.connect.tunnel.WebSocketTunnelTransport; import com.minekube.connect.tunnel.p2p.Libp2pTunnelTransport; @@ -89,6 +90,10 @@ protected void configure() { // another. Explicit parent bindings are inherited by every child injector. bind(BedrockAdmissionCoordinator.class).in(Singleton.class); + // Explicit parent binding: WatcherRegister claims a session id before it opens a local + // session and Tunneler refuses to dial an abandoned one, so both must see the same state. + bind(SessionDialGuard.class).in(Singleton.class); + Multibinder transports = Multibinder.newSetBinder(binder(), TunnelClientTransport.class); transports.addBinding().to(WebSocketTunnelTransport.class); diff --git a/core/src/main/java/com/minekube/connect/network/netty/LocalChannelInboundHandler.java b/core/src/main/java/com/minekube/connect/network/netty/LocalChannelInboundHandler.java index eb4ed4987..ebc2502c8 100644 --- a/core/src/main/java/com/minekube/connect/network/netty/LocalChannelInboundHandler.java +++ b/core/src/main/java/com/minekube/connect/network/netty/LocalChannelInboundHandler.java @@ -36,6 +36,7 @@ import io.grpc.protobuf.StatusProto; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; +import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.util.concurrent.atomic.AtomicLong; @@ -44,6 +45,11 @@ public class LocalChannelInboundHandler extends SimpleChannelInboundHandler { private static final String FORCE_TUNNEL_SERVICE_ADDR = System.getenv( "CONNECT_FORCE_TUNNEL_SERVICE_ADDR"); + /** Player-safe rejection for a session the tunnel service already abandoned. */ + private static final Status SESSION_ABANDONED_STATUS = Status.newBuilder() + .setCode(Code.UNAVAILABLE_VALUE) + .setMessage("session is no longer available at the tunnel service") + .build(); private final Context context; private final ConnectLogger logger; @@ -154,23 +160,56 @@ private String tunnelSvcAddr() { public void channelActive(@NotNull ChannelHandlerContext ctx) throws Exception { logger.debug("Connect local backend channel active player={} session={} local={} remote={}", playerName(), sessionId(), ctx.channel().localAddress(), ctx.channel().remoteAddress()); - // Start tunnel from downstream server -> upstream TunnelService - if (FORCE_TUNNEL_SERVICE_ADDR != null && !FORCE_TUNNEL_SERVICE_ADDR.isEmpty()) { - tunnelConn = tunneler.tunnel( - tunnelSvcAddr(), - context.getSessionProposal().getSession().getId(), - new TunnelHandler(logger, ctx.channel(), playerName(), sessionId()) - ); - } else { - tunnelConn = tunneler.tunnel( - context.getSessionProposal().getSession(), - new TunnelHandler(logger, ctx.channel(), playerName(), sessionId()) - ); + SessionAwareTunnelHandler handler = new SessionAwareTunnelHandler(ctx.channel()); + try { + // Start tunnel from downstream server -> upstream TunnelService + if (FORCE_TUNNEL_SERVICE_ADDR != null && !FORCE_TUNNEL_SERVICE_ADDR.isEmpty()) { + tunnelConn = tunneler.tunnel( + tunnelSvcAddr(), + context.getSessionProposal().getSession().getId(), + handler + ); + } else { + tunnelConn = tunneler.tunnel( + context.getSessionProposal().getSession(), + handler + ); + } + } catch (Tunneler.SessionAbandonedException e) { + // The tunnel service already gave up on this session (its pending entry was released + // and is never re-armed), so the dial could only be answered with "not found" again. + // Reject locally with a player-safe status instead of leaving the player hanging. + logger.info("Skipping tunnel dial for player={} session={} because the tunnel service " + + "already abandoned the session", + playerName(), sessionId()); + rejectProposal(context, SESSION_ABANDONED_STATUS); + ctx.close(); + return; } context.tunnelConn.set(tunnelConn); super.channelActive(ctx); } + /** + * Latches the session as abandoned when the tunnel service refuses the upgrade because it no + * longer knows the session, so no later delivery of the same session id dials again, and the + * local session is torn down with a player-safe status instead of an internal error. + */ + private final class SessionAwareTunnelHandler extends TunnelHandler { + private SessionAwareTunnelHandler(Channel downstreamServerConn) { + super(logger, downstreamServerConn, playerName(), sessionId()); + } + + @Override + public void onSessionAbandoned(int httpStatus) { + tunneler.dialGuard().abandon(sessionId()); + rejectProposal(context, SESSION_ABANDONED_STATUS); + logger.info("Tunnel service no longer knows player={} session={} (status={}); " + + "not retrying the dial", playerName(), sessionId(), httpStatus); + super.onClose(); + } + } + @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) { int readableBytes = buf.readableBytes(); diff --git a/core/src/main/java/com/minekube/connect/tunnel/SessionDialGuard.java b/core/src/main/java/com/minekube/connect/tunnel/SessionDialGuard.java new file mode 100644 index 000000000..24b06d159 --- /dev/null +++ b/core/src/main/java/com/minekube/connect/tunnel/SessionDialGuard.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2021-2022 Minekube. https://minekube.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @author Minekube + * @link https://github.com/minekube/connect-java + */ + +package com.minekube.connect.tunnel; + +import java.time.Duration; +import com.google.inject.Inject; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.LongSupplier; + +/** + * Remembers, per session id, that the connector already owns the session's one dial. + * + *

Two failure modes are prevented, both measured on the fleet: + * + *

+ * + *

Session ids are single use, so entries are retained for a bounded window instead of being + * released: {@link #DEFAULT_RETENTION} comfortably exceeds one attempt - the edge's answer budget + * (2 x 3 s) plus the connector's 10 s local connect timeout plus a dial - and the map is capped at + * {@link #DEFAULT_MAX_ENTRIES} with oldest-first eviction, so a long-running proxy cannot grow it + * without bound. The connector never guesses a lifetime from its own clock: an id it has not been + * told about is dialled normally. + */ +public final class SessionDialGuard { + /** Edge answer budget (2 x 3 s) + local connect timeout (10 s) + dial, with head-room. */ + static final Duration DEFAULT_RETENTION = Duration.ofSeconds(30); + static final int DEFAULT_MAX_ENTRIES = 8192; + + private final long retentionMillis; + private final int maxEntries; + private final LongSupplier clock; + /** + * Insertion-ordered; every entry is re-inserted on write and has the same retention, so the + * head is always the entry that expires first. + */ + private final Map entries = new LinkedHashMap<>(); + + @Inject + public SessionDialGuard() { + this(DEFAULT_RETENTION, DEFAULT_MAX_ENTRIES, System::currentTimeMillis); + } + + SessionDialGuard(Duration retention, int maxEntries, LongSupplier clock) { + if (retention == null || retention.isNegative() || retention.isZero()) { + throw new IllegalArgumentException("retention must be positive"); + } + if (maxEntries <= 0) { + throw new IllegalArgumentException("maxEntries must be positive"); + } + this.retentionMillis = retention.toMillis(); + this.maxEntries = maxEntries; + this.clock = clock; + } + + /** + * Claims a session proposal delivery. + * + * @param sessionId the proposed session id + * @return {@code true} when this delivery owns the session (it may dial), {@code false} when a + * delivery is already in flight and this one must be dropped. An abandoned session is + * accepted without changing the latch: {@link Tunneler} refuses to dial it and the + * caller rejects the delivery, so the edge gets an answer. + */ + public synchronized boolean tryAcceptDelivery(String sessionId) { + if (sessionId == null || sessionId.isEmpty()) { + // Not addressable: the tunnel transports reject an empty id on their own. + return true; + } + long now = clock.getAsLong(); + Entry entry = live(sessionId, now); + if (entry != null) { + return entry.state == Entry.State.ABANDONED; + } + put(sessionId, Entry.State.IN_FLIGHT, now); + return true; + } + + /** + * Releases the in-flight claim of a delivery that was rejected or failed, so a redelivery of + * the same session id is served. An abandoned session stays latched. + */ + public synchronized void release(String sessionId) { + if (sessionId == null || sessionId.isEmpty()) { + return; + } + Entry entry = entries.get(sessionId); + if (entry != null && entry.state == Entry.State.IN_FLIGHT) { + entries.remove(sessionId); + } + } + + /** + * Latches that the tunnel service no longer knows this session, so it may never be dialled + * again inside the retention window. + */ + public synchronized void abandon(String sessionId) { + if (sessionId == null || sessionId.isEmpty()) { + return; + } + put(sessionId, Entry.State.ABANDONED, clock.getAsLong()); + } + + /** Whether the tunnel service has already abandoned this session. */ + public synchronized boolean isAbandoned(String sessionId) { + if (sessionId == null || sessionId.isEmpty()) { + return false; + } + Entry entry = live(sessionId, clock.getAsLong()); + return entry != null && entry.state == Entry.State.ABANDONED; + } + + /** Number of live entries. Bounded by {@link #DEFAULT_MAX_ENTRIES}; exposed for tests. */ + synchronized int trackedSessions() { + pruneExpired(clock.getAsLong()); + return entries.size(); + } + + private Entry live(String sessionId, long now) { + Entry entry = entries.get(sessionId); + if (entry == null) { + return null; + } + if (entry.isExpired(now)) { + entries.remove(sessionId); + return null; + } + return entry; + } + + private void put(String sessionId, Entry.State state, long now) { + // Remove first: re-putting an existing key would keep its old position in the order. + entries.remove(sessionId); + entries.put(sessionId, new Entry(state, now + retentionMillis)); + pruneExpired(now); + if (entries.size() > maxEntries) { + // Oldest insertion goes first: the oldest session is the least likely to be dialled. + Iterator oldest = entries.keySet().iterator(); + if (oldest.hasNext()) { + oldest.next(); + oldest.remove(); + } + } + } + + /** Stops at the first live entry: later entries were inserted later and expire later. */ + private void pruneExpired(long now) { + Iterator iterator = entries.values().iterator(); + while (iterator.hasNext() && iterator.next().isExpired(now)) { + iterator.remove(); + } + } + + private static final class Entry { + enum State { + IN_FLIGHT, + ABANDONED + } + + private final State state; + private final long expiresAtMillis; + + private Entry(State state, long expiresAtMillis) { + this.state = state; + this.expiresAtMillis = expiresAtMillis; + } + + private boolean isExpired(long now) { + return now >= expiresAtMillis; + } + } +} diff --git a/core/src/main/java/com/minekube/connect/tunnel/TunnelConn.java b/core/src/main/java/com/minekube/connect/tunnel/TunnelConn.java index 98998d1ec..b8550482c 100644 --- a/core/src/main/java/com/minekube/connect/tunnel/TunnelConn.java +++ b/core/src/main/java/com/minekube/connect/tunnel/TunnelConn.java @@ -34,6 +34,20 @@ public interface Handler { default void onClose() { } + + /** + * Called instead of {@link #onError(Throwable)} when the tunnel service refused the + * upgrade because it no longer knows this session (its pending entry was released, + * expired, or claimed by another request), i.e. the player can never be served on it. + * + *

This is a permanent, expected outcome for that session id, not a transport failure: + * implementations should tear the local session down without retrying and without + * reporting an internal error. + * + * @param httpStatus the refusal status the tunnel service answered with + */ + default void onSessionAbandoned(int httpStatus) { + } } public abstract void write(byte[] data); diff --git a/core/src/main/java/com/minekube/connect/tunnel/Tunneler.java b/core/src/main/java/com/minekube/connect/tunnel/Tunneler.java index aee81db3a..3192935f5 100644 --- a/core/src/main/java/com/minekube/connect/tunnel/Tunneler.java +++ b/core/src/main/java/com/minekube/connect/tunnel/Tunneler.java @@ -41,17 +41,27 @@ public class Tunneler implements Closeable { private final Map transports; + private final SessionDialGuard dialGuard; @Inject - public Tunneler(Set transports) { + public Tunneler(Set transports, SessionDialGuard dialGuard) { this.transports = new EnumMap<>(Type.class); for (TunnelClientTransport transport : transports) { this.transports.put(transport.type(), transport); } + this.dialGuard = dialGuard; } - public Tunneler(TunnelClientTransport transport) { - this(Collections.singleton(transport)); + public Tunneler(TunnelClientTransport transport, SessionDialGuard dialGuard) { + this(Collections.singleton(transport), dialGuard); + } + + /** + * Session ids this tunneler has already taken a proposal for and will not dial again once the + * tunnel service abandoned them. + */ + public SessionDialGuard dialGuard() { + return dialGuard; } public void prepare(Session session) { @@ -65,6 +75,7 @@ public void prepare(Session session) { } public TunnelConn tunnel(final String tunnelServiceAddr, String sessionId, Handler handler) { + checkNotAbandoned(sessionId); TunnelClientTransport transport = transports.get(Type.TYPE_WEBSOCKET); if (transport == null) { throw new IllegalStateException("no websocket tunnel transport configured"); @@ -73,6 +84,7 @@ public TunnelConn tunnel(final String tunnelServiceAddr, String sessionId, Handl } public TunnelConn tunnel(Session session, Handler handler) { + checkNotAbandoned(session.getId()); RuntimeException lastFailure = null; for (SelectedTransport selected : select(session)) { try { @@ -87,6 +99,12 @@ public TunnelConn tunnel(Session session, Handler handler) { throw new IllegalStateException("no compatible tunnel transport configured"); } + private void checkNotAbandoned(String sessionId) { + if (dialGuard.isAbandoned(sessionId)) { + throw new SessionAbandonedException(sessionId); + } + } + @Override public void close() { for (TunnelClientTransport transport : transports.values()) { @@ -122,6 +140,27 @@ private void addAdvertisedTransport( } } + /** + * Thrown instead of dialling when the tunnel service already abandoned the session. + * + *

The edge never re-arms a released pending entry, so the dial could only ever produce a + * tunnel that is upgraded and closed again. Callers reject the proposal with a player-safe + * status rather than reporting an internal error. + */ + public static final class SessionAbandonedException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final String sessionId; + + SessionAbandonedException(String sessionId) { + super("session " + sessionId + " was abandoned by the tunnel service"); + this.sessionId = sessionId; + } + + public String sessionId() { + return sessionId; + } + } + private static final class SelectedTransport { private final TunnelClientTransport transport; private final String address; diff --git a/core/src/main/java/com/minekube/connect/tunnel/WebSocketTunnelTransport.java b/core/src/main/java/com/minekube/connect/tunnel/WebSocketTunnelTransport.java index 21a9c7353..2618b66bf 100644 --- a/core/src/main/java/com/minekube/connect/tunnel/WebSocketTunnelTransport.java +++ b/core/src/main/java/com/minekube/connect/tunnel/WebSocketTunnelTransport.java @@ -33,8 +33,10 @@ import com.minekube.connect.tunnel.TunnelConn.Handler; import com.minekube.connect.util.ReflectionUtils; import java.io.EOFException; +import java.io.IOException; import java.lang.reflect.Field; import java.util.Collection; +import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; import minekube.connect.v1alpha1.WatchServiceOuterClass.TunnelTransport.Type; @@ -51,6 +53,7 @@ public class WebSocketTunnelTransport implements TunnelClientTransport { private static final String SESSION_HEADER = "Connect-Session"; + private static final long MAX_REFUSAL_BODY_BYTES = 1024; private static final Field DATA = ReflectionUtils.getField(ByteString.class, "data"); private final OkHttpClient httpClient; @@ -100,6 +103,14 @@ public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String re @Override public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) { + if (isSessionAbandoned(response)) { + // The tunnel service answered the upgrade with "session gone": the + // session's pending entry is gone for good, so this is not a transport + // failure and must not be retried or logged as an internal error. + handler.onSessionAbandoned(response.code()); + handlerOnClose.run(); + return; + } if (!(t instanceof EOFException)) { handler.onError(t); } @@ -154,6 +165,42 @@ public boolean opened() { }; } + /** + * The tunnel service answers a tunnel request whose pending session is gone either with + * {@code 410 Gone} or with a {@code 404} whose body reports {@code pending metadata released} + * (moxy's missing-session path: "tunnel session not found; ...; pending metadata released + * request_kind=...; likely causes: ..."). Both mean "this session id will never be dialable + * again", which is categorically different from a transport failure. + * + *

The body's trailing "likely causes" list always mentions "released session", so only the + * {@code pending metadata } field is authoritative: {@code absent}, {@code pending} and + * {@code consumed} (wrong instance, expired, duplicate tunnel) must not latch, and neither must + * a bare 404 from a load balancer or a wrong route, which could block a session that is still + * dialable elsewhere. + */ + private static final java.util.regex.Pattern RELEASED_PENDING_METADATA = + java.util.regex.Pattern.compile("pending metadata released(\\s|;|$)"); + + private static boolean isSessionAbandoned(@Nullable Response response) { + if (response == null) { + return false; + } + int code = response.code(); + if (code == 410) { + return true; + } + if (code != 404) { + return false; + } + try { + String body = response.peekBody(MAX_REFUSAL_BODY_BYTES).string().toLowerCase(Locale.ROOT); + return body.contains("tunnel session not found") + && RELEASED_PENDING_METADATA.matcher(body).find(); + } catch (IOException | RuntimeException e) { + return false; + } + } + @Override public void close() { // cancel queued connections diff --git a/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pSessionResponder.java b/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pSessionResponder.java index 08ad0ca0f..f80533305 100644 --- a/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pSessionResponder.java +++ b/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pSessionResponder.java @@ -27,6 +27,7 @@ import com.google.rpc.Code; import com.google.rpc.Status; +import com.minekube.connect.tunnel.SessionDialGuard; import com.minekube.connect.tunnel.Tunneler; import com.minekube.connect.bedrock.BedrockAdmissionCoordinator; import com.minekube.connect.watch.SessionProposal; @@ -122,11 +123,12 @@ void handleOffer(Stream stream, SessionOffer offer) { ? new SessionProposal(raw, rejectProposal, endpointId, endpointOrgId) : admissionCoordinator.proposal(raw, rejectProposal, endpointId, endpointOrgId); try { + // One stream carries one session, so there is no cross-offer abandonment to remember. Tunneler tunneler = new Tunneler(new SameStreamTunnelTransport(stream, acceptedSessionId -> writeResponse(stream, SessionResponse.newBuilder() .setSessionId(acceptedSessionId) .setAccepted(SessionAccepted.newBuilder().setSameStreamData(true)) - .build()))); + .build())), new SessionDialGuard()); starter.start(proposal, tunneler); } catch (RuntimeException e) { reject(proposal, Status.newBuilder() diff --git a/core/src/main/java/com/minekube/connect/watch/WatchClient.java b/core/src/main/java/com/minekube/connect/watch/WatchClient.java index ba05b4050..f21f5aeeb 100644 --- a/core/src/main/java/com/minekube/connect/watch/WatchClient.java +++ b/core/src/main/java/com/minekube/connect/watch/WatchClient.java @@ -36,6 +36,7 @@ import com.minekube.connect.bedrock.BedrockAdmissionCoordinator; import com.minekube.connect.bedrock.BedrockPrincipalReadiness; import com.minekube.connect.config.ConnectConfig; +import com.minekube.connect.tunnel.SessionDialGuard; import java.io.IOException; import minekube.connect.v1alpha1.WatchServiceOuterClass.SessionRejection; import minekube.connect.v1alpha1.WatchServiceOuterClass.SessionRejection.Builder; @@ -63,6 +64,7 @@ public class WatchClient { private final BedrockIdentityReadiness bedrockIdentityReadiness; private final BedrockAdmissionCoordinator admissionCoordinator; private final BedrockPrincipalReadiness bedrockPrincipalReadiness; + private final SessionDialGuard dialGuard; @Inject public WatchClient( @@ -70,27 +72,33 @@ public WatchClient( ConnectConfig config, BedrockIdentityReadiness bedrockIdentityReadiness, BedrockPrincipalReadiness bedrockPrincipalReadiness, - BedrockAdmissionCoordinator admissionCoordinator) { + BedrockAdmissionCoordinator admissionCoordinator, + SessionDialGuard dialGuard) { this.httpClient = httpClient; this.config = config; this.bedrockIdentityReadiness = bedrockIdentityReadiness; this.bedrockPrincipalReadiness = bedrockPrincipalReadiness; this.admissionCoordinator = admissionCoordinator; + this.dialGuard = dialGuard; } public WatchClient( @Named("watchHttpClient") OkHttpClient httpClient, ConnectConfig config, BedrockIdentityReadiness bedrockIdentityReadiness, - BedrockAdmissionCoordinator admissionCoordinator) { + BedrockAdmissionCoordinator admissionCoordinator, + SessionDialGuard dialGuard) { this(httpClient, config, bedrockIdentityReadiness, - new BedrockPrincipalReadiness(config), admissionCoordinator); + new BedrockPrincipalReadiness(config), admissionCoordinator, dialGuard); } - public WatchClient(@Named("watchHttpClient") OkHttpClient httpClient, ConnectConfig config) { + public WatchClient( + @Named("watchHttpClient") OkHttpClient httpClient, + ConnectConfig config, + SessionDialGuard dialGuard) { this(httpClient, config, new BedrockIdentityReadiness( config, new BedrockIdentityKeyProvider(config, new OkHttpClient())), - new BedrockPrincipalReadiness(config), null); + new BedrockPrincipalReadiness(config), null, dialGuard); } public WebSocket watch(Watcher watcher) { @@ -176,7 +184,10 @@ public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) { } String sessionId = res.getSession().getId(); + // Every rejection (local failure, refused dial, closed coordinator) frees the claim + // below so the edge's redelivery of this session id is served instead of dropped. java.util.function.Consumer rejectProposal = reason -> { + dialGuard.release(sessionId); Builder responseRejection = SessionRejection.newBuilder() .setId(sessionId); if (reason != null) { @@ -188,6 +199,14 @@ public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) { .toByteArray() )); }; + // Claim the session id before the coordinator stages an admission: a staged + // admission supersedes the previous one for the same id, so a repeat delivery that + // is dropped must never reach the coordinator. The edge re-proposes an unanswered + // session and a watch fail-over re-publishes it; one session id carries one local + // session and one tunnel, and the delivery still in flight answers for it. + if (!dialGuard.tryAcceptDelivery(sessionId)) { + return; + } SessionProposal prop; try { prop = admissionCoordinator == null diff --git a/core/src/test/java/com/minekube/connect/bedrock/BedrockIdentityDefaultConfigTest.java b/core/src/test/java/com/minekube/connect/bedrock/BedrockIdentityDefaultConfigTest.java index a0c9521cb..e282d4a07 100644 --- a/core/src/test/java/com/minekube/connect/bedrock/BedrockIdentityDefaultConfigTest.java +++ b/core/src/test/java/com/minekube/connect/bedrock/BedrockIdentityDefaultConfigTest.java @@ -143,7 +143,9 @@ void untouchedDefaultsAdvertiseDuringWatchRegistrationWithoutFetchingMetadata() config, new BedrockIdentityKeyProvider(config, metadataClient(metadataRequests), () -> FIXTURE_TIME)); OkHttpClient watchHttpClient = mock(OkHttpClient.class); - WatchClient watchClient = new WatchClient(watchHttpClient, config, readiness, null); + WatchClient watchClient = new WatchClient( + watchHttpClient, config, readiness, null, + new com.minekube.connect.tunnel.SessionDialGuard()); watchClient.watch(new Watcher() { @Override public void onOpen(com.minekube.connect.watch.WatchBootstrap bootstrap) { } diff --git a/core/src/test/java/com/minekube/connect/register/TunnelDialAfterAbandonTest.java b/core/src/test/java/com/minekube/connect/register/TunnelDialAfterAbandonTest.java new file mode 100644 index 000000000..6708efc7f --- /dev/null +++ b/core/src/test/java/com/minekube/connect/register/TunnelDialAfterAbandonTest.java @@ -0,0 +1,334 @@ +package com.minekube.connect.register; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.rpc.Code; +import com.google.rpc.Status; +import com.minekube.connect.api.SimpleConnectApi; +import com.minekube.connect.api.inject.PlatformInjector; +import com.minekube.connect.api.logger.ConnectLogger; +import com.minekube.connect.network.netty.LocalSession; +import com.minekube.connect.config.ConnectConfig; +import com.minekube.connect.tunnel.SessionDialGuard; +import com.minekube.connect.tunnel.TunnelClientTransport; +import com.minekube.connect.tunnel.TunnelConn; +import com.minekube.connect.tunnel.Tunneler; +import com.minekube.connect.tunnel.WebSocketTunnelTransport; +import com.minekube.connect.tunnel.p2p.Libp2pEndpoint; +import com.minekube.connect.watch.SessionProposal; +import com.minekube.connect.watch.WatchClient; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.DefaultEventLoopGroup; +import io.netty.channel.local.LocalAddress; +import io.netty.channel.local.LocalServerChannel; +import java.lang.reflect.Field; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import minekube.connect.v1alpha1.WatchServiceOuterClass.GameProfile; +import minekube.connect.v1alpha1.WatchServiceOuterClass.Player; +import minekube.connect.v1alpha1.WatchServiceOuterClass.Session; +import minekube.connect.v1alpha1.WatchServiceOuterClass.TunnelTransport; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; +import okio.ByteString; +import minekube.connect.v1alpha1.WatchServiceOuterClass.WatchRequest; +import minekube.connect.v1alpha1.WatchServiceOuterClass.WatchResponse; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Regression guards for the connector side of the "released" 404 class: one session id must + * produce exactly one local session and exactly one tunnel dial, and a session the tunnel service + * has already abandoned must never be dialled again. + * + *

The dial is a side effect of finishing local-session setup + * ({@code LocalSession.connect} -> {@code LocalChannelInboundHandler.channelActive} -> + * {@code Tunneler.tunnel}), so these tests drive the real proposal intake + * ({@code WatcherRegister.WatcherImpl.onProposal}) against a real in-process local server and a + * recording/RFC-compliant tunnel endpoint. Counting dials is therefore counting the production + * path, not a mock's bookkeeping. + */ +class TunnelDialAfterAbandonTest { + private static final String SESSION_ID = "session-abandoned-1"; + + private final DefaultEventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(1); + private final AtomicInteger acceptedLocalConnections = new AtomicInteger(); + private final AtomicReference firstRejection = new AtomicReference<>(); + /** Rejections the connector sent over the watch socket, in order. */ + private final List wireRejections = new CopyOnWriteArrayList<>(); + + private WatcherRegister register; + private LocalAddress localAddress; + private WebSocketListener watchListener; + private final WebSocket watchSocket = mock(WebSocket.class); + private Channel localServer; + private MockWebServer tunnelService; + + @AfterEach + void tearDown() { + if (register != null) { + register.stop(); + } + if (localServer != null) { + localServer.close().syncUninterruptibly(); + } + if (tunnelService != null) { + try { + tunnelService.shutdown(); + } catch (Exception ignored) { + // The tunnel endpoint is a test fixture; a failed shutdown must not mask assertions. + } + } + LocalSession.setPlatformEventLoopGroup(null); + eventLoopGroup.shutdownGracefully().syncUninterruptibly(); + } + + /** + * The edge re-proposes the same session id (its unanswered-proposal retry, or a watch + * fail-over re-publish). One session id may only ever carry one local session and one tunnel: + * a second dial would create a second data path, which the edge's invariant forbids. + */ + @Test + void repeatedProposalForTheSameSessionDialsExactlyOneTunnel() throws Exception { + RecordingTransport transport = new RecordingTransport(); + start(transport); + + deliver(SESSION_ID, "ws://127.0.0.1:1/tunnel"); + deliver(SESSION_ID, "ws://127.0.0.1:1/tunnel"); + // A different session sent after the repeat: once it is dialled, everything queued before + // it on the single local event loop has run, so a second dial of SESSION_ID would be + // visible by now. + deliver("session-sentinel", "ws://127.0.0.1:1/tunnel"); + + await().atMost(5, SECONDS).untilAsserted(() -> + assertTrue(transport.dialled.contains("session-sentinel"))); + + assertEquals(1, transport.dialled.stream().filter(SESSION_ID::equals).count(), + "one session id must produce exactly one tunnel dial"); + assertEquals(2, acceptedLocalConnections.get(), + "one local session per session id: the session and the sentinel"); + assertTrue(wireRejections.isEmpty(), + "the repeat delivery is absorbed by the in-flight session; it is not a rejection"); + } + + /** + * Once the tunnel service answers "session not found" the session can never be dialled again + * (the edge does not re-arm a released pending entry). The connector must remember that for the + * session id, refuse to dial it again, and reject locally with a player-safe status instead of + * an internal error. + */ + @Test + void sessionRefusedByTheTunnelServiceIsNeverDialledAgain() throws Exception { + tunnelService = new MockWebServer(); + tunnelService.enqueue(new MockResponse() + .setResponseCode(404) + .setBody("tunnel session not found; connector version 0.15.18; requested Fly instance a; current Fly instance b; pending metadata released request_kind=join protocol=java age=4.1s released_ago=30ms; likely causes: expired session, released session (the dial ended before this request arrived), duplicate tunnel, stale connector, or tunnel request reached the wrong instance")); + tunnelService.start(); + String tunnelAddress = "ws://" + tunnelService.getHostName() + ":" + tunnelService.getPort() + "/"; + start(new WebSocketTunnelTransport(new OkHttpClient())); + + deliver(SESSION_ID, tunnelAddress); + + await().atMost(5, SECONDS).untilAsserted(() -> { + assertEquals(1, wireRejections.size(), "a refused tunnel must reject the proposal"); + assertEquals(Code.UNAVAILABLE_VALUE, wireRejections.get(0).getCode(), + "a session the edge abandoned is not an internal error; got " + + wireRejections.get(0)); + }); + assertEquals(1, tunnelService.getRequestCount()); + + // The edge re-proposes the same id after its 3 s answer timeout: no second dial. + deliver(SESSION_ID, tunnelAddress); + + await().atMost(5, SECONDS).untilAsserted(() -> + assertEquals(2, wireRejections.size(), + "an abandoned session must be rejected locally, never left hanging")); + assertEquals(Code.UNAVAILABLE_VALUE, wireRejections.get(1).getCode(), + "an abandoned session must be rejected with the player-safe status; got " + + wireRejections.get(1)); + assertEquals(1, tunnelService.getRequestCount(), + "the connector must never dial a session the tunnel service already abandoned"); + } + + /** + * A delivery that fails locally before it dials (here: the local server is gone) is rejected, + * and that frees the claim: the edge's redelivery must be served, not dropped without a reply. + */ + @Test + void redeliveryAfterATransientLocalFailureIsServed() throws Exception { + RecordingTransport transport = new RecordingTransport(); + start(transport); + localServer.close().syncUninterruptibly(); + localServer = null; + + deliver(SESSION_ID, "ws://127.0.0.1:1/tunnel"); + await().atMost(5, SECONDS).untilAsserted(() -> + assertEquals(1, wireRejections.size(), "the failed delivery must be rejected")); + + bindLocalServer(localAddress); + deliver(SESSION_ID, "ws://127.0.0.1:1/tunnel"); + + await().atMost(5, SECONDS).untilAsserted(() -> + assertEquals(1, transport.dialled.size(), + "the redelivery after the failure must be dialled")); + } + + /** + * Defence in depth for the dial site itself: if a local session for an already abandoned id is + * ever in flight (a delivery that raced the abandonment latch), finishing its setup must not + * dial, and the player must be rejected instead of left waiting on a tunnel that cannot exist. + */ + @Test + void localSessionForAnAbandonedSessionNeverDials() throws Exception { + RecordingTransport transport = new RecordingTransport(); + SessionDialGuard guard = new SessionDialGuard(); + guard.abandon(SESSION_ID); + Tunneler tunneler = new Tunneler(transport, guard); + LocalAddress target = bindLocalServer(); + LocalSession.setPlatformEventLoopGroup(eventLoopGroup); + + SessionProposal proposal = new SessionProposal( + session("ws://127.0.0.1:1/tunnel"), firstRejection::set); + new LocalSession( + mock(ConnectLogger.class), + new SimpleConnectApi(mock(ConnectLogger.class)), + tunneler, + target, + proposal).connect(); + + await().atMost(5, SECONDS).untilAsserted(() -> + assertTrue(transport.dialled.isEmpty(), + "channelActive must not dial a session the tunnel service abandoned")); + + assertNotNull(firstRejection.get(), "the abandoned session must be rejected locally"); + assertEquals(Code.UNAVAILABLE_VALUE, firstRejection.get().getCode(), + "an abandoned session is not an internal error; got " + firstRejection.get()); + } + + private void start(TunnelClientTransport transport) throws Exception { + LocalAddress target = bindLocalServer(); + localAddress = target; + LocalSession.setPlatformEventLoopGroup(eventLoopGroup); + + PlatformInjector platformInjector = mock(PlatformInjector.class); + when(platformInjector.getServerSocketAddress()).thenReturn(target); + + // Real WatchClient over a captured socket listener: deliveries take the production path + // (claim, proposal, WatcherRegister.onProposal) and rejections go out as wire messages. + SessionDialGuard guard = new SessionDialGuard(); + OkHttpClient httpClient = mock(OkHttpClient.class); + when(httpClient.newWebSocket(any(Request.class), any(WebSocketListener.class))) + .thenAnswer(invocation -> { + watchListener = invocation.getArgument(1); + return watchSocket; + }); + when(watchSocket.send(any(ByteString.class))).thenAnswer(invocation -> { + ByteString sent = invocation.getArgument(0); + wireRejections.add(WatchRequest.parseFrom(sent.toByteArray()) + .getSessionRejection().getReason()); + return true; + }); + + register = new WatcherRegister(); + inject(register, "watchClient", new WatchClient(httpClient, new ConnectConfig(), guard)); + inject(register, "tunneler", new Tunneler(transport, guard)); + inject(register, "platformInjector", platformInjector); + inject(register, "logger", mock(ConnectLogger.class)); + inject(register, "api", new SimpleConnectApi(mock(ConnectLogger.class))); + inject(register, "libp2pEndpoint", mock(Libp2pEndpoint.class)); + + register.start(); + assertNotNull(watchListener, "the register must open the watch"); + } + + private void deliver(String sessionId, String tunnelServiceAddress) { + watchListener.onMessage(watchSocket, ByteString.of(WatchResponse.newBuilder() + .setSession(session(sessionId, tunnelServiceAddress)).build().toByteArray())); + } + + private LocalAddress bindLocalServer() throws Exception { + LocalAddress target = new LocalAddress("connect-abandon-" + UUID.randomUUID()); + bindLocalServer(target); + return target; + } + + private void bindLocalServer(LocalAddress target) throws Exception { + localServer = new ServerBootstrap() + .group(eventLoopGroup) + .channel(LocalServerChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) { + acceptedLocalConnections.incrementAndGet(); + } + }) + .bind(target) + .sync() + .channel(); + } + + private static Session session(String tunnelServiceAddress) { + return session(SESSION_ID, tunnelServiceAddress); + } + + private static Session session(String sessionId, String tunnelServiceAddress) { + return Session.newBuilder() + .setId(sessionId) + .setTunnelServiceAddr(tunnelServiceAddress) + .setPlayer(Player.newBuilder() + .setAddr("127.0.0.1") + .setProfile(GameProfile.newBuilder() + .setId("00000000-0000-0000-0000-000000000001") + .setName("Player") + .build()) + .build()) + .build(); + } + + private static void inject(WatcherRegister register, String fieldName, Object value) + throws Exception { + Field field = WatcherRegister.class.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(register, value); + } + + /** Records every tunnel dial and never opens a tunnel, like a tunnel service that refuses. */ + private static final class RecordingTransport implements TunnelClientTransport { + private final List dialled = new CopyOnWriteArrayList<>(); + + @Override + public TunnelTransport.Type type() { + return TunnelTransport.Type.TYPE_WEBSOCKET; + } + + @Override + public TunnelConn tunnel(String address, String sessionId, TunnelConn.Handler handler) { + dialled.add(sessionId); + return new TunnelConn() { + @Override + public void write(byte[] data) { + } + + @Override + public void close(Throwable t) { + } + }; + } + } +} diff --git a/core/src/test/java/com/minekube/connect/tunnel/SessionDialGuardTest.java b/core/src/test/java/com/minekube/connect/tunnel/SessionDialGuardTest.java new file mode 100644 index 000000000..957cbdf66 --- /dev/null +++ b/core/src/test/java/com/minekube/connect/tunnel/SessionDialGuardTest.java @@ -0,0 +1,193 @@ +package com.minekube.connect.tunnel; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import org.junit.jupiter.api.Test; + +class SessionDialGuardTest { + private final AtomicLong now = new AtomicLong(1_000); + private final SessionDialGuard guard = new SessionDialGuard( + Duration.ofMillis(100), 4, now::get); + + @Test + void firstDeliveryOwnsTheSessionAndRepeatsAreAbsorbed() { + assertTrue(guard.tryAcceptDelivery("session-1")); + assertFalse(guard.tryAcceptDelivery("session-1")); + assertFalse(guard.tryAcceptDelivery("session-1")); + assertTrue(guard.tryAcceptDelivery("session-2"), "a different session id is unaffected"); + } + + @Test + void abandonedSessionIsNeverAcceptedAgain() { + assertTrue(guard.tryAcceptDelivery("session-1")); + + guard.abandon("session-1"); + + assertTrue(guard.isAbandoned("session-1")); + assertTrue(guard.tryAcceptDelivery("session-1"), + "an abandoned session is let through so the caller can reject it; the latch stays"); + assertTrue(guard.isAbandoned("session-1"), "accepting a delivery must not clear the latch"); + assertFalse(guard.isAbandoned("session-2"), "abandonment is per session id"); + } + + @Test + void abandonBeforeAnyDeliveryIsHonoured() { + guard.abandon("session-1"); + + assertTrue(guard.isAbandoned("session-1")); + assertTrue(guard.tryAcceptDelivery("session-1")); + assertTrue(guard.isAbandoned("session-1")); + } + + @Test + void releasedClaimServesTheRedelivery() { + assertTrue(guard.tryAcceptDelivery("session-1")); + + guard.release("session-1"); + + assertTrue(guard.tryAcceptDelivery("session-1"), + "a rejected or failed delivery must not block the edge's redelivery"); + assertFalse(guard.tryAcceptDelivery("session-1")); + } + + @Test + void releaseNeverClearsAnAbandonedSession() { + assertTrue(guard.tryAcceptDelivery("session-1")); + guard.abandon("session-1"); + + guard.release("session-1"); + + assertTrue(guard.isAbandoned("session-1")); + } + + @Test + void entriesExpireAfterTheRetentionWindow() { + assertTrue(guard.tryAcceptDelivery("session-1")); + guard.abandon("session-2"); + + now.addAndGet(101); + + assertFalse(guard.isAbandoned("session-2"), "the abandonment latch is bounded"); + assertTrue(guard.tryAcceptDelivery("session-1"), "an expired claim no longer blocks a dial"); + assertTrue(guard.tryAcceptDelivery("session-2")); + } + + @Test + void trackedEntriesStayBounded() { + for (int i = 0; i < 50; i++) { + assertTrue(guard.tryAcceptDelivery("session-" + i)); + } + + assertEquals(4, guard.trackedSessions(), "a long-running proxy must not grow the map"); + assertFalse(guard.tryAcceptDelivery("session-49"), "the newest entry is still claimed"); + assertTrue(guard.tryAcceptDelivery("session-0"), "the evicted entry is claimable again"); + } + + @Test + void concurrentClaimsAndAbandonmentsStayExactAndBounded() throws Exception { + int maxEntries = 64; + int threads = 16; + int sessions = 40; // fewer than maxEntries, so no claim is evicted mid-test + SessionDialGuard shared = new SessionDialGuard(Duration.ofMinutes(1), maxEntries, now::get); + ExecutorService pool = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger[] winners = new AtomicInteger[sessions]; + for (int i = 0; i < sessions; i++) { + winners[i] = new AtomicInteger(); + } + try { + List> done = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + done.add(pool.submit(() -> { + start.await(); + for (int i = 0; i < sessions; i++) { + if (shared.tryAcceptDelivery("session-" + i)) { + winners[i].incrementAndGet(); + } + } + for (int i = 0; i < sessions; i++) { + shared.abandon("session-" + i); + } + return null; + })); + } + start.countDown(); + for (Future f : done) { + f.get(10, TimeUnit.SECONDS); + } + } finally { + pool.shutdownNow(); + } + + // A claim that races an abandon may be accepted again (an abandoned id is let through), + // but every id was claimed at least once and is latched at the end. + for (int i = 0; i < sessions; i++) { + assertTrue(winners[i].get() >= 1, "session-" + i + " was never accepted"); + assertTrue(shared.isAbandoned("session-" + i), "session-" + i + " must end latched"); + } + assertEquals(sessions, shared.trackedSessions()); + + for (int i = 0; i < 10_000; i++) { + shared.tryAcceptDelivery("flood-" + i); + } + assertEquals(maxEntries, shared.trackedSessions(), "the guard must stay bounded"); + } + + @Test + void concurrentClaimsOfOneSessionHaveExactlyOneWinner() throws Exception { + int threads = 32; + ExecutorService pool = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + AtomicInteger winners = new AtomicInteger(); + try { + List> done = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + done.add(pool.submit(() -> { + start.await(); + if (guard.tryAcceptDelivery("contended")) { + winners.incrementAndGet(); + } + return null; + })); + } + start.countDown(); + for (Future f : done) { + f.get(10, TimeUnit.SECONDS); + } + } finally { + pool.shutdownNow(); + } + + assertEquals(1, winners.get(), "one session id must carry exactly one dial"); + } + + @Test + void emptySessionIdIsNotTracked() { + assertTrue(guard.tryAcceptDelivery("")); + assertTrue(guard.tryAcceptDelivery(""), "an unaddressable id is left to the transport checks"); + assertFalse(guard.isAbandoned("")); + guard.abandon(""); + assertEquals(0, guard.trackedSessions()); + } + + @Test + void rejectsUnboundedConfiguration() { + assertThrows(IllegalArgumentException.class, + () -> new SessionDialGuard(Duration.ZERO, 1, now::get)); + assertThrows(IllegalArgumentException.class, + () -> new SessionDialGuard(Duration.ofSeconds(1), 0, now::get)); + } +} diff --git a/core/src/test/java/com/minekube/connect/tunnel/TunnelerTest.java b/core/src/test/java/com/minekube/connect/tunnel/TunnelerTest.java index 018ca2351..73ad57f02 100644 --- a/core/src/test/java/com/minekube/connect/tunnel/TunnelerTest.java +++ b/core/src/test/java/com/minekube/connect/tunnel/TunnelerTest.java @@ -45,7 +45,7 @@ public void close(Throwable t) { }; transport.next = expected; CapturingHandler handler = new CapturingHandler(); - Tunneler tunneler = new Tunneler(transport); + Tunneler tunneler = new Tunneler(transport, new SessionDialGuard()); TunnelConn actual = tunneler.tunnel("ws://connect.example/tunnel", "session-123", handler); tunneler.close(); @@ -82,7 +82,7 @@ public void close(Throwable t) { }; libp2p.next = expected; CapturingHandler handler = new CapturingHandler(); - Tunneler tunneler = new Tunneler(new HashSet<>(Arrays.asList(websocket, libp2p))); + Tunneler tunneler = new Tunneler(new HashSet<>(Arrays.asList(websocket, libp2p)), new SessionDialGuard()); TunnelConn actual = tunneler.tunnel(session( "session-456", @@ -112,7 +112,7 @@ public void close(Throwable t) { } }; websocket.next = expected; - Tunneler tunneler = new Tunneler(websocket); + Tunneler tunneler = new Tunneler(websocket, new SessionDialGuard()); TunnelConn actual = tunneler.tunnel(session( "session-789", @@ -129,7 +129,7 @@ public void close(Throwable t) { void preparesSelectedTransports() { RecordingTransport websocket = new RecordingTransport(Type.TYPE_WEBSOCKET); RecordingTransport libp2p = new RecordingTransport(Type.TYPE_LIBP2P); - Tunneler tunneler = new Tunneler(new HashSet<>(Arrays.asList(websocket, libp2p))); + Tunneler tunneler = new Tunneler(new HashSet<>(Arrays.asList(websocket, libp2p)), new SessionDialGuard()); tunneler.prepare(session( "session-prepare", @@ -157,7 +157,7 @@ public void close(Throwable t) { } }; websocket.next = expected; - Tunneler tunneler = new Tunneler(new HashSet<>(Arrays.asList(websocket, libp2p))); + Tunneler tunneler = new Tunneler(new HashSet<>(Arrays.asList(websocket, libp2p)), new SessionDialGuard()); Session session = session( "session-prepare-fallback", "ws://connect.example/fallback", @@ -210,7 +210,7 @@ void omitsFlyForceInstanceHeaderWhenTunnelAddressTargetsFlyMachine() throws Exce server.start(); String tunnelUrl = webSocketUrl(server) + "?fi=machine-123&cid="; - conn = new Tunneler(new WebSocketTunnelTransport(client)) + conn = new Tunneler(new WebSocketTunnelTransport(client), new SessionDialGuard()) .tunnel(tunnelUrl, "session-123", new CapturingHandler()); RecordedRequest request = server.takeRequest(5, SECONDS); @@ -238,7 +238,7 @@ void omitsFlyForceInstanceHeaderWhenTunnelAddressHasNoFlyTarget() throws Excepti })); server.start(); - conn = new Tunneler(new WebSocketTunnelTransport(client)) + conn = new Tunneler(new WebSocketTunnelTransport(client), new SessionDialGuard()) .tunnel(webSocketUrl(server), "session-456", new CapturingHandler()); RecordedRequest request = server.takeRequest(5, SECONDS); @@ -269,7 +269,7 @@ public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { })); server.start(); - conn = new Tunneler(new WebSocketTunnelTransport(client)) + conn = new Tunneler(new WebSocketTunnelTransport(client), new SessionDialGuard()) .tunnel(webSocketUrl(server), "test-session", handler); return handler.awaitReceived(); diff --git a/core/src/test/java/com/minekube/connect/tunnel/WebSocketTunnelRefusalTest.java b/core/src/test/java/com/minekube/connect/tunnel/WebSocketTunnelRefusalTest.java new file mode 100644 index 000000000..c70df9941 --- /dev/null +++ b/core/src/test/java/com/minekube/connect/tunnel/WebSocketTunnelRefusalTest.java @@ -0,0 +1,110 @@ +package com.minekube.connect.tunnel; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import okhttp3.OkHttpClient; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.Test; + +/** Which tunnel service refusals mean "this session id is gone for good". */ +class WebSocketTunnelRefusalTest { + @Test + void goneIsAnAbandonedSession() throws Exception { + Outcome outcome = refuse(new MockResponse().setResponseCode(410)); + + assertEquals(410, outcome.abandonedStatus.get()); + assertNull(outcome.error.get()); + } + + @Test + void notFoundReportingAReleasedPendingEntryIsAnAbandonedSession() throws Exception { + Outcome outcome = refuse(new MockResponse() + .setResponseCode(404) + .setBody("tunnel session not found; connector version 0.15.18; requested Fly instance a; current Fly instance b; pending metadata released request_kind=join protocol=java age=4.1s released_ago=30ms; likely causes: expired session, released session (the dial ended before this request arrived), duplicate tunnel, stale connector, or tunnel request reached the wrong instance")); + + assertEquals(404, outcome.abandonedStatus.get()); + assertNull(outcome.error.get()); + } + + @Test + void notFoundWithAnyOtherPendingStateNeverLatchesDespiteTheStaticCausesText() throws Exception { + for (String state : new String[] {"absent", "pending", "consumed"}) { + Outcome outcome = refuse(new MockResponse() + .setResponseCode(404) + .setBody("tunnel session not found; connector version 0.15.18; requested Fly instance a; current Fly instance b; pending metadata "+state+" request_kind=join protocol=java age=4.1s released_ago=30ms; likely causes: expired session, released session (the dial ended before this request arrived), duplicate tunnel, stale connector, or tunnel request reached the wrong instance")); + + assertNotNull(outcome.error.get(), "pending metadata " + state + " is an ordinary dial failure"); + assertEquals(0, outcome.abandonedStatus.get(), "pending metadata " + state + " must not latch"); + } + } + + @Test + void bareNotFoundIsATransportFailureAndNeverLatches() throws Exception { + Outcome outcome = refuse(new MockResponse().setResponseCode(404).setBody("no route")); + + assertNotNull(outcome.error.get(), "a bare 404 is reported as an ordinary dial failure"); + assertEquals(0, outcome.abandonedStatus.get(), + "a 404 from a load balancer or a wrong route must not abandon the session"); + } + + @Test + void emptyNotFoundIsATransportFailureAndNeverLatches() throws Exception { + Outcome outcome = refuse(new MockResponse().setResponseCode(404)); + + assertNotNull(outcome.error.get()); + assertEquals(0, outcome.abandonedStatus.get()); + } + + private static Outcome refuse(MockResponse response) throws Exception { + OkHttpClient client = new OkHttpClient(); + Outcome outcome = new Outcome(); + try (MockWebServer server = new MockWebServer()) { + server.enqueue(response); + server.start(); + String url = server.url("/tunnel").toString().replaceFirst("^http:", "ws:"); + + new Tunneler(new WebSocketTunnelTransport(client), new SessionDialGuard()) + .tunnel(url, "s-1", outcome); + + await().atMost(5, SECONDS).until(outcome.closed::get); + return outcome; + } finally { + client.dispatcher().cancelAll(); + client.dispatcher().executorService().shutdownNow(); + client.connectionPool().evictAll(); + } + } + + private static final class Outcome implements TunnelConn.Handler { + private final AtomicInteger abandonedStatus = new AtomicInteger(); + private final AtomicReference error = new AtomicReference<>(); + private final java.util.concurrent.atomic.AtomicBoolean closed = + new java.util.concurrent.atomic.AtomicBoolean(); + + @Override + public void onReceive(byte[] data) { + } + + @Override + public void onError(Throwable t) { + error.set(t); + } + + @Override + public void onSessionAbandoned(int httpStatus) { + abandonedStatus.set(httpStatus); + } + + @Override + public void onClose() { + closed.set(true); + } + } +} diff --git a/core/src/test/java/com/minekube/connect/watch/WatchClientTest.java b/core/src/test/java/com/minekube/connect/watch/WatchClientTest.java index 8957b875c..ae9c61837 100644 --- a/core/src/test/java/com/minekube/connect/watch/WatchClientTest.java +++ b/core/src/test/java/com/minekube/connect/watch/WatchClientTest.java @@ -17,6 +17,9 @@ import com.minekube.connect.bedrock.BedrockPrincipalReadiness; import com.minekube.connect.bedrock.VerifiedBedrockIdentityRegistry; import com.minekube.connect.config.ConnectConfig; +import com.minekube.connect.tunnel.SessionDialGuard; +import java.util.ArrayList; +import java.util.List; import java.util.concurrent.atomic.AtomicReference; import minekube.connect.v1alpha1.WatchServiceOuterClass.Authentication; import minekube.connect.v1alpha1.WatchServiceOuterClass.GameProfile; @@ -49,7 +52,8 @@ void privateWatchSessionUsesCoordinatorTokenAndSanitizedProposal() { new BedrockIdentityReadiness( config, new BedrockIdentityKeyProvider(config, new OkHttpClient())), - coordinator); + coordinator, + new SessionDialGuard()); AtomicReference proposalRef = new AtomicReference<>(); Watcher watcher = new Watcher() { @Override public void onOpen(WatchBootstrap bootstrap) { } @@ -93,6 +97,111 @@ void privateWatchSessionUsesCoordinatorTokenAndSanitizedProposal() { } } + /** + * The edge re-proposes an unanswered session and a watch fail-over re-publishes it. A repeat + * delivery that is dropped must not stage a new admission: the coordinator supersedes the + * previous admission of a session id, which would invalidate the first delivery's token while + * it is still being set up. + */ + @Test + void repeatDeliveryIsDroppedWithoutSupersedingTheFirstAdmission() { + ConnectConfig config = new ConnectConfig(); + OkHttpClient httpClient = mock(OkHttpClient.class); + BedrockAdmissionCoordinator coordinator = + new BedrockAdmissionCoordinator(new VerifiedBedrockIdentityRegistry()); + WatchClient client = new WatchClient( + httpClient, + config, + new BedrockIdentityReadiness( + config, + new BedrockIdentityKeyProvider(config, new OkHttpClient())), + coordinator, + new SessionDialGuard()); + List proposals = new ArrayList<>(); + Watcher watcher = new Watcher() { + @Override public void onOpen(WatchBootstrap bootstrap) { } + @Override public void onProposal(SessionProposal proposal) { proposals.add(proposal); } + @Override public void onCompleted() { } + @Override public void onError(Throwable throwable) { } + }; + + try { + client.watch(watcher); + ArgumentCaptor listener = ArgumentCaptor.forClass(WebSocketListener.class); + verify(httpClient).newWebSocket(any(Request.class), listener.capture()); + WebSocket socket = mock(WebSocket.class); + ByteString delivery = ByteString.of(WatchResponse.newBuilder() + .setSession(rawSession("session-repeat")).build().toByteArray()); + + listener.getValue().onMessage(socket, delivery); + listener.getValue().onMessage(socket, delivery); + + assertEquals(1, proposals.size(), "the repeat delivery must be dropped"); + assertDoesNotThrow(() -> coordinator.stage(proposals.get(0)), + "the repeat delivery must not supersede the first delivery's admission"); + verify(socket, org.mockito.Mockito.never()).send(any(ByteString.class)); + } finally { + coordinator.close(); + } + } + + /** + * A claim only dedupes deliveries while the first one is alive. Once the first delivery is + * rejected (a transient local failure, a failed dial) the edge's redelivery must be served. + */ + @Test + void rejectedDeliveryReleasesTheClaimSoTheRedeliveryIsServed() { + ConnectConfig config = new ConnectConfig(); + OkHttpClient httpClient = mock(OkHttpClient.class); + BedrockAdmissionCoordinator coordinator = + new BedrockAdmissionCoordinator(new VerifiedBedrockIdentityRegistry()); + WatchClient client = new WatchClient( + httpClient, + config, + new BedrockIdentityReadiness( + config, + new BedrockIdentityKeyProvider(config, new OkHttpClient())), + coordinator, + new SessionDialGuard()); + List proposals = new ArrayList<>(); + Watcher watcher = new Watcher() { + @Override public void onOpen(WatchBootstrap bootstrap) { } + @Override public void onProposal(SessionProposal proposal) { proposals.add(proposal); } + @Override public void onCompleted() { } + @Override public void onError(Throwable throwable) { } + }; + + try { + client.watch(watcher); + ArgumentCaptor listener = ArgumentCaptor.forClass(WebSocketListener.class); + verify(httpClient).newWebSocket(any(Request.class), listener.capture()); + WebSocket socket = mock(WebSocket.class); + ByteString delivery = ByteString.of(WatchResponse.newBuilder() + .setSession(rawSession("session-retry")).build().toByteArray()); + + listener.getValue().onMessage(socket, delivery); + coordinator.reject(proposals.get(0), com.google.rpc.Status.newBuilder() + .setCode(com.google.rpc.Code.UNAVAILABLE_VALUE).build()); + listener.getValue().onMessage(socket, delivery); + + assertEquals(2, proposals.size(), "a redelivery after a rejection must be served"); + assertDoesNotThrow(() -> coordinator.stage(proposals.get(1))); + } finally { + coordinator.close(); + } + } + + private static Session rawSession(String id) { + return Session.newBuilder() + .setId(id) + .setPlayer(Player.newBuilder() + .setAddr("127.0.0.1") + .setProfile(GameProfile.newBuilder() + .setId("f912bf90-8349-565f-9dc0-9891923c0cc3") + .setName("Player"))) + .build(); + } + @Test void closedCoordinatorRejectsProposalInsteadOfFailingTheWatch() throws Exception { ConnectConfig config = new ConnectConfig(); @@ -105,7 +214,8 @@ void closedCoordinatorRejectsProposalInsteadOfFailingTheWatch() throws Exception new BedrockIdentityReadiness( config, new BedrockIdentityKeyProvider(config, new OkHttpClient())), - coordinator); + coordinator, + new SessionDialGuard()); java.util.concurrent.atomic.AtomicReference proposalRef = new java.util.concurrent.atomic.AtomicReference<>(); java.util.concurrent.atomic.AtomicReference errorRef = @@ -154,7 +264,7 @@ void closedCoordinatorRejectsProposalInsteadOfFailingTheWatch() throws Exception @Test void defaultDisabledConfigurationDoesNotAdvertiseBedrockIdentity() { OkHttpClient httpClient = mock(OkHttpClient.class); - WatchClient client = new WatchClient(httpClient, new ConnectConfig()); + WatchClient client = new WatchClient(httpClient, new ConnectConfig(), new SessionDialGuard()); client.watch(new Watcher() { @Override public void onOpen(WatchBootstrap bootstrap) { } @@ -173,7 +283,7 @@ void defaultDisabledConfigurationDoesNotAdvertiseBedrockIdentity() { void readinessChallengeIsAnsweredAndNeverDeliveredAsSession() { ConnectConfig config = new ConnectConfig(); OkHttpClient httpClient = mock(OkHttpClient.class); - WatchClient client = new WatchClient(httpClient, config); + WatchClient client = new WatchClient(httpClient, config, new SessionDialGuard()); Watcher watcher = mock(Watcher.class); WebSocket socket = mock(WebSocket.class);