-
-
Notifications
You must be signed in to change notification settings - Fork 722
/
SocketProtocolBase.cs
89 lines (75 loc) · 2.53 KB
/
SocketProtocolBase.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using StrawberryShake.Transport.WebSockets.Messages;
namespace StrawberryShake.Transport.WebSockets;
/// <summary>
/// A protocol that can be used to communicate to a GraphQL server over
/// <see cref="ISocketClient"/>
/// </summary>
public abstract class SocketProtocolBase : ISocketProtocol
{
private bool _disposed;
private readonly HashSet<OnReceiveAsync> _listeners = new();
/// <inheritdoc />
public event EventHandler Disposed = default!;
/// <inheritdoc />
public abstract Task StartOperationAsync(
string operationId,
OperationRequest request,
CancellationToken cancellationToken);
/// <inheritdoc />
public abstract Task StopOperationAsync(
string operationId,
CancellationToken cancellationToken);
/// <inheritdoc />
public abstract Task InitializeAsync(CancellationToken cancellationToken);
/// <inheritdoc />
public abstract Task TerminateAsync(CancellationToken cancellationToken);
/// <inheritdoc />
public void Subscribe(OnReceiveAsync listener)
{
_listeners.Add(listener);
}
/// <inheritdoc />
public void Unsubscribe(OnReceiveAsync listener)
{
_listeners.Remove(listener);
}
/// <summary>
/// Notify all listeners that a message is received
/// </summary>
/// <param name="operationId">The ide of the operation that the message belongs to</param>
/// <param name="message">The operation message</param>
/// <param name="cancellationToken">A token to cancel processing the message</param>
/// <returns>A value task that is completed once all subscribers are notified</returns>
protected async ValueTask Notify(
string operationId,
OperationMessage message,
CancellationToken cancellationToken)
{
foreach (var listener in _listeners)
{
await listener(operationId, message, cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public async ValueTask NotifyCompletion(
string operationId,
CancellationToken cancellationToken)
{
await Notify(operationId, CompleteOperationMessage.Default, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public virtual ValueTask DisposeAsync()
{
if (!_disposed)
{
return default;
}
Disposed.Invoke(this, EventArgs.Empty);
_disposed = true;
return default;
}
}