aboutsummaryrefslogtreecommitdiff
path: root/lib/Plugins.Essentials/src/WebSocketSession.cs
blob: 6c77003d028bbcdedfefdc336bde8d22e9a3b3c0 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Essentials
* File: WebSocketSession.cs 
*
* WebSocketSession.cs is part of VNLib.Plugins.Essentials which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Essentials is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Essentials is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.IO;
using System.Threading;
using System.Net.WebSockets;
using System.Threading.Tasks;

using VNLib.Net.Http;

namespace VNLib.Plugins.Essentials
{
    /// <summary>
    /// A callback method to invoke when an HTTP service successfully transfers protocols to 
    /// the WebSocket protocol and the socket is ready to be used
    /// </summary>
    /// <param name="session">The open websocket session instance</param>
    /// <returns>
    /// A <see cref="Task"/> that will be awaited by the HTTP layer. When the task completes, the transport 
    /// will be closed and the session disposed
    /// </returns>

    public delegate Task WebSocketAcceptedCallback(WebSocketSession session);

    /// <summary>
    /// A callback method to invoke when an HTTP service successfully transfers protocols to 
    /// the WebSocket protocol and the socket is ready to be used
    /// </summary>
    /// <typeparam name="T">The type of the user state object</typeparam>
    /// <param name="session">The open websocket session instance</param>
    /// <returns>
    /// A <see cref="Task"/> that will be awaited by the HTTP layer. When the task completes, the transport 
    /// will be closed and the session disposed
    /// </returns>

    public delegate Task WebSocketAcceptedCallback<T>(WebSocketSession<T> session);

    /// <summary>
    /// Represents a <see cref="WebSocket"/> wrapper to manage the lifetime of the captured
    /// connection context and the underlying transport. This session is managed by the parent
    /// <see cref="HttpServer"/> that it was created on.
    /// </summary>
    public class WebSocketSession(WebSocketAcceptedCallback callback) : AlternateProtocolBase
    {
        internal WebSocket? WsHandle;
        internal readonly WebSocketAcceptedCallback AcceptedCallback = callback;

        /// <summary>
        /// A cancellation token that can be monitored to reflect the state 
        /// of the webscocket
        /// </summary>
        public CancellationToken Token => CancelSource.Token;

        /// <summary>
        /// Id assigned to this instance on creation
        /// </summary>
        public required string SocketID { get; init; }

        /// <summary>
        /// Negotiated sub-protocol
        /// </summary>
        public string? SubProtocol { get; internal init; }        
       
        /// <summary>
        /// The websocket keep-alive interval
        /// </summary>
        internal TimeSpan KeepAlive { get; init; }

        /// <summary>
        /// Initialzes the created websocket with the specified protocol 
        /// </summary>
        /// <param name="transport">Transport stream to use for the websocket</param>
        /// <returns>The accept callback function specified during object initialization</returns>
        protected override async Task RunAsync(Stream transport)
        {
            try
            {
                WebSocketCreationOptions ce = new()
                {
                    IsServer = true,
                    KeepAliveInterval = KeepAlive,
                    SubProtocol = SubProtocol,
                };
                
                //Create a new websocket from the context stream
                WsHandle = WebSocket.CreateFromStream(transport, ce);

                //Register token to abort the websocket so the managed ws uses the non-fallback send/recv method
                using CancellationTokenRegistration abortReg = Token.Register(WsHandle.Abort);
                
                //Return the callback function to explcitly invoke it
                await AcceptedCallback(this);
            }
            finally
            {
                WsHandle?.Dispose();
            }
        }

        /// <summary>
        /// Asynchronously receives data from the Websocket and copies the data to the specified buffer
        /// </summary>
        /// <param name="buffer">The buffer to store read data</param>
        /// <returns>A task that resolves a <see cref="WebSocketReceiveResult"/> which contains the status of the operation</returns>
        /// <exception cref="OperationCanceledException"></exception>
        public Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer) => WsHandle!.ReceiveAsync(buffer, CancellationToken.None);

        /// <summary>
        /// Asynchronously receives data from the Websocket and copies the data to the specified buffer
        /// </summary>
        /// <param name="buffer">The buffer to store read data</param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException"></exception>
        public ValueTask<ValueWebSocketReceiveResult> ReceiveAsync(Memory<byte> buffer) => WsHandle!.ReceiveAsync(buffer, CancellationToken.None);

        /// <summary>
        /// Asynchronously sends the specified buffer to the client of the specified type
        /// </summary>
        /// <param name="buffer">The buffer containing data to send</param>
        /// <param name="type">The message/data type of the packet to send</param>
        /// <param name="endOfMessage">A value that indicates this message is the final message of the transaction</param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException"></exception>
        public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType type, bool endOfMessage) => WsHandle!.SendAsync(buffer, type, endOfMessage, CancellationToken.None);


        /// <summary>
        /// Asynchronously sends the specified buffer to the client of the specified type
        /// </summary>
        /// <param name="buffer">The buffer containing data to send</param>
        /// <param name="type">The message/data type of the packet to send</param>
        /// <param name="endOfMessage">A value that indicates this message is the final message of the transaction</param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException"></exception>
        public ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType type, bool endOfMessage)
        {
            //Begin receive operation only with the internal token
            return SendAsync(buffer, type, endOfMessage ? WebSocketMessageFlags.EndOfMessage : WebSocketMessageFlags.None);
        }

        /// <summary>
        /// Asynchronously sends the specified buffer to the client of the specified type
        /// </summary>
        /// <param name="buffer">The buffer containing data to send</param>
        /// <param name="type">The message/data type of the packet to send</param>
        /// <param name="flags">Websocket message flags</param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException"></exception>
        public ValueTask SendAsync(ReadOnlyMemory<byte> buffer, WebSocketMessageType type, WebSocketMessageFlags flags) 
            => WsHandle!.SendAsync(buffer, type, flags, CancellationToken.None);


        /// <summary>
        /// Properly closes a currently connected websocket 
        /// </summary>
        /// <param name="status">Set the close status</param>
        /// <param name="reason">Set the close reason</param>
        /// <exception cref="ObjectDisposedException"></exception>
        public Task CloseSocketAsync(WebSocketCloseStatus status, string reason) => WsHandle!.CloseAsync(status, reason, CancellationToken.None);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="status"></param>
        /// <param name="reason"></param>
        /// <param name="cancellation"></param>
        /// <returns></returns>
        public Task CloseSocketOutputAsync(WebSocketCloseStatus status, string reason, CancellationToken cancellation = default)
        {
            if (WsHandle!.State == WebSocketState.Open || WsHandle.State == WebSocketState.CloseSent)
            {
                return WsHandle.CloseOutputAsync(status, reason, cancellation);
            }
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// <inheritdoc/>
    /// </summary>
    /// <typeparam name="T">The user-state type</typeparam>
    public sealed class WebSocketSession<T> : WebSocketSession
    {

#nullable disable
        
        /// <summary>
        /// A user-defined state object passed during socket accept handshake
        /// </summary>
        public T UserState { get; internal init; }

#nullable enable

        internal WebSocketSession(WebSocketAcceptedCallback<T> callback)
          : base((ses) => callback((ses as WebSocketSession<T>)!))
        {
            UserState = default;
        }
    }
}