annotate win32-mingw/include/kj/async-io.h @ 69:7aeed7906520

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