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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<TunnelClientTransport> transports =
Multibinder.newSetBinder(binder(), TunnelClientTransport.class);
transports.addBinding().to(WebSocketTunnelTransport.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -44,6 +45,11 @@
public class LocalChannelInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {
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;
Expand Down Expand Up @@ -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();
Expand Down
210 changes: 210 additions & 0 deletions core/src/main/java/com/minekube/connect/tunnel/SessionDialGuard.java
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>Two failure modes are prevented, both measured on the fleet:
*
* <ul>
* <li><b>Two dials for one session id.</b> A session proposal is delivered more than once for
* the same id (the edge's unanswered-proposal retry every {@code proposalAnswerTimeout}, a
* watch fail-over re-publish, or a transport-level retry). Every delivery used to open its
* own {@code LocalSession} and therefore its own tunnel. The edge's invariant allows one
* tunnel per session, so the repeats must be absorbed. {@link #tryAcceptDelivery(String)}
* claims the id; a repeat delivery is dropped instead of dialled. The claim is released by
* {@link #release(String)} when the delivery is rejected or fails, so a redelivery after a
* transient failure is served instead of silently dropped.</li>
* <li><b>Dialling after the edge gave up.</b> When the tunnel service answers the dial with
* "session gone" (410, or a 404 saying its pending entry was released) the
* session is gone for good - the edge never re-arms a released entry - so every later dial
* for that id is guaranteed to fail. {@link #abandon(String)} latches that, and
* {@link #isAbandoned(String)} is what {@link Tunneler} refuses to dial through.</li>
* </ul>
*
* <p>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<String, Entry> 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<String> 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<Entry> 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;
}
}
}
14 changes: 14 additions & 0 deletions core/src/main/java/com/minekube/connect/tunnel/TunnelConn.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
* <p>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);
Expand Down
Loading
Loading