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"
20#include "AsyncError.h"
24SC_DECLARE_ASSERT_PROVIDER(AsyncAssert, SC_ASYNC_EXPORT);
26#define SC_ASYNC_ASSERT_RELEASE(e) SC_ASSERT_PROVIDER_RELEASE(SC::AsyncAssert, e)
27#define SC_ASYNC_ASSERT_DEBUG(e) SC_ASSERT_PROVIDER_DEBUG(SC::AsyncAssert, e)
28#define SC_ASYNC_TRUST_RESULT(expression) SC_ASYNC_ASSERT_RELEASE(expression)
67struct AsyncTaskSequence;
70enum class AsyncThreadPoolMode : uint8_t
78struct AsyncWinOverlapped;
79struct AsyncWinOverlappedDefinition
81 static constexpr int Windows =
sizeof(
void*) * 4 +
sizeof(uint64_t);
82 static constexpr size_t Alignment =
alignof(
void*);
84 using Object = AsyncWinOverlapped;
86using WinOverlappedOpaque = OpaqueObject<AsyncWinOverlappedDefinition>;
88struct AsyncWinWaitDefinition
90 using Handle = FileDescriptor::Handle;
91 static constexpr Handle Invalid = FileDescriptor::Invalid;
93 static Result releaseHandle(Handle& waitHandle);
95struct SC_ASYNC_EXPORT WinWaitHandle :
public UniqueHandle<AsyncWinWaitDefinition>
143 void setDebugName(
const char* newDebugName);
152 AsyncThreadPoolMode mode = AsyncThreadPoolMode::NativePreferred);
181 AsyncRequest(
Type type) : state(State::Free), type(type), flags(0), unused(0), userFlags(0) {}
208 void setUserFlags(uint16_t externalFlags) { userFlags = externalFlags; }
216 [[nodiscard]]
const Function<void(
AsyncResult&)>* getCloseCallback()
const {
return closeCallback; }
221 void queueSubmission(AsyncEventLoop& eventLoop);
223 AsyncSequence* sequence =
nullptr;
225 AsyncTaskSequence* getTask();
227 [[nodiscard]]
bool isThreadPoolForced()
const;
230 Function<void(AsyncResult&)>* closeCallback =
nullptr;
232 friend struct AsyncEventLoop;
233 friend struct AsyncResult;
237 [[nodiscard]]
static const char* TypeToString(Type type);
238 enum class State : uint8_t
248#if SC_ASYNC_ENABLE_LOG
249 const char* debugName =
"None";
268 bool clearSequenceOnCancel =
true;
269 bool clearSequenceOnError =
true;
272 bool runningAsync =
false;
273 bool tracked =
false;
277 IntrusiveDoubleLinkedList<AsyncRequest> submissions;
291 : eventLoop(eventLoop), async(request), hasBeenReactivated(hasBeenReactivated), returnCode(res)
299 [[nodiscard]]
const SC::Result&
isValid()
const {
return returnCode; }
307 bool shouldCallCallback =
true;
308 bool* hasBeenReactivated =
nullptr;
310 SC::Result& returnCode;
316template <
typename T,
typename C>
319 T& getAsync() {
return static_cast<T&
>(AsyncResult::async); }
320 const T& getAsync()
const {
return static_cast<const T&
>(AsyncResult::async); }
325 int32_t eventIndex = 0;
338 using AsyncRequest::start;
358 TimeMs expirationTime;
395 uint32_t deliveryCount = 1;
415 int32_t consumePendingWakeUps();
416 int32_t getPendingWakeUps()
const;
443 SC::Result get(
int& status)
445 status = completionData.exitStatus;
449 using AsyncRequest::start;
462 FileDescriptor::Handle handle = FileDescriptor::Invalid;
463#if SC_PLATFORM_WINDOWS
464 detail::WinOverlappedOpaque overlapped;
465 detail::WinWaitHandle waitHandle;
467#elif SC_PLATFORM_LINUX
513 int signalNumber = 0;
514 uint32_t deliveryCount = 1;
521 using AsyncRequest::start;
532 int signalNumber = 0;
534#if SC_PLATFORM_WINDOWS
535 detail::WinOverlappedOpaque overlapped;
537#elif SC_PLATFORM_LINUX
539 FileDescriptor::Handle signalFdHandle = FileDescriptor::Invalid;
548struct SC_ASYNC_EXPORT AsyncSocketAcceptData
550#if SC_PLATFORM_WINDOWS
551 void (*pAcceptEx)() =
nullptr;
552 detail::WinOverlappedOpaque overlapped;
554 uint8_t acceptBuffer[288] = {0};
555#elif SC_PLATFORM_LINUX
556 AlignedStorage<128> sockAddrHandle;
557 uint32_t sockAddrLen;
562struct SC_ASYNC_EXPORT AsyncSocketAcceptBase :
public AsyncRequest
564 AsyncSocketAcceptBase() : AsyncRequest(Type::SocketAccept) {}
566 struct CompletionData :
public AsyncCompletionData
568 SocketDescriptor acceptedClient;
571 struct Result :
public AsyncResultOf<AsyncSocketAccept, CompletionData>
573 using AsyncResultOf<AsyncSocketAccept, CompletionData>::AsyncResultOf;
575 SC::Result moveTo(SocketDescriptor& client)
578 return SC::Result(client.assign(move(completionData.acceptedClient)));
581 using AsyncRequest::start;
584 SC::Result start(AsyncEventLoop& eventLoop,
const SocketDescriptor& socketDescriptor, AsyncSocketAcceptData& data);
585 SC::Result validate(AsyncEventLoop&);
587 Function<void(Result&)> callback;
588 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
589 SocketFlags::AddressFamily addressFamily = SocketFlags::AddressFamilyIPV4;
590 AsyncSocketAcceptData* acceptData =
nullptr;
607 using AsyncSocketAcceptBase::start;
613 detail::AsyncSocketAcceptData data;
630 using AsyncRequest::start;
638 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
645#if SC_PLATFORM_WINDOWS
646 void (*pConnectEx)() =
nullptr;
647 detail::WinOverlappedOpaque overlapped;
667 using AsyncRequest::start;
677 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
679 SC::Result closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
683 bool singleBuffer =
true;
690 size_t totalBytesWritten = 0;
691#if SC_PLATFORM_WINDOWS
692 detail::WinOverlappedOpaque overlapped;
712 Span<const char> data);
715 Span<Span<const char>> data);
718 Span<const char> data);
721 Span<Span<const char>> data);
724 using AsyncSocketSend::start;
728 AlignedStorage<56> typeErasedMsgHdr;
750 bool disconnected =
false;
751 bool truncated =
false;
758 bool isEnded()
const {
return completionData.disconnected; }
760 bool isTruncated()
const {
return completionData.truncated; }
765 SC::Result
get(Span<char>& outData)
767 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, outData));
778 using AsyncRequest::start;
786 SocketDescriptor::Handle handle = SocketDescriptor::Invalid;
788 SC::Result
closeHandle() {
return detail::SocketDescriptorDefinition::releaseHandle(handle); }
792 friend struct AsyncEventLoop;
793 SC::Result validate(AsyncEventLoop&);
794#if SC_PLATFORM_WINDOWS
795 detail::WinOverlappedOpaque overlapped;
811 using AsyncSocketReceive::start;
818 AlignedStorage<56> typeErasedMsgHdr;
819#elif SC_PLATFORM_WINDOWS
820 unsigned long receiveFlags = 0;
822 bool truncatedSync =
false;
855 bool endOfFile =
false;
862 bool isEnded()
const {
return completionData.endOfFile; }
864 SC::Result get(Span<char>& data)
866 SC_TRY(getAsync().buffer.sliceStartLength(0, completionData.numBytes, data));
870 using AsyncRequest::start;
875 Function<void(
Result&)> callback;
880 SC::Result
closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
897 bool useOffset =
false;
898 bool endedSync =
false;
901#if SC_PLATFORM_WINDOWS
902 uint64_t readCursor = 0;
903 detail::WinOverlappedOpaque overlapped;
941 SC::Result get(
size_t& writtenSizeInBytes)
943 writtenSizeInBytes = completionData.numBytes;
948 using AsyncRequest::start;
967 SC::Result closeHandle() {
return detail::FileDescriptorDefinition::releaseHandle(handle); }
971 bool singleBuffer =
true;
988#if SC_PLATFORM_WINDOWS
989 bool endedSync =
false;
991 bool isWatchable =
false;
993 bool useOffset =
false;
994 uint64_t offset = 0xffffffffffffffff;
996 size_t totalBytesWritten = 0;
997#if SC_PLATFORM_WINDOWS
998 detail::WinOverlappedOpaque overlapped;
1015 Function<void(
Result&)> callback;
1021 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1031 size_t bytesTransferred = 0;
1040#if SC_PLATFORM_WINDOWS
1042 SC::Result start(
AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1045 [[nodiscard]]
void* getWindowsOverlapped();
1054 [[nodiscard]]
bool hasSubmissionPending()
const {
return submissionPending; }
1056 Function<void(Result&)> callback;
1062 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1063 size_t bytesTransferred = 0;
1064 bool manualMode =
true;
1065 bool submissionPending =
false;
1066 bool completionPosted =
false;
1067#if SC_PLATFORM_WINDOWS
1068 detail::WinOverlappedOpaque overlapped;
1102 size_t bytesTransferred = 0;
1103 bool usedZeroCopy =
false;
1114 [[nodiscard]]
bool usedZeroCopy()
const {
return completionData.usedZeroCopy; }
1119 return returnCode && completionData.bytesTransferred == getAsync().length;
1123 using AsyncRequest::start;
1135 int64_t offset = 0,
size_t length = 0,
size_t pipeSize = 0);
1140 FileDescriptor::Handle fileHandle = FileDescriptor::Invalid;
1141 SocketDescriptor::Handle socketHandle = SocketDescriptor::Invalid;
1145 size_t bytesSent = 0;
1150#if SC_PLATFORM_WINDOWS
1151 detail::WinOverlappedOpaque overlapped;
1152#elif SC_PLATFORM_LINUX
1153 size_t pipeBufferSize = 0;
1155 size_t spliceBytesPending = 0;
1165 FileDescriptor::Handle handle = FileDescriptor::Invalid;
1168 size_t numBytes = 0;
1174struct SC_ASYNC_EXPORT AsyncCompletionVariant
1176 AsyncCompletionVariant() {}
1177 ~AsyncCompletionVariant() { destroy(); }
1179 AsyncCompletionVariant(
const AsyncCompletionVariant&) =
delete;
1180 AsyncCompletionVariant(AsyncCompletionVariant&&) =
delete;
1181 AsyncCompletionVariant& operator=(
const AsyncCompletionVariant&) =
delete;
1182 AsyncCompletionVariant& operator=(AsyncCompletionVariant&&) =
delete;
1184 bool inited =
false;
1186 AsyncRequest::Type type;
1189 AsyncCompletionData completionDataLoopWork;
1190 AsyncLoopTimeout::CompletionData completionDataLoopTimeout;
1191 AsyncLoopWakeUp::CompletionData completionDataLoopWakeUp;
1192 AsyncProcessExit::CompletionData completionDataProcessExit;
1193 AsyncSignal::CompletionData completionDataSignal;
1194 AsyncSocketAccept::CompletionData completionDataSocketAccept;
1195 AsyncSocketConnect::CompletionData completionDataSocketConnect;
1196 AsyncSocketSend::CompletionData completionDataSocketSend;
1197 AsyncSocketSendTo::CompletionData completionDataSocketSendTo;
1198 AsyncSocketReceive::CompletionData completionDataSocketReceive;
1199 AsyncSocketReceiveFrom::CompletionData completionDataSocketReceiveFrom;
1200 AsyncFileRead::CompletionData completionDataFileRead;
1201 AsyncFileWrite::CompletionData completionDataFileWrite;
1202 AsyncFileSend::CompletionData completionDataFileSend;
1203 AsyncFileReadiness::CompletionData completionDataFileReadiness;
1204 AsyncExternalCompletion::CompletionData completionDataExternalCompletion;
1206 AsyncFileSystemOperationCompletionData completionDataFileSystemOperation;
1209 auto& getCompletion(AsyncLoopWork&) {
return completionDataLoopWork; }
1210 auto& getCompletion(AsyncLoopTimeout&) {
return completionDataLoopTimeout; }
1211 auto& getCompletion(AsyncLoopWakeUp&) {
return completionDataLoopWakeUp; }
1212 auto& getCompletion(AsyncProcessExit&) {
return completionDataProcessExit; }
1213 auto& getCompletion(AsyncSignal&) {
return completionDataSignal; }
1214 auto& getCompletion(AsyncSocketAccept&) {
return completionDataSocketAccept; }
1215 auto& getCompletion(AsyncSocketConnect&) {
return completionDataSocketConnect; }
1216 auto& getCompletion(AsyncSocketSend&) {
return completionDataSocketSend; }
1217 auto& getCompletion(AsyncSocketReceive&) {
return completionDataSocketReceive; }
1218 auto& getCompletion(AsyncFileRead&) {
return completionDataFileRead; }
1219 auto& getCompletion(AsyncFileWrite&) {
return completionDataFileWrite; }
1220 auto& getCompletion(AsyncFileSend&) {
return completionDataFileSend; }
1221 auto& getCompletion(AsyncFileReadiness&) {
return completionDataFileReadiness; }
1222 auto& getCompletion(AsyncExternalCompletion&) {
return completionDataExternalCompletion; }
1223 auto& getCompletion(AsyncFileSystemOperation&) {
return completionDataFileSystemOperation; }
1225 template <
typename T>
1226 auto& construct(T& t)
1229 placementNew(getCompletion(t));
1232 return getCompletion(t);
1250 detail::AsyncCompletionVariant completion;
1252 SC::Result returnCode = SC::Result(
true);
1271 Function<SC::Result()> work;
1320#ifdef RemoveDirectory
1321#undef RemoveDirectory
1323 enum class Operation
1367 SC::Result
read(
AsyncEventLoop& eventLoop, FileDescriptor::Handle handle, Span<char> buffer, uint64_t offset);
1418 Operation operation = Operation::None;
1419 AsyncThreadPoolMode threadPoolMode = AsyncThreadPoolMode::NativePreferred;
1425 struct FileDescriptorData
1427 FileDescriptor::Handle handle;
1438 FileDescriptor::Handle handle;
1445 FileDescriptor::Handle handle;
1446 Span<const char> buffer;
1453 StringSpan destinationPath;
1454 FileSystemCopyFlags copyFlags;
1457 using CopyDirectoryData = CopyFileData;
1459 using CloseData = FileDescriptorData;
1475 CloseData closeData;
1477 WriteData writeData;
1478 CopyFileData copyFileData;
1479 CopyDirectoryData copyDirectoryData;
1480 RenameData renameData;
1481 RemoveData removeData;
1486 SC::Result start(AsyncEventLoop& eventLoop, FileDescriptor::Handle fileDescriptor);
1487 SC::Result validate(AsyncEventLoop&);
1498 int numberOfEvents = 0;
1529 Options() { apiType = ApiType::Automatic; }
1735 static constexpr int Windows = 576;
1736 static constexpr int Apple = 552;
1737 static constexpr int Linux = 816;
1738 static constexpr int Default = Linux;
1740 static constexpr size_t Alignment = 8;
1742 using Object = Internal;
1745 using InternalOpaque = OpaqueObject<InternalDefinition>;
1748 InternalOpaque internalOpaque;
1789#pragma warning(push)
1790#pragma warning(disable : 4324)
1792 alignas(uint64_t) uint8_t eventsMemory[8 * 1024];
1808 bool wakeUpHasBeenCalled =
false;
1810 Result monitoringLoopThread(
Thread& thread);
Empty base struct for all AsyncRequest-derived CompletionData (internal) structs.
Definition Async.h:282
Allow library user to provide callbacks signaling different phases of async event loop cycle.
Definition Async.h:1505
Monitors Async I/O events from a background thread using a blocking kernel function (no CPU usage on ...
Definition Async.h:1763
Function< void(void)> onNewEventsAvailable
Informs to call dispatchCompletions on GUI Event Loop.
Definition Async.h:1764
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:1520
ApiType apiType
Criteria to choose Async IO API.
Definition Async.h:1527
ApiType
Definition Async.h:1522
Asynchronous I/O (files, sockets, timers, processes, fs events, threads wake-up) (see Async) AsyncEve...
Definition Async.h:1517
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.
Result createAsyncSocket(SocketFlags::AddressFamily family, SocketFlags::SocketType socketType, SocketFlags::ProtocolType protocol, SocketDescriptor &outDescriptor)
Creates a non-blocking socket registered with the event loop.
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:1028
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:849
FileDescriptor::Handle handle
The writeable span of memory where to data will be written.
Definition Async.h:877
Span< char > buffer
Callback called when some data has been read from the file into the buffer.
Definition Async.h:876
SC::Result closeHandle()
The file/pipe descriptor handle to read data from.
Definition Async.h:880
void setOffset(uint64_t fileOffset)
Sets the offset in bytes at which start reading.
Definition Async.h:887
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:883
Starts a file descriptor readiness operation.
Definition Async.h:1006
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:1111
bool usedZeroCopy() const
Check if zero-copy was used for this transfer.
Definition Async.h:1114
bool isComplete() const
Check if the entire requested range was sent.
Definition Async.h:1117
Sends file contents to a socket using zero-copy when available (sendfile, TransmitFile).
Definition Async.h:1097
Function< void(Result &)> callback
Called when send completes or fails.
Definition Async.h:1137
SC::Result start(AsyncEventLoop &eventLoop, const FileDescriptor &file, const SocketDescriptor &socket, int64_t offset=0, size_t length=0, size_t pipeSize=0)
Start file send.
Starts an asynchronous file system operation (open, close, read, write, sendFile, stat,...
Definition Async.h:1314
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:1346
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:929
uint64_t getOffset() const
Returns the last offset set with AsyncFileWrite::setOffset.
Definition Async.h:974
FileDescriptor::Handle handle
The file/pipe descriptor to write data to.
Definition Async.h:964
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:978
Function< void(Result &)> callback
Callback called when descriptor is ready to be written with more data.
Definition Async.h:962
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:970
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:969
Allows user to supply a block of memory that will store kernel I/O events retrieved from AsyncEventLo...
Definition Async.h:1494
Span< uint8_t > eventsMemory
User supplied block of memory used to store kernel I/O events.
Definition Async.h:1495
Starts a Timeout that is invoked only once after expiration (relative) time has passed.
Definition Async.h:333
TimeMs getExpirationTime() const
Gets computed absolute expiration time that determines when this timeout get executed.
Definition Async.h:353
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:350
Function< void(Result &)> callback
Called after given expiration time since AsyncLoopTimeout::start has passed.
Definition Async.h:348
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:363
bool coalesce
Merge repeated pending wakeUp() calls into a single callback (default true, matching libuv uv_async_t...
Definition Async.h:366
Starts a wake-up operation, allowing threads to execute callbacks on loop thread.
Definition Async.h:390
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:409
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:1261
Function< void(Result &)> callback
Called to execute the work in a background threadpool thread.
Definition Async.h:1272
SC::Result setThreadPool(ThreadPool &threadPool, AsyncThreadPoolMode mode=AsyncThreadPoolMode::NativePreferred)
Sets the ThreadPool that will supply the thread to run the async work on.
Waits for a child process to exit and reports its exit status.
Definition Async.h:431
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:456
Base class for all async requests, holding state and type.
Definition Async.h:139
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:181
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:211
Function< void(AsyncResult &)> * getCloseCallback()
Returns currently set close callback (if any) passed to AsyncRequest::stop.
Definition Async.h:214
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:202
void setUserFlags(uint16_t externalFlags)
Sets user flags, holding some meaningful data for the caller.
Definition Async.h:208
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:159
Helper holding CompletionData for a specific AsyncRequest-derived class.
Definition Async.h:318
Base class for all async results (argument of completion callbacks).
Definition Async.h:288
const SC::Result & isValid() const
Check if the returnCode of this result is valid.
Definition Async.h:299
AsyncResult(AsyncEventLoop &eventLoop, AsyncRequest &request, SC::Result &res, bool *hasBeenReactivated=nullptr)
Constructs an async result from a request and a result.
Definition Async.h:290
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:264
Options for AsyncSignal request configuration.
Definition Async.h:474
Mode
Reserved signal watching policy.
Definition Async.h:480
@ 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:484
bool coalesce
Backend hint; portable code should inspect CompletionData::deliveryCount.
Definition Async.h:485
Starts monitoring a signal, notifying about its reception.
Definition Async.h:508
Function< void(Result &)> callback
Called when the signal is raised.
Definition Async.h:526
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:605
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:625
Function< void(Result &)> callback
Called after socket is finally connected to endpoint.
Definition Async.h:636
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:809
SC::Result get(Span< char > &outData)
Get a Span of the actually read data.
Definition Async.h:765
SocketIPAddress getSourceAddress() const
Returns the source when it is an IPv4 or IPv6 address.
SocketAddress getSourceSocketAddress() const
Returns the family-neutral source address for receive-from operations.
Starts a socket receive operation, receiving bytes from a remote endpoint.
Definition Async.h:744
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:788
Span< char > buffer
The writeable span of memory where to data will be written.
Definition Async.h:785
Function< void(Result &)> callback
Called after data has been received.
Definition Async.h:783
Starts an unconnected socket send to operation, sending bytes to a remote endpoint.
Definition Async.h:706
Starts a socket send operation, sending bytes to a remote endpoint.
Definition Async.h:660
Function< void(Result &)> callback
Called when socket is ready to send more data.
Definition Async.h:675
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:682
Span< const char > buffer
Span of bytes to send (singleBuffer == true)
Definition Async.h:681
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:1242
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:77
Read / Write pipe (Process stdin/stdout and IPC communication)
Definition File.h:302
Family-neutral native socket address.
Definition Socket.h:168
Low-level OS socket handle.
Definition Socket.h:207
SocketType
Sets the socket type to datagram or stream.
Definition Socket.h:82
AddressFamily
Sets the socket address family.
Definition Socket.h:74
ProtocolType
Sets the socket protocol type.
Definition Socket.h:89
Native representation of an IP Address.
Definition Socket.h:117
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:45
A native OS thread.
Definition Threading.h:127