annotate win64-msvc/include/kj/async-io.h @ 145:13a516fa8999

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