5#include "../Common/CompilerMacrosExport.h"
6#ifndef SC_EXPORT_LIBRARY_ASYNC
7#define SC_EXPORT_LIBRARY_ASYNC 0
9#define SC_ASYNC_EXPORT SC_COMPILER_LIBRARY_EXPORT(SC_EXPORT_LIBRARY_ASYNC)
11#include "../Async/Internal/IntrusiveDoubleLinkedList.h"
12#include "../Common/Assert.h"
13#include "../Common/Function.h"
14#include "../Common/OpaqueObject.h"
15#include "../File/File.h"
16#include "../FileSystem/FileSystem.h"
17#include "../Socket/Socket.h"
18#include "../Threading/Atomic.h"
19#include "../Threading/ThreadPool.h"
23SC_DECLARE_ASSERT_PROVIDER(AsyncAssert, SC_ASYNC_EXPORT);
25#define SC_ASYNC_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::AsyncAssert, e)
26#define SC_ASYNC_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::AsyncAssert, e)
27#define SC_ASYNC_TRUST_RESULT(expression) SC_ASYNC_ASSERT_RELEASE(expression)
66struct AsyncTaskSequence;
69enum class AsyncThreadPoolMode : uint8_t
77struct AsyncWinOverlapped;
78struct AsyncWinOverlappedDefinition
80 static constexpr int Windows =
sizeof(
void*) * 4 +
sizeof(uint64_t);
81 static constexpr size_t Alignment =
alignof(
void*);
83 using Object = AsyncWinOverlapped;
85using WinOverlappedOpaque = OpaqueObject<AsyncWinOverlappedDefinition>;
87struct AsyncWinWaitDefinition
89 using Handle = FileDescriptor::Handle;
90 static constexpr Handle Invalid = FileDescriptor::Invalid;
92 static Result releaseHandle(Handle& waitHandle);
94struct SC_ASYNC_EXPORT WinWaitHandle :
public UniqueHandle<AsyncWinWaitDefinition>
142 void setDebugName(
const char* newDebugName);
151 AsyncThreadPoolMode mode = AsyncThreadPoolMode::NativePreferred);
180 AsyncRequest(
Type type) : state(State::Free), type(type), flags(0), unused(0), userFlags(0) {}
207 void setUserFlags(uint16_t externalFlags) { userFlags = externalFlags; }
215 [[nodiscard]]
const Function<void(
AsyncResult&)>* getCloseCallback()
const {
return closeCallback; }
220 void queueSubmission(AsyncEventLoop& eventLoop);
222 AsyncSequence* sequence =
nullptr;
224 AsyncTaskSequence* getTask();
226 [[nodiscard]]
bool isThreadPoolForced()
const;
229 Function<void(AsyncResult&)>* closeCallback =
nullptr;
231 friend struct AsyncEventLoop;
232 friend struct AsyncResult;
236 [[nodiscard]]
static const char* TypeToString(Type type);
237 enum class State : uint8_t
247#if SC_ASYNC_ENABLE_LOG
248 const char* debugName =
"None";
267 bool clearSequenceOnCancel =
true;
268 bool clearSequenceOnError =
true;
271 bool runningAsync =
false;
272 bool tracked =
false;
276 IntrusiveDoubleLinkedList<AsyncRequest> submissions;
290 : eventLoop(eventLoop), async(request), hasBeenReactivated(hasBeenReactivated), returnCode(res)
298 [[nodiscard]]
const SC::Result&
isValid()
const {
return returnCode; }
306 bool shouldCallCallback =
true;
307 bool* hasBeenReactivated =
nullptr;
309 SC::Result& returnCode;
315template <
typename T,
typename C>
318 T& getAsync() {
return static_cast<T&
>(AsyncResult::async); }
319 const T& getAsync()
const {
return static_cast<const T&
>(AsyncResult::async); }
324 int32_t eventIndex = 0;
337 using AsyncRequest::start;
357 TimeMs expirationTime;
393 uint32_t deliveryCount = 1;
413 int32_t consumePendingWakeUps();
414 int32_t getPendingWakeUps()
const;
437 SC::Result get(
int& status)
439 status = completionData.exitStatus;
443 using AsyncRequest::start;
456 FileDescriptor::Handle handle = FileDescriptor::Invalid;
457#if SC_PLATFORM_WINDOWS
458 detail::WinOverlappedOpaque overlapped;
459 detail::WinWaitHandle waitHandle;
461#elif SC_PLATFORM_LINUX
507 int signalNumber = 0;
508 uint32_t deliveryCount = 1;
515 using AsyncRequest::start;
526 int signalNumber = 0;
528#if SC_PLATFORM_WINDOWS
529 detail::WinOverlappedOpaque overlapped;
531#elif SC_PLATFORM_LINUX
533 FileDescriptor::Handle signalFdHandle = FileDescriptor::Invalid;
542struct SC_ASYNC_EXPORT AsyncSocketAcceptData
544#if SC_PLATFORM_WINDOWS
545 void (*pAcceptEx)() =
nullptr;
546 detail::WinOverlappedOpaque overlapped;
548 uint8_t acceptBuffer[288] = {0};
549#elif SC_PLATFORM_LINUX
550 AlignedStorage<28> sockAddrHandle;
551 uint32_t sockAddrLen;
556struct SC_ASYNC_EXPORT AsyncSocketAcceptBase :
public AsyncRequest
558 AsyncSocketAcceptBase() : AsyncRequest(Type::SocketAccept) {}
560 struct CompletionData :
public AsyncCompletionData
562 SocketDescriptor acceptedClient;
565 struct Result :
public AsyncResultOf<AsyncSocketAccept, CompletionData>
567 using AsyncResultOf<AsyncSocketAccept, CompletionData>::AsyncResultOf;
569 SC::Result moveTo(SocketDescriptor& client)
572 return SC::Result(client.assign(move(completionData.acceptedClient)));
575 using AsyncRequest::start;
578 SC::Result start(AsyncEventLoop& eventLoop,
const SocketDescriptor& socketDescriptor, AsyncSocketAcceptData& data);
579 SC::Result validate(AsyncEventLoop&);
581 Function<void(Result&)> callback;
582 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
583 SocketFlags::AddressFamily addressFamily = SocketFlags::AddressFamilyIPV4;
584 AsyncSocketAcceptData* acceptData =
nullptr;
601 using AsyncSocketAcceptBase::start;
607 detail::AsyncSocketAcceptData data;
624 using AsyncRequest::start;
631 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
638#if SC_PLATFORM_WINDOWS
639 void (*pConnectEx)() =
nullptr;
640 detail::WinOverlappedOpaque overlapped;
660 using AsyncRequest::start;
670 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
672 SC::Result closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
676 bool singleBuffer =
true;
683 size_t totalBytesWritten = 0;
684#if SC_PLATFORM_WINDOWS
685 detail::WinOverlappedOpaque overlapped;
705 Span<const char> data);
708 Span<Span<const char>> data);
711 using AsyncSocketSend::start;
715 AlignedStorage<56> typeErasedMsgHdr;
737 bool disconnected =
false;
744 bool isEnded()
const {
return completionData.disconnected; }
749 SC::Result
get(Span<char>& outData)
751 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, outData));
757 using AsyncRequest::start;
765 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
767 SC::Result
closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
771 friend struct AsyncEventLoop;
772 SC::Result validate(AsyncEventLoop&);
773#if SC_PLATFORM_WINDOWS
774 detail::WinOverlappedOpaque overlapped;
790 using AsyncSocketReceive::start;
797 AlignedStorage<56> typeErasedMsgHdr;
830 bool endOfFile =
false;
837 bool isEnded()
const {
return completionData.endOfFile; }
839 SC::Result get(Span<char>& data)
841 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, data));
845 using AsyncRequest::start;
850 Function<void(
Result&)> callback;
855 SC::Result
closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
872 bool useOffset =
false;
873 bool endedSync =
false;
876#if SC_PLATFORM_WINDOWS
877 uint64_t readCursor = 0;
878 detail::WinOverlappedOpaque overlapped;
916 SC::Result get(
size_t& writtenSizeInBytes)
918 writtenSizeInBytes = completionData.numBytes;
923 using AsyncRequest::start;
942 SC::Result closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
946 bool singleBuffer =
true;
963#if SC_PLATFORM_WINDOWS
964 bool endedSync =
false;
966 bool isWatchable =
false;
968 bool useOffset =
false;
969 uint64_t offset = 0xffffffffffffffff;
971 size_t totalBytesWritten = 0;
972#if SC_PLATFORM_WINDOWS
973 detail::WinOverlappedOpaque overlapped;
990 Function<void(
Result&)> callback;
996 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1006 size_t bytesTransferred = 0;
1015#if SC_PLATFORM_WINDOWS
1017 SC::Result start(
AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1020 [[nodiscard]]
void* getWindowsOverlapped();
1029 [[nodiscard]]
bool hasSubmissionPending()
const {
return submissionPending; }
1031 Function<void(Result&)> callback;
1037 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1038 size_t bytesTransferred = 0;
1039 bool manualMode =
true;
1040 bool submissionPending =
false;
1041 bool completionPosted =
false;
1042#if SC_PLATFORM_WINDOWS
1043 detail::WinOverlappedOpaque overlapped;
1077 size_t bytesTransferred = 0;
1078 bool usedZeroCopy =
false;
1089 [[nodiscard]]
bool usedZeroCopy()
const {
return completionData.usedZeroCopy; }
1094 return returnCode && completionData.bytesTransferred == getAsync().length;
1098 using AsyncRequest::start;
1110 int64_t offset = 0,
size_t length = 0,
size_t pipeSize = 0);
1115 FileDescriptor::Handle fileHandle = FileDescriptor::Invalid;
1116 SocketDescriptor::Handle socketHandle = SocketDescriptor::Invalid;
1120 size_t bytesSent = 0;
1125#if SC_PLATFORM_WINDOWS
1126 detail::WinOverlappedOpaque overlapped;
1127#elif SC_PLATFORM_LINUX
1128 size_t pipeBufferSize = 0;
1139 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1142 size_t numBytes = 0;
1148struct SC_ASYNC_EXPORT AsyncCompletionVariant
1150 AsyncCompletionVariant() {}
1151 ~AsyncCompletionVariant() { destroy(); }
1153 AsyncCompletionVariant(
const AsyncCompletionVariant&) =
delete;
1154 AsyncCompletionVariant(AsyncCompletionVariant&&) =
delete;
1155 AsyncCompletionVariant& operator=(
const AsyncCompletionVariant&) =
delete;
1156 AsyncCompletionVariant& operator=(AsyncCompletionVariant&&) =
delete;
1158 bool inited =
false;
1160 AsyncRequest::Type type;
1163 AsyncCompletionData completionDataLoopWork;
1164 AsyncLoopTimeout::CompletionData completionDataLoopTimeout;
1165 AsyncLoopWakeUp::CompletionData completionDataLoopWakeUp;
1166 AsyncProcessExit::CompletionData completionDataProcessExit;
1167 AsyncSignal::CompletionData completionDataSignal;
1168 AsyncSocketAccept::CompletionData completionDataSocketAccept;
1169 AsyncSocketConnect::CompletionData completionDataSocketConnect;
1170 AsyncSocketSend::CompletionData completionDataSocketSend;
1171 AsyncSocketSendTo::CompletionData completionDataSocketSendTo;
1172 AsyncSocketReceive::CompletionData completionDataSocketReceive;
1173 AsyncSocketReceiveFrom::CompletionData completionDataSocketReceiveFrom;
1174 AsyncFileRead::CompletionData completionDataFileRead;
1175 AsyncFileWrite::CompletionData completionDataFileWrite;
1176 AsyncFileSend::CompletionData completionDataFileSend;
1177 AsyncFileReadiness::CompletionData completionDataFileReadiness;
1178 AsyncExternalCompletion::CompletionData completionDataExternalCompletion;
1180 AsyncFileSystemOperationCompletionData completionDataFileSystemOperation;
1183 auto& getCompletion(AsyncLoopWork&) {
return completionDataLoopWork; }
1184 auto& getCompletion(AsyncLoopTimeout&) {
return completionDataLoopTimeout; }
1185 auto& getCompletion(AsyncLoopWakeUp&) {
return completionDataLoopWakeUp; }
1186 auto& getCompletion(AsyncProcessExit&) {
return completionDataProcessExit; }
1187 auto& getCompletion(AsyncSignal&) {
return completionDataSignal; }
1188 auto& getCompletion(AsyncSocketAccept&) {
return completionDataSocketAccept; }
1189 auto& getCompletion(AsyncSocketConnect&) {
return completionDataSocketConnect; }
1190 auto& getCompletion(AsyncSocketSend&) {
return completionDataSocketSend; }
1191 auto& getCompletion(AsyncSocketReceive&) {
return completionDataSocketReceive; }
1192 auto& getCompletion(AsyncFileRead&) {
return completionDataFileRead; }
1193 auto& getCompletion(AsyncFileWrite&) {
return completionDataFileWrite; }
1194 auto& getCompletion(AsyncFileSend&) {
return completionDataFileSend; }
1195 auto& getCompletion(AsyncFileReadiness&) {
return completionDataFileReadiness; }
1196 auto& getCompletion(AsyncExternalCompletion&) {
return completionDataExternalCompletion; }
1197 auto& getCompletion(AsyncFileSystemOperation&) {
return completionDataFileSystemOperation; }
1199 template <
typename T>
1200 auto& construct(T& t)
1203 placementNew(getCompletion(t));
1206 return getCompletion(t);
1224 detail::AsyncCompletionVariant completion;
1226 SC::Result returnCode = SC::Result(
true);
1245 Function<SC::Result()> work;
1294#ifdef RemoveDirectory
1295#undef RemoveDirectory
1297 enum class Operation
1341 SC::Result
read(
AsyncEventLoop& eventLoop, FileDescriptor::Handle handle, Span<char> buffer, uint64_t offset);
1392 Operation operation = Operation::None;
1393 AsyncThreadPoolMode threadPoolMode = AsyncThreadPoolMode::NativePreferred;
1399 struct FileDescriptorData
1401 FileDescriptor::Handle handle;
1412 FileDescriptor::Handle handle;
1419 FileDescriptor::Handle handle;
1420 Span<const char> buffer;
1427 StringSpan destinationPath;
1428 FileSystemCopyFlags copyFlags;
1431 using CopyDirectoryData = CopyFileData;
1433 using CloseData = FileDescriptorData;
1449 CloseData closeData;
1451 WriteData writeData;
1452 CopyFileData copyFileData;
1453 CopyDirectoryData copyDirectoryData;
1454 RenameData renameData;
1455 RemoveData removeData;
1460 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1461 SC::Result validate(AsyncEventLoop&);
1472 int numberOfEvents = 0;
1503 Options() { apiType = ApiType::Automatic; }
1705 static constexpr int Windows = 576;
1706 static constexpr int Apple = 552;
1707 static constexpr int Linux = 816;
1708 static constexpr int Default = Linux;
1710 static constexpr size_t Alignment = 8;
1712 using Object = Internal;
1715 using InternalOpaque = OpaqueObject<InternalDefinition>;
1718 InternalOpaque internalOpaque;
1759#pragma warning(push)
1760#pragma warning(disable : 4324)
1762 alignas(uint64_t) uint8_t eventsMemory[8 * 1024];
1778 bool wakeUpHasBeenCalled =
false;
1780 Result monitoringLoopThread(
Thread& thread);
Empty base struct for all AsyncRequest-derived CompletionData (internal) structs.
Definition Async.h:281
Allow library user to provide callbacks signaling different phases of async event loop cycle.
Definition Async.h:1479
Monitors Async I/O events from a background thread using a blocking kernel function (no CPU usage on ...
Definition Async.h:1733
Function< void(void)> onNewEventsAvailable
Informs to call dispatchCompletions on GUI Event Loop.
Definition Async.h:1734
Result startMonitoring()
Queue all async requests submissions and start monitoring loop events on a background thread.
Result close()
Stop monitoring the AsyncEventLoop, disposing all resources.
Result stopMonitoringAndDispatchCompletions()
Stops monitoring events on the background thread and dispatches callbacks for completed requests.
Result create(AsyncEventLoop &eventLoop)
Create the monitoring thread for an AsyncEventLoop.
Options given to AsyncEventLoop::create.
Definition Async.h:1494
ApiType apiType
Criteria to choose Async IO API.
Definition Async.h:1501
ApiType
Definition Async.h:1496
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1491
bool needsThreadPoolForFileOperations() const
Returns true if backend needs a thread pool for non-blocking fs operations (anything but io_uring bas...
Result associateExternallyCreatedFileDescriptor(FileDescriptor &outDescriptor)
Associates a previously created File Descriptor with the eventLoop.
Result wakeUpFromExternalThread()
Wake up the event loop from a thread different than the one where run() is called (and potentially bl...
Result runNoWait()
Process ready requests if any, dispatching their completions, or returns immediately without blocking...
static Result removeAllAssociationsFor(SocketDescriptor &outDescriptor)
Removes association of a TCP Socket with any event loop.
void updateTime()
Updates loop time to "now".
static bool tryProbingIOUring()
Check if io_uring can be created directly (only on Linux)
static bool isExcludedFromActiveCount(const AsyncRequest &async)
Checks if excludeFromActiveCount() has been called on the given request.
Result associateExternallyCreatedSocket(SocketDescriptor &outDescriptor)
Associates a previously created TCP / UDP socket with the eventLoop.
Result associateExternallyCreatedFileDescriptorHandle(FileDescriptor::Handle handle)
Associates a previously created File Descriptor handle with the eventLoop.
Result blockingPoll(AsyncKernelEvents &kernelEvents)
Blocks until at least one event happens, ensuring forward progress, without executing completions.
void clearSequence(AsyncSequence &sequence)
Clears the sequence.
int getNumberOfSubmittedRequests() const
Obtain the total number of submitted requests.
Result submitRequests(AsyncKernelEvents &kernelEvents)
Submits all queued async requests without running user callbacks.
void enumerateRequests(Function< void(AsyncRequest &)> enumerationCallback)
Enumerates user-visible request objects associated with this loop.
Result postExternalCompletion(AsyncExternalCompletion &async, size_t bytesTransferred=0)
Posts completion for an AsyncExternalCompletion started in manual mode.
TimeMs getLoopTime() const
Get Loop time (monotonic)
Result associateExternallyCreatedSocketHandle(SocketDescriptor::Handle handle)
Associates a previously created TCP / UDP socket handle with the eventLoop.
Result start(AsyncRequest &async)
Queues an async request request that has been correctly setup.
AsyncLoopTimeout * findEarliestLoopTimeout() const
Returns the next AsyncLoopTimeout that will be executed (shortest relativeTimeout)
void setListeners(AsyncEventLoopListeners *listeners)
Sets listeners invoked around AsyncEventLoop::blockingPoll.
Result dispatchCompletions(AsyncKernelEvents &kernelEvents)
Invokes completions for the AsyncKernelEvents collected by a call to AsyncEventLoop::blockingPoll.
void interrupt()
Interrupts AsyncEventLoop::run, causing it to return even if counted active work remains.
Result wakeUpFromExternalThread(AsyncLoopWakeUp &wakeUp)
Wake up the event loop from a thread different than the one where run() is called (and potentially bl...
bool isInitialized() const
Returns true if create has been already called (successfully)
static Result removeAllAssociationsForSocketHandle(SocketDescriptor::Handle handle)
Removes association of a TCP Socket handle with any event loop.
Result create(Options options=Options())
Creates the event loop kernel object.
Result createAsyncTCPSocket(SocketFlags::AddressFamily family, SocketDescriptor &outDescriptor)
Creates an async TCP (IPV4 / IPV6) socket registered with the eventLoop.
Result close()
Closes the event loop kernel object.
static Result removeAllAssociationsForFileDescriptorHandle(FileDescriptor::Handle handle)
Removes association of a File Descriptor handle with any event loop.
Result createAsyncUDPSocket(SocketFlags::AddressFamily family, SocketDescriptor &outDescriptor)
Creates an async UCP (IPV4 / IPV6) socket registered with the eventLoop.
static Result removeAllAssociationsFor(FileDescriptor &outDescriptor)
Removes association of a File Descriptor with any event loop.
Result runOnce()
Blocks until at least one request proceeds, ensuring forward progress, dispatching ready completions.
void excludeFromActiveCount(AsyncRequest &async)
Excludes the request from active handles count so it does not keep AsyncEventLoop::run alive.
Result run()
Blocks until there are no more counted active, submitted, or cancelling requests, dispatching complet...
void includeInActiveCount(AsyncRequest &async)
Reverses the effect of excludeFromActiveCount for the request.
int getNumberOfActiveRequests() const
Obtain the total number of active requests.
Integrates externally-submitted completion based operations with AsyncEventLoop.
Definition Async.h:1003
SC::Result clearSubmissionPending()
Clears a pending submission after an external submission failed synchronously.
SC::Result start(AsyncEventLoop &eventLoop)
Starts a manual external completion. The request remains active until postExternalCompletion() or sto...
SC::Result markSubmissionPending()
Marks that a native/manual external operation has been submitted and must complete before reuse.
Starts a file read operation, reading bytes from a file (or pipe).
Definition Async.h:824
FileDescriptor::Handle handle
The writeable span of memory where to data will be written.
Definition Async.h:852
Span< char > buffer
Callback called when some data has been read from the file into the buffer.
Definition Async.h:851
SC::Result closeHandle()
The file/pipe descriptor handle to read data from.
Definition Async.h:855
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start reading.
Definition Async.h:862
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &descriptor, Span< char > data)
Sets async request members and calls AsyncEventLoop::start.
uint64_t getOffset() const
Returns the last offset set with AsyncFileRead::setOffset.
Definition Async.h:858
Starts a file descriptor readiness operation.
Definition Async.h:981
SC::Result start(AsyncEventLoop &eventLoop, FileDescriptor::Handle fileDescriptor)
Starts a file descriptor poll operation, monitoring its readiness with appropriate OS API.
size_t getBytesTransferred() const
Get the number of bytes transferred.
Definition Async.h:1086
bool usedZeroCopy() const
Check if zero-copy was used for this transfer.
Definition Async.h:1089
bool isComplete() const
Check if the entire requested range was sent.
Definition Async.h:1092
Sends file contents to a socket using zero-copy when available (sendfile, TransmitFile).
Definition Async.h:1072
Function< void(Result &)> callback
Called when send completes or fails.
Definition Async.h:1112
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &file, const SocketDescriptor &socket, int64_t offset=0, size_t length=0, size_t pipeSize=0)
Start the file send operation.
Starts an asynchronous file system operation (open, close, read, write, sendFile, stat,...
Definition Async.h:1288
SC::Result stop(AsyncEventLoop &eventLoop, Function< void(AsyncResult &)> *afterStopped=nullptr)
Stops the operation, including the internal thread-pool work item when used.
SC::Result copyDirectory(AsyncEventLoop &eventLoop, StringSpan path, StringSpan destinationPath, FileSystemCopyFlags copyFlags=FileSystemCopyFlags())
Copies a directory from one location to another.
SC::Result removeEmptyDirectory(AsyncEventLoop &eventLoop, StringSpan path)
Removes a directory asynchronously.
SC::Result setThreadPool(ThreadPool &threadPool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Sets the thread pool to use for the operation.
SC::Result rename(AsyncEventLoop &eventLoop, StringSpan path, StringSpan newPath)
Renames a file.
SC::Result removeFile(AsyncEventLoop &eventLoop, StringSpan path)
Removes a file asynchronously.
SC::Result read(AsyncEventLoop &eventLoop, FileDescriptor::Handle handle, Span< char > buffer, uint64_t offset)
Reads data from a file descriptor at a given offset.
SC::Result write(AsyncEventLoop &eventLoop, FileDescriptor::Handle handle, Span< const char > buffer, uint64_t offset)
Writes data to a file descriptor at a given offset.
SC::Result close(AsyncEventLoop &eventLoop, FileDescriptor::Handle handle)
Closes a file descriptor asynchronously.
Function< void(Result &)> callback
Called after the operation is completed, on the event loop thread.
Definition Async.h:1320
SC::Result copyFile(AsyncEventLoop &eventLoop, StringSpan path, StringSpan destinationPath, FileSystemCopyFlags copyFlags=FileSystemCopyFlags())
Copies a file from one location to another.
SC::Result open(AsyncEventLoop &eventLoop, StringSpan path, FileOpen mode)
Opens a file asynchronously and returns its corresponding file descriptor.
Starts a file write operation, writing bytes to a file (or pipe).
Definition Async.h:904
uint64_t getOffset() const
Returns the last offset set with AsyncFileWrite::setOffset.
Definition Async.h:949
FileDescriptor::Handle handle
The file/pipe descriptor to write data to.
Definition Async.h:939
SC::Result start(AsyncEventLoop &eventLoop, Span< const char > data)
Sets async request members and calls AsyncEventLoop::start.
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &descriptor, Span< Span< const char > > data)
Sets async request members and calls AsyncEventLoop::start.
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start writing.
Definition Async.h:953
Function< void(Result &)> callback
Callback called when descriptor is ready to be written with more data.
Definition Async.h:937
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &descriptor, Span< const char > data)
Sets async request members and calls AsyncEventLoop::start.
Span< Span< const char > > buffers
The read-only spans of memory where to read the data from.
Definition Async.h:945
SC::Result start(AsyncEventLoop &eventLoop, Span< Span< const char > > data)
Sets async request members and calls AsyncEventLoop::start.
Span< const char > buffer
The read-only span of memory where to read the data from.
Definition Async.h:944
Allows user to supply a block of memory that will store kernel I/O events retrieved from AsyncEventLo...
Definition Async.h:1468
Span< uint8_t > eventsMemory
User supplied block of memory used to store kernel I/O events.
Definition Async.h:1469
Starts a Timeout that is invoked only once after expiration (relative) time has passed.
Definition Async.h:332
TimeMs getExpirationTime() const
Gets computed absolute expiration time that determines when this timeout get executed.
Definition Async.h:352
SC::Result start(AsyncEventLoop &eventLoop, TimeMs relativeTimeout)
Sets async request members and calls AsyncEventLoop::start.
TimeMs relativeTimeout
First timer expiration (relative) time in milliseconds.
Definition Async.h:349
Function< void(Result &)> callback
Called after given expiration time since AsyncLoopTimeout::start has passed.
Definition Async.h:347
SC::Result unschedule(AsyncEventLoop &eventLoop)
Synchronously removes an unsequenced timeout from the event loop schedule without invoking its callba...
Options for AsyncLoopWakeUp configuration.
Definition Async.h:362
bool coalesce
Merge repeated pending wakeUp() calls into a single callback (default true, matching libuv uv_async_t...
Definition Async.h:365
Starts a wake-up operation, allowing threads to execute callbacks on loop thread.
Definition Async.h:388
SC::Result start(AsyncEventLoop &eventLoop, EventObject &eventObject, AsyncLoopWakeUpOptions options={})
Sets async request members and calls AsyncEventLoop::start.
Function< void(Result &)> callback
Callback called by SC::AsyncEventLoop::run after SC::AsyncLoopWakeUp::wakeUp.
Definition Async.h:407
SC::Result wakeUp(AsyncEventLoop &eventLoop)
Wakes up event loop, scheduling AsyncLoopWakeUp::callback on next AsyncEventLoop::run (or its variati...
SC::Result start(AsyncEventLoop &eventLoop, AsyncLoopWakeUpOptions options={})
Sets async request members and calls AsyncEventLoop::start.
Executes work in a thread pool and then invokes a callback on the event loop thread.
Definition Async.h:1235
Function< void(Result &)> callback
Called to execute the work in a background threadpool thread.
Definition Async.h:1246
SC::Result setThreadPool(ThreadPool &threadPool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Sets the ThreadPool that will supply the thread to run the async work on.
Starts monitoring a process, notifying about its termination.
Definition Async.h:425
SC::Result start(AsyncEventLoop &eventLoop, FileDescriptor::Handle process)
Sets async request members and calls AsyncEventLoop::start.
Function< void(Result &)> callback
Called when process has exited.
Definition Async.h:450
Base class for all async requests, holding state and type.
Definition Async.h:138
bool isCancelling() const
Returns true if this request is being cancelled.
AsyncRequest(Type type)
Constructs a free async request of given type.
Definition Async.h:180
Result start(AsyncEventLoop &eventLoop)
Shortcut for AsyncEventLoop::start.
uint16_t getUserFlags() const
Gets user flags, holding some meaningful data for the caller.
Definition Async.h:210
Function< void(AsyncResult &)> * getCloseCallback()
Returns currently set close callback (if any) passed to AsyncRequest::stop.
Definition Async.h:213
bool isActive() const
Returns true if this request is active or being reactivated.
Result executeOn(AsyncTaskSequence &task, ThreadPool &pool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Adds the request to be executed on a specific AsyncTaskSequence.
bool isFree() const
Returns true if this request is free.
void disableThreadPool()
Disables the thread-pool usage for this request.
Type getType() const
Returns request type.
Definition Async.h:201
void setUserFlags(uint16_t externalFlags)
Sets user flags, holding some meaningful data for the caller.
Definition Async.h:207
Result stop(AsyncEventLoop &eventLoop, Function< void(AsyncResult &)> *afterStopped=nullptr)
Ask to stop current async operation.
void executeOn(AsyncSequence &sequence)
Adds the request to be executed on a specific AsyncSequence.
Type
Type of async request.
Definition Async.h:158
Helper holding CompletionData for a specific AsyncRequest-derived class.
Definition Async.h:317
Base class for all async results (argument of completion callbacks).
Definition Async.h:287
const SC::Result & isValid() const
Check if the returnCode of this result is valid.
Definition Async.h:298
AsyncResult(AsyncEventLoop &eventLoop, AsyncRequest &request, SC::Result &res, bool *hasBeenReactivated=nullptr)
Constructs an async result from a request and a result.
Definition Async.h:289
void reactivateRequest(bool shouldBeReactivated)
Ask the event loop to re-activate this request after it was already completed.
Execute AsyncRequests serially, by submitting the next one after the previous one is completed.
Definition Async.h:263
Options for AsyncSignal request configuration.
Definition Async.h:468
Mode
Reserved signal watching policy.
Definition Async.h:474
@ Persistent
Default policy; future backend parity work may use it for automatic persistence.
@ OneShot
Future policy for explicit one-shot watchers.
Mode mode
Currently does not bypass the AsyncRequest reactivation contract.
Definition Async.h:478
bool coalesce
Backend hint; portable code should inspect CompletionData::deliveryCount.
Definition Async.h:479
Starts monitoring a signal, notifying about its reception.
Definition Async.h:502
Function< void(Result &)> callback
Called when the signal is raised.
Definition Async.h:520
SC::Result start(AsyncEventLoop &eventLoop, int num, AsyncSignalOptions options={})
Sets async request members and calls AsyncEventLoop::start.
Starts a socket accept operation, obtaining a new socket from a listening socket.
Definition Async.h:599
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &socketDescriptor)
Sets async request members and calls AsyncEventLoop::start.
Starts a socket connect operation, connecting to a remote endpoint.
Definition Async.h:619
Function< void(Result &)> callback
Called after socket is finally connected to endpoint.
Definition Async.h:629
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, SocketIPAddress address)
Sets async request members and calls AsyncEventLoop::start.
Starts an unconnected socket receive from operation, receiving bytes from a remote endpoint.
Definition Async.h:788
SC::Result get(Span< char > &outData)
Get a Span of the actually read data.
Definition Async.h:749
Starts a socket receive operation, receiving bytes from a remote endpoint.
Definition Async.h:731
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, Span< char > data)
Sets async request members and calls AsyncEventLoop::start.
SC::Result closeHandle()
The Socket Descriptor handle to read data from.
Definition Async.h:767
Span< char > buffer
The writeable span of memory where to data will be written.
Definition Async.h:764
Function< void(Result &)> callback
Called after data has been received.
Definition Async.h:762
Starts an unconnected socket send to operation, sending bytes to a remote endpoint.
Definition Async.h:699
Starts a socket send operation, sending bytes to a remote endpoint.
Definition Async.h:653
Function< void(Result &)> callback
Called when socket is ready to send more data.
Definition Async.h:668
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, Span< const char > data)
Sets async request members and calls AsyncEventLoop::start.
Span< Span< const char > > buffers
Spans of bytes to send (singleBuffer == false)
Definition Async.h:675
Span< const char > buffer
Span of bytes to send (singleBuffer == true)
Definition Async.h:674
SC::Result start(AsyncEventLoop &eventLoop, const SocketDescriptor &descriptor, Span< Span< const char > > data)
Sets async request members and calls AsyncEventLoop::start.
An AsyncSequence using a SC::ThreadPool to execute one or more SC::AsyncRequest in a background threa...
Definition Async.h:1216
Atomic variables (only for int and bool for now).
Definition Atomic.h:42
An automatically reset event object to synchronize two threads.
Definition Threading.h:243
[UniqueHandleDeclaration2Snippet]
Definition File.h:130
Options used to open a file descriptor.
Definition File.h:101
A structure to describe copy flags.
Definition FileSystem.h:76
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:302
Low-level OS socket handle.
Definition Socket.h:167
AddressFamily
Sets the address family of an IP Address (IPv4 or IPV6)
Definition Socket.h:74
Native representation of an IP Address.
Definition Socket.h:114
A small task containing a function to execute that can be queued in the thread pool.
Definition ThreadPool.h:16
Simple thread pool that executes tasks in a fixed number of worker threads.
Definition ThreadPool.h:38
A native OS thread.
Definition Threading.h:127