diff --git a/bridge/include/IFileSystemBridge.h b/bridge/include/IFileSystemBridge.h index 1ea90e55..ad417613 100644 --- a/bridge/include/IFileSystemBridge.h +++ b/bridge/include/IFileSystemBridge.h @@ -32,6 +32,18 @@ typedef int FileFindHandle_t; namespace SourceMod { +typedef void *AsyncControl_t; + +enum AsyncStatus +{ + AsyncStatus_FileOpenError = -1, + AsyncStatus_Ok = 0, + AsyncStatus_Pending, + AsyncStatus_InProgress, + AsyncStatus_Aborted, + AsyncStatus_Unserviced, +}; + class IFileSystemBridge { public: @@ -59,6 +71,14 @@ public: virtual void CreateDirHierarchy(const char *path, const char *pathID = 0) = 0; virtual int GetSearchPath(const char* pathID, bool bGetPackFiles, char* pPath, int nMaxLen) = 0; virtual const char * GetGameBinArchSubdirectory() = 0; + virtual bool SupportsAsync() = 0; + virtual int AsyncRead(const char *filename, const char *pathID, AsyncControl_t *control) = 0; + virtual int AsyncWrite(const char *filename, const void *data, int size, bool append, + AsyncControl_t *control) = 0; + virtual int AsyncStatus(AsyncControl_t control) = 0; + virtual int AsyncGetResult(AsyncControl_t control, void **data, int *size) = 0; + virtual void AsyncAbort(AsyncControl_t control) = 0; + virtual void AsyncRelease(AsyncControl_t control) = 0; }; } // namespace SourceMod diff --git a/core/logic/smn_filesystem.cpp b/core/logic/smn_filesystem.cpp index 30c8d6ab..9b5438b7 100644 --- a/core/logic/smn_filesystem.cpp +++ b/core/logic/smn_filesystem.cpp @@ -30,9 +30,20 @@ */ #include +#include +#include +#include +#include #include #include #include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -42,6 +53,7 @@ #include "common_logic.h" #include "Logger.h" #include "sprintf.h" +#include #include #include "handle_helpers.h" #include @@ -266,6 +278,798 @@ private: FILE *fp_; }; +enum FileAsyncResult +{ + FileAsync_Success = 0, + FileAsync_NotFound, + FileAsync_Error, +}; + +enum FileAsyncOperation +{ + FileAsync_Delete, + FileAsync_Rename, + FileAsync_Copy, + FileAsync_FileExists, + FileAsync_DirExists, + FileAsync_FileSize, + FileAsync_CreateDirectory, + FileAsync_RemoveDirectory, + FileAsync_Read, + FileAsync_Write, + FileAsync_OpenDirectory, +}; + +enum FileAsyncCallback +{ + FileAsync_ResultCallback, + FileAsync_ExistsCallback, + FileAsync_SizeCallback, + FileAsync_ReadCallback, + FileAsync_DirectoryCallback, +}; + +struct FileAsyncDirectoryEntry +{ + std::string name; + cell_t type; +}; + +class SnapshotDirectory final : public IDirectory +{ +public: + explicit SnapshotDirectory(std::vector entries) + : entries_(std::move(entries)), index_(0) + { + } + + bool MoreFiles() override + { + return index_ < entries_.size(); + } + + void NextEntry() override + { + if (MoreFiles()) + index_++; + } + + const char *GetEntryName() override + { + return MoreFiles() ? entries_[index_].name.c_str() : ""; + } + + bool IsEntryDirectory() override + { + return MoreFiles() && entries_[index_].type == 1; + } + + bool IsEntryFile() override + { + return MoreFiles() && entries_[index_].type == 2; + } + + bool IsEntryValid() override + { + return MoreFiles(); + } + +private: + std::vector entries_; + size_t index_; +}; + +class FileAsyncTask +{ +public: + FileAsyncTask(FileAsyncOperation operation, FileAsyncCallback callback, + IPluginFunction *function, IdentityToken_t *owner, const char *path, + const char *realpath, cell_t data, const char *other_realpath = nullptr, + cell_t mode = 0, std::vector contents = {}, bool append = false, + bool valve = false, const char *pathID = nullptr, const char *other_pathID = nullptr) + : operation_(operation), callback_(callback), function_(function), owner_(owner), + path_(path), realpath_(realpath), other_realpath_(other_realpath ? other_realpath : ""), + data_(data), mode_(mode), result_(FileAsync_Error), exists_(false), size_(-1), + contents_(std::move(contents)), append_(append), cancelled_(false), valve_(valve), + pathID_(pathID ? pathID : ""), other_pathID_(other_pathID ? other_pathID : "") + { + } + + void Run() + { + try + { + if (valve_) + { + RunValve(); + return; + } + + switch (operation_) + { + case FileAsync_Delete: + result_ = SystemFile::Delete(realpath_.c_str()) ? FileAsync_Success : ResultFromErrno(); + break; + case FileAsync_Rename: + result_ = Rename() ? FileAsync_Success : ResultFromErrno(); + break; + case FileAsync_Copy: + Copy(); + break; + case FileAsync_FileExists: + exists_ = IsRegularFile(realpath_.c_str()); + result_ = FileAsync_Success; + break; + case FileAsync_DirExists: + exists_ = IsDirectory(realpath_.c_str()); + result_ = FileAsync_Success; + break; + case FileAsync_FileSize: + FileSize(); + break; + case FileAsync_CreateDirectory: + result_ = CreateDirectory() ? FileAsync_Success : ResultFromErrno(); + break; + case FileAsync_RemoveDirectory: + result_ = rmdir(realpath_.c_str()) == 0 ? FileAsync_Success : ResultFromErrno(); + break; + case FileAsync_Read: + Read(); + break; + case FileAsync_Write: + Write(); + break; + case FileAsync_OpenDirectory: + OpenDirectory(); + break; + } + } + catch (...) + { + contents_.clear(); + result_ = FileAsync_Error; + } + } + + void Deliver() + { + if (cancelled_ || !function_->IsRunnable()) + return; + + switch (callback_) + { + case FileAsync_ResultCallback: + function_->PushCell(result_); + function_->PushString(path_.c_str()); + function_->PushCell(data_); + break; + case FileAsync_ExistsCallback: + function_->PushCell(exists_ ? 1 : 0); + function_->PushString(path_.c_str()); + function_->PushCell(data_); + break; + case FileAsync_SizeCallback: + function_->PushCell(result_); + function_->PushString(path_.c_str()); + function_->PushCell(size_); + function_->PushCell(data_); + break; + case FileAsync_ReadCallback: + DeliverRead(); + break; + case FileAsync_DirectoryCallback: + DeliverDirectory(); + break; + } + function_->Execute(nullptr); + } + + IdentityToken_t *owner() const + { + return owner_; + } + + void Cancel() + { + cancelled_ = true; + } + +private: + static FileAsyncResult ResultFromErrno() + { + return errno == ENOENT ? FileAsync_NotFound : FileAsync_Error; + } + + static bool IsRegularFile(const char *path) + { +#ifdef PLATFORM_WINDOWS + struct _stat s; + return _stat(path, &s) == 0 && (s.st_mode & S_IFREG); +#else + struct stat s; + return stat(path, &s) == 0 && S_ISREG(s.st_mode); +#endif + } + + static bool IsDirectory(const char *path) + { +#ifdef PLATFORM_WINDOWS + struct _stat s; + return _stat(path, &s) == 0 && (s.st_mode & S_IFDIR); +#else + struct stat s; + return stat(path, &s) == 0 && S_ISDIR(s.st_mode); +#endif + } + + bool Rename() + { +#ifdef PLATFORM_WINDOWS + return MoveFileExA(other_realpath_.c_str(), realpath_.c_str(), + MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0; +#else + return rename(other_realpath_.c_str(), realpath_.c_str()) == 0; +#endif + } + + void Copy() + { + std::error_code ec; + std::filesystem::copy_file(other_realpath_, realpath_, + std::filesystem::copy_options::overwrite_existing, ec); + if (!ec) + { + result_ = FileAsync_Success; + return; + } + result_ = ec == std::errc::no_such_file_or_directory + ? FileAsync_NotFound + : FileAsync_Error; + } + + void FileSize() + { +#ifdef PLATFORM_WINDOWS + struct _stat s; + if (_stat(realpath_.c_str(), &s) != 0) +#else + struct stat s; + if (stat(realpath_.c_str(), &s) != 0) +#endif + { + result_ = ResultFromErrno(); + return; + } + +#ifdef PLATFORM_WINDOWS + if (s.st_mode & S_IFREG) +#else + if (S_ISREG(s.st_mode)) +#endif + { + size_ = static_cast(s.st_size); + result_ = FileAsync_Success; + return; + } + result_ = FileAsync_Error; + } + + void RunValve() + { + switch (operation_) + { + case FileAsync_Delete: + if (!bridge->filesystem->FileExists(realpath_.c_str(), pathID_.c_str())) + result_ = FileAsync_NotFound; + else + { + bridge->filesystem->RemoveFile(realpath_.c_str(), pathID_.c_str()); + result_ = bridge->filesystem->FileExists(realpath_.c_str(), pathID_.c_str()) + ? FileAsync_Error : FileAsync_Success; + } + break; + case FileAsync_Rename: + if (!bridge->filesystem->FileExists(other_realpath_.c_str(), pathID_.c_str())) + { + result_ = FileAsync_NotFound; + break; + } + bridge->filesystem->RenameFile(other_realpath_.c_str(), realpath_.c_str(), pathID_.c_str()); + result_ = !bridge->filesystem->FileExists(other_realpath_.c_str(), pathID_.c_str()) + && bridge->filesystem->FileExists(realpath_.c_str(), pathID_.c_str()) + ? FileAsync_Success : FileAsync_Error; + break; + case FileAsync_Copy: + CopyValve(); + break; + case FileAsync_FileExists: + exists_ = bridge->filesystem->FileExists(realpath_.c_str(), pathID_.c_str()); + result_ = FileAsync_Success; + break; + case FileAsync_DirExists: + exists_ = bridge->filesystem->IsDirectory(realpath_.c_str(), pathID_.c_str()); + result_ = FileAsync_Success; + break; + case FileAsync_FileSize: + if (!bridge->filesystem->FileExists(realpath_.c_str(), pathID_.c_str())) + result_ = FileAsync_NotFound; + else + { + size_ = static_cast(bridge->filesystem->Size(realpath_.c_str(), pathID_.c_str())); + result_ = FileAsync_Success; + } + break; + case FileAsync_CreateDirectory: + if (bridge->filesystem->IsDirectory(realpath_.c_str(), pathID_.c_str())) + result_ = FileAsync_Error; + else + { + bridge->filesystem->CreateDirHierarchy(realpath_.c_str(), pathID_.c_str()); + result_ = bridge->filesystem->IsDirectory(realpath_.c_str(), pathID_.c_str()) + ? FileAsync_Success : FileAsync_Error; + } + break; + default: + result_ = FileAsync_Error; + break; + } + } + + void CopyValve() + { + if (!bridge->filesystem->FileExists(other_realpath_.c_str(), other_pathID_.c_str())) + { + result_ = FileAsync_NotFound; + return; + } + + FileHandle_t source = bridge->filesystem->Open(other_realpath_.c_str(), "rb", other_pathID_.c_str()); + if (!source) + { + result_ = FileAsync_Error; + return; + } + FileHandle_t destination = bridge->filesystem->Open(realpath_.c_str(), "wb", pathID_.c_str()); + if (!destination) + { + bridge->filesystem->Close(source); + result_ = FileAsync_Error; + return; + } + + char buffer[8192]; + bool success = true; + while (!bridge->filesystem->EndOfFile(source)) + { + int read = bridge->filesystem->Read(buffer, sizeof(buffer), source); + if (read < 0 || (read == 0 && !bridge->filesystem->EndOfFile(source)) || + (read && bridge->filesystem->Write(buffer, read, destination) != read)) + { + success = false; + break; + } + } + success = success && bridge->filesystem->IsOk(source) && bridge->filesystem->IsOk(destination); + bridge->filesystem->Close(destination); + bridge->filesystem->Close(source); + result_ = success ? FileAsync_Success : FileAsync_Error; + } + + bool CreateDirectory() + { +#ifdef PLATFORM_WINDOWS + return mkdir(realpath_.c_str()) == 0; +#else + return mkdir(realpath_.c_str(), mode_) == 0; +#endif + } + + void Read() + { + std::error_code ec; + auto size = std::filesystem::file_size(realpath_, ec); + if (ec) + { + result_ = ec == std::errc::no_such_file_or_directory + ? FileAsync_NotFound + : FileAsync_Error; + return; + } + if (size > static_cast((std::numeric_limits::max)())) + { + result_ = FileAsync_Error; + return; + } + + contents_.resize(static_cast(size)); + FILE *file = fopen(realpath_.c_str(), "rb"); + if (!file) + { + contents_.clear(); + result_ = ResultFromErrno(); + return; + } + + size_t read = contents_.empty() ? 0 : fread(contents_.data(), 1, contents_.size(), file); + bool success = read == contents_.size() && !ferror(file); + if (fclose(file) != 0) + success = false; + if (!success) + { + contents_.clear(); + result_ = FileAsync_Error; + return; + } + result_ = FileAsync_Success; + } + + void Write() + { + FILE *file = fopen(realpath_.c_str(), append_ ? "ab" : "wb"); + if (!file) + { + result_ = ResultFromErrno(); + return; + } + + size_t written = contents_.empty() ? 0 : fwrite(contents_.data(), 1, contents_.size(), file); + bool success = written == contents_.size() && !ferror(file); + if (fclose(file) != 0) + success = false; + result_ = success ? FileAsync_Success : FileAsync_Error; + } + + void OpenDirectory() + { + IDirectory *directory = libsys->OpenDirectory(realpath_.c_str()); + if (!directory) + { + result_ = IsDirectory(realpath_.c_str()) ? FileAsync_Error : FileAsync_NotFound; + return; + } + + while (directory->MoreFiles()) + { + FileAsyncDirectoryEntry entry; + entry.name = directory->GetEntryName(); + entry.type = directory->IsEntryDirectory() ? 1 : (directory->IsEntryFile() ? 2 : 0); + entries_.push_back(std::move(entry)); + directory->NextEntry(); + } + libsys->CloseDirectory(directory); + result_ = FileAsync_Success; + } + + void DeliverRead() + { + char empty = '\0'; + size_t buffer_size = contents_.empty() ? 1 : contents_.size(); + function_->PushCell(result_); + function_->PushString(path_.c_str()); + function_->PushStringEx(contents_.empty() ? &empty : reinterpret_cast(contents_.data()), + buffer_size, SM_PARAM_STRING_BINARY | SM_PARAM_STRING_COPY, 0); + function_->PushCell(result_ == FileAsync_Success ? static_cast(contents_.size()) : 0); + function_->PushCell(data_); + } + + void DeliverDirectory() + { + Handle_t handle = 0; + if (result_ == FileAsync_Success) + { + SnapshotDirectory *directory = new SnapshotDirectory(std::move(entries_)); + handle = handlesys->CreateHandle(g_DirType, directory, owner_, g_pCoreIdent, nullptr); + if (!handle) + { + delete directory; + result_ = FileAsync_Error; + } + } + function_->PushCell(result_); + function_->PushString(path_.c_str()); + function_->PushCell(handle); + function_->PushCell(data_); + } + +private: + FileAsyncOperation operation_; + FileAsyncCallback callback_; + IPluginFunction *function_; + IdentityToken_t *owner_; + std::string path_; + std::string realpath_; + std::string other_realpath_; + cell_t data_; + cell_t mode_; + FileAsyncResult result_; + bool exists_; + cell_t size_; + std::vector contents_; + std::vector entries_; + bool append_; + bool cancelled_; + bool valve_; + std::string pathID_; + std::string other_pathID_; +}; + +class FileAsyncWorker +{ +public: + void Start() + { + thread_ = ke::NewThread("SM File Async", [this] { ThreadMain(); }); + } + + void Shutdown() + { + { + std::lock_guard lock(mutex_); + stopping_ = true; + for (FileAsyncTask *task : tasks_) + task->Cancel(); + } + condition_.notify_one(); + if (thread_) + { + thread_->join(); + thread_.reset(); + } + + std::lock_guard lock(mutex_); + for (FileAsyncTask *task : tasks_) + delete task; + tasks_.clear(); + pending_.clear(); + completed_.clear(); + } + + bool Enqueue(FileAsyncTask *task) + { + std::lock_guard lock(mutex_); + if (stopping_) + return false; + tasks_.insert(task); + pending_.push_back(task); + condition_.notify_one(); + return true; + } + + void ProcessCompleted() + { + std::deque completed; + { + std::lock_guard lock(mutex_); + completed.swap(completed_); + for (FileAsyncTask *task : completed) + tasks_.erase(task); + } + + for (FileAsyncTask *task : completed) + { + task->Deliver(); + delete task; + } + } + + void CancelPlugin(IdentityToken_t *owner) + { + std::lock_guard lock(mutex_); + for (FileAsyncTask *task : tasks_) + { + if (task->owner() == owner) + task->Cancel(); + } + } + +private: + void ThreadMain() + { + for (;;) + { + FileAsyncTask *task; + { + std::unique_lock lock(mutex_); + condition_.wait(lock, [this] { return stopping_ || !pending_.empty(); }); + if (stopping_) + return; + task = pending_.front(); + pending_.pop_front(); + } + + task->Run(); + + std::lock_guard lock(mutex_); + completed_.push_back(task); + } + } + +private: + std::mutex mutex_; + std::condition_variable condition_; + std::unique_ptr thread_; + std::deque pending_; + std::deque completed_; + std::unordered_set tasks_; + bool stopping_ = false; +}; + +class ValveFileAsyncTask +{ +public: + ValveFileAsyncTask(FileAsyncOperation operation, IPluginFunction *function, + IdentityToken_t *owner, const char *path, cell_t data, std::vector contents = {}) + : operation_(operation), function_(function), owner_(owner), path_(path), data_(data), + result_(FileAsync_Error), contents_(std::move(contents)), control_(nullptr) + { + } + + bool Start(const char *pathID, bool append = false) + { + int status; + if (operation_ == FileAsync_Read) + status = bridge->filesystem->AsyncRead(path_.c_str(), pathID, &control_); + else + status = bridge->filesystem->AsyncWrite(path_.c_str(), contents_.data(), + static_cast(contents_.size()), append, &control_); + + return status >= SourceMod::AsyncStatus_Ok && control_ != nullptr; + } + + bool Process() + { + int status = bridge->filesystem->AsyncStatus(control_); + if (status > SourceMod::AsyncStatus_Ok) + return false; + + if (status == SourceMod::AsyncStatus_Ok && operation_ == FileAsync_Read) + { + void *data = nullptr; + int size = 0; + status = bridge->filesystem->AsyncGetResult(control_, &data, &size); + if (status == SourceMod::AsyncStatus_Ok && size >= 0 && (size == 0 || data != nullptr)) + { + contents_.resize(size); + if (size) + memcpy(contents_.data(), data, size); + } + } + + if (status == SourceMod::AsyncStatus_Ok) + result_ = FileAsync_Success; + else if (status == SourceMod::AsyncStatus_FileOpenError) + result_ = FileAsync_NotFound; + else + result_ = FileAsync_Error; + + bridge->filesystem->AsyncRelease(control_); + control_ = nullptr; + Deliver(); + return true; + } + + void Cancel() + { + if (control_) + { + bridge->filesystem->AsyncAbort(control_); + bridge->filesystem->AsyncRelease(control_); + control_ = nullptr; + } + } + + IdentityToken_t *owner() const + { + return owner_; + } + +private: + void Deliver() + { + if (!function_->IsRunnable()) + return; + + if (operation_ == FileAsync_Read) + { + char empty = '\0'; + size_t buffer_size = contents_.empty() ? 1 : contents_.size(); + function_->PushCell(result_); + function_->PushString(path_.c_str()); + function_->PushStringEx(contents_.empty() ? &empty : reinterpret_cast(contents_.data()), + buffer_size, SM_PARAM_STRING_BINARY | SM_PARAM_STRING_COPY, 0); + function_->PushCell(result_ == FileAsync_Success ? static_cast(contents_.size()) : 0); + function_->PushCell(data_); + } + else + { + function_->PushCell(result_); + function_->PushString(path_.c_str()); + function_->PushCell(data_); + } + function_->Execute(nullptr); + } + +private: + FileAsyncOperation operation_; + IPluginFunction *function_; + IdentityToken_t *owner_; + std::string path_; + cell_t data_; + FileAsyncResult result_; + std::vector contents_; + SourceMod::AsyncControl_t control_; +}; + +class ValveFileAsyncQueue +{ +public: + ~ValveFileAsyncQueue() + { + Shutdown(); + } + + bool Enqueue(ValveFileAsyncTask *task, const char *pathID, bool append = false) + { + if (!bridge->filesystem->SupportsAsync() || !task->Start(pathID, append)) + return false; + tasks_.push_back(task); + return true; + } + + void Process() + { + for (auto iter = tasks_.begin(); iter != tasks_.end();) + { + ValveFileAsyncTask *task = *iter; + if (!task->Process()) + { + ++iter; + continue; + } + delete task; + iter = tasks_.erase(iter); + } + } + + void CancelPlugin(IdentityToken_t *owner) + { + for (auto iter = tasks_.begin(); iter != tasks_.end();) + { + ValveFileAsyncTask *task = *iter; + if (task->owner() != owner) + { + ++iter; + continue; + } + task->Cancel(); + delete task; + iter = tasks_.erase(iter); + } + } + + void Shutdown() + { + for (ValveFileAsyncTask *task : tasks_) + { + task->Cancel(); + delete task; + } + tasks_.clear(); + } + +private: + std::vector tasks_; +}; + +static FileAsyncWorker *g_FileAsyncWorker = nullptr; +static ValveFileAsyncQueue *g_ValveFileAsyncQueue = nullptr; + +static void FileAsyncFrame(bool) +{ + g_FileAsyncWorker->ProcessCompleted(); + g_ValveFileAsyncQueue->Process(); +} + struct ValveDirectory { FileFindHandle_t hndl = -1; @@ -289,9 +1093,18 @@ public: g_ValveDirType = handlesys->CreateType("ValveDirectory", this, 0, NULL, NULL, g_pCoreIdent, NULL); g_pLogHook = forwardsys->CreateForwardEx(NULL, ET_Hook, 1, NULL, Param_String); pluginsys->AddPluginsListener(this); + g_FileAsyncWorker = &m_AsyncWorker; + g_ValveFileAsyncQueue = &m_ValveAsyncQueue; + m_AsyncWorker.Start(); + g_pSM->AddGameFrameHook(&FileAsyncFrame); } virtual void OnSourceModShutdown() { + g_pSM->RemoveGameFrameHook(&FileAsyncFrame); + m_ValveAsyncQueue.Shutdown(); + m_AsyncWorker.Shutdown(); + g_FileAsyncWorker = nullptr; + g_ValveFileAsyncQueue = nullptr; pluginsys->RemovePluginsListener(this); forwardsys->ReleaseForward(g_pLogHook); handlesys->RemoveType(g_DirType, g_pCoreIdent); @@ -339,6 +1152,23 @@ public: g_pLogHook->Execute(&result); return result >= Pl_Handled; } + virtual void OnPluginWillUnload(IPlugin *plugin) + { + m_AsyncWorker.CancelPlugin(plugin->GetIdentity()); + m_ValveAsyncQueue.CancelPlugin(plugin->GetIdentity()); + } + bool EnqueueAsyncTask(FileAsyncTask *task) + { + return m_AsyncWorker.Enqueue(task); + } + bool EnqueueValveAsyncTask(ValveFileAsyncTask *task, const char *pathID, bool append = false) + { + return m_ValveAsyncQueue.Enqueue(task, pathID, append); + } + +private: + FileAsyncWorker m_AsyncWorker; + ValveFileAsyncQueue m_ValveAsyncQueue; } s_FileNatives; bool OnLogPrint(const char *msg) @@ -562,6 +1392,302 @@ static cell_t sm_DeleteFile(IPluginContext *pContext, const cell_t *params) } } +static cell_t QueueFileAsyncTask(IPluginContext *pContext, FileAsyncTask *task) +{ + if (s_FileNatives.EnqueueAsyncTask(task)) + return 0; + + delete task; + return pContext->ThrowNativeError("Async file worker is shutting down"); +} + +static cell_t QueueValveWorkerFileAsyncTask(IPluginContext *pContext, FileAsyncTask *task) +{ + if (!bridge->filesystem->SupportsAsync()) + { + delete task; + return pContext->ThrowNativeError("Valve filesystem async operations are unavailable on this engine"); + } + return QueueFileAsyncTask(pContext, task); +} + +static cell_t QueueValveFileAsyncTask(IPluginContext *pContext, ValveFileAsyncTask *task, + const char *pathID, bool append = false) +{ + if (s_FileNatives.EnqueueValveAsyncTask(task, pathID, append)) + return 0; + + delete task; + return pContext->ThrowNativeError("Valve filesystem async operations are unavailable on this engine"); +} + +static IPluginFunction *GetFileAsyncCallback(IPluginContext *pContext, cell_t function) +{ + IPluginFunction *callback = pContext->GetFunctionById(function); + if (!callback) + pContext->ThrowNativeError("Invalid function id (%X)", function); + return callback; +} + +static cell_t sm_DeleteFileAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (params[0] >= 4 && params[4]) + { + char *pathID; + pContext->LocalToString(params[5], &pathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Delete, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), path, path, params[3], + nullptr, 0, {}, false, true, pathID)); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Delete, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + +static cell_t sm_RenameFileAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[3]); + if (!callback) + return 0; + + char *newpath, *oldpath; + pContext->LocalToString(params[1], &newpath); + pContext->LocalToString(params[2], &oldpath); + if (params[0] >= 5 && params[5]) + { + char *pathID; + pContext->LocalToString(params[6], &pathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Rename, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), newpath, newpath, params[4], + oldpath, 0, {}, false, true, pathID)); + } + + char new_realpath[PLATFORM_MAX_PATH], old_realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, new_realpath, sizeof(new_realpath), "%s", newpath); + g_pSM->BuildPath(Path_Game, old_realpath, sizeof(old_realpath), "%s", oldpath); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Rename, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), newpath, new_realpath, + params[4], old_realpath)); +} + +static cell_t sm_CopyFileAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[3]); + if (!callback) + return 0; + + char *newpath, *oldpath; + pContext->LocalToString(params[1], &newpath); + pContext->LocalToString(params[2], &oldpath); + if (params[0] >= 5 && params[5]) + { + char *sourcePathID, *destinationPathID; + pContext->LocalToString(params[6], &sourcePathID); + pContext->LocalToString(params[7], &destinationPathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Copy, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), newpath, newpath, params[4], + oldpath, 0, {}, false, true, destinationPathID, sourcePathID)); + } + + char new_realpath[PLATFORM_MAX_PATH], old_realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, new_realpath, sizeof(new_realpath), "%s", newpath); + g_pSM->BuildPath(Path_Game, old_realpath, sizeof(old_realpath), "%s", oldpath); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Copy, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), newpath, new_realpath, + params[4], old_realpath)); +} + +static cell_t sm_FileExistsAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (params[0] >= 4 && params[4]) + { + char *pathID; + pContext->LocalToString(params[5], &pathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_FileExists, + FileAsync_ExistsCallback, callback, pContext->GetIdentity(), path, path, params[3], + nullptr, 0, {}, false, true, pathID)); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_FileExists, + FileAsync_ExistsCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + +static cell_t sm_DirExistsAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (!path[0]) + return pContext->ThrowNativeError("Invalid path. An empty path string is not valid, use \".\" to refer to the current working directory."); + if (params[0] >= 4 && params[4]) + { + char *pathID; + pContext->LocalToString(params[5], &pathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_DirExists, + FileAsync_ExistsCallback, callback, pContext->GetIdentity(), path, path, params[3], + nullptr, 0, {}, false, true, pathID)); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_DirExists, + FileAsync_ExistsCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + +static cell_t sm_FileSizeAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (params[0] >= 4 && params[4]) + { + char *pathID; + pContext->LocalToString(params[5], &pathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_FileSize, + FileAsync_SizeCallback, callback, pContext->GetIdentity(), path, path, params[3], + nullptr, 0, {}, false, true, pathID)); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_FileSize, + FileAsync_SizeCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + +static cell_t sm_ReadFileAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (params[0] >= 4 && params[4]) + { + char *pathID; + pContext->LocalToString(params[5], &pathID); + return QueueValveFileAsyncTask(pContext, new ValveFileAsyncTask(FileAsync_Read, + callback, pContext->GetIdentity(), path, params[3]), pathID); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Read, + FileAsync_ReadCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + +static cell_t sm_WriteFileAsync(IPluginContext *pContext, const cell_t *params) +{ + if (params[3] < 0) + return pContext->ThrowNativeError("Invalid size %d", params[3]); + + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[4]); + if (!callback) + return 0; + + cell_t *buffer; + pContext->LocalToPhysAddr(params[2], &buffer); + std::vector contents(params[3]); + if (!contents.empty()) + memcpy(contents.data(), buffer, contents.size()); + + char *path; + pContext->LocalToString(params[1], &path); + if (params[0] >= 7 && params[7]) + { + char *pathID; + pContext->LocalToString(params[8], &pathID); + if (strcmp(pathID, "DEFAULT_WRITE_PATH") != 0) + return pContext->ThrowNativeError("Valve async writes only support DEFAULT_WRITE_PATH"); + return QueueValveFileAsyncTask(pContext, new ValveFileAsyncTask(FileAsync_Write, + callback, pContext->GetIdentity(), path, params[5], std::move(contents)), pathID, + params[6] != 0); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_Write, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), path, realpath, + params[5], nullptr, 0, std::move(contents), params[6] != 0)); +} + +static cell_t sm_CreateDirectoryAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[3]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (params[0] >= 5 && params[5]) + { + char *pathID; + pContext->LocalToString(params[6], &pathID); + return QueueValveWorkerFileAsyncTask(pContext, new FileAsyncTask(FileAsync_CreateDirectory, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), path, path, params[4], + nullptr, params[2], {}, false, true, pathID)); + } + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_CreateDirectory, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), path, realpath, + params[4], nullptr, params[2])); +} + +static cell_t sm_OpenDirectoryAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + if (!path[0]) + return pContext->ThrowNativeError("Invalid path. An empty path string is not valid, use \".\" to refer to the current working directory."); + + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_OpenDirectory, + FileAsync_DirectoryCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + +static cell_t sm_RemoveDirectoryAsync(IPluginContext *pContext, const cell_t *params) +{ + IPluginFunction *callback = GetFileAsyncCallback(pContext, params[2]); + if (!callback) + return 0; + + char *path; + pContext->LocalToString(params[1], &path); + char realpath[PLATFORM_MAX_PATH]; + g_pSM->BuildPath(Path_Game, realpath, sizeof(realpath), "%s", path); + return QueueFileAsyncTask(pContext, new FileAsyncTask(FileAsync_RemoveDirectory, + FileAsync_ResultCallback, callback, pContext->GetIdentity(), path, realpath, params[3])); +} + static cell_t sm_ReadFileLine(IPluginContext *pContext, const cell_t *params) { char *buf; @@ -1313,19 +2439,28 @@ static cell_t File_WriteTyped(IPluginContext *pContext, const cell_t *params) REGISTER_NATIVES(filesystem) { {"OpenDirectory", sm_OpenDirectory}, + {"OpenDirectoryAsync", sm_OpenDirectoryAsync}, {"ReadDirEntry", sm_ReadDirEntry}, {"OpenFile", sm_OpenFile}, {"DeleteFile", sm_DeleteFile}, + {"DeleteFileAsync", sm_DeleteFileAsync}, + {"ReadFileAsync", sm_ReadFileAsync}, + {"WriteFileAsync", sm_WriteFileAsync}, {"ReadFileLine", sm_ReadFileLine}, {"IsEndOfFile", sm_IsEndOfFile}, {"FileSeek", sm_FileSeek}, {"FilePosition", sm_FilePosition}, {"FileExists", sm_FileExists}, {"RenameFile", sm_RenameFile}, + {"RenameFileAsync", sm_RenameFileAsync}, {"CopyFile", sm_CopyFile}, + {"CopyFileAsync", sm_CopyFileAsync}, {"DirExists", sm_DirExists}, + {"DirExistsAsync", sm_DirExistsAsync}, {"FileSize", sm_FileSize}, + {"FileSizeAsync", sm_FileSizeAsync}, {"RemoveDir", sm_RemoveDir}, + {"RemoveDirectoryAsync", sm_RemoveDirectoryAsync}, {"WriteFileLine", sm_WriteFileLine}, {"BuildPath", sm_BuildPath}, {"LogToGame", sm_LogToGame}, @@ -1342,6 +2477,8 @@ REGISTER_NATIVES(filesystem) {"AddGameLogHook", sm_AddGameLogHook}, {"RemoveGameLogHook", sm_RemoveGameLogHook}, {"CreateDirectory", sm_CreateDirectory}, + {"CreateDirectoryAsync", sm_CreateDirectoryAsync}, + {"FileExistsAsync", sm_FileExistsAsync}, {"SetFilePermissions", sm_SetFilePermissions}, {"GetFilePermissions", sm_GetFilePermissions}, diff --git a/core/logic_bridge.cpp b/core/logic_bridge.cpp index feeabf0d..4c86d592 100644 --- a/core/logic_bridge.cpp +++ b/core/logic_bridge.cpp @@ -46,8 +46,11 @@ #include "IDBDriver.h" #include "provider.h" #include "sm_convar.h" -#include -#include +#include +#include +#include +#include +#include #include #include #include @@ -194,7 +197,7 @@ public: { return filesystem->GetSearchPath(pathID, bGetPackFiles, pPath, nMaxLen); } - const char* GetGameBinArchSubdirectory() override + const char* GetGameBinArchSubdirectory() override { #if defined( KE_ARCH_X64 ) && SOURCE_ENGINE >= SE_BLADE #if defined( PLATFORM_WINDOWS ) @@ -212,8 +215,111 @@ public: // Already included in the GameBin path(s), if required return ""; #endif // defined( KE_ARCH_X64 ) && SOURCE_ENGINE >= SE_BLADE - } -} fs_wrapper; + } + bool SupportsAsync() override + { +#if SOURCE_ENGINE == SE_MOCK + return false; +#else + return true; +#endif + } + int AsyncRead(const char *filename, const char *pathID, SourceMod::AsyncControl_t *control) override + { +#if SOURCE_ENGINE == SE_MOCK + return SourceMod::AsyncStatus_FileOpenError; +#else + auto request = std::make_unique(); + request->request.pszFilename = filename; + request->request.pszPathID = pathID; + request->request.pfnCallback = AsyncReadCallback; + request->request.pContext = request.get(); + FSAsyncControl_t native_control = nullptr; + int status = filesystem->AsyncReadMultiple(&request->request, 1, &native_control); + if (status >= SourceMod::AsyncStatus_Ok && native_control) + async_requests_.emplace(native_control, std::move(request)); + *control = native_control; + return status; +#endif + } + int AsyncWrite(const char *filename, const void *data, int size, bool append, + SourceMod::AsyncControl_t *control) override + { +#if SOURCE_ENGINE == SE_MOCK || SOURCE_ENGINE == SE_DARKMESSIAH + return SourceMod::AsyncStatus_FileOpenError; +#else + return filesystem->AsyncWrite(filename, data, size, false, append, + reinterpret_cast(control)); +#endif + } + int AsyncStatus(SourceMod::AsyncControl_t control) override + { +#if SOURCE_ENGINE == SE_MOCK + return SourceMod::AsyncStatus_FileOpenError; +#else + return filesystem->AsyncStatus(reinterpret_cast(control)); +#endif + } + int AsyncGetResult(SourceMod::AsyncControl_t control, void **data, int *size) override + { +#if SOURCE_ENGINE == SE_MOCK + return SourceMod::AsyncStatus_FileOpenError; +#else + FSAsyncControl_t native_control = reinterpret_cast(control); + void *engine_data; + int engine_size; + int status = filesystem->AsyncGetResult(native_control, &engine_data, &engine_size); + if (status != SourceMod::AsyncStatus_Ok) + return status; + + auto iter = async_requests_.find(native_control); + if (iter == async_requests_.end()) + return SourceMod::AsyncStatus_FileOpenError; + + if (data) + *data = iter->second->contents.empty() ? nullptr : iter->second->contents.data(); + if (size) + *size = static_cast(iter->second->contents.size()); + return status; +#endif + } + void AsyncAbort(SourceMod::AsyncControl_t control) override + { +#if SOURCE_ENGINE != SE_MOCK + filesystem->AsyncAbort(reinterpret_cast(control)); +#endif + } + void AsyncRelease(SourceMod::AsyncControl_t control) override + { +#if SOURCE_ENGINE != SE_MOCK + FSAsyncControl_t native_control = reinterpret_cast(control); + filesystem->AsyncRelease(native_control); + async_requests_.erase(native_control); +#endif + } + +private: +#if SOURCE_ENGINE != SE_MOCK + struct AsyncReadRequest + { + FileAsyncRequest_t request; + std::vector contents; + }; + + static void AsyncReadCallback(const FileAsyncRequest_t &request, int bytes, FSAsyncStatus_t status) + { + auto *async_request = static_cast(request.pContext); + if (status != FSASYNC_OK || bytes < 0 || (bytes && !request.pData)) + return; + + async_request->contents.resize(bytes); + if (bytes) + memcpy(async_request->contents.data(), request.pData, bytes); + } + + std::unordered_map> async_requests_; +#endif +} fs_wrapper; class VPlayerInfo_Logic : public IPlayerInfoBridge { diff --git a/plugins/include/files.inc b/plugins/include/files.inc index ec88d76a..b821d7df 100644 --- a/plugins/include/files.inc +++ b/plugins/include/files.inc @@ -610,6 +610,233 @@ native bool RemoveDir(const char[] path); */ native bool CreateDirectory(const char[] path, int mode=FPERM_O_READ|FPERM_O_EXEC|FPERM_G_READ|FPERM_G_EXEC|FPERM_U_READ|FPERM_U_WRITE|FPERM_U_EXEC, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH"); +/** + * Results reported by asynchronous filesystem operations. + */ +enum FileOpResult +{ + FileOp_Success = 0, + FileOp_NotFound, + FileOp_Error, +}; + +/** + * Called when an asynchronous filesystem operation completes. + * + * @param result Operation result. + * @param path Path supplied to the operation. + * @param data User data supplied to the operation. + */ +typedef FileOpCallback = function void(FileOpResult result, const char[] path, any data); + +/** + * Called when an asynchronous existence check completes. + * + * @param exists Whether the requested entry exists and has the requested type. + * @param path Path supplied to the operation. + * @param data User data supplied to the operation. + */ +typedef FileExistsCallback = function void(bool exists, const char[] path, any data); + +/** + * Called when an asynchronous file-size query completes. + * + * @param result Operation result. + * @param path Path supplied to the operation. + * @param size File size in bytes, or -1 on failure. + * @param data User data supplied to the operation. + */ +typedef FileSizeCallback = function void(FileOpResult result, const char[] path, int size, any data); + +/** + * Called when an asynchronous whole-file read completes. + * + * contents contains the raw file bytes. It is binary-safe, including embedded + * NUL bytes, and its length is given by size. Do not use string-focused natives + * on it unless the data is known to be a string. + * + * @param result Operation result. + * @param path Path supplied to the operation. + * @param contents Raw-byte buffer. + * @param size Number of file bytes in contents. + * @param data User data supplied to the operation. + */ +typedef FileReadCallback = function void(FileOpResult result, const char[] path, const char[] contents, int size, any data); + +/** + * Called when an asynchronous directory snapshot has been materialized. + * + * On success, listing contains a fully-materialized DirectoryListing and must + * be closed by the callback. It is independent of later filesystem changes. + * On failure, listing is null. + * + * @param result Operation result. + * @param path Path supplied to the operation. + * @param listing Materialized directory listing, or null on failure. + * @param data User data supplied to the operation. + */ +typedef FileDirectoryCallback = function void(FileOpResult result, const char[] path, DirectoryListing listing, any data); + +/** + * Deletes a file without blocking the game thread. + * + * @param path Path to the file. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void DeleteFileAsync(const char[] path, FileOpCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="DEFAULT_WRITE_PATH"); + +/** + * Renames a file without blocking the game thread. + * + * @param newpath New path to the file. + * @param oldpath Path to the existing file. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void RenameFileAsync(const char[] newpath, const char[] oldpath, + FileOpCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="DEFAULT_WRITE_PATH"); + +/** + * Copies a file without blocking the game thread. Existing destinations are + * overwritten. + * + * @param newpath Path to the destination file. + * @param oldpath Path to the existing source file. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param source_path_id Valve filesystem search path for the source. + * @param dest_path_id Valve filesystem search path for the destination. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void CopyFileAsync(const char[] newpath, const char[] oldpath, + FileOpCallback callback, any data=0, + bool use_valve_fs=false, + const char[] source_path_id="GAME", + const char[] dest_path_id="DEFAULT_WRITE_PATH"); + +/** + * Checks for a regular file without blocking the game thread. + * + * @param path Path to the file. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void FileExistsAsync(const char[] path, FileExistsCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="GAME"); + +/** + * Checks for a directory without blocking the game thread. + * + * @param path Path to the directory. Use "." for the game directory. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The path is empty, the callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void DirExistsAsync(const char[] path, FileExistsCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="GAME"); + +/** + * Gets a file's size without blocking the game thread. + * + * @param path Path to the file. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void FileSizeAsync(const char[] path, FileSizeCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="GAME"); + +/** + * Reads a whole file without blocking the game thread. + * + * @param path Path to the file. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void ReadFileAsync(const char[] path, FileReadCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="GAME"); + +/** + * Enumerates an OS filesystem directory without blocking the game thread. + * The callback receives a fully-materialized DirectoryListing snapshot. + * + * @param path Path to the directory. Use "." for the game directory. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @error The path is empty, the callback is invalid, or the async worker is shutting down. + */ +native void OpenDirectoryAsync(const char[] path, FileDirectoryCallback callback, any data=0); + +/** + * Writes size raw bytes from contents without blocking the game thread. + * + * @param path Path to the file. + * @param contents Raw-byte buffer to write. + * @param size Number of bytes to write from contents. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param append If true, append rather than overwrite. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem path; must be DEFAULT_WRITE_PATH. + * @error The size is negative, the callback is invalid, the async worker is shutting down, Valve async operations are unavailable, or valve_path_id is unsupported. + */ +native void WriteFileAsync(const char[] path, const char[] contents, int size, + FileOpCallback callback, any data=0, bool append=false, + bool use_valve_fs=false, + const char[] valve_path_id="DEFAULT_WRITE_PATH"); + +/** + * Creates a directory without blocking the game thread. + * + * @param path Path to create. + * @param mode Permissions for an OS filesystem directory. Ignored by the Valve filesystem. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @param use_valve_fs If true, use the Valve filesystem. + * @param valve_path_id Valve filesystem search path when use_valve_fs is true. + * @error The callback is invalid, the async worker is shutting down, or Valve async operations are unavailable. + */ +native void CreateDirectoryAsync(const char[] path, int mode, + FileOpCallback callback, any data=0, + bool use_valve_fs=false, + const char[] valve_path_id="DEFAULT_WRITE_PATH"); + +/** + * Removes an empty OS filesystem directory without blocking the game thread. + * + * @param path Path to the directory. + * @param callback Callback invoked on completion. + * @param data User data passed to the callback. + * @error The callback is invalid or the async worker is shutting down. + */ +native void RemoveDirectoryAsync(const char[] path, FileOpCallback callback, any data=0); + /** * Changes a file or directories permissions. * diff --git a/plugins/testsuite/mock/test_async_file.sp b/plugins/testsuite/mock/test_async_file.sp new file mode 100644 index 00000000..a8f2958a --- /dev/null +++ b/plugins/testsuite/mock/test_async_file.sp @@ -0,0 +1,178 @@ +#pragma semicolon 1 +#pragma newdecls required + +#include +#include + +static const char g_Source[] = "test_async_file_source.txt"; +static const char g_Destination[] = "test_async_file_destination.txt"; +static const char g_BinarySource[] = "test_async_file_binary_source.dat"; +static const char g_BinaryDestination[] = "test_async_file_binary_destination.dat"; +static const char g_Directory[] = "test_async_file_dir"; +static const char g_DirectoryFirst[] = "test_async_file_dir/first.txt"; +static const char g_DirectorySecond[] = "test_async_file_dir/second.txt"; +static bool g_NativeReturned; + +static void WriteTestFile(const char[] path, const char[] contents) +{ + File file = OpenFile(path, "wb"); + AssertTrue("open_for_write", file != null); + file.WriteString(contents, false); + delete file; +} + +static void ReadTestFile(const char[] path, char[] buffer, int maxlength) +{ + File file = OpenFile(path, "rb"); + AssertTrue("open_for_read", file != null); + file.ReadString(buffer, maxlength); + delete file; +} + +static void WriteBinaryTestFile(const char[] path, const int[] bytes, int count) +{ + File file = OpenFile(path, "wb"); + AssertTrue("open_binary_for_write", file != null); + AssertTrue("write_binary", file.Write(bytes, count, 1)); + delete file; +} + +public void OnPluginStart() +{ + DeleteFile(g_Source); + DeleteFile(g_Destination); + DeleteFile(g_BinarySource); + DeleteFile(g_BinaryDestination); + DeleteFile(g_DirectoryFirst); + DeleteFile(g_DirectorySecond); + RemoveDir(g_Directory); + WriteTestFile(g_Source, "async copyfile"); + AssertTrue("create_directory", CreateDirectory(g_Directory)); + WriteTestFile(g_DirectoryFirst, "first"); + WriteTestFile(g_DirectorySecond, "second"); + + SetTestContext("AsyncCopyCreatesDestination"); + CopyFileAsync(g_Destination, g_Source, OnCopyComplete, 42); + g_NativeReturned = true; +} + +void OnCopyComplete(FileOpResult result, const char[] path, any data) +{ + char buffer[64]; + + AssertTrue("callback_after_native", g_NativeReturned); + AssertEq("copy_result", result, FileOp_Success); + AssertStrEq("copy_path", path, g_Destination); + AssertEq("copy_data", data, 42); + AssertTrue("dest_exists", FileExists(g_Destination)); + ReadTestFile(g_Destination, buffer, sizeof(buffer)); + AssertStrEq("dest_contents", buffer, "async copyfile"); + + SetTestContext("AsyncFileExists"); + FileExistsAsync(g_Destination, OnExistsComplete, 43); +} + +void OnExistsComplete(bool exists, const char[] path, any data) +{ + AssertTrue("exists", exists); + AssertStrEq("exists_path", path, g_Destination); + AssertEq("exists_data", data, 43); + + SetTestContext("AsyncCopyMissingSource"); + CopyFileAsync(g_Destination, "test_async_file_missing.txt", OnMissingCopyComplete, 44); +} + +void OnMissingCopyComplete(FileOpResult result, const char[] path, any data) +{ + char buffer[64]; + + AssertEq("copy_result", result, FileOp_NotFound); + AssertStrEq("copy_path", path, g_Destination); + AssertEq("copy_data", data, 44); + AssertTrue("dest_preserved", FileExists(g_Destination)); + ReadTestFile(g_Destination, buffer, sizeof(buffer)); + AssertStrEq("dest_contents", buffer, "async copyfile"); + + int bytes[] = {0x00, 0x01, 0x41, 0x00, 0xff, 0x7f}; + WriteBinaryTestFile(g_BinarySource, bytes, sizeof(bytes)); + + SetTestContext("AsyncReadBinary"); + ReadFileAsync(g_BinarySource, OnReadComplete, 45); +} + +void OnReadComplete(FileOpResult result, const char[] path, const char[] contents, int size, any data) +{ + int expected[] = {0x00, 0x01, 0x41, 0x00, 0xff, 0x7f}; + + AssertEq("read_result", result, FileOp_Success); + AssertStrEq("read_path", path, g_BinarySource); + AssertEq("read_size", size, sizeof(expected)); + AssertEq("read_data", data, 45); + for (int i = 0; i < sizeof(expected); i++) + { + AssertEq("read_byte", contents[i] & 0xff, expected[i]); + } + + SetTestContext("AsyncWriteBinary"); + WriteFileAsync(g_BinaryDestination, contents, size, OnWriteComplete, 46); +} + +void OnWriteComplete(FileOpResult result, const char[] path, any data) +{ + int expected[] = {0x00, 0x01, 0x41, 0x00, 0xff, 0x7f}; + int actual[sizeof(expected)]; + File file; + + AssertEq("write_result", result, FileOp_Success); + AssertStrEq("write_path", path, g_BinaryDestination); + AssertEq("write_data", data, 46); + file = OpenFile(g_BinaryDestination, "rb"); + AssertTrue("open_binary_for_read", file != null); + AssertEq("read_binary", file.Read(actual, sizeof(actual), 1), sizeof(actual)); + delete file; + for (int i = 0; i < sizeof(expected); i++) + { + AssertEq("written_byte", actual[i], expected[i]); + } + + SetTestContext("AsyncDirectorySnapshot"); + OpenDirectoryAsync(g_Directory, OnDirectoryComplete, 47); +} + +void OnDirectoryComplete(FileOpResult result, const char[] path, DirectoryListing listing, any data) +{ + char name[PLATFORM_MAX_PATH]; + FileType type; + bool foundFirst; + bool foundSecond; + + AssertEq("directory_result", result, FileOp_Success); + AssertStrEq("directory_path", path, g_Directory); + AssertEq("directory_data", data, 47); + AssertTrue("directory_listing", listing != null); + while (listing.GetNext(name, sizeof(name), type)) + { + if (StrEqual(name, "first.txt")) + { + AssertEq("first_type", type, FileType_File); + foundFirst = true; + } + else if (StrEqual(name, "second.txt")) + { + AssertEq("second_type", type, FileType_File); + foundSecond = true; + } + } + delete listing; + AssertTrue("directory_first", foundFirst); + AssertTrue("directory_second", foundSecond); + + DeleteFile(g_Source); + DeleteFile(g_Destination); + DeleteFile(g_BinarySource); + DeleteFile(g_BinaryDestination); + DeleteFile(g_DirectoryFirst); + DeleteFile(g_DirectorySecond); + RemoveDir(g_Directory); + PrintToServer("OK"); +} diff --git a/plugins/testsuite/mock/test_copyfile.sp b/plugins/testsuite/mock/test_copyfile.sp new file mode 100644 index 00000000..45738d5b --- /dev/null +++ b/plugins/testsuite/mock/test_copyfile.sp @@ -0,0 +1,69 @@ +#pragma semicolon 1 +#pragma newdecls required +#include +#include + +// Only the non-Valve-fs path is exercised here. The hl2sdk-mock file system +// reports IsOk() inverted, so ValveFile::HasError() is always true under the +// mock and the Valve-fs streaming copy cannot be meaningfully tested there. + +static void WriteTestFile(const char[] path, const char[] contents) +{ + File f = OpenFile(path, "wb"); + AssertTrue("open_for_write", f != null); + f.WriteString(contents, false); + delete f; +} + +static void ReadTestFile(const char[] path, char[] buffer, int maxlength) +{ + File f = OpenFile(path, "rb"); + AssertTrue("open_for_read", f != null); + f.ReadString(buffer, maxlength); + delete f; +} + +public void OnPluginStart() +{ + char src[] = "test_copyfile_src.txt"; + char dst[] = "test_copyfile_dst.txt"; + char buffer[256]; + + // Clean up any leftovers from a previous run. + DeleteFile(src); + DeleteFile(dst); + + // -------------------------------------------------------------------------------- + + SetTestContext("CopyCreatesDestination"); + + WriteTestFile(src, "hello copyfile"); + AssertTrue("copy_returns_true", CopyFile(dst, src)); + AssertTrue("dest_exists", FileExists(dst)); + ReadTestFile(dst, buffer, sizeof(buffer)); + AssertStrEq("dest_contents", buffer, "hello copyfile"); + + // -------------------------------------------------------------------------------- + + SetTestContext("CopyOverwritesDestination"); + + WriteTestFile(dst, "OLD CONTENT that is longer than the source"); + AssertTrue("copy_returns_true", CopyFile(dst, src)); + ReadTestFile(dst, buffer, sizeof(buffer)); + AssertStrEq("dest_overwritten", buffer, "hello copyfile"); + + // -------------------------------------------------------------------------------- + + SetTestContext("CopyMissingSourceFails"); + + DeleteFile(dst); + AssertFalse("copy_returns_false", CopyFile(dst, "test_copyfile_missing.txt")); + AssertFalse("dest_not_created", FileExists(dst)); + + // -------------------------------------------------------------------------------- + + DeleteFile(src); + DeleteFile(dst); + + PrintToServer("OK"); +}