annotate win32-mingw/include/kj/async-io.h @ 50:37d53a7e8262

Headers for KJ/Capnp Win32
author Chris Cannam
date Wed, 26 Oct 2016 13:18:45 +0100
parents
children eccd51b72864
rev   line source
Chris@50 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
Chris@50 2 // Licensed under the MIT License:
Chris@50 3 //
Chris@50 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
Chris@50 5 // of this software and associated documentation files (the "Software"), to deal
Chris@50 6 // in the Software without restriction, including without limitation the rights
Chris@50 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
Chris@50 8 // copies of the Software, and to permit persons to whom the Software is
Chris@50 9 // furnished to do so, subject to the following conditions:
Chris@50 10 //
Chris@50 11 // The above copyright notice and this permission notice shall be included in
Chris@50 12 // all copies or substantial portions of the Software.
Chris@50 13 //
Chris@50 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Chris@50 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Chris@50 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Chris@50 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Chris@50 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
Chris@50 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
Chris@50 20 // THE SOFTWARE.
Chris@50 21
Chris@50 22 #ifndef KJ_ASYNC_IO_H_
Chris@50 23 #define KJ_ASYNC_IO_H_
Chris@50 24
Chris@50 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
Chris@50 26 #pragma GCC system_header
Chris@50 27 #endif
Chris@50 28
Chris@50 29 #include "async.h"
Chris@50 30 #include "function.h"
Chris@50 31 #include "thread.h"
Chris@50 32 #include "time.h"
Chris@50 33
Chris@50 34 struct sockaddr;
Chris@50 35
Chris@50 36 namespace kj {
Chris@50 37
Chris@50 38 class UnixEventPort;
Chris@50 39 class NetworkAddress;
Chris@50 40
Chris@50 41 // =======================================================================================
Chris@50 42 // Streaming I/O
Chris@50 43
Chris@50 44 class AsyncInputStream {
Chris@50 45 // Asynchronous equivalent of InputStream (from io.h).
Chris@50 46
Chris@50 47 public:
Chris@50 48 virtual Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) = 0;
Chris@50 49 virtual Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) = 0;
Chris@50 50
Chris@50 51 Promise<void> read(void* buffer, size_t bytes);
Chris@50 52 };
Chris@50 53
Chris@50 54 class AsyncOutputStream {
Chris@50 55 // Asynchronous equivalent of OutputStream (from io.h).
Chris@50 56
Chris@50 57 public:
Chris@50 58 virtual Promise<void> write(const void* buffer, size_t size) = 0;
Chris@50 59 virtual Promise<void> write(ArrayPtr<const ArrayPtr<const byte>> pieces) = 0;
Chris@50 60 };
Chris@50 61
Chris@50 62 class AsyncIoStream: public AsyncInputStream, public AsyncOutputStream {
Chris@50 63 // A combination input and output stream.
Chris@50 64
Chris@50 65 public:
Chris@50 66 virtual void shutdownWrite() = 0;
Chris@50 67 // Cleanly shut down just the write end of the stream, while keeping the read end open.
Chris@50 68
Chris@50 69 virtual void abortRead() {}
Chris@50 70 // Similar to shutdownWrite, but this will shut down the read end of the stream, and should only
Chris@50 71 // be called when an error has occurred.
Chris@50 72
Chris@50 73 virtual void getsockopt(int level, int option, void* value, uint* length);
Chris@50 74 virtual void setsockopt(int level, int option, const void* value, uint length);
Chris@50 75 // Corresponds to getsockopt() and setsockopt() syscalls. Will throw an "unimplemented" exception
Chris@50 76 // if the stream is not a socket or the option is not appropriate for the socket type. The
Chris@50 77 // default implementations always throw "unimplemented".
Chris@50 78
Chris@50 79 virtual void getsockname(struct sockaddr* addr, uint* length);
Chris@50 80 virtual void getpeername(struct sockaddr* addr, uint* length);
Chris@50 81 // Corresponds to getsockname() and getpeername() syscalls. Will throw an "unimplemented"
Chris@50 82 // exception if the stream is not a socket. The default implementations always throw
Chris@50 83 // "unimplemented".
Chris@50 84 //
Chris@50 85 // Note that we don't provide methods that return NetworkAddress because it usually wouldn't
Chris@50 86 // be useful. You can't connect() to or listen() on these addresses, obviously, because they are
Chris@50 87 // ephemeral addresses for a single connection.
Chris@50 88 };
Chris@50 89
Chris@50 90 struct OneWayPipe {
Chris@50 91 // A data pipe with an input end and an output end. (Typically backed by pipe() system call.)
Chris@50 92
Chris@50 93 Own<AsyncInputStream> in;
Chris@50 94 Own<AsyncOutputStream> out;
Chris@50 95 };
Chris@50 96
Chris@50 97 struct TwoWayPipe {
Chris@50 98 // A data pipe that supports sending in both directions. Each end's output sends data to the
Chris@50 99 // other end's input. (Typically backed by socketpair() system call.)
Chris@50 100
Chris@50 101 Own<AsyncIoStream> ends[2];
Chris@50 102 };
Chris@50 103
Chris@50 104 class ConnectionReceiver {
Chris@50 105 // Represents a server socket listening on a port.
Chris@50 106
Chris@50 107 public:
Chris@50 108 virtual Promise<Own<AsyncIoStream>> accept() = 0;
Chris@50 109 // Accept the next incoming connection.
Chris@50 110
Chris@50 111 virtual uint getPort() = 0;
Chris@50 112 // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't
Chris@50 113 // specify a port when constructing the NetworkAddress -- one will have been assigned
Chris@50 114 // automatically.
Chris@50 115
Chris@50 116 virtual void getsockopt(int level, int option, void* value, uint* length);
Chris@50 117 virtual void setsockopt(int level, int option, const void* value, uint length);
Chris@50 118 // Same as the methods of AsyncIoStream.
Chris@50 119 };
Chris@50 120
Chris@50 121 // =======================================================================================
Chris@50 122 // Datagram I/O
Chris@50 123
Chris@50 124 class AncillaryMessage {
Chris@50 125 // Represents an ancillary message (aka control message) received using the recvmsg() system
Chris@50 126 // call (or equivalent). Most apps will not use this.
Chris@50 127
Chris@50 128 public:
Chris@50 129 inline AncillaryMessage(int level, int type, ArrayPtr<const byte> data);
Chris@50 130 AncillaryMessage() = default;
Chris@50 131
Chris@50 132 inline int getLevel() const;
Chris@50 133 // Originating protocol / socket level.
Chris@50 134
Chris@50 135 inline int getType() const;
Chris@50 136 // Protocol-specific message type.
Chris@50 137
Chris@50 138 template <typename T>
Chris@50 139 inline Maybe<const T&> as();
Chris@50 140 // Interpret the ancillary message as the given struct type. Most ancillary messages are some
Chris@50 141 // sort of struct, so this is a convenient way to access it. Returns nullptr if the message
Chris@50 142 // is smaller than the struct -- this can happen if the message was truncated due to
Chris@50 143 // insufficient ancillary buffer space.
Chris@50 144
Chris@50 145 template <typename T>
Chris@50 146 inline ArrayPtr<const T> asArray();
Chris@50 147 // Interpret the ancillary message as an array of items. If the message size does not evenly
Chris@50 148 // divide into elements of type T, the remainder is discarded -- this can happen if the message
Chris@50 149 // was truncated due to insufficient ancillary buffer space.
Chris@50 150
Chris@50 151 private:
Chris@50 152 int level;
Chris@50 153 int type;
Chris@50 154 ArrayPtr<const byte> data;
Chris@50 155 // Message data. In most cases you should use `as()` or `asArray()`.
Chris@50 156 };
Chris@50 157
Chris@50 158 class DatagramReceiver {
Chris@50 159 // Class encapsulating the recvmsg() system call. You must specify the DatagramReceiver's
Chris@50 160 // capacity in advance; if a received packet is larger than the capacity, it will be truncated.
Chris@50 161
Chris@50 162 public:
Chris@50 163 virtual Promise<void> receive() = 0;
Chris@50 164 // Receive a new message, overwriting this object's content.
Chris@50 165 //
Chris@50 166 // receive() may reuse the same buffers for content and ancillary data with each call.
Chris@50 167
Chris@50 168 template <typename T>
Chris@50 169 struct MaybeTruncated {
Chris@50 170 T value;
Chris@50 171
Chris@50 172 bool isTruncated;
Chris@50 173 // True if the Receiver's capacity was insufficient to receive the value and therefore the
Chris@50 174 // value is truncated.
Chris@50 175 };
Chris@50 176
Chris@50 177 virtual MaybeTruncated<ArrayPtr<const byte>> getContent() = 0;
Chris@50 178 // Get the content of the datagram.
Chris@50 179
Chris@50 180 virtual MaybeTruncated<ArrayPtr<const AncillaryMessage>> getAncillary() = 0;
Chris@50 181 // Ancilarry messages received with the datagram. See the recvmsg() system call and the cmsghdr
Chris@50 182 // struct. Most apps don't need this.
Chris@50 183 //
Chris@50 184 // If the returned value is truncated, then the last message in the array may itself be
Chris@50 185 // truncated, meaning its as<T>() method will return nullptr or its asArray<T>() method will
Chris@50 186 // return fewer elements than expected. Truncation can also mean that additional messages were
Chris@50 187 // available but discarded.
Chris@50 188
Chris@50 189 virtual NetworkAddress& getSource() = 0;
Chris@50 190 // Get the datagram sender's address.
Chris@50 191
Chris@50 192 struct Capacity {
Chris@50 193 size_t content = 8192;
Chris@50 194 // How much space to allocate for the datagram content. If a datagram is received that is
Chris@50 195 // larger than this, it will be truncated, with no way to recover the tail.
Chris@50 196
Chris@50 197 size_t ancillary = 0;
Chris@50 198 // How much space to allocate for ancillary messages. As with content, if the ancillary data
Chris@50 199 // is larger than this, it will be truncated.
Chris@50 200 };
Chris@50 201 };
Chris@50 202
Chris@50 203 class DatagramPort {
Chris@50 204 public:
Chris@50 205 virtual Promise<size_t> send(const void* buffer, size_t size, NetworkAddress& destination) = 0;
Chris@50 206 virtual Promise<size_t> send(ArrayPtr<const ArrayPtr<const byte>> pieces,
Chris@50 207 NetworkAddress& destination) = 0;
Chris@50 208
Chris@50 209 virtual Own<DatagramReceiver> makeReceiver(
Chris@50 210 DatagramReceiver::Capacity capacity = DatagramReceiver::Capacity()) = 0;
Chris@50 211 // Create a new `Receiver` that can be used to receive datagrams. `capacity` specifies how much
Chris@50 212 // space to allocate for the received message. The `DatagramPort` must outlive the `Receiver`.
Chris@50 213
Chris@50 214 virtual uint getPort() = 0;
Chris@50 215 // Gets the port number, if applicable (i.e. if listening on IP). This is useful if you didn't
Chris@50 216 // specify a port when constructing the NetworkAddress -- one will have been assigned
Chris@50 217 // automatically.
Chris@50 218
Chris@50 219 virtual void getsockopt(int level, int option, void* value, uint* length);
Chris@50 220 virtual void setsockopt(int level, int option, const void* value, uint length);
Chris@50 221 // Same as the methods of AsyncIoStream.
Chris@50 222 };
Chris@50 223
Chris@50 224 // =======================================================================================
Chris@50 225 // Networks
Chris@50 226
Chris@50 227 class NetworkAddress {
Chris@50 228 // Represents a remote address to which the application can connect.
Chris@50 229
Chris@50 230 public:
Chris@50 231 virtual Promise<Own<AsyncIoStream>> connect() = 0;
Chris@50 232 // Make a new connection to this address.
Chris@50 233 //
Chris@50 234 // The address must not be a wildcard ("*"). If it is an IP address, it must have a port number.
Chris@50 235
Chris@50 236 virtual Own<ConnectionReceiver> listen() = 0;
Chris@50 237 // Listen for incoming connections on this address.
Chris@50 238 //
Chris@50 239 // The address must be local.
Chris@50 240
Chris@50 241 virtual Own<DatagramPort> bindDatagramPort();
Chris@50 242 // Open this address as a datagram (e.g. UDP) port.
Chris@50 243 //
Chris@50 244 // The address must be local.
Chris@50 245
Chris@50 246 virtual Own<NetworkAddress> clone() = 0;
Chris@50 247 // Returns an equivalent copy of this NetworkAddress.
Chris@50 248
Chris@50 249 virtual String toString() = 0;
Chris@50 250 // Produce a human-readable string which hopefully can be passed to Network::parseAddress()
Chris@50 251 // to reproduce this address, although whether or not that works of course depends on the Network
Chris@50 252 // implementation. This should be called only to display the address to human users, who will
Chris@50 253 // hopefully know what they are able to do with it.
Chris@50 254 };
Chris@50 255
Chris@50 256 class Network {
Chris@50 257 // Factory for NetworkAddress instances, representing the network services offered by the
Chris@50 258 // operating system.
Chris@50 259 //
Chris@50 260 // This interface typically represents broad authority, and well-designed code should limit its
Chris@50 261 // use to high-level startup code and user interaction. Low-level APIs should accept
Chris@50 262 // NetworkAddress instances directly and work from there, if at all possible.
Chris@50 263
Chris@50 264 public:
Chris@50 265 virtual Promise<Own<NetworkAddress>> parseAddress(StringPtr addr, uint portHint = 0) = 0;
Chris@50 266 // Construct a network address from a user-provided string. The format of the address
Chris@50 267 // strings is not specified at the API level, and application code should make no assumptions
Chris@50 268 // about them. These strings should always be provided by humans, and said humans will know
Chris@50 269 // what format to use in their particular context.
Chris@50 270 //
Chris@50 271 // `portHint`, if provided, specifies the "standard" IP port number for the application-level
Chris@50 272 // service in play. If the address turns out to be an IP address (v4 or v6), and it lacks a
Chris@50 273 // port number, this port will be used. If `addr` lacks a port number *and* `portHint` is
Chris@50 274 // omitted, then the returned address will only support listen() and bindDatagramPort()
Chris@50 275 // (not connect()), and an unused port will be chosen each time one of those methods is called.
Chris@50 276
Chris@50 277 virtual Own<NetworkAddress> getSockaddr(const void* sockaddr, uint len) = 0;
Chris@50 278 // Construct a network address from a legacy struct sockaddr.
Chris@50 279 };
Chris@50 280
Chris@50 281 // =======================================================================================
Chris@50 282 // I/O Provider
Chris@50 283
Chris@50 284 class AsyncIoProvider {
Chris@50 285 // Class which constructs asynchronous wrappers around the operating system's I/O facilities.
Chris@50 286 //
Chris@50 287 // Generally, the implementation of this interface must integrate closely with a particular
Chris@50 288 // `EventLoop` implementation. Typically, the EventLoop implementation itself will provide
Chris@50 289 // an AsyncIoProvider.
Chris@50 290
Chris@50 291 public:
Chris@50 292 virtual OneWayPipe newOneWayPipe() = 0;
Chris@50 293 // Creates an input/output stream pair representing the ends of a one-way pipe (e.g. created with
Chris@50 294 // the pipe(2) system call).
Chris@50 295
Chris@50 296 virtual TwoWayPipe newTwoWayPipe() = 0;
Chris@50 297 // Creates two AsyncIoStreams representing the two ends of a two-way pipe (e.g. created with
Chris@50 298 // socketpair(2) system call). Data written to one end can be read from the other.
Chris@50 299
Chris@50 300 virtual Network& getNetwork() = 0;
Chris@50 301 // Creates a new `Network` instance representing the networks exposed by the operating system.
Chris@50 302 //
Chris@50 303 // DO NOT CALL THIS except at the highest levels of your code, ideally in the main() function. If
Chris@50 304 // you call this from low-level code, then you are preventing higher-level code from injecting an
Chris@50 305 // alternative implementation. Instead, if your code needs to use network functionality, it
Chris@50 306 // should ask for a `Network` as a constructor or method parameter, so that higher-level code can
Chris@50 307 // chose what implementation to use. The system network is essentially a singleton. See:
Chris@50 308 // http://www.object-oriented-security.org/lets-argue/singletons
Chris@50 309 //
Chris@50 310 // Code that uses the system network should not make any assumptions about what kinds of
Chris@50 311 // addresses it will parse, as this could differ across platforms. String addresses should come
Chris@50 312 // strictly from the user, who will know how to write them correctly for their system.
Chris@50 313 //
Chris@50 314 // With that said, KJ currently supports the following string address formats:
Chris@50 315 // - IPv4: "1.2.3.4", "1.2.3.4:80"
Chris@50 316 // - IPv6: "1234:5678::abcd", "[1234:5678::abcd]:80"
Chris@50 317 // - Local IP wildcard (covers both v4 and v6): "*", "*:80"
Chris@50 318 // - Symbolic names: "example.com", "example.com:80", "example.com:http", "1.2.3.4:http"
Chris@50 319 // - Unix domain: "unix:/path/to/socket"
Chris@50 320
Chris@50 321 struct PipeThread {
Chris@50 322 // A combination of a thread and a two-way pipe that communicates with that thread.
Chris@50 323 //
Chris@50 324 // The fields are intentionally ordered so that the pipe will be destroyed (and therefore
Chris@50 325 // disconnected) before the thread is destroyed (and therefore joined). Thus if the thread
Chris@50 326 // arranges to exit when it detects disconnect, destruction should be clean.
Chris@50 327
Chris@50 328 Own<Thread> thread;
Chris@50 329 Own<AsyncIoStream> pipe;
Chris@50 330 };
Chris@50 331
Chris@50 332 virtual PipeThread newPipeThread(
Chris@50 333 Function<void(AsyncIoProvider&, AsyncIoStream&, WaitScope&)> startFunc) = 0;
Chris@50 334 // Create a new thread and set up a two-way pipe (socketpair) which can be used to communicate
Chris@50 335 // with it. One end of the pipe is passed to the thread's start function and the other end of
Chris@50 336 // the pipe is returned. The new thread also gets its own `AsyncIoProvider` instance and will
Chris@50 337 // already have an active `EventLoop` when `startFunc` is called.
Chris@50 338 //
Chris@50 339 // TODO(someday): I'm not entirely comfortable with this interface. It seems to be doing too
Chris@50 340 // much at once but I'm not sure how to cleanly break it down.
Chris@50 341
Chris@50 342 virtual Timer& getTimer() = 0;
Chris@50 343 // Returns a `Timer` based on real time. Time does not pass while event handlers are running --
Chris@50 344 // it only updates when the event loop polls for system events. This means that calling `now()`
Chris@50 345 // on this timer does not require a system call.
Chris@50 346 //
Chris@50 347 // This timer is not affected by changes to the system date. It is unspecified whether the timer
Chris@50 348 // continues to count while the system is suspended.
Chris@50 349 };
Chris@50 350
Chris@50 351 class LowLevelAsyncIoProvider {
Chris@50 352 // Similar to `AsyncIoProvider`, but represents a lower-level interface that may differ on
Chris@50 353 // different operating systems. You should prefer to use `AsyncIoProvider` over this interface
Chris@50 354 // whenever possible, as `AsyncIoProvider` is portable and friendlier to dependency-injection.
Chris@50 355 //
Chris@50 356 // On Unix, this interface can be used to import native file descriptors into the async framework.
Chris@50 357 // Different implementations of this interface might work on top of different event handling
Chris@50 358 // primitives, such as poll vs. epoll vs. kqueue vs. some higher-level event library.
Chris@50 359 //
Chris@50 360 // On Windows, this interface can be used to import native HANDLEs into the async framework.
Chris@50 361 // Different implementations of this interface might work on top of different event handling
Chris@50 362 // primitives, such as I/O completion ports vs. completion routines.
Chris@50 363 //
Chris@50 364 // TODO(port): Actually implement Windows support.
Chris@50 365
Chris@50 366 public:
Chris@50 367 // ---------------------------------------------------------------------------
Chris@50 368 // Unix-specific stuff
Chris@50 369
Chris@50 370 enum Flags {
Chris@50 371 // Flags controlling how to wrap a file descriptor.
Chris@50 372
Chris@50 373 TAKE_OWNERSHIP = 1 << 0,
Chris@50 374 // The returned object should own the file descriptor, automatically closing it when destroyed.
Chris@50 375 // The close-on-exec flag will be set on the descriptor if it is not already.
Chris@50 376 //
Chris@50 377 // If this flag is not used, then the file descriptor is not automatically closed and the
Chris@50 378 // close-on-exec flag is not modified.
Chris@50 379
Chris@50 380 ALREADY_CLOEXEC = 1 << 1,
Chris@50 381 // Indicates that the close-on-exec flag is known already to be set, so need not be set again.
Chris@50 382 // Only relevant when combined with TAKE_OWNERSHIP.
Chris@50 383 //
Chris@50 384 // On Linux, all system calls which yield new file descriptors have flags or variants which
Chris@50 385 // set the close-on-exec flag immediately. Unfortunately, other OS's do not.
Chris@50 386
Chris@50 387 ALREADY_NONBLOCK = 1 << 2
Chris@50 388 // Indicates that the file descriptor is known already to be in non-blocking mode, so the flag
Chris@50 389 // need not be set again. Otherwise, all wrap*Fd() methods will enable non-blocking mode
Chris@50 390 // automatically.
Chris@50 391 //
Chris@50 392 // On Linux, all system calls which yield new file descriptors have flags or variants which
Chris@50 393 // enable non-blocking mode immediately. Unfortunately, other OS's do not.
Chris@50 394 };
Chris@50 395
Chris@50 396 virtual Own<AsyncInputStream> wrapInputFd(int fd, uint flags = 0) = 0;
Chris@50 397 // Create an AsyncInputStream wrapping a file descriptor.
Chris@50 398 //
Chris@50 399 // `flags` is a bitwise-OR of the values of the `Flags` enum.
Chris@50 400
Chris@50 401 virtual Own<AsyncOutputStream> wrapOutputFd(int fd, uint flags = 0) = 0;
Chris@50 402 // Create an AsyncOutputStream wrapping a file descriptor.
Chris@50 403 //
Chris@50 404 // `flags` is a bitwise-OR of the values of the `Flags` enum.
Chris@50 405
Chris@50 406 virtual Own<AsyncIoStream> wrapSocketFd(int fd, uint flags = 0) = 0;
Chris@50 407 // Create an AsyncIoStream wrapping a socket file descriptor.
Chris@50 408 //
Chris@50 409 // `flags` is a bitwise-OR of the values of the `Flags` enum.
Chris@50 410
Chris@50 411 virtual Promise<Own<AsyncIoStream>> wrapConnectingSocketFd(int fd, uint flags = 0) = 0;
Chris@50 412 // Create an AsyncIoStream wrapping a socket that is in the process of connecting. The returned
Chris@50 413 // promise should not resolve until connection has completed -- traditionally indicated by the
Chris@50 414 // descriptor becoming writable.
Chris@50 415 //
Chris@50 416 // `flags` is a bitwise-OR of the values of the `Flags` enum.
Chris@50 417
Chris@50 418 virtual Own<ConnectionReceiver> wrapListenSocketFd(int fd, uint flags = 0) = 0;
Chris@50 419 // Create an AsyncIoStream wrapping a listen socket file descriptor. This socket should already
Chris@50 420 // have had `bind()` and `listen()` called on it, so it's ready for `accept()`.
Chris@50 421 //
Chris@50 422 // `flags` is a bitwise-OR of the values of the `Flags` enum.
Chris@50 423
Chris@50 424 virtual Own<DatagramPort> wrapDatagramSocketFd(int fd, uint flags = 0);
Chris@50 425
Chris@50 426 virtual Timer& getTimer() = 0;
Chris@50 427 // Returns a `Timer` based on real time. Time does not pass while event handlers are running --
Chris@50 428 // it only updates when the event loop polls for system events. This means that calling `now()`
Chris@50 429 // on this timer does not require a system call.
Chris@50 430 //
Chris@50 431 // This timer is not affected by changes to the system date. It is unspecified whether the timer
Chris@50 432 // continues to count while the system is suspended.
Chris@50 433 };
Chris@50 434
Chris@50 435 Own<AsyncIoProvider> newAsyncIoProvider(LowLevelAsyncIoProvider& lowLevel);
Chris@50 436 // Make a new AsyncIoProvider wrapping a `LowLevelAsyncIoProvider`.
Chris@50 437
Chris@50 438 struct AsyncIoContext {
Chris@50 439 Own<LowLevelAsyncIoProvider> lowLevelProvider;
Chris@50 440 Own<AsyncIoProvider> provider;
Chris@50 441 WaitScope& waitScope;
Chris@50 442
Chris@50 443 UnixEventPort& unixEventPort;
Chris@50 444 // TEMPORARY: Direct access to underlying UnixEventPort, mainly for waiting on signals. This
Chris@50 445 // field will go away at some point when we have a chance to improve these interfaces.
Chris@50 446 };
Chris@50 447
Chris@50 448 AsyncIoContext setupAsyncIo();
Chris@50 449 // Convenience method which sets up the current thread with everything it needs to do async I/O.
Chris@50 450 // The returned objects contain an `EventLoop` which is wrapping an appropriate `EventPort` for
Chris@50 451 // doing I/O on the host system, so everything is ready for the thread to start making async calls
Chris@50 452 // and waiting on promises.
Chris@50 453 //
Chris@50 454 // You would typically call this in your main() loop or in the start function of a thread.
Chris@50 455 // Example:
Chris@50 456 //
Chris@50 457 // int main() {
Chris@50 458 // auto ioContext = kj::setupAsyncIo();
Chris@50 459 //
Chris@50 460 // // Now we can call an async function.
Chris@50 461 // Promise<String> textPromise = getHttp(*ioContext.provider, "http://example.com");
Chris@50 462 //
Chris@50 463 // // And we can wait for the promise to complete. Note that you can only use `wait()`
Chris@50 464 // // from the top level, not from inside a promise callback.
Chris@50 465 // String text = textPromise.wait(ioContext.waitScope);
Chris@50 466 // print(text);
Chris@50 467 // return 0;
Chris@50 468 // }
Chris@50 469 //
Chris@50 470 // WARNING: An AsyncIoContext can only be used in the thread and process that created it. In
Chris@50 471 // particular, note that after a fork(), an AsyncIoContext created in the parent process will
Chris@50 472 // not work correctly in the child, even if the parent ceases to use its copy. In particular
Chris@50 473 // note that this means that server processes which daemonize themselves at startup must wait
Chris@50 474 // until after daemonization to create an AsyncIoContext.
Chris@50 475
Chris@50 476 // =======================================================================================
Chris@50 477 // inline implementation details
Chris@50 478
Chris@50 479 inline AncillaryMessage::AncillaryMessage(
Chris@50 480 int level, int type, ArrayPtr<const byte> data)
Chris@50 481 : level(level), type(type), data(data) {}
Chris@50 482
Chris@50 483 inline int AncillaryMessage::getLevel() const { return level; }
Chris@50 484 inline int AncillaryMessage::getType() const { return type; }
Chris@50 485
Chris@50 486 template <typename T>
Chris@50 487 inline Maybe<const T&> AncillaryMessage::as() {
Chris@50 488 if (data.size() >= sizeof(T)) {
Chris@50 489 return *reinterpret_cast<const T*>(data.begin());
Chris@50 490 } else {
Chris@50 491 return nullptr;
Chris@50 492 }
Chris@50 493 }
Chris@50 494
Chris@50 495 template <typename T>
Chris@50 496 inline ArrayPtr<const T> AncillaryMessage::asArray() {
Chris@50 497 return arrayPtr(reinterpret_cast<const T*>(data.begin()), data.size() / sizeof(T));
Chris@50 498 }
Chris@50 499
Chris@50 500 } // namespace kj
Chris@50 501
Chris@50 502 #endif // KJ_ASYNC_IO_H_