annotate win32-mingw/include/kj/async-io.h @ 169:223a55898ab9 tip default

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