ConnectionManager: no longer throw IOExceptions, add async method for getting connections, and change getURIs to add explicitly advertised addresses.

This commit is contained in:
Nekojimi 2025-10-02 00:13:01 +01:00
parent a14701f5c5
commit fee20875a1

View file

@ -1,12 +1,17 @@
package moe.nekojimi.friendcloud.network;
import moe.nekojimi.friendcloud.Main;
import moe.nekojimi.friendcloud.objects.ObjectID;
import moe.nekojimi.friendcloud.objects.Peer;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class ConnectionManager
{
@ -31,17 +36,17 @@ public class ConnectionManager
}
}
public PeerConnection getNodeConnection(URI uri) throws IOException
public PeerConnection getNodeConnection(URI uri)
{
return getNodeConnection(uri, null);
}
public PeerConnection getNodeConnection(URI uri, Peer peer) throws IOException
public PeerConnection getNodeConnection(URI uri, Peer peer)
{
purgeDeadConnections();
for (PeerConnection peerConnection: activeConnections)
{
if (peerConnection.getUri() == uri)
if (peerConnection.getUri().equals(uri))
return peerConnection;
}
@ -68,19 +73,19 @@ public class ConnectionManager
for (URI address : peer.getAddresses())
{
try
{
return getNodeConnection(address, peer);
}
catch (IOException ex)
{
System.err.println("ConnectionManager: Couldn't create PeerConnection to " + address + " : " + ex.getMessage());
}
PeerConnection connection = getNodeConnection(address, peer);
if (connection != null)
return connection;
}
System.err.println("ConnectionManager: Failed to create PeerConnection to " + peer + "!");
return null;
}
public CompletableFuture<Optional<PeerConnection>> getNodeConnectionAsync(Peer peer)
{
return CompletableFuture.supplyAsync(() -> Optional.ofNullable(getNodeConnection(peer)), Main.getInstance().getExecutor());
}
public void shutdown()
{
for (ConnectionBackend<?> backend : backends.values())
@ -123,9 +128,24 @@ public class ConnectionManager
public List<URI> getURIs()
{
return backends.values().stream()
.filter(ConnectionBackend::isListening)
.flatMap(connectionBackend -> connectionBackend.getURIs().stream())
.toList();
List<URI> ret = new ArrayList<>();
for (String advertiseAddress : Main.getInstance().getArgs().getAdvertiseAddresses())
{
try
{
URI uri = new URI(advertiseAddress);
ret.add(uri);
} catch (URISyntaxException e)
{
System.err.println("ERROR: " + advertiseAddress + " isn't a valid URI: " + e.getMessage());
}
}
for (ConnectionBackend<?> backend: backends.values())
{
if (!backend.isListening())
continue;
ret.addAll(backend.getURIs());
}
return ret;
}
}