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 "../AsyncStreams/AsyncRequestStreams.h"
5#include "HttpConnection.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
21struct SC_COMPILER_EXPORT HttpAsyncConnectionBase : public HttpConnection
22{
24 {
25 size_t readQueueSize = 3;
26 size_t writeQueueSize = 3;
27 size_t buffersQueueSize = 6;
28 size_t headerBytesLength = 8 * 1024;
29 size_t streamBytesLength = 512 * 1024;
30 };
31
32 struct Memory
33 {
36 Span<AsyncBufferView> allBuffers;
37 Span<char> allHeaders;
38 Span<char> allStreams;
39
42 };
43 ReadableSocketStream readableSocketStream;
44 WritableSocketStream writableSocketStream;
45 SocketDescriptor socket;
46};
47
49template <int ReadQueue, int WriteQueue, int HeaderBytes, int StreamBytes>
50struct SC_COMPILER_EXPORT HttpAsyncConnection : public HttpAsyncConnectionBase
51{
52 AsyncReadableStream::Request readQueue[ReadQueue];
53 AsyncWritableStream::Request writeQueue[WriteQueue];
54 AsyncBufferView buffers[ReadQueue + WriteQueue];
55
56 char headerStorage[HeaderBytes];
57 char streamStorage[StreamBytes];
58
59 constexpr HttpAsyncConnection()
60 {
61 constexpr const size_t NumSlices = ReadQueue;
62 constexpr const size_t SliceLength = StreamBytes / NumSlices;
63
64 Span<char> memory = streamStorage;
65 for (size_t idx = 0; idx < NumSlices; ++idx)
66 {
67 Span<char> slice;
68 (void)memory.sliceStartLength(idx * SliceLength, SliceLength, slice);
69 buffers[idx] = slice;
70 buffers[idx].setReusable(true);
71 }
72 HttpConnection::setHeaderMemory(headerStorage);
73 HttpConnection::buffersPool.setBuffers(buffers);
74 readableSocketStream.setReadQueue(readQueue);
75 writableSocketStream.setWriteQueue(writeQueue);
76 }
77};
78
91struct SC_COMPILER_EXPORT HttpAsyncServer
92{
94 template <typename T,
97 {
98 return initInternal({clients.data(), clients.sizeInElements(), sizeof(T)});
99 }
100
101 template <typename T,
103 Result resize(Span<T> clients)
104 {
105 return resizeInternal({clients.data(), clients.sizeInElements(), sizeof(T)});
106 }
107
111
118
122
124 [[nodiscard]] bool isStarted() const { return started; }
125
126 [[nodiscard]] const HttpConnectionsPool& getConnections() const { return connections; }
127
130
131 private:
132 HttpConnectionsPool connections;
133
134 uint32_t maxHeaderSize = 8 * 1024;
135
136 bool started = false;
137 bool stopping = false;
138
139 void onNewClient(AsyncSocketAccept::Result& result);
140 void closeAsync(HttpAsyncConnectionBase& requestClient);
141 void onStreamReceive(HttpAsyncConnectionBase& client, AsyncBufferView::ID bufferID);
142
143 Result waitForStopToFinish();
144 Result initInternal(SpanWithStride<HttpAsyncConnectionBase> connections);
145 Result resizeInternal(SpanWithStride<HttpAsyncConnectionBase> connections);
146
147 AsyncEventLoop* eventLoop = nullptr;
148 SocketDescriptor serverSocket;
149 AsyncSocketAccept asyncServerAccept;
150};
151} // namespace SC
unsigned short uint16_t
Platform independent (2) bytes unsigned int.
Definition PrimitiveTypes.h:37
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:38
struct SC_COMPILER_EXPORT Function
Wraps function pointers, member functions and lambdas without ever allocating.
Definition Function.h:19
Definition AsyncStreams.h:52
A Span of bytes memory to be read or written by async streams.
Definition AsyncStreams.h:50
void setReusable(bool reusable)
Tags this AsyncBufferView as reusable after its refCount goes to zero.
Definition AsyncStreams.h:75
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1195
Definition AsyncStreams.h:189
Starts a socket accept operation, obtaining a new socket from a listening socket.
Definition Async.h:466
Definition AsyncStreams.h:289
Definition HttpAsyncServer.h:24
Definition HttpAsyncServer.h:33
Contains fields used by HttpAsyncServer for each connection.
Definition HttpAsyncServer.h:22
Adds compile-time configurable read and write queues to HttpAsyncConnectionBase.
Definition HttpAsyncServer.h:51
Async Http Server.
Definition HttpAsyncServer.h:92
Result start(AsyncEventLoop &loop, StringSpan address, uint16_t port)
Starts the http server on the given AsyncEventLoop, address and port.
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:96
Function< void(HttpConnection &)> onRequest
Called after enough data from a newly connected client has arrived, causing all headers to be parsed.
Definition HttpAsyncServer.h:129
bool isStarted() const
Returns true if the server has been started.
Definition HttpAsyncServer.h:124
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:100
A pool of HttpConnection that can be active or inactive.
Definition HttpConnection.h:189
Uses an SC::AsyncFileWrite to stream data from a socket.
Definition AsyncRequestStreams.h:74
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
Low-level OS socket handle.
Definition Socket.h:153
View over a contiguous sequence of items with a custom stride between elements.
Definition HttpConnection.h:145
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
constexpr bool sliceStartLength(SizeType offsetInElements, SizeType lengthInElements, Span &destination) const
Creates another Span, starting at an offset in elements from current Span of specified length.
Definition Span.h:121
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37
EnableIf conditionally defines a type if a boolean template parameter is true.
Definition TypeTraits.h:25
IsBaseOf evaluates to true if the type Base is a base class of Derived, false otherwise.
Definition HttpAsyncServer.h:14
Uses an SC::AsyncFileWrite to stream data to a socket.
Definition AsyncRequestStreams.h:80