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
31struct SC_HTTP_EXPORT HttpAsyncServerTransportSetup
32{
33 HttpConnection* connection = nullptr;
34 AsyncEventLoop* eventLoop = nullptr;
35
36 Function<void(Result)> complete;
37};
38
51struct SC_HTTP_EXPORT HttpAsyncServer
52{
54 template <typename T,
55 typename = typename TypeTraits::EnableIf<TypeTraits::IsBaseOf<HttpConnection, T>::value>::type>
56 Result init(Span<T> clients)
57 {
58 return initInternal({clients.data(), clients.sizeInElements(), sizeof(T)});
59 }
60
61 template <typename T,
62 typename = typename TypeTraits::EnableIf<TypeTraits::IsBaseOf<HttpConnection, T>::value>::type>
63 Result resize(Span<T> clients)
64 {
65 return resizeInternal({clients.data(), clients.sizeInElements(), sizeof(T)});
66 }
67
70 Result close();
71
77 Result start(AsyncEventLoop& loop, StringSpan address, uint16_t port);
78
81 Result stop();
82
85 void setMaxHeaderSize(uint32_t bytes) { maxHeaderSize = bytes; }
86
88 [[nodiscard]] uint32_t getMaxHeaderSize() const { return maxHeaderSize; }
89
91 void setTransportSetup(Function<Result(HttpAsyncServerTransportSetup&)>&& setup) { transportSetup = move(setup); }
92
94 void setTransportClose(Function<void(HttpConnection&)>&& close) { transportClose = move(close); }
95
98 {
99 transportSetup = {};
100 transportClose = {};
101 }
102
104 [[nodiscard]] bool isStarted() const { return state == State::Started; }
105
106 [[nodiscard]] const HttpConnectionsPool& getConnections() const { return connections; }
107
109 Function<void(HttpConnection&)> onRequest;
110
112 Function<void(Result)> onError;
113
117 void setDefaultKeepAlive(bool enabled) { defaultKeepAlive = enabled; }
118
120 [[nodiscard]] bool getDefaultKeepAlive() const { return defaultKeepAlive; }
121
124 void setMaxRequestsPerConnection(uint32_t maxRequests) { maxRequestsPerConnection = maxRequests; }
125
127 [[nodiscard]] uint32_t getMaxRequestsPerConnection() const { return maxRequestsPerConnection; }
128
129 private:
130 HttpConnectionsPool connections;
131
132 uint32_t maxHeaderSize = 8 * 1024;
133
134 Function<Result(HttpAsyncServerTransportSetup&)> transportSetup;
135 Function<void(HttpConnection&)> transportClose;
136
137 enum class State
138 {
139 Stopped, // Server was not started at all, or it was stopped and wait(ed)ForStopToFinish
140 Started, // Server has been started (successfully)
141 Stopping, // Server has stop() called and needs waitForStopToFinish() call
142 };
143
144 State state = State::Stopped;
145
146 bool defaultKeepAlive = true;
147 uint32_t maxRequestsPerConnection = 0;
148
149 void onNewClient(AsyncSocketAccept::Result& result);
150 void closeAsync(HttpConnection& requestClient);
151 void deactivateConnection(HttpConnection& requestClient);
152 Result beginHttpConnection(HttpConnection& client);
153 Result beginTransportConnection(HttpConnection& client);
154 void onStreamReceive(HttpConnection& client, AsyncBufferView::ID bufferID);
155 void onRequestBodyData(HttpConnection& client, AsyncBufferView::ID bufferID);
156 void onTransportSetupComplete(HttpConnection& client, Result result);
157
158 Result waitForStopToFinish();
159 Result initInternal(SpanWithStride<HttpConnection> connections);
160 Result resizeInternal(SpanWithStride<HttpConnection> connections);
161
162 AsyncEventLoop* eventLoop = nullptr;
163 SocketDescriptor serverSocket;
164 AsyncSocketAccept asyncServerAccept;
165
166 struct EventDataListener;
167 struct EventBodyDataListener;
168 struct EventEndListener;
169 struct EventCloseListener;
170};
171} // namespace SC
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1486
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:32
Async Http Server.
Definition HttpAsyncServer.h:52
void setTransportSetup(Function< Result(HttpAsyncServerTransportSetup &)> &&setup)
Sets an optional transport setup hook invoked after accepting TCP and before HTTP reads request bytes...
Definition HttpAsyncServer.h:91
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:127
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:56
bool getDefaultKeepAlive() const
Get the default keep-alive setting.
Definition HttpAsyncServer.h:120
void setDefaultKeepAlive(bool enabled)
Set default keep-alive behavior for all connections.
Definition HttpAsyncServer.h:117
Function< void(HttpConnection &)> onRequest
Called after enough data from a newly connected client has arrived, causing all headers to be parsed.
Definition HttpAsyncServer.h:109
Function< void(Result)> onError
Called on accept, parse, protocol, or streaming errors before the affected connection is closed.
Definition HttpAsyncServer.h:112
void setMaxRequestsPerConnection(uint32_t maxRequests)
Set maximum requests per keep-alive connection.
Definition HttpAsyncServer.h:124
bool isStarted() const
Returns true if the server has been started.
Definition HttpAsyncServer.h:104
void setMaxHeaderSize(uint32_t bytes)
Sets the maximum accepted request-header size in bytes.
Definition HttpAsyncServer.h:85
uint32_t getMaxHeaderSize() const
Gets the maximum accepted request-header size in bytes.
Definition HttpAsyncServer.h:88
void clearTransportSetup()
Clears optional transport setup and teardown hooks.
Definition HttpAsyncServer.h:97
void setTransportClose(Function< void(HttpConnection &)> &&close)
Sets an optional transport teardown hook invoked before HTTP destroys an accepted socket's streams.
Definition HttpAsyncServer.h:94
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:490
A pool of HttpConnection that can be active or inactive.
Definition HttpConnection.h:589
Adds compile-time configurable read and write queues to any class subclassing HttpConnectionBase.
Definition HttpConnection.h:654
IsBaseOf evaluates to true if the type Base is a base class of Derived, false otherwise.
Definition HttpAsyncServer.h:14