Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
HttpAsyncServer.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "HttpConnection.h"
5#include "HttpExport.h"
6
7namespace SC
8{
9namespace TypeTraits
10{
12template <typename Base, typename Derived>
14{
15 static constexpr bool value = __is_base_of(Base, Derived);
16};
17
18} // namespace TypeTraits
19
21template <int ReadQueue, int WriteQueue, int HeaderBytes, int StreamBytes>
22struct SC_HTTP_EXPORT HttpAsyncConnection
23 : public HttpStaticConnection<ReadQueue, WriteQueue, HeaderBytes, StreamBytes, 8, HttpConnection>
24{
25};
26
32struct SC_HTTP_EXPORT HttpAsyncServerTransportSetup
33{
34 HttpConnection* connection = nullptr;
35 AsyncEventLoop* eventLoop = nullptr;
36
37 Function<void(Result)> complete;
38 Function<void(Result)> fail;
39};
40
53struct SC_HTTP_EXPORT HttpAsyncServer
54{
56 template <typename T,
57 typename = typename TypeTraits::EnableIf<TypeTraits::IsBaseOf<HttpConnection, T>::value>::type>
58 Result init(Span<T> clients)
59 {
60 return initInternal({clients.data(), clients.sizeInElements(), sizeof(T)});
61 }
62
63 template <typename T,
64 typename = typename TypeTraits::EnableIf<TypeTraits::IsBaseOf<HttpConnection, T>::value>::type>
65 Result resize(Span<T> clients)
66 {
67 return resizeInternal({clients.data(), clients.sizeInElements(), sizeof(T)});
68 }
69
72 Result close();
73
81 Result start(AsyncEventLoop& loop, StringSpan address, uint16_t port);
82
87
93 AsyncWritableStream& writable);
94
97 Result stop();
98
101 void setMaxHeaderSize(uint32_t bytes) { maxHeaderSize = bytes; }
102
104 [[nodiscard]] uint32_t getMaxHeaderSize() const { return maxHeaderSize; }
105
107 Result setTransportSetup(Function<Result(HttpAsyncServerTransportSetup&)>&& setup, const void* owner = nullptr)
108 {
109 SC_TRY(checkTransportMutation(owner));
110 transportSetup = move(setup);
111 return Result(true);
112 }
113
116 Result setTransportClose(Function<void(HttpConnection&)>&& close, const void* owner = nullptr)
117 {
118 SC_TRY(checkTransportMutation(owner));
119 transportClose = move(close);
120 return Result(true);
121 }
122
124 Result setTransportReuse(Function<Result(HttpConnection&)>&& reuse, const void* owner = nullptr)
125 {
126 SC_TRY(checkTransportMutation(owner));
127 transportReuse = move(reuse);
128 return Result(true);
129 }
130
132 Result setTransportShutdown(Function<Result(HttpConnection&, Function<void(Result)>)>&& shutdown,
133 const void* owner = nullptr)
134 {
135 SC_TRY(checkTransportMutation(owner));
136 transportShutdown = move(shutdown);
137 return Result(true);
138 }
139
141 Result clearTransportSetup(const void* owner = nullptr);
142
146 Result claimTransport(const void* owner);
147
150 Result releaseTransport(const void* owner);
151
153 [[nodiscard]] bool isStarted() const { return state == State::Started; }
154
155 [[nodiscard]] const HttpConnectionsPool& getConnections() const { return connections; }
156
158 Function<void(HttpConnection&)> onRequest;
159
161 Function<void(Result)> onError;
162
166 void setDefaultKeepAlive(bool enabled) { defaultKeepAlive = enabled; }
167
169 [[nodiscard]] bool getDefaultKeepAlive() const { return defaultKeepAlive; }
170
173 void setMaxRequestsPerConnection(uint32_t maxRequests) { maxRequestsPerConnection = maxRequests; }
174
176 [[nodiscard]] uint32_t getMaxRequestsPerConnection() const { return maxRequestsPerConnection; }
177
178 private:
179 Result checkTransportMutation(const void* owner) const;
180 Result checkTransportQuiescence() const;
181
182 HttpConnectionsPool connections;
183
184 uint32_t maxHeaderSize = 8 * 1024;
185
186 Function<Result(HttpAsyncServerTransportSetup&)> transportSetup;
187 Function<Result(HttpConnection&)> transportReuse;
188 Function<Result(HttpConnection&, Function<void(Result)>)> transportShutdown;
189 Function<void(HttpConnection&)> transportClose;
190
191 const void* transportOwner = nullptr;
192
193 uint32_t transportCallbackDepth = 0;
194
195 enum class State
196 {
197 Stopped, // Server was not started at all, or it was stopped and wait(ed)ForStopToFinish
198 Started, // Server has been started (successfully)
199 Stopping, // Server has stop() called and needs waitForStopToFinish() call
200 };
201
202 State state = State::Stopped;
203
204 bool defaultKeepAlive = true;
205 uint32_t maxRequestsPerConnection = 0;
206
207 void onNewClient(AsyncSocketAccept::Result& result);
208 void closeAsync(HttpConnection& requestClient);
209 void shutdownTransport(HttpConnection& requestClient);
210 void tryDeactivateConnection(HttpConnection& requestClient);
211 void deactivateConnection(HttpConnection& requestClient);
212 Result beginHttpConnection(HttpConnection& client);
213 Result beginTransportConnection(HttpConnection& client);
214 void onStreamReceive(HttpConnection& client, AsyncBufferView::ID bufferID);
215 void onRequestBodyData(HttpConnection& client, AsyncBufferView::ID bufferID);
216 void onTransportSetupComplete(HttpConnection& client, Result result);
217
218 Result waitForStopToFinish();
219 Result initInternal(SpanWithStride<HttpConnection> connections);
220 Result resizeInternal(SpanWithStride<HttpConnection> connections);
221
222 AsyncEventLoop* eventLoop = nullptr;
223 SocketDescriptor serverSocket;
224 AsyncSocketAccept asyncServerAccept;
225 bool externalListener = false;
226
227 struct EventDataListener;
228 struct EventBodyDataListener;
229 struct EventEndListener;
230 struct EventCloseListener;
231};
232} // namespace SC
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1521
Async source abstraction emitting data events in caller provided byte buffers.
Definition AsyncStreams.h:229
Async destination abstraction where bytes can be written to.
Definition AsyncStreams.h:365
Adds compile-time configurable read and write queues to HttpConnection.
Definition HttpAsyncServer.h:24
Mutable transport setup view used by HttpAsyncServer after accepting a TCP socket.
Definition HttpAsyncServer.h:33
Async Http Server.
Definition HttpAsyncServer.h:54
Result start(AsyncEventLoop &loop, StringSpan address, uint16_t port)
Starts the http server on the given AsyncEventLoop, address and port.
uint32_t getMaxRequestsPerConnection() const
Get the maximum requests per connection.
Definition HttpAsyncServer.h:176
Result setTransportClose(Function< void(HttpConnection &)> &&close, const void *owner=nullptr)
Sets an optional transport teardown hook invoked before HTTP destroys the installed transport streams...
Definition HttpAsyncServer.h:116
Result stop()
Stops http server asynchronously pushing cancel and close requests to the event loop.
Result init(Span< T > clients)
Initializes the async server with all needed memory buffers.
Definition HttpAsyncServer.h:58
Result releaseTransport(const void *owner)
Clears hooks and releases only the matching owner's claim after complete server teardown.
Result clearTransportSetup(const void *owner=nullptr)
Clears optional transport setup, reuse, shutdown, and teardown hooks.
bool getDefaultKeepAlive() const
Get the default keep-alive setting.
Definition HttpAsyncServer.h:169
Result startExternal(AsyncEventLoop &loop)
Starts the HTTP state machine without creating a native listener.
void setDefaultKeepAlive(bool enabled)
Set default keep-alive behavior for all connections.
Definition HttpAsyncServer.h:166
Function< void(HttpConnection &)> onRequest
Called after enough data from a newly connected client has arrived, causing all headers to be parsed.
Definition HttpAsyncServer.h:158
Function< void(Result)> onError
Called on accept, parse, protocol, or streaming errors before the affected connection is closed.
Definition HttpAsyncServer.h:161
void setMaxRequestsPerConnection(uint32_t maxRequests)
Set maximum requests per keep-alive connection.
Definition HttpAsyncServer.h:173
bool isStarted() const
Returns true if the server has been started.
Definition HttpAsyncServer.h:153
void setMaxHeaderSize(uint32_t bytes)
Sets the maximum accepted request-header size in bytes.
Definition HttpAsyncServer.h:101
uint32_t getMaxHeaderSize() const
Gets the maximum accepted request-header size in bytes.
Definition HttpAsyncServer.h:104
Result setTransportShutdown(Function< Result(HttpConnection &, Function< void(Result)>)> &&shutdown, const void *owner=nullptr)
Sets an optional asynchronous hook that drains a terminal response before closing its socket.
Definition HttpAsyncServer.h:132
Result setTransportSetup(Function< Result(HttpAsyncServerTransportSetup &)> &&setup, const void *owner=nullptr)
Sets an optional transport setup hook invoked after accepting TCP and before HTTP reads request bytes...
Definition HttpAsyncServer.h:107
Result acceptExternalConnection(HttpConnection &connection, AsyncReadableStream &readable, AsyncWritableStream &writable)
Activates a specific connection slot for externally accepted plaintext streams.
Result setTransportReuse(Function< Result(HttpConnection &)> &&reuse, const void *owner=nullptr)
Sets an optional hook that reopens an alternate writable transport for the next keep-alive response.
Definition HttpAsyncServer.h:124
Result claimTransport(const void *owner)
Claims the transport hook group with a non-null address-stable owner token.
Result close()
Closes the server, removing references to the memory buffers passed during init.
Http connection abstraction holding both the incoming and outgoing messages in an HTTP transaction.
Definition HttpConnection.h:489
A pool of HttpConnection that can be active or inactive.
Definition HttpConnection.h:588
Adds compile-time configurable read and write queues to any class subclassing HttpConnectionBase.
Definition HttpConnection.h:656
IsBaseOf evaluates to true if the type Base is a base class of Derived, false otherwise.
Definition HttpAsyncServer.h:14