]> git.sesse.net Git - cubemap/blob - server.h
5ebc060e10924e88c675f695fe6caefcb8cd520b
[cubemap] / server.h
1 #ifndef _SERVER_H
2 #define _SERVER_H 1
3
4 #include <stdint.h>
5 #include <pthread.h>
6 #include <sys/epoll.h>
7 #include <string>
8 #include <map>
9 #include <vector>
10
11 #define BACKLOG_SIZE 1048576
12 #define EPOLL_MAX_EVENTS 8192
13 #define EPOLL_TIMEOUT_MS 20
14 #define MAX_CLIENT_REQUEST 16384
15
16 class ClientProto;
17 class CubemapStateProto;
18 class Stream;
19 class StreamProto;
20
21 struct Client {
22         Client() {}
23         Client(int sock);
24
25         // Serialization/deserialization.
26         Client(const ClientProto &serialized, Stream *stream);
27         ClientProto serialize() const;
28
29         // The file descriptor associated with this socket.
30         int sock;
31
32         enum State { READING_REQUEST, SENDING_HEADER, SENDING_DATA, SENDING_ERROR };
33         State state;
34
35         // The HTTP request, as sent by the client. If we are in READING_REQUEST,
36         // this might not be finished.
37         std::string request;
38
39         // What stream we're connecting to; parsed from <request>.
40         // Not relevant for READING_REQUEST.
41         std::string stream_id;
42         Stream *stream;
43
44         // The header we want to send. This is nominally a copy of Stream::header,
45         // but since that might change on reconnects etc., we keep a local copy here.
46         // Only relevant for SENDING_HEADER or SENDING_ERROR; blank otherwise.
47         std::string header_or_error;
48
49         // Number of bytes we've sent of the header. Only relevant for SENDING_HEADER
50         // or SENDING_ERROR.
51         size_t header_or_error_bytes_sent;
52
53         // Number of bytes we've sent of data. Only relevant for SENDING_DATA.
54         size_t bytes_sent;
55 };
56
57 struct Stream {
58         Stream(const std::string &stream_id);
59         ~Stream();
60
61         // Serialization/deserialization.
62         Stream(const StreamProto &serialized);
63         StreamProto serialize() const;
64
65         std::string stream_id;
66
67         // The HTTP response header, plus the video stream header (if any).
68         std::string header;
69
70         // The stream data itself, stored in a circular buffer.
71         char *data;
72
73         // How many bytes <data> contains. Can very well be larger than BACKLOG_SIZE,
74         // since the buffer wraps.
75         size_t data_size;
76         
77         // Clients that are in SENDING_DATA, but that we don't listen on,
78         // because we currently don't have any data for them.
79         // See put_client_to_sleep() and wake_up_all_clients().
80         std::vector<Client *> sleeping_clients;
81
82         // Clients that we recently got data for (when they were in
83         // <sleeping_clients>).
84         std::vector<Client *> to_process;
85
86         // Put client to sleep, since there is no more data for it; we will on
87         // longer listen on POLLOUT until we get more data. Also, it will be put
88         // in the list of clients to wake up when we do.
89         void put_client_to_sleep(Client *client);
90
91         // We have more data, so mark all clients that are sleeping as ready to go.
92         void wake_up_all_clients();
93
94 private:
95         Stream(const Stream& other);
96 };
97
98 class Server {
99 public:
100         Server();
101         ~Server();
102
103         // Start a new thread that handles clients.
104         void run();
105
106         // Stop the thread.
107         void stop();
108
109         // Set header (both HTTP header and any stream headers) for the given stream.
110         void set_header(const std::string &stream_id, const std::string &header);
111
112         // These will be deferred until the next time an iteration in do_work() happens,
113         // and the order between them are undefined.
114         // XXX: header should ideally be ordered with respect to data.
115         void add_client_deferred(int sock);
116         void add_data_deferred(const std::string &stream_id, const char *data, size_t bytes);
117
118         // These should not be called while running, since that would violate
119         // threading assumptions (ie., that epoll is only called from one thread
120         // at the same time).
121         CubemapStateProto serialize();
122         void add_client_from_serialized(const ClientProto &client);
123         void add_stream(const std::string &stream_id);
124         void add_stream_from_serialized(const StreamProto &stream);
125
126 private:
127         pthread_t worker_thread;
128
129         // Mutex protecting queued_data only. Note that if you want to hold both this
130         // and <mutex> below, you will need to take <mutex> before this one.
131         pthread_mutex_t queued_data_mutex;
132
133         // Deferred commands that should be run from the do_work() thread as soon as possible.
134         // We defer these for two reasons:
135         //
136         //  - We only want to fiddle with epoll from one thread at any given time,
137         //    and doing add_client() from the acceptor thread would violate that.
138         //  - We don't want the input thread(s) hanging on <mutex> when doing
139         //    add_data(), since they want to do add_data() rather often, and <mutex>
140         //    can be taken a lot of the time.
141         //      
142         // Protected by <queued_data_mutex>.
143         std::vector<int> queued_add_clients;
144         std::map<std::string, std::string> queued_data;
145
146         // All variables below this line are protected by the mutex.
147         pthread_mutex_t mutex;
148
149         // If the thread should stop or not.
150         bool should_stop;       
151
152         // Map from stream ID to stream.
153         std::map<std::string, Stream *> streams;
154
155         // Map from file descriptor to client.
156         std::map<int, Client> clients;
157
158         // Used for epoll implementation (obviously).
159         int epoll_fd;
160         epoll_event events[EPOLL_MAX_EVENTS];
161
162         // Recover the this pointer, and call do_work().
163         static void *do_work_thunk(void *arg);
164
165         // The actual worker thread.
166         void do_work();
167
168         // Process a client; read and write data as far as we can.
169         // After this call, one of these four is true:
170         //
171         //  1. The socket is closed, and the client deleted.
172         //  2. We are still waiting for more data from the client.
173         //  3. We've sent all the data we have to the client,
174         //     and put it in <sleeping_clients>.
175         //  4. The socket buffer is full (which means we still have
176         //     data outstanding).
177         //
178         // For #2, we listen for EPOLLIN events. For #3 and #4, we listen
179         // for EPOLLOUT in edge-triggered mode; it will never fire for #3,
180         // but it's cheaper than taking it in and out all the time.
181         void process_client(Client *client);
182
183         // Close a given client socket, and clean up after it.
184         void close_client(Client *client);
185
186         // Parse the HTTP request. Returns a HTTP status code (200/400/404).
187         int parse_request(Client *client);
188
189         // Construct the HTTP header, and set the client into
190         // the SENDING_HEADER state.
191         void construct_header(Client *client);
192
193         // Construct a generic error with the given line, and set the client into
194         // the SENDING_ERROR state.
195         void construct_error(Client *client, int error_code);
196
197         // TODO: This function should probably die.
198         Stream *find_stream(const std::string &stream_id);
199
200         void process_queued_data();
201
202         void add_client(int sock);
203         void add_data(const std::string &stream_id, const char *data, size_t bytes);
204 };
205
206 #endif  // !defined(_SERVER_H)