Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
HttpConnection.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "HttpParser.h"
5
6#include "../Async/Async.h"
7#include "../AsyncStreams/AsyncRequestStreams.h"
8#include "../Foundation/Function.h"
9#include "../Foundation/StringSpan.h"
10
11namespace SC
12{
15
17struct SC_COMPILER_EXPORT HttpRequest
18{
20 const HttpParser& getParser() const { return parser; }
21
23 StringSpan getURL() const { return url; }
24
26 void reset();
27
28 private:
29 friend struct HttpConnectionsPool;
30 friend struct HttpResponse;
31 friend struct HttpAsyncServer;
32
37 [[nodiscard]] bool findParserToken(HttpParser::Token token, StringSpan& res) const;
38
40 Result writeHeaders(const uint32_t maxHeaderSize, Span<const char> readData);
41
42 struct SC_COMPILER_EXPORT HttpHeaderOffset
43 {
44 HttpParser::Token token = HttpParser::Token::Method;
45
46 uint32_t start = 0;
47 uint32_t length = 0;
48 };
49 Span<char> readHeaders;
50 Span<char> availableHeader;
51
52 bool headersEndReceived = false;
53 bool parsedSuccessfully = true;
54
55 HttpParser parser;
56 StringSpan url;
57
58 static constexpr size_t MaxNumHeaders = 64;
59
60 HttpHeaderOffset headerOffsets[MaxNumHeaders];
61 size_t numHeaders = 0;
62};
63
65struct SC_COMPILER_EXPORT HttpResponse
66{
68 Result startResponse(int httpCode);
69
71 Result addHeader(StringSpan headerName, StringSpan headerValue);
72
75
77 void reset();
78
81
83 AsyncWritableStream& getWritableStream() { return *writableStream; }
84
85 private:
86 friend struct HttpConnectionsPool;
87 friend struct HttpAsyncServer;
88
90 void grabUnusedHeaderMemory(HttpRequest& request);
91
92 Span<char> responseHeaders;
93 size_t responseHeadersCapacity = 0;
94
95 bool headersSent = false;
96
97 AsyncWritableStream* writableStream = nullptr;
98};
99
101struct SC_COMPILER_EXPORT HttpConnection
102{
104
105 struct SC_COMPILER_EXPORT ID
106 {
107 size_t getIndex() const { return index; }
108
109 private:
110 friend struct HttpConnectionsPool;
111 size_t index = 0;
112 };
113
115 void reset();
116
118 ID getConnectionID() const { return connectionID; }
119
120 HttpRequest request;
121 HttpResponse response;
122
123 private:
124 enum class State
125 {
126 Inactive,
127 Active
128 };
129 friend struct HttpConnectionsPool;
130 friend struct HttpAsyncServer;
131
132 State state = State::Inactive;
133 ID connectionID;
134
135 ReadableSocketStream readableSocketStream;
136 WritableSocketStream writableSocketStream;
137
138 SocketDescriptor socket;
139};
140
142struct SC_COMPILER_EXPORT HttpConnectionsPool
143{
145 Result init(Span<HttpConnection> connectionsStorage, Span<char> headersMemoryStorage);
146
149
151 [[nodiscard]] size_t getNumActiveConnections() const { return numConnections; }
152
154 [[nodiscard]] size_t getNumTotalConnections() const { return connections.sizeInElements(); }
155
158 {
159 return connections[connectionID.index];
160 }
161
163 [[nodiscard]] HttpConnection& getConnectionAt(size_t idx) { return connections[idx]; }
164
166 [[nodiscard]] bool activateNew(HttpConnection::ID& connectionID);
167
169 [[nodiscard]] bool deactivate(HttpConnection::ID connectionID);
170
171 private:
172 Span<HttpConnection> connections;
173 Span<char> headersMemory;
174
175 size_t numConnections = 0;
176};
178
179} // namespace SC
unsigned int uint32_t
Platform independent (4) bytes unsigned int.
Definition PrimitiveTypes.h:38
Async destination abstraction where bytes can be written to.
Definition AsyncStreams.h:268
Async Http Server.
Definition HttpAsyncServer.h:20
Definition HttpConnection.h:106
Http connection abstraction holding both the incoming and outgoing messages in an HTTP transaction.
Definition HttpConnection.h:102
void reset()
Prepare this client for re-use, marking it as Inactive.
ID getConnectionID() const
The ID used to find this client in HttpConnectionsPool.
Definition HttpConnection.h:118
A pool of HttpConnection that can be active or inactive.
Definition HttpConnection.h:143
size_t getNumActiveConnections() const
Returns only the number of active connections.
Definition HttpConnection.h:151
HttpConnection & getConnectionAt(size_t idx)
Returns a connection in the [0, getNumTotalConnections] range.
Definition HttpConnection.h:163
Result init(Span< HttpConnection > connectionsStorage, Span< char > headersMemoryStorage)
Initializes the server with memory buffers for connections and headers.
bool activateNew(HttpConnection::ID &connectionID)
Finds an available connection (if any), activates it and returns its ID to use with getConnection(id)
HttpConnection & getConnection(HttpConnection::ID connectionID)
Returns a connection by ID.
Definition HttpConnection.h:157
size_t getNumTotalConnections() const
Returns the total number of connections (active + inactive)
Definition HttpConnection.h:154
Result close()
Closes the server, removing references to the memory buffers passed during init.
bool deactivate(HttpConnection::ID connectionID)
De-activates a connection previously returned by activateNew.
Incremental HTTP request or response parser.
Definition HttpParser.h:14
Token
One possible Token reported by the parser.
Definition HttpParser.h:39
Incoming message from the perspective of the participants of an HTTP transaction.
Definition HttpConnection.h:18
const HttpParser & getParser() const
Gets the associated HttpParser.
Definition HttpConnection.h:20
StringSpan getURL() const
Gets the request URL.
Definition HttpConnection.h:23
void reset()
Resets this object for it to be re-usable.
Outgoing message from the perspective of the participants of an HTTP transaction.
Definition HttpConnection.h:66
Result startResponse(int httpCode)
Starts the response with a http standard code (200 OK, 404 NOT FOUND etc.)
Result sendHeaders()
Start sending response headers, before sending any data.
Result addHeader(StringSpan headerName, StringSpan headerValue)
Writes an http header to this response.
Result end()
Finalizes the writable stream after sending all in progress writes.
void reset()
Resets this object for it to be re-usable.
AsyncWritableStream & getWritableStream()
Obtain writable stream for sending content back to connected client.
Definition HttpConnection.h:83
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
View over a contiguous sequence of items (pointer + size in elements).
Definition Span.h:29
An read-only view over a string (to avoid including Strings library when parsing is not needed).
Definition StringSpan.h:37