annotate osx/include/kj/async-io.h @ 49:3ab5a40c4e3b

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