Skip to content
This repository was archived by the owner on Jan 5, 2026. It is now read-only.
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 @@ -23,6 +23,7 @@ public abstract class StreamingConnection : IDisposable
private readonly TaskCompletionSource<bool> _sessionInitializedTask = new TaskCompletionSource<bool>();

private StreamingTransport _transport;
private TransportHandler _application;
private StreamingSession _session;

private bool _disposedValue;
Expand Down Expand Up @@ -77,6 +78,9 @@ public virtual async Task<ReceiveResponse> SendStreamingRequestAsync(StreamingRe
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public virtual async Task ListenAsync(RequestHandler requestHandler, CancellationToken cancellationToken = default)
{
_transport?.Dispose();
_application?.Dispose();

if (requestHandler == null)
{
throw new ArgumentNullException(nameof(requestHandler));
Expand All @@ -86,14 +90,14 @@ public virtual async Task ListenAsync(RequestHandler requestHandler, Cancellatio

// Create transport and application
_transport = CreateStreamingTransport(duplexPipePair.Application);
var application = new TransportHandler(duplexPipePair.Transport, Logger);
_application = new TransportHandler(duplexPipePair.Transport, Logger);

// Create session
_session = new StreamingSession(requestHandler, application, Logger, cancellationToken);
_session = new StreamingSession(requestHandler, _application, Logger, cancellationToken);

// Start transport and application
var transportTask = _transport.ConnectAsync(cancellationToken);
var applicationTask = application.ListenAsync(cancellationToken);
var transportTask = _transport.ConnectAsync(default, cancellationToken);
var applicationTask = _application.ListenAsync(cancellationToken);

var tasks = new List<Task> { transportTask, applicationTask };

Expand Down Expand Up @@ -125,6 +129,7 @@ protected virtual void Dispose(bool disposing)
if (disposing)
{
_transport?.Dispose();
_application?.Dispose();
}

_disposedValue = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public async Task ConnectAsync(IDictionary<string, string> requestHeaders)
public async Task ConnectAsync(IDictionary<string, string> requestHeaders, CancellationToken cancellationToken)
{
await ConnectImplAsync(
connectFunc: transport => transport.ConnectAsync(_url, requestHeaders, cancellationToken),
connectFunc: (transport, connectionStatusChanged) => transport.ConnectAsync(_url, connectionStatusChanged, requestHeaders, cancellationToken),
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
Expand Down Expand Up @@ -137,7 +137,7 @@ public void Dispose()
internal async Task ConnectInternalAsync(CancellationToken cancellationToken)
{
await ConnectImplAsync(
connectFunc: transport => transport.ConnectAsync(cancellationToken),
connectFunc: (transport, connectionStatusChanged) => transport.ConnectAsync(connectionStatusChanged, cancellationToken),
cancellationToken: cancellationToken)
.ConfigureAwait(false);
}
Expand Down Expand Up @@ -182,10 +182,13 @@ private static bool IsSuccessResponse(ReceiveResponse response)
return response != null && response.StatusCode >= 200 && response.StatusCode <= 299;
}

private async Task ConnectImplAsync(Func<StreamingTransport, Task> connectFunc, CancellationToken cancellationToken)
private async Task ConnectImplAsync(Func<StreamingTransport, Action<bool>, Task> connectFunc, CancellationToken cancellationToken)
{
CheckDisposed();

_transport?.Dispose();
_application?.Dispose();

TimerAwaitable timer = null;
Task timerTask = null;

Expand All @@ -207,7 +210,7 @@ private async Task ConnectImplAsync(Func<StreamingTransport, Task> connectFunc,
_disconnectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

// Start transport and application
var transportTask = connectFunc(_transport);
var transportTask = connectFunc(_transport, connect => IsConnected = connect);
var applicationTask = _application.ListenAsync(_disconnectCts.Token);
var combinedTask = Task.WhenAll(transportTask, applicationTask);

Expand All @@ -221,9 +224,6 @@ private async Task ConnectImplAsync(Func<StreamingTransport, Task> connectFunc,
timerTask = TimerLoopAsync(timer);
}

// We are connected!
IsConnected = true;

// Block until transport or application ends.
await combinedTask.ConfigureAwait(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ internal class NamedPipeTransport : StreamingTransport
private PipeStream _receiver;
private PipeStream _sender;
private bool _disposedValue;
private int _tryTimes;

public NamedPipeTransport(string pipeName, IDuplexPipe application, ILogger logger)
: base(application, logger)
Expand All @@ -34,64 +35,44 @@ public NamedPipeTransport(string pipeName, IDuplexPipe application, ILogger logg
_pipeName = pipeName;
}

public override async Task ConnectAsync(CancellationToken cancellationToken)
public override async Task ConnectAsync(Action<bool> connectionStatusChanged = null, CancellationToken cancellationToken = default)
{
Log.NamedPipeOpened(Logger);

try
{
_receiver = new NamedPipeServerStream(
pipeName: _pipeName + ServerIncomingPath,
PipeDirection.In,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);

await ((NamedPipeServerStream)_receiver).WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);

_sender = new NamedPipeServerStream(
pipeName: _pipeName + ServerOutgoingPath,
PipeDirection.Out,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);

await ((NamedPipeServerStream)_sender).WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);

await RetryToSucceedAsync(CreateNamedPipeServerAsync, cancellationToken).ConfigureAwait(false);
connectionStatusChanged?.Invoke(true);
await ProcessAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception)
{
throw;
}
finally
{
Log.NamedPipeClosed(Logger);
connectionStatusChanged?.Invoke(false);
}
}

public override async Task ConnectAsync(string url, IDictionary<string, string> requestHeaders = null, CancellationToken cancellationToken = default)
public override async Task ConnectAsync(string url, Action<bool> connectionStatusChanged = null, IDictionary<string, string> requestHeaders = null, CancellationToken cancellationToken = default)
{
Log.NamedPipeOpened(Logger);

try
{
_sender = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName + ServerIncomingPath,
PipeDirection.Out,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);

await ((NamedPipeClientStream)_sender).ConnectAsync(cancellationToken).ConfigureAwait(false);

_receiver = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName + ServerOutgoingPath,
PipeDirection.In,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);

await ((NamedPipeClientStream)_receiver).ConnectAsync(cancellationToken).ConfigureAwait(false);

await RetryToSucceedAsync(CreateNamedPipeClientAsync, cancellationToken).ConfigureAwait(false);
connectionStatusChanged?.Invoke(true);
await ProcessAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception)
{
throw;
}
finally
{
connectionStatusChanged?.Invoke(false);
Log.NamedPipeClosed(Logger);
}
}
Expand All @@ -106,11 +87,12 @@ protected override async Task<int> ReceiveAsync(Memory<byte> buffer, Cancellatio
var result = await _receiver.ReadAsync(temp, offset: 0, count, cancellationToken).ConfigureAwait(false);
temp.CopyTo(buffer.Span);

return result;
// NamedPipe disconnection not always throw InvalidOperationException
return _receiver.IsConnected ? result : -1;
Comment thread
woasishen marked this conversation as resolved.
Resolved
}
catch (InvalidOperationException)
{
// Named Pipe is disconnected
// NamedPipe is disconnected
return -1;
}
}
Expand Down Expand Up @@ -152,6 +134,93 @@ protected override void Dispose(bool disposing)
}
}

private async Task RetryToSucceedAsync(Func<CancellationToken, Task> createNamedPipeFactory, CancellationToken cancellationToken)
{
_tryTimes = 0;

// TryTimes exhausted happens when customers use the app.UsedNamedPipe in their bot, but do not enable ase.
while (!cancellationToken.IsCancellationRequested && _tryTimes < 100)
{
_tryTimes++;

// To avoid NamedPipeServer and NamedPipeClient dead lock, use random backoff when create NamePipe
using (var source = new CancellationTokenSource())
{
try
{
// NamedPipeServer and NamedPipeClient dead lock can be break by time out
// Add this random backoff to avoid a special dead lock when machine run slow.
// At least 5 seconds, because :
// If ASE update to new version but customer still use old version bot(SDK). Quick retry will make this connection never connect.
var timeoutTask = Task.Delay(TimeSpan.FromSeconds((new Random(DateTime.Now.Millisecond).NextDouble() * _tryTimes) + 5), cancellationToken);
Comment thread
woasishen marked this conversation as resolved.
Resolved
var createTask = createNamedPipeFactory(source.Token);

if (timeoutTask == await Task.WhenAny(timeoutTask, createTask).ConfigureAwait(false))
{
Log.NamedPipeCreateTimeout(Logger);
source.Cancel();
continue;
}

// Check createTask finish code. (Task.WhenAny can't catch exception in createTask)
await createTask.ConfigureAwait(false);

// Connect succeed
return;
}
#pragma warning disable CA1031 // Catch all exceptions and retry
catch (Exception e)
#pragma warning restore CA1031
{
Log.NamedPipeCreateException(Logger, e);
source.Cancel();
}
}
}
}

private async Task CreateNamedPipeClientAsync(CancellationToken cancellationToken)
{
_sender?.Dispose();
_receiver?.Dispose();

_sender = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName + ServerIncomingPath,
PipeDirection.Out,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);
await ((NamedPipeClientStream)_sender).ConnectAsync(cancellationToken).ConfigureAwait(false);

_receiver = new NamedPipeClientStream(
serverName: ".",
pipeName: _pipeName + ServerOutgoingPath,
PipeDirection.In,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);
await ((NamedPipeClientStream)_receiver).ConnectAsync(cancellationToken).ConfigureAwait(false);
}

private async Task CreateNamedPipeServerAsync(CancellationToken cancellationToken)
{
_sender?.Dispose();
_receiver?.Dispose();

_receiver = new NamedPipeServerStream(
pipeName: _pipeName + ServerIncomingPath,
PipeDirection.In,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);
await ((NamedPipeServerStream)_receiver).WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);

_sender = new NamedPipeServerStream(
pipeName: _pipeName + ServerOutgoingPath,
PipeDirection.Out,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
options: System.IO.Pipes.PipeOptions.WriteThrough | System.IO.Pipes.PipeOptions.Asynchronous);
await ((NamedPipeServerStream)_sender).WaitForConnectionAsync(cancellationToken).ConfigureAwait(false);
}

/// <summary>
/// Log messages for <see cref="NamedPipeTransport"/>.
/// </summary>
Expand All @@ -161,12 +230,22 @@ protected override void Dispose(bool disposing)
/// </remarks>
private static class Log
{
private static readonly Action<ILogger, Exception> _namedPipeCreateTimeout = LoggerMessage.Define(
LogLevel.Information, new EventId(1, nameof(NamedPipeOpened)), "Create NamedPipe Timeout.");

private static readonly Action<ILogger, Exception> _namedPipeCreateException = (_, e) => LoggerMessage.Define(
LogLevel.Information, new EventId(1, nameof(NamedPipeOpened)), $"Create NamedPipe with exception:{e}");

private static readonly Action<ILogger, Exception> _namedPipeOpened = LoggerMessage.Define(
LogLevel.Information, new EventId(1, nameof(NamedPipeOpened)), "Named Pipe transport connection opened.");

private static readonly Action<ILogger, Exception> _namedPipeClosed = LoggerMessage.Define(
LogLevel.Information, new EventId(2, nameof(NamedPipeClosed)), "Named Pipe transport connection closed.");

public static void NamedPipeCreateException(ILogger logger, Exception e) => _namedPipeCreateException(logger, e);

public static void NamedPipeCreateTimeout(ILogger logger) => _namedPipeCreateTimeout(logger, null);

public static void NamedPipeOpened(ILogger logger) => _namedPipeOpened(logger, null);

public static void NamedPipeClosed(ILogger logger) => _namedPipeClosed(logger, null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ protected StreamingTransport(IDuplexPipe application, ILogger logger)

protected ILogger Logger { get; }

public abstract Task ConnectAsync(CancellationToken cancellationToken);
public abstract Task ConnectAsync(Action<bool> connectionStatusChanged = null, CancellationToken cancellationToken = default);

public abstract Task ConnectAsync(string url, IDictionary<string, string> requestHeaders = null, CancellationToken cancellationToken = default);
public abstract Task ConnectAsync(string url, Action<bool> connectionStatusChanged = null, IDictionary<string, string> requestHeaders = null, CancellationToken cancellationToken = default);

/// <inheritdoc />
public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,23 @@ public WebSocketTransport(WebSocket socket, IDuplexPipe application, ILogger log
_socket = socket ?? throw new ArgumentNullException(nameof(socket));
}

public override async Task ConnectAsync(CancellationToken cancellationToken)
public override async Task ConnectAsync(Action<bool> connectionStatusChanged = null, CancellationToken cancellationToken = default)
{
Log.SocketOpened(Logger);

try
{
connectionStatusChanged?.Invoke(true);
await ProcessAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
connectionStatusChanged?.Invoke(false);
Log.SocketClosed(Logger);
}
}

public override async Task ConnectAsync(string url, IDictionary<string, string> requestHeaders = null, CancellationToken cancellationToken = default)
public override async Task ConnectAsync(string url, Action<bool> connectionStatusChanged = null, IDictionary<string, string> requestHeaders = null, CancellationToken cancellationToken = default)
{
Log.SocketOpened(Logger);

Expand All @@ -55,7 +57,7 @@ public override async Task ConnectAsync(string url, IDictionary<string, string>
}

await clientSocket.ConnectAsync(new Uri(url), cancellationToken).ConfigureAwait(false);

connectionStatusChanged?.Invoke(true);
await ProcessAsync(cancellationToken).ConfigureAwait(false);
}
else
Expand All @@ -65,6 +67,7 @@ public override async Task ConnectAsync(string url, IDictionary<string, string>
}
finally
{
connectionStatusChanged?.Invoke(false);
Log.SocketClosed(Logger);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ public async Task WebSocketTransport_ClientServer_WhatIsSentIsReceived()
var serverTransport = new WebSocketTransport(await webSocketFeature.AcceptAsync(), serverPipePair.Application, NullLogger.Instance);

// Accept server web socket, start receiving / sending at the transport level
var serverTask = serverTransport.ConnectAsync(CancellationToken.None);
var serverTask = serverTransport.ConnectAsync();
Comment thread
woasishen marked this conversation as resolved.
Resolved

var clientTransport = new WebSocketTransport(webSocketFeature.Client, clientPipePair.Application, NullLogger.Instance);
var clientTask = clientTransport.ConnectAsync(CancellationToken.None);
var clientTask = clientTransport.ConnectAsync();

// Send a frame client -> server
await clientPipePair.Transport.Output.WriteAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")));
Expand Down
Loading