annotate win64-msvc/include/kj/async-io.h @ 47:d93140aac40b

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