Skip to content

Commit

Permalink
Use EndpointInfo (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShortDevelopment committed Mar 12, 2024
1 parent 4e05e07 commit be987ad
Show file tree
Hide file tree
Showing 30 changed files with 107 additions and 160 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ void HandleStartTransfer(CdpMessage msg, ValueSet payload)
}
_fileTransferToken = new()
{
DeviceName = Channel.Session.Device.Name,
DeviceName = Channel.Session.DeviceName,
TotalBytes = bytesToSend,
Files = files
};
Expand All @@ -88,7 +88,7 @@ void HandleStartTransfer(CdpMessage msg, ValueSet payload)

NearShareReceiver.OnReceivedUri(new()
{
DeviceName = Channel.Session.Device.Name,
DeviceName = Channel.Session.DeviceName,
Uri = uri
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using ShortDev.Microsoft.ConnectedDevices.Messages.Session;
using ShortDev.Microsoft.ConnectedDevices.NearShare.Apps;
using ShortDev.Microsoft.ConnectedDevices.NearShare.Messages;
using ShortDev.Microsoft.ConnectedDevices.Platforms;
using ShortDev.Microsoft.ConnectedDevices.Serialization;

namespace ShortDev.Microsoft.ConnectedDevices.NearShare;
Expand All @@ -12,9 +11,9 @@ public sealed class NearShareSender(ConnectedDevicesPlatform platform)
{
public ConnectedDevicesPlatform Platform { get; } = platform;

async Task<SenderStateMachine> PrepareTransferInternalAsync(CdpDevice device, CancellationToken cancellationToken)
async Task<SenderStateMachine> PrepareTransferInternalAsync(EndpointInfo endpoint, CancellationToken cancellationToken)
{
var session = await Platform.ConnectAsync(device);
var session = await Platform.ConnectAsync(endpoint);

Guid operationId = Guid.NewGuid();

Expand All @@ -32,7 +31,7 @@ async Task<SenderStateMachine> PrepareTransferInternalAsync(CdpDevice device, Ca

public async Task SendUriAsync(CdpDevice device, Uri uri, CancellationToken cancellationToken = default)
{
using var senderStateMachine = await PrepareTransferInternalAsync(device, cancellationToken);
using var senderStateMachine = await PrepareTransferInternalAsync(device.Endpoint, cancellationToken);
await senderStateMachine.SendUriAsync(uri);
}

Expand All @@ -41,7 +40,7 @@ public async Task SendFileAsync(CdpDevice device, CdpFileProvider file, IProgres

public async Task SendFilesAsync(CdpDevice device, IReadOnlyList<CdpFileProvider> files, IProgress<NearShareProgress> progress, CancellationToken cancellationToken = default)
{
using var senderStateMachine = await PrepareTransferInternalAsync(device, cancellationToken);
using var senderStateMachine = await PrepareTransferInternalAsync(device.Endpoint, cancellationToken);
await senderStateMachine.SendFilesAsync(files, progress, cancellationToken);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/ShortDev.Microsoft.ConnectedDevices/CdpChannel.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using ShortDev.Microsoft.ConnectedDevices.Messages;
using ShortDev.Microsoft.ConnectedDevices.Messages.Control;
using ShortDev.Microsoft.ConnectedDevices.Messages.Session;
using ShortDev.Microsoft.ConnectedDevices.Platforms;
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System;
using System.Collections.Generic;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;

namespace ShortDev.Microsoft.ConnectedDevices.Platforms;
namespace ShortDev.Microsoft.ConnectedDevices;

public record CdpDevice(string Name, DeviceType Type, EndpointInfo Endpoint)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
using System.Collections.Generic;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection;
using System.Text.Json.Serialization;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;

namespace ShortDev.Microsoft.ConnectedDevices.Messages.Connection.DeviceInfo;
namespace ShortDev.Microsoft.ConnectedDevices;

public sealed record CdpDeviceInfo
{
Expand Down
6 changes: 2 additions & 4 deletions lib/ShortDev.Microsoft.ConnectedDevices/CdpLog.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using Microsoft.Extensions.Logging;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.DeviceInfo;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;
using ShortDev.Microsoft.ConnectedDevices.Messages.Control;
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System;
Expand All @@ -25,8 +23,8 @@ internal static partial class CdpLog
public static partial void ListeningStopped(this ILogger logger);


[LoggerMessage(EventId = 105, Level = LogLevel.Information, Message = "Device {DeviceName} connected with endpoint {Endpoint}")]
public static partial void DeviceConnected(this ILogger logger, string deviceName, EndpointInfo endpoint);
[LoggerMessage(EventId = 105, Level = LogLevel.Information, Message = "New socket from endpoint {Endpoint}")]
public static partial void NewSocket(this ILogger logger, EndpointInfo endpoint);



Expand Down
30 changes: 17 additions & 13 deletions lib/ShortDev.Microsoft.ConnectedDevices/CdpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.Authentication;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.DeviceInfo;
using ShortDev.Microsoft.ConnectedDevices.Messages.Control;
using ShortDev.Microsoft.ConnectedDevices.Platforms;
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System.Collections.Concurrent;

namespace ShortDev.Microsoft.ConnectedDevices;
Expand All @@ -26,27 +26,29 @@ public sealed class CdpSession : IDisposable
public PeerCapabilities ClientCapabilities { get; private set; } = 0;

public ConnectedDevicesPlatform Platform { get; }
public CdpDevice Device { get; private set; }
public CdpDeviceInfo? DeviceInfo { get; private set; }
public string DeviceName => DeviceInfo?.Name ?? "UNKNOWN";
public EndpointInfo Endpoint { get; private set; }

readonly ILogger<CdpSession> _logger;
readonly UpgradeHandler _upgradeHandler;
readonly ConnectHandler _connectHandler;
private CdpSession(ConnectedDevicesPlatform platform, CdpDevice device, SessionId sessionId)
private CdpSession(ConnectedDevicesPlatform platform, EndpointInfo initialEndpoint, SessionId sessionId)
{
Platform = platform;
Device = device;
Endpoint = initialEndpoint;
SessionId = sessionId;

_logger = platform.CreateLogger<CdpSession>();
_upgradeHandler = new(this, device);
_upgradeHandler = new(this, initialEndpoint);
_connectHandler = new(this, _upgradeHandler);
}

#region Registration
static readonly AutoKeyRegistry<uint, CdpSession> _sessionRegistry = [];
internal static CdpSession GetOrCreate(ConnectedDevicesPlatform platform, CdpDevice device, CommonHeader header)
internal static CdpSession GetOrCreate(ConnectedDevicesPlatform platform, EndpointInfo initialEndpoint, CommonHeader header)
{
ArgumentNullException.ThrowIfNull(device);
ArgumentNullException.ThrowIfNull(initialEndpoint);
ArgumentNullException.ThrowIfNull(header);

var (_, localSessionId, remoteSessionId) = SessionId.Parse(header.SessionId);
Expand Down Expand Up @@ -74,7 +76,7 @@ internal static CdpSession GetOrCreate(ConnectedDevicesPlatform platform, CdpDev
// Create
return _sessionRegistry.Create(localSessionId => new(
platform,
device,
initialEndpoint,
sessionId: new(IsHost: true, localSessionId, remoteSessionId)
), out _);
}
Expand All @@ -83,7 +85,7 @@ internal static async Task<CdpSession> CreateClientAndConnectAsync(ConnectedDevi
{
var session = _sessionRegistry.Create(localSessionId => new(
platform,
socket.RemoteDevice,
socket.Endpoint,
sessionId: new(IsHost: false, localSessionId)
), out _);

Expand Down Expand Up @@ -175,7 +177,7 @@ public void HandleMessage(CdpSocket socket, CommonHeader header, ref EndianReade
}

if (!_upgradeHandler.IsSocketAllowed(socket))
throw UnexpectedMessage(socket.RemoteDevice.Endpoint.Address);
throw UnexpectedMessage(socket.Endpoint.Address);

if (header.Type == MessageType.Control)
{
Expand Down Expand Up @@ -255,7 +257,7 @@ public void HandleConnect(CdpSocket socket, CommonHeader header, ref EndianReade
return;

if (!_upgradeHandler.IsSocketAllowed(socket))
throw UnexpectedMessage(socket.RemoteDevice.Endpoint.Address);
throw UnexpectedMessage(socket.Endpoint.Address);

if (connectionHeader.MessageType == ConnectionType.ConnectRequest)
{
Expand Down Expand Up @@ -428,7 +430,7 @@ async void PrepareSession(CdpSocket socket)
socket = await _upgradeHandler.RequestUpgradeAsync(oldSocket);
oldSocket.Dispose();

_session.Device = socket.RemoteDevice;
_session.Endpoint = socket.Endpoint;
}
catch (Exception ex)
{
Expand Down Expand Up @@ -495,6 +497,8 @@ void HandleDeviceInfoMessage(CommonHeader header, ref EndianReader reader, CdpSo
var msg = DeviceInfoMessage.Parse(ref reader);
_logger.ReceivedDeviceInfo(msg.DeviceInfo);

_session.DeviceInfo = msg.DeviceInfo;

header.Flags = 0;
_session.SendMessage(socket, header, (writer) =>
{
Expand Down Expand Up @@ -637,7 +641,7 @@ public async Task<CdpChannel> StartClientChannelAsync(string appId, string appNa
if (IsHost)
throw new InvalidOperationException("Session is not a client");

var socket = await Platform.CreateSocketAsync(Device);
var socket = await Platform.CreateSocketAsync(Endpoint);
return await StartClientChannelAsync(appId, appName, handler, socket, cancellationToken);
}

Expand Down
31 changes: 14 additions & 17 deletions lib/ShortDev.Microsoft.ConnectedDevices/ConnectedDevicesPlatform.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using Microsoft.Extensions.Logging;
using ShortDev.Microsoft.ConnectedDevices.Encryption;
using ShortDev.Microsoft.ConnectedDevices.Messages;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.DeviceInfo;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;
using ShortDev.Microsoft.ConnectedDevices.Platforms;
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System.Buffers;
using System.Collections.Concurrent;
Expand Down Expand Up @@ -87,7 +84,7 @@ public async void Listen(CancellationToken cancellationToken)

private void OnDeviceConnected(ICdpTransport sender, CdpSocket socket)
{
_logger.DeviceConnected(socket.RemoteDevice.Name, socket.RemoteDevice.Endpoint);
_logger.NewSocket(socket.Endpoint);
ReceiveLoop(socket);
}
#endregion
Expand Down Expand Up @@ -121,33 +118,33 @@ public async void Discover(CancellationToken cancellationToken)
}
}

public async Task<CdpSession> ConnectAsync(CdpDevice device)
public async Task<CdpSession> ConnectAsync(EndpointInfo endpoint)
{
var socket = await CreateSocketAsync(device);
var socket = await CreateSocketAsync(endpoint);
return await CdpSession.CreateClientAndConnectAsync(this, socket);
}

internal async Task<CdpSocket> CreateSocketAsync(CdpDevice device)
internal async Task<CdpSocket> CreateSocketAsync(EndpointInfo endpoint)
{
if (TryGetKnownSocket(device.Endpoint, out var knownSocket))
if (TryGetKnownSocket(endpoint, out var knownSocket))
return knownSocket;

var transport = TryGetTransport(device.Endpoint.TransportType) ?? throw new InvalidOperationException($"No single transport found for type {device.Endpoint.TransportType}");
var socket = await transport.ConnectAsync(device);
var transport = TryGetTransport(endpoint.TransportType) ?? throw new InvalidOperationException($"No single transport found for type {endpoint.TransportType}");
var socket = await transport.ConnectAsync(endpoint);
ReceiveLoop(socket);
return socket;
}

internal async Task<CdpSocket?> TryCreateSocketAsync(CdpDevice device, TimeSpan connectTimeout)
internal async Task<CdpSocket?> TryCreateSocketAsync(EndpointInfo endpoint, TimeSpan connectTimeout)
{
if (TryGetKnownSocket(device.Endpoint, out var knownSocket))
if (TryGetKnownSocket(endpoint, out var knownSocket))
return knownSocket;

var transport = TryGetTransport(device.Endpoint.TransportType);
var transport = TryGetTransport(endpoint.TransportType);
if (transport == null)
return null;

var socket = await transport.TryConnectAsync(device, connectTimeout);
var socket = await transport.TryConnectAsync(endpoint, connectTimeout);
if (socket == null)
return null;

Expand Down Expand Up @@ -177,7 +174,7 @@ private void ReceiveLoop(CdpSocket socket)
session = CdpSession.GetOrCreate(
this,
socket.RemoteDevice ?? throw new InvalidDataException(),
socket.Endpoint,
header
);
Expand Down Expand Up @@ -215,11 +212,11 @@ void RegisterKnownSocket(CdpSocket socket)
socket.Disposed += OnSocketClosed;
void OnSocketClosed()
{
_knownSockets.TryRemove(socket.RemoteDevice.Endpoint, out _); // ToDo: We might remove a newer socket here!!
_knownSockets.TryRemove(socket.Endpoint, out _); // ToDo: We might remove a newer socket here!!
socket.Disposed -= OnSocketClosed;
}

_knownSockets.AddOrUpdate(socket.RemoteDevice.Endpoint, socket, (key, current) =>
_knownSockets.AddOrUpdate(socket.Endpoint, socket, (key, current) =>
{
// ToDo: Alive check
return socket;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.Json.Serialization;

namespace ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;
namespace ShortDev.Microsoft.ConnectedDevices;

public record class EndpointInfo(
[property: JsonPropertyName("endpointType")] CdpTransportType TransportType,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System.Collections;

namespace ShortDev.Microsoft.ConnectedDevices.Internal;

internal sealed class ConcurrentList<T>
internal sealed class SynchronizedList<T> : IEnumerable<T>
{
readonly List<T> _data = [];

Expand All @@ -23,4 +23,10 @@ public bool Contains(T item)
lock (_data)
return _data.Contains(item);
}

public IEnumerator<T> GetEnumerator()
=> _data.GetEnumerator();

IEnumerator IEnumerable.GetEnumerator()
=> _data.GetEnumerator();
}
Loading

0 comments on commit be987ad

Please sign in to comment.