From 477703098b0f00aa84d61fca7e9c957090bd4b97 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:16:45 +0800 Subject: [PATCH 1/9] refactor(task): run one operator per task SmbTask kept a list of operators, a pending counter, and per-op progress for spawn(), which no operator calls. Each task also started a detached thread while the thread that launched it blocked in start(). Run the single operator inline on the thread that starts the task. - remove spawn, launchOp, appendOps, pending_, and OperatorContext::opIndex - track one progress entry; onOpStatus/onOpProgress drop the op index - run() replaces start() and calls the operator instead of waiting on a completion future --- cpp/shared/bridge/HybridSMB.cpp | 2 +- cpp/shared/core/OperatorContext.hpp | 6 +- cpp/shared/core/SmbTask.cpp | 83 +++++---------------------- cpp/shared/core/SmbTask.hpp | 18 ++---- cpp/shared/core/SmbTaskCore.cpp | 28 ++------- cpp/shared/core/SmbTaskCore.hpp | 25 ++------ cpp/shared/operators/OperatorBase.cpp | 12 ++-- cpp/shared/operators/OperatorBase.hpp | 3 +- cpp/shared/util/SmbException.hpp | 2 +- 9 files changed, 40 insertions(+), 139 deletions(-) diff --git a/cpp/shared/bridge/HybridSMB.cpp b/cpp/shared/bridge/HybridSMB.cpp index 01314fd..03fb4b1 100644 --- a/cpp/shared/bridge/HybridSMB.cpp +++ b/cpp/shared/bridge/HybridSMB.cpp @@ -72,7 +72,7 @@ std::shared_ptr HybridSMB::startTask(const std::string& taskId, std::un std::shared_ptr state; ~RunCompletionGuard() { HybridSMB::releaseTaskRun(state); } } guard{taskRuns}; - task->start(); + task->run(); self->forgetTask(taskId); }; diff --git a/cpp/shared/core/OperatorContext.hpp b/cpp/shared/core/OperatorContext.hpp index c938a68..f6a34ca 100644 --- a/cpp/shared/core/OperatorContext.hpp +++ b/cpp/shared/core/OperatorContext.hpp @@ -1,7 +1,5 @@ #pragma once -#include - #include "CancellationToken.hpp" namespace react_native_smb { @@ -10,15 +8,13 @@ class SmbTask; class SmbConnectionPool; // Everything an operator needs, injected by OperatorBase::start() before run(). -// - task : back-pointer to report status/progress and spawn() more work +// - task : back-pointer to report status/progress // - pool : connection pool; op calls requestContext() when it needs a slot // - cancel : shared token the operator polls in its loop -// - opIndex : this operator's stable index for per-op aggregation struct OperatorContext { SmbTask* task{nullptr}; // non-owning SmbConnectionPool* pool{nullptr}; // non-owning CancellationToken cancel; // shared with the task - size_t opIndex{0}; }; } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.cpp b/cpp/shared/core/SmbTask.cpp index 9d7676b..311d181 100644 --- a/cpp/shared/core/SmbTask.cpp +++ b/cpp/shared/core/SmbTask.cpp @@ -1,7 +1,5 @@ #include "SmbTask.hpp" -#include - #include "../connection/SmbConnectionPool.hpp" #include "../operators/OperatorBase.hpp" #include "../util/SmbErrorMapper.hpp" @@ -9,13 +7,11 @@ #include "EntryStream.hpp" namespace react_native_smb { -SmbTask::SmbTask(std::string id, std::unique_ptr seedOp, std::shared_ptr pool) - : SmbTaskCore(std::move(id), seedOp->kind()), pool_(pool) { - if (seedOp->kind() == SmbOperatorKind::ListDirectory) { +SmbTask::SmbTask(std::string id, std::unique_ptr op, std::shared_ptr pool) + : SmbTaskCore(std::move(id), op->kind()), op_(std::move(op)), pool_(pool) { + if (op_->kind() == SmbOperatorKind::ListDirectory) { entries_ = std::make_shared(); } - ops_.push_back(std::move(seedOp)); - opProgress_.resize(1); } SmbTask::~SmbTask() = default; @@ -27,79 +23,30 @@ void SmbTask::cancel() { if (auto pool = pool_.lock()) pool->cancelRequestsForTask(getId()); } -void SmbTask::start() { +void SmbTask::run() { markRunning(); - auto fut = completionFuture(); - { - std::lock_guard lk(stateMutex_); - pending_ = 1; - launchOp(0); - } - fut.wait(); -} - -void SmbTask::launchOp(size_t opIndex) { - auto self = shared_from_this(); - std::thread([self, opIndex] { - if (self->cancel_.cancelled()) { - self->onOpFinished(); - return; - } - OperatorBase* op = nullptr; - { - std::lock_guard lk(self->stateMutex_); - if (opIndex < self->ops_.size()) op = self->ops_[opIndex].get(); - } - if (!op) { - self->onOpFinished(); - return; - } - auto pool = self->pool_.lock(); - if (!pool) { - if (!self->cancel_.cancelled()) { - self->settle(SmbTaskStatus::Error, "SMB connection pool is unavailable", static_cast(SmbErrorCode::NotConnected)); - } - self->onOpFinished(); - return; + auto pool = pool_.lock(); + if (!pool) { + if (!cancel_.cancelled()) { + settle(SmbTaskStatus::Error, "SMB connection pool is unavailable", static_cast(SmbErrorCode::NotConnected)); } + } else if (!cancel_.cancelled()) { try { - op->start(self.get(), pool.get(), self->cancel_, opIndex); + op_->start(this, pool.get(), cancel_); } catch (const SmbException& e) { if (e.code() == SmbErrorCode::Cancelled) { - self->SmbTaskCore::cancel(); + SmbTaskCore::cancel(); } else { - self->settle(SmbTaskStatus::Error, e.what(), e.codeInt()); + settle(SmbTaskStatus::Error, e.what(), e.codeInt()); } } catch (const std::exception& e) { const int code = SmbErrorMapper::fromErrnoOrMessage(0, e.what()); - self->settle(SmbTaskStatus::Error, e.what(), code); + settle(SmbTaskStatus::Error, e.what(), code); } catch (...) { - self->settle(SmbTaskStatus::Error, "unknown error", static_cast(SmbErrorCode::Unknown)); + settle(SmbTaskStatus::Error, "unknown error", static_cast(SmbErrorCode::Unknown)); } - self->onOpFinished(); - }).detach(); -} - -size_t SmbTask::appendOps(std::vector>& more) { - const size_t first = ops_.size(); - for (auto& op : more) { - ops_.push_back(std::move(op)); - } - opProgress_.resize(ops_.size()); - return first; -} - -size_t SmbTask::spawn(std::vector> moreOps) { - if (moreOps.empty()) return ops_.size(); - const size_t count = moreOps.size(); - size_t first; - { - std::lock_guard lk(stateMutex_); - first = appendOps(moreOps); - pending_ += count; - for (size_t i = 0; i < count; ++i) launchOp(first + i); } - return first; + maybeSettle(); } } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.hpp b/cpp/shared/core/SmbTask.hpp index 211ed57..e9e6af6 100644 --- a/cpp/shared/core/SmbTask.hpp +++ b/cpp/shared/core/SmbTask.hpp @@ -1,10 +1,7 @@ #pragma once -#include -#include #include #include -#include #include "SmbTaskCore.hpp" @@ -13,15 +10,14 @@ namespace react_native_smb { class OperatorBase; class SmbConnectionPool; class EntryStream; -struct SmbFileInfo; -class SmbTask : public SmbTaskCore, public std::enable_shared_from_this { +class SmbTask : public SmbTaskCore { public: - SmbTask(std::string id, std::unique_ptr seedOp, std::shared_ptr pool); + SmbTask(std::string id, std::unique_ptr op, std::shared_ptr pool); ~SmbTask(); - void start(); - size_t spawn(std::vector> moreOps); + // Runs the operator on the calling thread and settles the task. + void run(); using SmbTaskCore::getState; using SmbTaskCore::subscribe; @@ -32,14 +28,10 @@ class SmbTask : public SmbTaskCore, public std::enable_shared_from_this const std::shared_ptr& entryStream() const { return entries_; } - std::future result() { return completionFuture(); } - private: + std::unique_ptr op_; std::weak_ptr pool_; std::shared_ptr entries_; // non-null only for ListDirectory - - void launchOp(size_t opIndex); - size_t appendOps(std::vector>& more); }; } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTaskCore.cpp b/cpp/shared/core/SmbTaskCore.cpp index 4ed7a2e..7d872a6 100644 --- a/cpp/shared/core/SmbTaskCore.cpp +++ b/cpp/shared/core/SmbTaskCore.cpp @@ -3,7 +3,6 @@ #include #include -#include "../operators/OperatorBase.hpp" #include "../util/SmbErrorMapper.hpp" #include "../util/SmbLog.hpp" @@ -76,12 +75,11 @@ void SmbTaskCore::addExpectedBytes(int64_t bytes) { notifyListeners(); } -void SmbTaskCore::onOpStatus(size_t opIndex, SmbTaskStatus s, const std::string& error, int code) { +void SmbTaskCore::onOpStatus(SmbTaskStatus s, const std::string& error, int code) { { std::lock_guard lk(stateMutex_); if (settled_.load(std::memory_order_acquire)) return; if (status_.load() == SmbTaskStatus::Cancelled && s == SmbTaskStatus::Success) return; - if (opIndex < opProgress_.size()) opProgress_[opIndex].status = s; if (s == SmbTaskStatus::Error && status_.load() != SmbTaskStatus::Error) { errorMessage_ = error; errorCode_ = code; @@ -90,14 +88,12 @@ void SmbTaskCore::onOpStatus(size_t opIndex, SmbTaskStatus s, const std::string& notifyListeners(); } -void SmbTaskCore::onOpProgress(size_t opIndex, double done, double total) { +void SmbTaskCore::onOpProgress(double done, double total) { { std::lock_guard lk(stateMutex_); if (settled_.load(std::memory_order_acquire)) return; - if (opIndex < opProgress_.size()) { - opProgress_[opIndex].done = static_cast(done); - opProgress_[opIndex].total = static_cast(total); - } + opDone_ = static_cast(done); + opTotal_ = static_cast(total); recomputeAggregateLocked(); } notifyListeners(); @@ -125,8 +121,6 @@ SmbTaskResult SmbTaskCore::publishedResult() const { return resultValue_; } -std::future SmbTaskCore::completionFuture() { return done_.get_future(); } - void SmbTaskCore::markPending() { { std::lock_guard lk(stateMutex_); @@ -149,22 +143,14 @@ void SmbTaskCore::markRunning() { notifyListeners(); } -void SmbTaskCore::onOpFinished() { - const size_t before = pending_.fetch_sub(1); - if (before == 1) maybeSettle(); -} - void SmbTaskCore::recomputeAggregateLocked() { updatedAt_ = nowMs(); if (!isDeterminate(kind_)) { progress_ = 0.0; return; } - int64_t d = 0, t = 0; - for (const auto& p : opProgress_) { - d += p.done; - t += p.total; - } + const int64_t d = opDone_; + const int64_t t = opTotal_; bytesDone_ = d; const int64_t denom = std::max(t, std::max(d, totalBytes_.load())); totalBytes_ = denom; @@ -226,7 +212,6 @@ void SmbTaskCore::maybeSettle() { endedAt_ = nowMs(); } notifyListeners(); - done_.set_value(); } return; } @@ -273,7 +258,6 @@ void SmbTaskCore::settle(SmbTaskStatus finalStatus, const std::string& error, in SMB_LOG_INFO("Task %s (%s) completed", id_.c_str(), operationName(kind_)); } notifyListeners(); - done_.set_value(); } } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTaskCore.hpp b/cpp/shared/core/SmbTaskCore.hpp index f7df1cb..81092d6 100644 --- a/cpp/shared/core/SmbTaskCore.hpp +++ b/cpp/shared/core/SmbTaskCore.hpp @@ -3,7 +3,6 @@ #include #include #include -#include #include #include #include @@ -17,8 +16,6 @@ namespace react_native_smb { -class OperatorBase; - // Thread-safe state, result storage, and subscriber fan-out. No HybridObject, // no pool orchestration, no JSI. class SmbTaskCore { @@ -37,8 +34,8 @@ class SmbTaskCore { void setPaths(std::string source, std::string destination); void addExpectedBytes(int64_t bytes); - void onOpStatus(size_t opIndex, SmbTaskStatus s, const std::string& error, int code); - void onOpProgress(size_t opIndex, double done, double total); + void onOpStatus(SmbTaskStatus s, const std::string& error, int code); + void onOpProgress(double done, double total); void publishResult(SmbTaskResult value); SmbTaskResult publishedResult() const; @@ -46,25 +43,15 @@ class SmbTaskCore { std::string subscribe(SnapshotListener listener); void unsubscribe(const std::string& id); - std::future completionFuture(); - void markPending(); void markRunning(); protected: - struct OpProgress { - int64_t done{0}; - int64_t total{0}; - SmbTaskStatus status{SmbTaskStatus::Idle}; - }; - - std::vector> ops_; - std::vector opProgress_; - std::atomic pending_{0}; CancellationToken cancel_; - void onOpFinished(); void settle(SmbTaskStatus finalStatus, const std::string& error, int code); + // Settles from the operator's outcome once it has returned. + void maybeSettle(); static int64_t nowMs(); @@ -86,8 +73,9 @@ class SmbTaskCore { int64_t startedAt_{0}; int64_t updatedAt_{0}; int64_t endedAt_{0}; + int64_t opDone_{0}; + int64_t opTotal_{0}; - std::promise done_; std::atomic settled_{false}; std::map listeners_; @@ -99,7 +87,6 @@ class SmbTaskCore { void writeToSnapshot(SmbTaskState& out) const; void notifyListeners(); void recomputeAggregateLocked(); - void maybeSettle(); }; } // namespace react_native_smb diff --git a/cpp/shared/operators/OperatorBase.cpp b/cpp/shared/operators/OperatorBase.cpp index 4132fd5..cb99f73 100644 --- a/cpp/shared/operators/OperatorBase.cpp +++ b/cpp/shared/operators/OperatorBase.cpp @@ -5,8 +5,8 @@ namespace react_native_smb { -void OperatorBase::start(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel, size_t opIndex) { - setContext(OperatorContext{task, pool, cancel, opIndex}); +void OperatorBase::start(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel) { + setContext(OperatorContext{task, pool, cancel}); if (cancel.cancelled()) return; run(); } @@ -31,15 +31,11 @@ void OperatorBase::emitStatus(SmbTaskStatus s, const std::string& error, int cod if (!ctx_.task) return; if (isCancelled() && s == SmbTaskStatus::Success) return; if (ctx_.task->getStatus() == SmbTaskStatus::Cancelled && s == SmbTaskStatus::Success) return; - ctx_.task->onOpStatus(ctx_.opIndex, s, error, code); + ctx_.task->onOpStatus(s, error, code); } void OperatorBase::emitProgress(double done, double total) { - if (ctx_.task) ctx_.task->onOpProgress(ctx_.opIndex, done, total); -} - -size_t OperatorBase::spawn(std::vector> moreOps) { - return ctx_.task ? ctx_.task->spawn(std::move(moreOps)) : 0; + if (ctx_.task) ctx_.task->onOpProgress(done, total); } void OperatorBase::addExpectedBytes(int64_t bytes) { diff --git a/cpp/shared/operators/OperatorBase.hpp b/cpp/shared/operators/OperatorBase.hpp index d42d85a..9158b16 100644 --- a/cpp/shared/operators/OperatorBase.hpp +++ b/cpp/shared/operators/OperatorBase.hpp @@ -28,7 +28,7 @@ class OperatorBase { virtual SmbOperatorKind kind() const = 0; void setContext(const OperatorContext& ctx) { ctx_ = ctx; } - void start(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel, size_t opIndex); + void start(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel); protected: void emitStatus(SmbTaskStatus s, const std::string& error = "", int code = 0); @@ -42,7 +42,6 @@ class OperatorBase { MetadataContextLease makeMetadataLease(); std::string owningTaskId() const; - size_t spawn(std::vector> moreOps); void addExpectedBytes(int64_t bytes); void setSourceDestination(const std::string& source, const std::string& destination); void publishResult(SmbTaskResult value); diff --git a/cpp/shared/util/SmbException.hpp b/cpp/shared/util/SmbException.hpp index 8775e20..efa6e5f 100644 --- a/cpp/shared/util/SmbException.hpp +++ b/cpp/shared/util/SmbException.hpp @@ -11,7 +11,7 @@ namespace react_native_smb { // Typed native exception. Prefer throwing this at the error origin so -// SmbTask::launchOp can settle with a stable SmbErrorCode instead of +// SmbTask::run can settle with a stable SmbErrorCode instead of // re-guessing from message text. class SmbException : public std::runtime_error { public: From bf24d686689686bdda23a14175863d3d3627daa8 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:16:57 +0800 Subject: [PATCH 2/9] fix(task): guard the published result with the state mutex publishResult wrote resultValue_ without stateMutex_ while publishedResult read it under the lock, so a JS read could race the operator thread. - take stateMutex_ in publishResult --- cpp/shared/core/SmbTaskCore.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cpp/shared/core/SmbTaskCore.cpp b/cpp/shared/core/SmbTaskCore.cpp index 7d872a6..d763e11 100644 --- a/cpp/shared/core/SmbTaskCore.cpp +++ b/cpp/shared/core/SmbTaskCore.cpp @@ -112,6 +112,7 @@ void SmbTaskCore::unsubscribe(const std::string& id) { } void SmbTaskCore::publishResult(SmbTaskResult value) { + std::lock_guard lk(stateMutex_); if (settled_.load(std::memory_order_acquire)) return; resultValue_ = std::move(value); } From fde1c9317d0f37bf82c690114ff7d75581724b03 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:17:44 +0800 Subject: [PATCH 3/9] refactor(copy): pass the held context into copy trees MetadataContextLease only wrapped a PoolContextHandle, and copyTreeImpl acquired its own lease when a caller passed none. A caller that already held a slot could then wait on itself once the pool was full. Take the caller's handle instead. - delete MetadataContextLease.hpp and OperatorBase::makeMetadataLease - copyTreeImpl and inspectCopyTreeSource take a required PoolContextHandle& - copy and duplicate request a Metadata context directly --- .../connection/MetadataContextLease.hpp | 35 --------------- cpp/shared/io/SmbCopyTree.hpp | 43 ++++++++----------- cpp/shared/operators/OperatorBase.cpp | 7 --- cpp/shared/operators/OperatorBase.hpp | 2 - .../operators/mutate/CopyItemOperator.cpp | 6 +-- .../mutate/DuplicateItemOperator.cpp | 12 +++--- 6 files changed, 26 insertions(+), 79 deletions(-) delete mode 100644 cpp/shared/connection/MetadataContextLease.hpp diff --git a/cpp/shared/connection/MetadataContextLease.hpp b/cpp/shared/connection/MetadataContextLease.hpp deleted file mode 100644 index 509cc68..0000000 --- a/cpp/shared/connection/MetadataContextLease.hpp +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include - -#include "../core/SmbEnums.hpp" -#include "PoolContextHandle.hpp" -#include "PoolTypes.hpp" -#include "SmbConnectionPool.hpp" - -namespace react_native_smb { - -// Holds one metadata pool slot for multiple submitSync calls (e.g. entire copyTreeImpl). -class MetadataContextLease { - public: - MetadataContextLease(SmbConnectionPool& pool, SmbOperatorKind kind, const std::string& taskId) - : handle_(pool.requestContext(AcquireMode::Metadata, kind, taskId)) {} - - MetadataContextLease(MetadataContextLease&&) = default; - MetadataContextLease& operator=(MetadataContextLease&&) = default; - MetadataContextLease(const MetadataContextLease&) = delete; - MetadataContextLease& operator=(const MetadataContextLease&) = delete; - - template - auto submitSync(Fn&& fn) { - return handle_.submitSync(std::forward(fn)); - } - - SmbConnectionManager& manager() const { return handle_.manager(); } - - private: - PoolContextHandle handle_; -}; - -} // namespace react_native_smb diff --git a/cpp/shared/io/SmbCopyTree.hpp b/cpp/shared/io/SmbCopyTree.hpp index d28fa9a..bf00cb0 100644 --- a/cpp/shared/io/SmbCopyTree.hpp +++ b/cpp/shared/io/SmbCopyTree.hpp @@ -6,13 +6,11 @@ #include #include #include -#include #include #include #include "../core/SmbModels.hpp" -#include "../connection/MetadataContextLease.hpp" -#include "../connection/SmbConnectionPool.hpp" +#include "../connection/PoolContextHandle.hpp" #include "../core/CancellationToken.hpp" #include "../core/SmbEnums.hpp" #include "../util/SmbException.hpp" @@ -59,10 +57,10 @@ inline int64_t totalFileSize(const std::vector& entries) { } } // namespace copy_tree_detail -inline CopyTreeSourceInfo inspectCopyTreeSource(MetadataContextLease& lease, const std::string& fromPath, +inline CopyTreeSourceInfo inspectCopyTreeSource(PoolContextHandle& context, const std::string& fromPath, bool recursive, const CancellationToken& cancel) { CopyTreeSourceInfo source; - lease.submitSync([&](smb2_context* ctx) { + context.submitSync([&](smb2_context* ctx) { const std::string normalizedPath = path_util::normalized(fromPath); smb2_stat_64 st{}; const int result = smb2_stat(ctx, normalizedPath.c_str(), &st); @@ -80,17 +78,16 @@ inline CopyTreeSourceInfo inspectCopyTreeSource(MetadataContextLease& lease, con listing::DirectoryListOptions options; options.maxDepth = -1; options.countChildren = false; - source.entries = listing::listOnCtx(ctx, lease.manager(), fromPath, options, cancel); + source.entries = listing::listOnCtx(ctx, context.manager(), fromPath, options, cancel); source.totalSize = copy_tree_detail::totalFileSize(source.entries); }); return source; } -inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const std::string& fromPath, - const std::string& toPath, bool recursive, const CancellationToken& cancel, +inline void copyTreeImpl(PoolContextHandle& context, const std::string& fromPath, const std::string& toPath, + bool recursive, const CancellationToken& cancel, const std::function& onProgress, - const std::function& onExpectedBytes, const std::string& taskId = "", - MetadataContextLease* sharedLease = nullptr, + const std::function& onExpectedBytes, const CopyTreeSourceInfo* preparedSource = nullptr, const std::function& onRootClaimed = {}) { const std::string normFrom = path_util::normalized(fromPath); @@ -99,14 +96,8 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st SmbException::raise(SmbErrorCode::InvalidArgument, "Copy Failed: destination cannot be inside the source directory"); } - std::optional ownedLease; - if (!sharedLease) { - ownedLease.emplace(pool, kind, taskId); - sharedLease = &*ownedLease; - } - CopyTreeSourceInfo inspected; - if (!preparedSource) inspected = inspectCopyTreeSource(*sharedLease, fromPath, recursive, cancel); + if (!preparedSource) inspected = inspectCopyTreeSource(context, fromPath, recursive, cancel); const CopyTreeSourceInfo& source = preparedSource ? *preparedSource : inspected; auto totalBytesCopied = std::make_shared(0); @@ -126,8 +117,8 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st if (cancel.cancelled()) { SmbException::raise(SmbErrorCode::Cancelled, "Copy cancelled"); } - sharedLease->submitSync([&](smb2_context* ctx) { - smbCopyFileAsync(ctx, sharedLease->manager(), normFrom, normTo, totalBytesCopied, source.totalSize, + context.submitSync([&](smb2_context* ctx) { + smbCopyFileAsync(ctx, context.manager(), normFrom, normTo, totalBytesCopied, source.totalSize, onProgress, cancel, rootClaimed); }); if (onProgress) { @@ -138,7 +129,7 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st std::vector files; const std::string normToRoot = normTo; - sharedLease->submitSync([&](smb2_context* ctx) { + context.submitSync([&](smb2_context* ctx) { if (cancel.cancelled()) { SmbException::raise(SmbErrorCode::Cancelled, "Copy cancelled"); } @@ -159,7 +150,7 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st copy_tree_detail::collectFiles(source.entries, toPath, files); // Folders in parallel; each one's subfolders once it exists. - PipelinedOps ops(ctx, sharedLease->manager(), cancel, copy_tree_detail::kMaxFoldersInFlight, "Copy Failed"); + PipelinedOps ops(ctx, context.manager(), cancel, copy_tree_detail::kMaxFoldersInFlight, "Copy Failed"); std::function&, const std::string&)> createFolders = [&](const std::vector& items, const std::string& dstDir) { for (const auto& item : items) { @@ -191,8 +182,8 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st } const auto copyOne = [&](const copy_tree_detail::CopyJob& job) { - sharedLease->submitSync([&](smb2_context* ctx) { - smbCopyFileAsync(ctx, sharedLease->manager(), path_util::normalized(job.src), + context.submitSync([&](smb2_context* ctx) { + smbCopyFileAsync(ctx, context.manager(), path_util::normalized(job.src), path_util::normalized(job.dst), totalBytesCopied, source.totalSize, onProgress, cancel); }); }; @@ -210,7 +201,7 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st return; } - if (sharedLease->manager().capabilities().serverSideCopyUnsupported.load()) { + if (context.manager().capabilities().serverSideCopyUnsupported.load()) { for (const auto& job : files) { if (cancel.cancelled()) break; copyOne(job); @@ -219,8 +210,8 @@ inline void copyTreeImpl(SmbConnectionPool& pool, SmbOperatorKind kind, const st std::vector jobs; jobs.reserve(files.size()); for (const auto& job : files) jobs.push_back({path_util::normalized(job.src), path_util::normalized(job.dst)}); - sharedLease->submitSync([&](smb2_context* ctx) { - detail::copyFilesServerSide(ctx, sharedLease->manager(), jobs, copy_tree_detail::kMaxFilesInFlight, totalBytesCopied, + context.submitSync([&](smb2_context* ctx) { + detail::copyFilesServerSide(ctx, context.manager(), jobs, copy_tree_detail::kMaxFilesInFlight, totalBytesCopied, source.totalSize, onProgress, cancel); }); } diff --git a/cpp/shared/operators/OperatorBase.cpp b/cpp/shared/operators/OperatorBase.cpp index cb99f73..e1705d8 100644 --- a/cpp/shared/operators/OperatorBase.cpp +++ b/cpp/shared/operators/OperatorBase.cpp @@ -13,13 +13,6 @@ void OperatorBase::start(SmbTask* task, SmbConnectionPool* pool, const Cancellat std::string OperatorBase::owningTaskId() const { return ctx_.task ? ctx_.task->getId() : std::string(); } -MetadataContextLease OperatorBase::makeMetadataLease() { - if (ctx_.task) ctx_.task->markPending(); - MetadataContextLease lease(pool(), kind(), owningTaskId()); - if (ctx_.task && !isCancelled()) ctx_.task->markRunning(); - return lease; -} - PoolContextHandle OperatorBase::requestContext(AcquireMode mode) { if (ctx_.task) ctx_.task->markPending(); PoolContextHandle handle = pool().requestContext(mode, kind(), owningTaskId()); diff --git a/cpp/shared/operators/OperatorBase.hpp b/cpp/shared/operators/OperatorBase.hpp index 9158b16..d508738 100644 --- a/cpp/shared/operators/OperatorBase.hpp +++ b/cpp/shared/operators/OperatorBase.hpp @@ -5,7 +5,6 @@ #include #include -#include "../connection/MetadataContextLease.hpp" #include "../connection/PoolContextHandle.hpp" #include "../connection/PoolTypes.hpp" #include "../core/CancellationToken.hpp" @@ -39,7 +38,6 @@ class OperatorBase { SmbConnectionPool& pool() const { return *ctx_.pool; } PoolContextHandle requestContext(AcquireMode mode); - MetadataContextLease makeMetadataLease(); std::string owningTaskId() const; void addExpectedBytes(int64_t bytes); diff --git a/cpp/shared/operators/mutate/CopyItemOperator.cpp b/cpp/shared/operators/mutate/CopyItemOperator.cpp index 32f4bde..ef5bb13 100644 --- a/cpp/shared/operators/mutate/CopyItemOperator.cpp +++ b/cpp/shared/operators/mutate/CopyItemOperator.cpp @@ -6,9 +6,9 @@ namespace react_native_smb { void CopyItemOperator::run() { setSourceDestination(fromPath_, toPath_); - MetadataContextLease lease = makeMetadataLease(); - copyTreeImpl(pool(), kind(), fromPath_, toPath_, recursive_, cancelToken(), - [this](double done, double total) { emitProgress(done, total); }, [this](int64_t n) { addExpectedBytes(n); }, owningTaskId(), &lease); + auto handle = requestContext(AcquireMode::Metadata); + copyTreeImpl(handle, fromPath_, toPath_, recursive_, cancelToken(), + [this](double done, double total) { emitProgress(done, total); }, [this](int64_t n) { addExpectedBytes(n); }); if (isCancelled()) { emitStatus(SmbTaskStatus::Cancelled); return; diff --git a/cpp/shared/operators/mutate/DuplicateItemOperator.cpp b/cpp/shared/operators/mutate/DuplicateItemOperator.cpp index ec60824..26e1f11 100644 --- a/cpp/shared/operators/mutate/DuplicateItemOperator.cpp +++ b/cpp/shared/operators/mutate/DuplicateItemOperator.cpp @@ -20,13 +20,13 @@ void DuplicateItemOperator::run() { const std::string fileName = path_util::extractFileName(sourcePath); setSourceDestination(sourcePath, sourcePath); - MetadataContextLease lease = makeMetadataLease(); + auto handle = requestContext(AcquireMode::Metadata); if (isCancelled()) { emitStatus(SmbTaskStatus::Cancelled); return; } - const CopyTreeSourceInfo source = inspectCopyTreeSource(lease, sourcePath, /*recursive=*/true, token); + const CopyTreeSourceInfo source = inspectCopyTreeSource(handle, sourcePath, /*recursive=*/true, token); constexpr int kMaxRootClaimRetries = 64; std::string destPath; @@ -38,17 +38,17 @@ void DuplicateItemOperator::run() { return; } - lease.submitSync([&](smb2_context* ctx) { + handle.submitSync([&](smb2_context* ctx) { const std::string newName = - tree_ops::generateUniqueCopyName(ctx, lease.manager(), parentPath, fileName, token, nextNameIndex); + tree_ops::generateUniqueCopyName(ctx, handle.manager(), parentPath, fileName, token, nextNameIndex); destPath = path_util::buildUrl(parentPath, newName); }); try { copyTreeImpl( - pool(), kind(), sourcePath, destPath, /*recursive=*/true, token, + handle, sourcePath, destPath, /*recursive=*/true, token, [this](double done, double total) { emitProgress(done, total); }, - [this](int64_t n) { addExpectedBytes(n); }, owningTaskId(), &lease, &source, + [this](int64_t n) { addExpectedBytes(n); }, &source, [&] { rootClaimed = true; setSourceDestination(sourcePath, destPath); From 5cdd4d0ba0f8ddc75eadae9d34a00c908cd071a5 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:17:57 +0800 Subject: [PATCH 4/9] perf(delete): stat and delete on one held Metadata slot Delete gave up its slot after stat and again before unlink or the tree delete, so each phase queued behind other work for a new slot. Keep the first slot for the whole delete. - stat, unlink, and the listed tree delete share one context --- .../operators/mutate/DeleteItemOperator.cpp | 46 ++++++++----------- 1 file changed, 20 insertions(+), 26 deletions(-) diff --git a/cpp/shared/operators/mutate/DeleteItemOperator.cpp b/cpp/shared/operators/mutate/DeleteItemOperator.cpp index 8ef91ff..edfc630 100644 --- a/cpp/shared/operators/mutate/DeleteItemOperator.cpp +++ b/cpp/shared/operators/mutate/DeleteItemOperator.cpp @@ -88,21 +88,18 @@ void DeleteItemOperator::run() { if (norm.empty()) SmbException::raise(SmbErrorCode::InvalidArgument, "Delete Failed: refusing to delete the share root"); setSourceDestination(norm, ""); + auto handle = requestContext(AcquireMode::Metadata); bool isDirectory = false; - { - auto handle = requestContext(AcquireMode::Metadata); - handle.submitSync([&](smb2_context* ctx) { - struct smb2_stat_64 st; - const int result = smb2_stat(ctx, norm.c_str(), &st); - if (result < 0) { - SmbException::raiseFromSmb(ctx, result, "Delete Failed: Could not stat '" + path_ + "'. Error: " + smb2_get_error(ctx)); - } - isDirectory = (st.smb2_type & SMB2_TYPE_DIRECTORY) != 0; - }); - } + handle.submitSync([&](smb2_context* ctx) { + struct smb2_stat_64 st; + const int result = smb2_stat(ctx, norm.c_str(), &st); + if (result < 0) { + SmbException::raiseFromSmb(ctx, result, "Delete Failed: Could not stat '" + path_ + "'. Error: " + smb2_get_error(ctx)); + } + isDirectory = (st.smb2_type & SMB2_TYPE_DIRECTORY) != 0; + }); if (!isDirectory) { - auto handle = requestContext(AcquireMode::Metadata); handle.submitSync([&](smb2_context* ctx) { const int r = smb2_unlink(ctx, norm.c_str()); if (r < 0) SmbException::raiseFromSmb(ctx, r, "Failed to delete file '" + path_ + "': " + smb2_get_error(ctx)); @@ -111,20 +108,17 @@ void DeleteItemOperator::run() { return; } - { - listing::DirectoryListOptions options; - options.maxDepth = -1; - options.countChildren = false; - auto handle = requestContext(AcquireMode::Metadata); - handle.submitSync([&](smb2_context* ctx) { - const std::vector tree = listing::listOnCtx(ctx, handle.manager(), path_, options, token); - if (isCancelled()) return; - PipelinedOps ops(ctx, handle.manager(), token, kMaxDeletesInFlight, "Delete Failed"); - TreeDeleter deleter(ops); - deleter.deleteFolder(path_, tree); - ops.run(); - }); - } + listing::DirectoryListOptions options; + options.maxDepth = -1; + options.countChildren = false; + handle.submitSync([&](smb2_context* ctx) { + const std::vector tree = listing::listOnCtx(ctx, handle.manager(), path_, options, token); + if (isCancelled()) return; + PipelinedOps ops(ctx, handle.manager(), token, kMaxDeletesInFlight, "Delete Failed"); + TreeDeleter deleter(ops); + deleter.deleteFolder(path_, tree); + ops.run(); + }); if (isCancelled()) { emitStatus(SmbTaskStatus::Cancelled); return; From 99ee1b657147565549ce62ff14b27f7264686601 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:18:37 +0800 Subject: [PATCH 5/9] fix(pool): queue listShares as a normal Interactive request listShares was the only request that could not add a slot. When it reached the head of the queue with every slot busy, tryAssignNext stopped there, and growable requests behind it waited even though the pool could open another slot. The operator now requests a context like any other Interactive operation. - ListSharesOperator enumerates through the granted handle's manager - remove SmbConnectionPool::listShares and canGrowPoolSlot --- cpp/shared/connection/SmbConnectionPool.cpp | 7 +------ cpp/shared/connection/SmbConnectionPool.hpp | 1 - cpp/shared/core/SmbEnums.hpp | 16 ---------------- .../operators/connection/ListSharesOperator.cpp | 5 +++-- 4 files changed, 4 insertions(+), 25 deletions(-) diff --git a/cpp/shared/connection/SmbConnectionPool.cpp b/cpp/shared/connection/SmbConnectionPool.cpp index 72f2981..0eea657 100644 --- a/cpp/shared/connection/SmbConnectionPool.cpp +++ b/cpp/shared/connection/SmbConnectionPool.cpp @@ -97,7 +97,7 @@ void SmbConnectionPool::tryAssignNext() { if (!req) break; slotIdx = findIdleSlot(req->mode); - if (slotIdx == SIZE_MAX && canGrowPoolSlot(req->kind)) slotIdx = maybeGrowSlot(); + if (slotIdx == SIZE_MAX) slotIdx = maybeGrowSlot(); if (slotIdx == SIZE_MAX) { queue_.requeueFront(std::move(req)); break; @@ -399,11 +399,6 @@ void SmbConnectionPool::resetPool() { notifyObservers(); } -std::vector SmbConnectionPool::listShares(const std::string& taskId) { - auto handle = requestContext(AcquireMode::Interactive, SmbOperatorKind::ListShares, taskId); - return handle.manager().listShares(taskId); -} - bool SmbConnectionPool::isConnected() const { std::lock_guard lock(mutex_); return primarySlot().manager() && primarySlot().manager()->isConnected(); diff --git a/cpp/shared/connection/SmbConnectionPool.hpp b/cpp/shared/connection/SmbConnectionPool.hpp index 6e72e04..8d6ea3a 100644 --- a/cpp/shared/connection/SmbConnectionPool.hpp +++ b/cpp/shared/connection/SmbConnectionPool.hpp @@ -41,7 +41,6 @@ class SmbConnectionPool { void connectShare(const std::string& share, const std::string& taskId = "", const CancellationToken& cancel = {}); void disconnect(const std::string& taskId = "", const CancellationToken& cancel = {}); void resetPool(); - std::vector listShares(const std::string& taskId = ""); // [context] PoolContextHandle requestContext(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId = ""); diff --git a/cpp/shared/core/SmbEnums.hpp b/cpp/shared/core/SmbEnums.hpp index 162cc31..94d24b3 100644 --- a/cpp/shared/core/SmbEnums.hpp +++ b/cpp/shared/core/SmbEnums.hpp @@ -104,22 +104,6 @@ constexpr bool isTransferKind(SmbOperatorKind k) { } } -// Connection/session lifecycle ops stay on the primary path and must not grow -// the pool. Listing, transfers, and mutations may create a general slot when -// no idle slot is available (up to maxConnections). -constexpr bool canGrowPoolSlot(SmbOperatorKind k) { - switch (k) { - case SmbOperatorKind::Initialize: - case SmbOperatorKind::Connect: - case SmbOperatorKind::ConnectShare: - case SmbOperatorKind::Disconnect: - case SmbOperatorKind::ListShares: - return false; - default: - return true; - } -} - // Lowercase status name for the JS bridge. Index mirrors SmbTaskStatus. constexpr const char* statusName(SmbTaskStatus s) { switch (s) { diff --git a/cpp/shared/operators/connection/ListSharesOperator.cpp b/cpp/shared/operators/connection/ListSharesOperator.cpp index e51ea84..5c16261 100644 --- a/cpp/shared/operators/connection/ListSharesOperator.cpp +++ b/cpp/shared/operators/connection/ListSharesOperator.cpp @@ -1,11 +1,12 @@ #include "ListSharesOperator.hpp" -#include "../../connection/SmbConnectionPool.hpp" +#include "../../connection/SmbConnection.hpp" namespace react_native_smb { void ListSharesOperator::run() { - result_ = pool().listShares(owningTaskId()); + auto handle = requestContext(AcquireMode::Interactive); + result_ = handle.manager().listShares(owningTaskId()); publishThisResult(); emitStatus(SmbTaskStatus::Success); } From f383429e2bfd224cd82cfa7dd900dde2286e37f1 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:21:54 +0800 Subject: [PATCH 6/9] refactor(operators): acquire the context before run Each operator called requestContext inside run(), so its mode was only known once the operator was already running. Operators now declare their mode, and the task acquires the slot before run() and hands it over through context(). Argument checks and task paths move to prepare(), so they still happen before the task waits for a slot. - add acquireMode(); nullopt marks lifecycle operators - listDirectory picks Interactive or Metadata from maxDepth - add prepare() for validation and setSourceDestination, without SMB I/O - remove OperatorBase::requestContext; operators use context() --- cpp/shared/core/OperatorContext.hpp | 13 +++++++----- cpp/shared/core/SmbTask.cpp | 12 ++++++++++- cpp/shared/operators/OperatorBase.cpp | 19 ++++++++++-------- cpp/shared/operators/OperatorBase.hpp | 15 +++++++++----- .../operators/connection/ConnectOperator.hpp | 1 + .../connection/ConnectShareOperator.hpp | 1 + .../connection/DisconnectOperator.hpp | 1 + .../connection/InitializeOperator.hpp | 1 + .../connection/ListSharesOperator.cpp | 2 +- .../connection/ListSharesOperator.hpp | 1 + .../operators/listing/GetPathInfoOperator.cpp | 2 +- .../operators/listing/GetPathInfoOperator.hpp | 1 + .../listing/GetSecurityDescriptorOperator.cpp | 2 +- .../listing/GetSecurityDescriptorOperator.hpp | 1 + .../listing/ListDirectoryOperator.cpp | 2 +- .../listing/ListDirectoryOperator.hpp | 1 + .../operators/mutate/CopyItemOperator.cpp | 5 +++-- .../operators/mutate/CopyItemOperator.hpp | 2 ++ .../mutate/CreateDirectoryOperator.cpp | 2 +- .../mutate/CreateDirectoryOperator.hpp | 1 + .../operators/mutate/DeleteItemOperator.cpp | 16 ++++++++------- .../operators/mutate/DeleteItemOperator.hpp | 3 +++ .../mutate/DuplicateItemOperator.cpp | 16 +++++++-------- .../mutate/DuplicateItemOperator.hpp | 3 +++ .../operators/mutate/MoveItemOperator.cpp | 20 +++++++++---------- .../operators/mutate/MoveItemOperator.hpp | 4 ++++ .../operators/mutate/RenameItemOperator.cpp | 18 ++++++++--------- .../operators/mutate/RenameItemOperator.hpp | 4 ++++ .../transfer/DownloadFileOperator.cpp | 16 +++++++-------- .../transfer/DownloadFileOperator.hpp | 4 ++++ .../operators/transfer/UploadFileOperator.cpp | 16 +++++++-------- .../operators/transfer/UploadFileOperator.hpp | 4 ++++ 32 files changed, 131 insertions(+), 78 deletions(-) diff --git a/cpp/shared/core/OperatorContext.hpp b/cpp/shared/core/OperatorContext.hpp index f6a34ca..b897d25 100644 --- a/cpp/shared/core/OperatorContext.hpp +++ b/cpp/shared/core/OperatorContext.hpp @@ -6,15 +6,18 @@ namespace react_native_smb { class SmbTask; class SmbConnectionPool; +class PoolContextHandle; -// Everything an operator needs, injected by OperatorBase::start() before run(). +// Everything an operator needs, injected by the owning task before run(). // - task : back-pointer to report status/progress -// - pool : connection pool; op calls requestContext() when it needs a slot +// - pool : connection pool; lifecycle operators drive its transitions // - cancel : shared token the operator polls in its loop +// - context : slot granted before run(); null for lifecycle operators struct OperatorContext { - SmbTask* task{nullptr}; // non-owning - SmbConnectionPool* pool{nullptr}; // non-owning - CancellationToken cancel; // shared with the task + SmbTask* task{nullptr}; // non-owning + SmbConnectionPool* pool{nullptr}; // non-owning + CancellationToken cancel; // shared with the task + PoolContextHandle* context{nullptr}; // non-owning }; } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.cpp b/cpp/shared/core/SmbTask.cpp index 311d181..bcadaaa 100644 --- a/cpp/shared/core/SmbTask.cpp +++ b/cpp/shared/core/SmbTask.cpp @@ -1,5 +1,7 @@ #include "SmbTask.hpp" +#include + #include "../connection/SmbConnectionPool.hpp" #include "../operators/OperatorBase.hpp" #include "../util/SmbErrorMapper.hpp" @@ -32,7 +34,15 @@ void SmbTask::run() { } } else if (!cancel_.cancelled()) { try { - op_->start(this, pool.get(), cancel_); + op_->attach(this, pool.get(), cancel_); + op_->prepare(); + std::optional context; + if (const auto mode = op_->acquireMode()) { + markPending(); + context = pool->requestContext(*mode, getKind(), getId()); + markRunning(); + } + op_->start(context ? &*context : nullptr); } catch (const SmbException& e) { if (e.code() == SmbErrorCode::Cancelled) { SmbTaskCore::cancel(); diff --git a/cpp/shared/operators/OperatorBase.cpp b/cpp/shared/operators/OperatorBase.cpp index e1705d8..a36d3fc 100644 --- a/cpp/shared/operators/OperatorBase.cpp +++ b/cpp/shared/operators/OperatorBase.cpp @@ -2,22 +2,25 @@ #include "../connection/SmbConnectionPool.hpp" #include "../core/SmbTask.hpp" +#include "../util/SmbException.hpp" namespace react_native_smb { -void OperatorBase::start(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel) { - setContext(OperatorContext{task, pool, cancel}); - if (cancel.cancelled()) return; +void OperatorBase::attach(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel) { + ctx_ = OperatorContext{task, pool, cancel}; +} + +void OperatorBase::start(PoolContextHandle* context) { + ctx_.context = context; + if (isCancelled()) return; run(); } std::string OperatorBase::owningTaskId() const { return ctx_.task ? ctx_.task->getId() : std::string(); } -PoolContextHandle OperatorBase::requestContext(AcquireMode mode) { - if (ctx_.task) ctx_.task->markPending(); - PoolContextHandle handle = pool().requestContext(mode, kind(), owningTaskId()); - if (ctx_.task && !isCancelled()) ctx_.task->markRunning(); - return handle; +PoolContextHandle& OperatorBase::context() const { + if (!ctx_.context) SmbException::raise(SmbErrorCode::NotConnected, "operator has no pool context"); + return *ctx_.context; } void OperatorBase::emitStatus(SmbTaskStatus s, const std::string& error, int code) { diff --git a/cpp/shared/operators/OperatorBase.hpp b/cpp/shared/operators/OperatorBase.hpp index d508738..18d8e6e 100644 --- a/cpp/shared/operators/OperatorBase.hpp +++ b/cpp/shared/operators/OperatorBase.hpp @@ -2,8 +2,8 @@ #include #include +#include #include -#include #include "../connection/PoolContextHandle.hpp" #include "../connection/PoolTypes.hpp" @@ -23,11 +23,16 @@ class OperatorBase { public: virtual ~OperatorBase() = default; - virtual void run() = 0; virtual SmbOperatorKind kind() const = 0; + // Slot the task acquires before run(); nullopt for lifecycle operators, which run without one. + virtual std::optional acquireMode() const = 0; + // Validates arguments and records task paths before the task waits for a slot. No SMB I/O. + virtual void prepare() {} + virtual void run() = 0; - void setContext(const OperatorContext& ctx) { ctx_ = ctx; } - void start(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel); + void attach(SmbTask* task, SmbConnectionPool* pool, const CancellationToken& cancel); + // Runs the operator on the granted slot (null for lifecycle operators). + void start(PoolContextHandle* context); protected: void emitStatus(SmbTaskStatus s, const std::string& error = "", int code = 0); @@ -37,7 +42,7 @@ class OperatorBase { const CancellationToken& cancelToken() const { return ctx_.cancel; } SmbConnectionPool& pool() const { return *ctx_.pool; } - PoolContextHandle requestContext(AcquireMode mode); + PoolContextHandle& context() const; std::string owningTaskId() const; void addExpectedBytes(int64_t bytes); diff --git a/cpp/shared/operators/connection/ConnectOperator.hpp b/cpp/shared/operators/connection/ConnectOperator.hpp index 021c53f..576ab6b 100644 --- a/cpp/shared/operators/connection/ConnectOperator.hpp +++ b/cpp/shared/operators/connection/ConnectOperator.hpp @@ -12,6 +12,7 @@ class ConnectOperator : public Operator { ConnectOperator(std::string url, SmbCredentials credentials) : url_(std::move(url)), credentials_(std::move(credentials)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::Connect; } + std::optional acquireMode() const override { return std::nullopt; } void run() override; private: diff --git a/cpp/shared/operators/connection/ConnectShareOperator.hpp b/cpp/shared/operators/connection/ConnectShareOperator.hpp index c66ea71..b3ba75c 100644 --- a/cpp/shared/operators/connection/ConnectShareOperator.hpp +++ b/cpp/shared/operators/connection/ConnectShareOperator.hpp @@ -12,6 +12,7 @@ class ConnectShareOperator : public Operator { explicit ConnectShareOperator(std::string share) : share_(std::move(share)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::ConnectShare; } + std::optional acquireMode() const override { return std::nullopt; } void run() override; private: diff --git a/cpp/shared/operators/connection/DisconnectOperator.hpp b/cpp/shared/operators/connection/DisconnectOperator.hpp index 3e29045..17e0684 100644 --- a/cpp/shared/operators/connection/DisconnectOperator.hpp +++ b/cpp/shared/operators/connection/DisconnectOperator.hpp @@ -9,6 +9,7 @@ class DisconnectOperator : public OperatorBase { DisconnectOperator() = default; SmbOperatorKind kind() const override { return SmbOperatorKind::Disconnect; } + std::optional acquireMode() const override { return std::nullopt; } void run() override; }; diff --git a/cpp/shared/operators/connection/InitializeOperator.hpp b/cpp/shared/operators/connection/InitializeOperator.hpp index 0598fbe..4e7655b 100644 --- a/cpp/shared/operators/connection/InitializeOperator.hpp +++ b/cpp/shared/operators/connection/InitializeOperator.hpp @@ -12,6 +12,7 @@ class InitializeOperator : public OperatorBase { InitializeOperator(std::string url, SmbCredentials credentials) : url_(std::move(url)), credentials_(std::move(credentials)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::Initialize; } + std::optional acquireMode() const override { return std::nullopt; } void run() override; private: diff --git a/cpp/shared/operators/connection/ListSharesOperator.cpp b/cpp/shared/operators/connection/ListSharesOperator.cpp index 5c16261..eddbc43 100644 --- a/cpp/shared/operators/connection/ListSharesOperator.cpp +++ b/cpp/shared/operators/connection/ListSharesOperator.cpp @@ -5,7 +5,7 @@ namespace react_native_smb { void ListSharesOperator::run() { - auto handle = requestContext(AcquireMode::Interactive); + auto& handle = context(); result_ = handle.manager().listShares(owningTaskId()); publishThisResult(); emitStatus(SmbTaskStatus::Success); diff --git a/cpp/shared/operators/connection/ListSharesOperator.hpp b/cpp/shared/operators/connection/ListSharesOperator.hpp index d43f936..c0db779 100644 --- a/cpp/shared/operators/connection/ListSharesOperator.hpp +++ b/cpp/shared/operators/connection/ListSharesOperator.hpp @@ -12,6 +12,7 @@ class ListSharesOperator : public Operator> { ListSharesOperator() = default; SmbOperatorKind kind() const override { return SmbOperatorKind::ListShares; } + std::optional acquireMode() const override { return AcquireMode::Interactive; } void run() override; }; diff --git a/cpp/shared/operators/listing/GetPathInfoOperator.cpp b/cpp/shared/operators/listing/GetPathInfoOperator.cpp index 4ef87c7..68cf7f0 100644 --- a/cpp/shared/operators/listing/GetPathInfoOperator.cpp +++ b/cpp/shared/operators/listing/GetPathInfoOperator.cpp @@ -37,7 +37,7 @@ void onStat(smb2_context* smb2, int status, void* /*commandData*/, void* private void GetPathInfoOperator::run() { const std::string norm = path_util::normalized(path_); const CancellationToken token = cancelToken(); - auto handle = requestContext(AcquireMode::Interactive); + auto& handle = context(); SmbFileInfo info = handle.submitSync([&](smb2_context* ctx) { StatQuery stat; diff --git a/cpp/shared/operators/listing/GetPathInfoOperator.hpp b/cpp/shared/operators/listing/GetPathInfoOperator.hpp index 24d47bf..6bdc5aa 100644 --- a/cpp/shared/operators/listing/GetPathInfoOperator.hpp +++ b/cpp/shared/operators/listing/GetPathInfoOperator.hpp @@ -12,6 +12,7 @@ class GetPathInfoOperator : public Operator { explicit GetPathInfoOperator(std::string path) : path_(std::move(path)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::GetPathInfo; } + std::optional acquireMode() const override { return AcquireMode::Interactive; } void run() override; private: diff --git a/cpp/shared/operators/listing/GetSecurityDescriptorOperator.cpp b/cpp/shared/operators/listing/GetSecurityDescriptorOperator.cpp index e8b9cce..e4b3e68 100644 --- a/cpp/shared/operators/listing/GetSecurityDescriptorOperator.cpp +++ b/cpp/shared/operators/listing/GetSecurityDescriptorOperator.cpp @@ -8,7 +8,7 @@ namespace react_native_smb { void GetSecurityDescriptorOperator::run() { emitStatus(SmbTaskStatus::Running); - auto handle = requestContext(AcquireMode::Interactive); + auto& handle = context(); result_ = handle.submitSync([&](smb2_context* ctx) { return querySecurityDescriptorOnCtx(ctx, path_, handle.manager()); }); publishThisResult(); diff --git a/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp b/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp index 88df6dd..fdf4afc 100644 --- a/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp +++ b/cpp/shared/operators/listing/GetSecurityDescriptorOperator.hpp @@ -13,6 +13,7 @@ class GetSecurityDescriptorOperator : public Operator { explicit GetSecurityDescriptorOperator(std::string path) : path_(std::move(path)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::GetSecurityDescriptor; } + std::optional acquireMode() const override { return AcquireMode::Interactive; } void run() override; private: diff --git a/cpp/shared/operators/listing/ListDirectoryOperator.cpp b/cpp/shared/operators/listing/ListDirectoryOperator.cpp index 76cddcc..df736d9 100644 --- a/cpp/shared/operators/listing/ListDirectoryOperator.cpp +++ b/cpp/shared/operators/listing/ListDirectoryOperator.cpp @@ -19,7 +19,7 @@ void ListDirectoryOperator::run() { options.includeSecurityDescriptor = includeSecurityDescriptor_; if (batchSize_ > 0) options.minBatch = static_cast(batchSize_); - auto handle = requestContext(maxDepth_ == 0 ? AcquireMode::Interactive : AcquireMode::Metadata); + auto& handle = context(); handle.submitSync([&](smb2_context* ctx) { listing::DirectoryLister lister(ctx, handle.manager(), path_, options, cancelToken(), [&stream](std::vector&& batch) { stream->append(std::move(batch)); }); diff --git a/cpp/shared/operators/listing/ListDirectoryOperator.hpp b/cpp/shared/operators/listing/ListDirectoryOperator.hpp index 8da77b4..84465d0 100644 --- a/cpp/shared/operators/listing/ListDirectoryOperator.hpp +++ b/cpp/shared/operators/listing/ListDirectoryOperator.hpp @@ -16,6 +16,7 @@ class ListDirectoryOperator : public OperatorBase { : path_(std::move(path)), maxDepth_(maxDepth), includeSecurityDescriptor_(includeSecurityDescriptor), batchSize_(batchSize) {} SmbOperatorKind kind() const override { return SmbOperatorKind::ListDirectory; } + std::optional acquireMode() const override { return maxDepth_ == 0 ? AcquireMode::Interactive : AcquireMode::Metadata; } void run() override; private: diff --git a/cpp/shared/operators/mutate/CopyItemOperator.cpp b/cpp/shared/operators/mutate/CopyItemOperator.cpp index ef5bb13..2d916d3 100644 --- a/cpp/shared/operators/mutate/CopyItemOperator.cpp +++ b/cpp/shared/operators/mutate/CopyItemOperator.cpp @@ -4,9 +4,10 @@ namespace react_native_smb { +void CopyItemOperator::prepare() { setSourceDestination(fromPath_, toPath_); } + void CopyItemOperator::run() { - setSourceDestination(fromPath_, toPath_); - auto handle = requestContext(AcquireMode::Metadata); + auto& handle = context(); copyTreeImpl(handle, fromPath_, toPath_, recursive_, cancelToken(), [this](double done, double total) { emitProgress(done, total); }, [this](int64_t n) { addExpectedBytes(n); }); if (isCancelled()) { diff --git a/cpp/shared/operators/mutate/CopyItemOperator.hpp b/cpp/shared/operators/mutate/CopyItemOperator.hpp index 56d2dc2..1664458 100644 --- a/cpp/shared/operators/mutate/CopyItemOperator.hpp +++ b/cpp/shared/operators/mutate/CopyItemOperator.hpp @@ -14,6 +14,8 @@ class CopyItemOperator : public OperatorBase { CopyItemOperator(std::string fromPath, std::string toPath, bool recursive = true) : fromPath_(std::move(fromPath)), toPath_(std::move(toPath)), recursive_(recursive) {} SmbOperatorKind kind() const override { return SmbOperatorKind::CopyItem; } + std::optional acquireMode() const override { return AcquireMode::Metadata; } + void prepare() override; void run() override; private: diff --git a/cpp/shared/operators/mutate/CreateDirectoryOperator.cpp b/cpp/shared/operators/mutate/CreateDirectoryOperator.cpp index 6d55272..9568211 100644 --- a/cpp/shared/operators/mutate/CreateDirectoryOperator.cpp +++ b/cpp/shared/operators/mutate/CreateDirectoryOperator.cpp @@ -12,7 +12,7 @@ namespace react_native_smb { void CreateDirectoryOperator::run() { const std::string norm = path_util::normalized(path_); - auto handle = requestContext(AcquireMode::Interactive); + auto& handle = context(); handle.submitSync([&](smb2_context* ctx) { const int r = smb2_mkdir(ctx, norm.c_str()); diff --git a/cpp/shared/operators/mutate/CreateDirectoryOperator.hpp b/cpp/shared/operators/mutate/CreateDirectoryOperator.hpp index efb8220..384351d 100644 --- a/cpp/shared/operators/mutate/CreateDirectoryOperator.hpp +++ b/cpp/shared/operators/mutate/CreateDirectoryOperator.hpp @@ -11,6 +11,7 @@ class CreateDirectoryOperator : public OperatorBase { explicit CreateDirectoryOperator(std::string path) : path_(std::move(path)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::CreateDirectory; } + std::optional acquireMode() const override { return AcquireMode::Interactive; } void run() override; private: diff --git a/cpp/shared/operators/mutate/DeleteItemOperator.cpp b/cpp/shared/operators/mutate/DeleteItemOperator.cpp index edfc630..70279f1 100644 --- a/cpp/shared/operators/mutate/DeleteItemOperator.cpp +++ b/cpp/shared/operators/mutate/DeleteItemOperator.cpp @@ -82,17 +82,19 @@ class TreeDeleter { }; } // namespace +void DeleteItemOperator::prepare() { + norm_ = path_util::normalized(path_); + if (norm_.empty()) SmbException::raise(SmbErrorCode::InvalidArgument, "Delete Failed: refusing to delete the share root"); + setSourceDestination(norm_, ""); +} + void DeleteItemOperator::run() { const CancellationToken token = cancelToken(); - const std::string norm = path_util::normalized(path_); - if (norm.empty()) SmbException::raise(SmbErrorCode::InvalidArgument, "Delete Failed: refusing to delete the share root"); - setSourceDestination(norm, ""); - - auto handle = requestContext(AcquireMode::Metadata); + auto& handle = context(); bool isDirectory = false; handle.submitSync([&](smb2_context* ctx) { struct smb2_stat_64 st; - const int result = smb2_stat(ctx, norm.c_str(), &st); + const int result = smb2_stat(ctx, norm_.c_str(), &st); if (result < 0) { SmbException::raiseFromSmb(ctx, result, "Delete Failed: Could not stat '" + path_ + "'. Error: " + smb2_get_error(ctx)); } @@ -101,7 +103,7 @@ void DeleteItemOperator::run() { if (!isDirectory) { handle.submitSync([&](smb2_context* ctx) { - const int r = smb2_unlink(ctx, norm.c_str()); + const int r = smb2_unlink(ctx, norm_.c_str()); if (r < 0) SmbException::raiseFromSmb(ctx, r, "Failed to delete file '" + path_ + "': " + smb2_get_error(ctx)); }); emitStatus(SmbTaskStatus::Success); diff --git a/cpp/shared/operators/mutate/DeleteItemOperator.hpp b/cpp/shared/operators/mutate/DeleteItemOperator.hpp index c330125..b3a891d 100644 --- a/cpp/shared/operators/mutate/DeleteItemOperator.hpp +++ b/cpp/shared/operators/mutate/DeleteItemOperator.hpp @@ -14,10 +14,13 @@ class DeleteItemOperator : public OperatorBase { explicit DeleteItemOperator(std::string path) : path_(std::move(path)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::DeleteItem; } + std::optional acquireMode() const override { return AcquireMode::Metadata; } + void prepare() override; void run() override; private: std::string path_; + std::string norm_; }; } // namespace react_native_smb diff --git a/cpp/shared/operators/mutate/DuplicateItemOperator.cpp b/cpp/shared/operators/mutate/DuplicateItemOperator.cpp index 26e1f11..550032f 100644 --- a/cpp/shared/operators/mutate/DuplicateItemOperator.cpp +++ b/cpp/shared/operators/mutate/DuplicateItemOperator.cpp @@ -12,19 +12,17 @@ namespace react_native_smb { +void DuplicateItemOperator::prepare() { + sourcePath_ = path_util::normalized(path_); + setSourceDestination(sourcePath_, sourcePath_); +} + void DuplicateItemOperator::run() { const CancellationToken token = cancelToken(); - - const std::string sourcePath = path_util::normalized(path_); + const std::string& sourcePath = sourcePath_; const std::string parentPath = path_util::parentOf(sourcePath); const std::string fileName = path_util::extractFileName(sourcePath); - setSourceDestination(sourcePath, sourcePath); - - auto handle = requestContext(AcquireMode::Metadata); - if (isCancelled()) { - emitStatus(SmbTaskStatus::Cancelled); - return; - } + auto& handle = context(); const CopyTreeSourceInfo source = inspectCopyTreeSource(handle, sourcePath, /*recursive=*/true, token); constexpr int kMaxRootClaimRetries = 64; diff --git a/cpp/shared/operators/mutate/DuplicateItemOperator.hpp b/cpp/shared/operators/mutate/DuplicateItemOperator.hpp index 6f225f0..17abb53 100644 --- a/cpp/shared/operators/mutate/DuplicateItemOperator.hpp +++ b/cpp/shared/operators/mutate/DuplicateItemOperator.hpp @@ -14,10 +14,13 @@ class DuplicateItemOperator : public Operator { explicit DuplicateItemOperator(std::string path) : path_(std::move(path)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::DuplicateItem; } + std::optional acquireMode() const override { return AcquireMode::Metadata; } + void prepare() override; void run() override; private: std::string path_; + std::string sourcePath_; }; } // namespace react_native_smb diff --git a/cpp/shared/operators/mutate/MoveItemOperator.cpp b/cpp/shared/operators/mutate/MoveItemOperator.cpp index ed5395a..42f7f2a 100644 --- a/cpp/shared/operators/mutate/MoveItemOperator.cpp +++ b/cpp/shared/operators/mutate/MoveItemOperator.cpp @@ -9,21 +9,21 @@ namespace react_native_smb { -void MoveItemOperator::run() { - - const std::string from = path_util::normalized(fromPath_); - const std::string to = path_util::normalized(toPath_); - if (from.empty()) SmbException::raise(SmbErrorCode::InvalidArgument, "Move Failed: refusing to move the share root"); - if (path_util::isDescendant(from, to)) { +void MoveItemOperator::prepare() { + from_ = path_util::normalized(fromPath_); + to_ = path_util::normalized(toPath_); + if (from_.empty()) SmbException::raise(SmbErrorCode::InvalidArgument, "Move Failed: refusing to move the share root"); + if (path_util::isDescendant(from_, to_)) { SmbException::raise(SmbErrorCode::InvalidArgument, "Move Failed: destination cannot be inside the source directory"); } + setSourceDestination(from_, to_); +} - setSourceDestination(from, to); - - auto handle = requestContext(AcquireMode::Interactive); +void MoveItemOperator::run() { + auto& handle = context(); handle.submitSync([&](smb2_context* ctx) { - const int r = smb2_rename(ctx, from.c_str(), to.c_str()); + const int r = smb2_rename(ctx, from_.c_str(), to_.c_str()); if (r < 0) { SmbException::raiseFromSmb(ctx, r, "Move Failed: Could not move '" + fromPath_ + "' to '" + toPath_ + "'. Error: " + smb2_get_error(ctx)); } diff --git a/cpp/shared/operators/mutate/MoveItemOperator.hpp b/cpp/shared/operators/mutate/MoveItemOperator.hpp index 53f3766..eba49ef 100644 --- a/cpp/shared/operators/mutate/MoveItemOperator.hpp +++ b/cpp/shared/operators/mutate/MoveItemOperator.hpp @@ -11,11 +11,15 @@ class MoveItemOperator : public OperatorBase { MoveItemOperator(std::string fromPath, std::string toPath) : fromPath_(std::move(fromPath)), toPath_(std::move(toPath)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::MoveItem; } + std::optional acquireMode() const override { return AcquireMode::Interactive; } + void prepare() override; void run() override; private: std::string fromPath_; std::string toPath_; + std::string from_; + std::string to_; }; } // namespace react_native_smb diff --git a/cpp/shared/operators/mutate/RenameItemOperator.cpp b/cpp/shared/operators/mutate/RenameItemOperator.cpp index dce1db4..59a614c 100644 --- a/cpp/shared/operators/mutate/RenameItemOperator.cpp +++ b/cpp/shared/operators/mutate/RenameItemOperator.cpp @@ -9,22 +9,20 @@ namespace react_native_smb { -void RenameItemOperator::run() { +void RenameItemOperator::prepare() { if (newName_.empty() || newName_.find('/') != std::string::npos || newName_.find('\\') != std::string::npos) { SmbException::raise(SmbErrorCode::InvalidArgument, "Rename Failed: invalid new name '" + newName_ + "'"); } + from_ = path_util::normalized(currentPath_); + to_ = path_util::normalized(path_util::buildUrl(path_util::parentOf(currentPath_), newName_)); + setSourceDestination(from_, to_); +} - - const std::string normCurrent = path_util::normalized(currentPath_); - const std::string parentDir = path_util::parentOf(currentPath_); - const std::string newPath = path_util::normalized(path_util::buildUrl(parentDir, newName_)); - - setSourceDestination(normCurrent, newPath); - - auto handle = requestContext(AcquireMode::Interactive); +void RenameItemOperator::run() { + auto& handle = context(); handle.submitSync([&](smb2_context* ctx) { - const int r = smb2_rename(ctx, normCurrent.c_str(), newPath.c_str()); + const int r = smb2_rename(ctx, from_.c_str(), to_.c_str()); if (r < 0) { SmbException::raiseFromSmb(ctx, r, "Rename Failed: Could not rename '" + currentPath_ + "' to '" + newName_ + "'. Error: " + smb2_get_error(ctx)); } diff --git a/cpp/shared/operators/mutate/RenameItemOperator.hpp b/cpp/shared/operators/mutate/RenameItemOperator.hpp index 98418fe..0349b40 100644 --- a/cpp/shared/operators/mutate/RenameItemOperator.hpp +++ b/cpp/shared/operators/mutate/RenameItemOperator.hpp @@ -11,11 +11,15 @@ class RenameItemOperator : public OperatorBase { RenameItemOperator(std::string currentPath, std::string newName) : currentPath_(std::move(currentPath)), newName_(std::move(newName)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::RenameItem; } + std::optional acquireMode() const override { return AcquireMode::Interactive; } + void prepare() override; void run() override; private: std::string currentPath_; std::string newName_; + std::string from_; + std::string to_; }; } // namespace react_native_smb diff --git a/cpp/shared/operators/transfer/DownloadFileOperator.cpp b/cpp/shared/operators/transfer/DownloadFileOperator.cpp index 31f57f4..9f06c34 100644 --- a/cpp/shared/operators/transfer/DownloadFileOperator.cpp +++ b/cpp/shared/operators/transfer/DownloadFileOperator.cpp @@ -6,19 +6,19 @@ namespace react_native_smb { -void DownloadFileOperator::run() { - - const std::string remote = path_util::normalized(remotePath_); - const std::string local = path_util::convertUriToPath(localPath_); - - setSourceDestination(remote, local); +void DownloadFileOperator::prepare() { + remote_ = path_util::normalized(remotePath_); + local_ = path_util::convertUriToPath(localPath_); + setSourceDestination(remote_, local_); +} - auto handle = requestContext(AcquireMode::Metadata); +void DownloadFileOperator::run() { + auto& handle = context(); const CancellationToken token = cancelToken(); handle.submitSync([&](smb2_context* ctx) { smbReadFileAsync( - ctx, handle.manager(), remote, local, owningTaskId(), [this](double done, double total) { emitProgress(done, total); }, token); + ctx, handle.manager(), remote_, local_, owningTaskId(), [this](double done, double total) { emitProgress(done, total); }, token); }); emitStatus(SmbTaskStatus::Success); diff --git a/cpp/shared/operators/transfer/DownloadFileOperator.hpp b/cpp/shared/operators/transfer/DownloadFileOperator.hpp index 8556257..a3af101 100644 --- a/cpp/shared/operators/transfer/DownloadFileOperator.hpp +++ b/cpp/shared/operators/transfer/DownloadFileOperator.hpp @@ -11,11 +11,15 @@ class DownloadFileOperator : public OperatorBase { DownloadFileOperator(std::string remotePath, std::string localPath) : remotePath_(std::move(remotePath)), localPath_(std::move(localPath)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::DownloadFile; } + std::optional acquireMode() const override { return AcquireMode::Metadata; } + void prepare() override; void run() override; private: std::string remotePath_; std::string localPath_; + std::string remote_; + std::string local_; }; } // namespace react_native_smb diff --git a/cpp/shared/operators/transfer/UploadFileOperator.cpp b/cpp/shared/operators/transfer/UploadFileOperator.cpp index 5030cb8..667c778 100644 --- a/cpp/shared/operators/transfer/UploadFileOperator.cpp +++ b/cpp/shared/operators/transfer/UploadFileOperator.cpp @@ -6,19 +6,19 @@ namespace react_native_smb { -void UploadFileOperator::run() { - - const std::string remote = path_util::normalized(remotePath_); - const std::string local = path_util::convertUriToPath(localPath_); - - setSourceDestination(local, remote); // local -> remote for upload +void UploadFileOperator::prepare() { + local_ = path_util::convertUriToPath(localPath_); + remote_ = path_util::normalized(remotePath_); + setSourceDestination(local_, remote_); // local -> remote for upload +} - auto handle = requestContext(AcquireMode::Metadata); +void UploadFileOperator::run() { + auto& handle = context(); const CancellationToken token = cancelToken(); handle.submitSync([&](smb2_context* ctx) { smbWriteFileAsync( - ctx, handle.manager(), local, remote, owningTaskId(), [this](double done, double total) { emitProgress(done, total); }, token); + ctx, handle.manager(), local_, remote_, owningTaskId(), [this](double done, double total) { emitProgress(done, total); }, token); }); emitStatus(SmbTaskStatus::Success); diff --git a/cpp/shared/operators/transfer/UploadFileOperator.hpp b/cpp/shared/operators/transfer/UploadFileOperator.hpp index d7ff4e0..cb1e06a 100644 --- a/cpp/shared/operators/transfer/UploadFileOperator.hpp +++ b/cpp/shared/operators/transfer/UploadFileOperator.hpp @@ -11,11 +11,15 @@ class UploadFileOperator : public OperatorBase { UploadFileOperator(std::string localPath, std::string remotePath) : localPath_(std::move(localPath)), remotePath_(std::move(remotePath)) {} SmbOperatorKind kind() const override { return SmbOperatorKind::UploadFile; } + std::optional acquireMode() const override { return AcquireMode::Metadata; } + void prepare() override; void run() override; private: std::string localPath_; std::string remotePath_; + std::string local_; + std::string remote_; }; } // namespace react_native_smb From 50f2697fe86ec0f74278913ae75fee48f0a19b6a Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:25:52 +0800 Subject: [PATCH 7/9] perf(pool): admit work at the pool instead of Nitro's thread pool Every work task first waited in Nitro's shared Promise::async queue, which has at most 10 threads and grows lazily, and then kept one of those threads blocked for its whole run. Under bulk work, interactive requests waited behind it before they reached the pool's interactive-first queue. Queue work only at the pool and start a thread once a slot is granted. - requestContext is asynchronous: it queues ContextCallbacks and returns at once - SlotReservation is a move-only handle to a reserved slot; activate() connects on the runner thread, never on the JS thread or a releasing thread - callbacks fire outside the pool mutex; cancel, drain, and NotConnected reject queued requests without starting a thread - SmbTask::prepare/run/reject replace the blocking run; lifecycle tasks run inline on the lifecycle thread - remove ExecutionLane and PoolSlot::accepts; startTask routes by acquireMode() - queued tasks now report Pending instead of Idle --- cpp/shared/bridge/HybridSMB.cpp | 96 +++++--- cpp/shared/bridge/HybridSMB.hpp | 13 +- cpp/shared/connection/ContextRequest.hpp | 11 +- cpp/shared/connection/ContextRequestQueue.cpp | 94 ++----- cpp/shared/connection/ContextRequestQueue.hpp | 14 +- cpp/shared/connection/PoolSlot.cpp | 5 - cpp/shared/connection/PoolSlot.hpp | 1 - cpp/shared/connection/SlotReservation.cpp | 23 ++ cpp/shared/connection/SlotReservation.hpp | 44 ++++ cpp/shared/connection/SmbConnectionPool.cpp | 231 ++++++++---------- cpp/shared/connection/SmbConnectionPool.hpp | 15 +- cpp/shared/core/LifecycleSerialExecutor.hpp | 4 +- cpp/shared/core/SmbTask.cpp | 72 ++++-- cpp/shared/core/SmbTask.hpp | 16 +- 14 files changed, 337 insertions(+), 302 deletions(-) create mode 100644 cpp/shared/connection/SlotReservation.cpp create mode 100644 cpp/shared/connection/SlotReservation.hpp diff --git a/cpp/shared/bridge/HybridSMB.cpp b/cpp/shared/bridge/HybridSMB.cpp index 03fb4b1..9eb0181 100644 --- a/cpp/shared/bridge/HybridSMB.cpp +++ b/cpp/shared/bridge/HybridSMB.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include "../connection/PoolTypes.hpp" @@ -29,6 +30,7 @@ namespace margelo::nitro::smb { +using react_native_smb::SlotReservation; using react_native_smb::SmbTask; using DomainTaskState = react_native_smb::SmbTaskState; using DomainPoolSlotInfo = react_native_smb::PoolSlotInfo; @@ -44,14 +46,13 @@ void HybridSMB::releaseTaskRun(const std::shared_ptr& state) { state->cv.notify_all(); } -template -std::shared_ptr HybridSMB::startTask(const std::string& taskId, std::unique_ptr seedOp, ExecutionLane lane) { +std::shared_ptr HybridSMB::startTask(const std::string& taskId, std::unique_ptr op) { std::lock_guard shutdownLock(shutdownMutex_); if (disposed_.load(std::memory_order_acquire)) { SmbException::raise(SmbErrorCode::NotConnected, "SMB client has been destroyed"); } - auto task = std::make_shared(taskId, std::move(seedOp), pool_); + auto task = std::make_shared(taskId, std::move(op), pool_); if (observer_) { observer_->track(task); } @@ -65,36 +66,53 @@ std::shared_ptr HybridSMB::startTask(const std::string& taskId, std::un std::lock_guard lock(taskRuns->mutex); ++taskRuns->active; } - - auto* self = this; - auto runBody = [self, task, taskId, taskRuns] { - struct RunCompletionGuard { - std::shared_ptr state; - ~RunCompletionGuard() { HybridSMB::releaseTaskRun(state); } - } guard{taskRuns}; - task->run(); + // Runs once per task, after it settles on any path. + auto finish = [self = this, taskId, taskRuns] { self->forgetTask(taskId); + releaseTaskRun(taskRuns); }; - try { - if (lane == ExecutionLane::Lifecycle) { - lifecycleExecutor_.post(std::move(runBody)); - } else { - (void)Promise::async(std::move(runBody)); + if (!task->prepare()) { + finish(); + return task; + } + + const auto mode = task->acquireMode(); + if (!mode) { + try { + lifecycleExecutor_.post([task, finish] { + task->run(std::nullopt); + finish(); + }); + } catch (...) { + finish(); + throw; } - } catch (...) { - releaseTaskRun(taskRuns); - forgetTask(taskId); - throw; + return task; } + task->markPending(); + pool_->requestContext(*mode, task->getKind(), taskId, + {[task, finish](SlotReservation reservation) { + try { + std::thread([task, finish, reservation = std::move(reservation)]() mutable { + task->run(std::move(reservation)); + finish(); + }).detach(); + } catch (const std::exception& e) { + task->reject(static_cast(SmbErrorCode::Unknown), e.what()); + finish(); + } + }, + [task, finish](int code, const std::string& message) { + task->reject(code, message); + finish(); + }}); return task; } -template -std::shared_ptr HybridSMB::createTask(const std::string& taskId, std::unique_ptr seedOp, - ExecutionLane lane) { - return std::make_shared(startTask(taskId, std::move(seedOp), lane)); +std::shared_ptr HybridSMB::createTask(const std::string& taskId, std::unique_ptr op) { + return std::make_shared(startTask(taskId, std::move(op))); } HybridSMB::HybridSMB() : HybridObject(TAG) { @@ -169,23 +187,23 @@ bool HybridSMB::isInitialized() { return pool_->isInitialized(); } // --- connection --- std::shared_ptr HybridSMB::initialize(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) { - return createTask(taskId, std::make_unique(url, fromBridge(credentials)), ExecutionLane::Lifecycle); + return createTask(taskId, std::make_unique(url, fromBridge(credentials))); } std::shared_ptr HybridSMB::connect(const std::string& taskId, const std::string& url, const SmbCredentials& credentials) { - return createTask(taskId, std::make_unique(url, fromBridge(credentials)), ExecutionLane::Lifecycle); + return createTask(taskId, std::make_unique(url, fromBridge(credentials))); } std::shared_ptr HybridSMB::disconnect(const std::string& taskId) { - return createTask(taskId, std::make_unique(), ExecutionLane::Lifecycle); + return createTask(taskId, std::make_unique()); } std::shared_ptr HybridSMB::listShares(const std::string& taskId) { - return createTask(taskId, std::make_unique()); + return createTask(taskId, std::make_unique()); } std::shared_ptr HybridSMB::connectShare(const std::string& taskId, const std::string& share) { - return createTask(taskId, std::make_unique(share), ExecutionLane::Lifecycle); + return createTask(taskId, std::make_unique(share)); } // --- listing --- @@ -195,45 +213,45 @@ std::shared_ptr HybridSMB::listDirectory(const std: } std::shared_ptr HybridSMB::getPathInfo(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); + return createTask(taskId, std::make_unique(path)); } std::shared_ptr HybridSMB::getSecurityDescriptor(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); + return createTask(taskId, std::make_unique(path)); } // --- transfer --- std::shared_ptr HybridSMB::downloadFile(const std::string& taskId, const std::string& remotePath, const std::string& localPath) { - return createTask(taskId, std::make_unique(remotePath, localPath)); + return createTask(taskId, std::make_unique(remotePath, localPath)); } std::shared_ptr HybridSMB::uploadFile(const std::string& taskId, const std::string& localPath, const std::string& remotePath) { - return createTask(taskId, std::make_unique(localPath, remotePath)); + return createTask(taskId, std::make_unique(localPath, remotePath)); } // --- mutate --- std::shared_ptr HybridSMB::createDirectory(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); + return createTask(taskId, std::make_unique(path)); } std::shared_ptr HybridSMB::deleteItem(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); + return createTask(taskId, std::make_unique(path)); } std::shared_ptr HybridSMB::moveItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath) { - return createTask(taskId, std::make_unique(fromPath, toPath)); + return createTask(taskId, std::make_unique(fromPath, toPath)); } std::shared_ptr HybridSMB::renameItem(const std::string& taskId, const std::string& currentPath, const std::string& newName) { - return createTask(taskId, std::make_unique(currentPath, newName)); + return createTask(taskId, std::make_unique(currentPath, newName)); } std::shared_ptr HybridSMB::copyItem(const std::string& taskId, const std::string& fromPath, const std::string& toPath, bool recursive) { - return createTask(taskId, std::make_unique(fromPath, toPath, recursive)); + return createTask(taskId, std::make_unique(fromPath, toPath, recursive)); } std::shared_ptr HybridSMB::duplicateItem(const std::string& taskId, const std::string& path) { - return createTask(taskId, std::make_unique(path)); + return createTask(taskId, std::make_unique(path)); } // --- tasks --- diff --git a/cpp/shared/bridge/HybridSMB.hpp b/cpp/shared/bridge/HybridSMB.hpp index 0e3b532..6f1e8d5 100644 --- a/cpp/shared/bridge/HybridSMB.hpp +++ b/cpp/shared/bridge/HybridSMB.hpp @@ -57,15 +57,10 @@ class HybridSMB : public HybridReactNativeSmbSpec { std::mutex poolListenersMutex_; std::atomic poolListenerToken_{1}; - enum class ExecutionLane { Shared, Lifecycle }; - - template - std::shared_ptr startTask(const std::string& taskId, std::unique_ptr seedOp, - ExecutionLane lane = ExecutionLane::Shared); - - template - std::shared_ptr createTask(const std::string& taskId, std::unique_ptr seedOp, - ExecutionLane lane = ExecutionLane::Shared); + // Work operators queue at the pool and run on their own thread once a slot + // is granted; lifecycle operators run on the lifecycle executor. + std::shared_ptr startTask(const std::string& taskId, std::unique_ptr op); + std::shared_ptr createTask(const std::string& taskId, std::unique_ptr op); public: HybridSMB(); diff --git a/cpp/shared/connection/ContextRequest.hpp b/cpp/shared/connection/ContextRequest.hpp index aee771a..33e9a20 100644 --- a/cpp/shared/connection/ContextRequest.hpp +++ b/cpp/shared/connection/ContextRequest.hpp @@ -2,27 +2,22 @@ #include #include -#include #include #include #include "PoolTypes.hpp" -#include "../util/SmbErrorMapper.hpp" +#include "SlotReservation.hpp" namespace react_native_smb { -class PoolContextHandle; - struct ContextRequest { uint64_t id{0}; AcquireMode mode{AcquireMode::Interactive}; SmbOperatorKind kind{SmbOperatorKind::Initialize}; std::string taskId; - std::promise promise; + ContextCallbacks callbacks; + // Set while the slot activates; the reservation then fails instead of assigning. std::atomic cancelled{false}; - std::atomic fulfilled{false}; - std::string errorMessage; - int errorCode{static_cast(SmbErrorCode::Unknown)}; }; using ContextRequestPtr = std::shared_ptr; diff --git a/cpp/shared/connection/ContextRequestQueue.cpp b/cpp/shared/connection/ContextRequestQueue.cpp index c7f4210..80ee527 100644 --- a/cpp/shared/connection/ContextRequestQueue.cpp +++ b/cpp/shared/connection/ContextRequestQueue.cpp @@ -1,56 +1,30 @@ #include "ContextRequestQueue.hpp" -#include "PoolContextHandle.hpp" -#include "../core/SmbEnums.hpp" +#include +#include +#include namespace react_native_smb { -size_t ContextRequestQueue::pendingCount() const { - return interactivePending_.size() + metadataPending_.size(); -} - -void ContextRequestQueue::drainCancelledFromHead(std::deque& queue) { - while (!queue.empty()) { - auto& front = queue.front(); - if (!front->cancelled.load(std::memory_order_acquire)) break; - if (!front->fulfilled.load(std::memory_order_acquire)) { - front->fulfilled.store(true, std::memory_order_release); - try { - front->promise.set_value(PoolContextHandle{}); - } catch (...) { - } - } - queue.pop_front(); - } -} - -ContextRequestPtr ContextRequestQueue::enqueue(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId) { +void ContextRequestQueue::enqueue(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId, ContextCallbacks callbacks) { auto req = std::make_shared(); req->id = nextId_++; req->mode = mode; req->kind = kind; req->taskId = taskId; + req->callbacks = std::move(callbacks); auto& queue = (mode == AcquireMode::Interactive) ? interactivePending_ : metadataPending_; - queue.push_back(req); - return req; + queue.push_back(std::move(req)); } ContextRequestPtr ContextRequestQueue::takeNext() { - drainCancelledFromHead(interactivePending_); - if (!interactivePending_.empty()) { - ContextRequestPtr out = std::move(interactivePending_.front()); - interactivePending_.pop_front(); - return out; - } - - drainCancelledFromHead(metadataPending_); - if (!metadataPending_.empty()) { - ContextRequestPtr out = std::move(metadataPending_.front()); - metadataPending_.pop_front(); + for (auto* queue : {&interactivePending_, &metadataPending_}) { + if (queue->empty()) continue; + ContextRequestPtr out = std::move(queue->front()); + queue->pop_front(); return out; } - return nullptr; } @@ -60,42 +34,22 @@ void ContextRequestQueue::requeueFront(ContextRequestPtr req) { queue.push_front(std::move(req)); } -void ContextRequestQueue::cancelForTask(const std::string& taskId) { - auto cancelIn = [&](std::deque& queue) { - for (auto& req : queue) { - if (req->taskId != taskId) continue; - if (req->fulfilled.load(std::memory_order_acquire)) continue; - req->cancelled.store(true, std::memory_order_release); - req->fulfilled.store(true, std::memory_order_release); - try { - req->promise.set_value(PoolContextHandle{}); - } catch (...) { - } - } - }; - cancelIn(interactivePending_); - cancelIn(metadataPending_); -} - -void ContextRequestQueue::cancelAll() { - auto cancelIn = [](std::deque& queue) { - for (auto& req : queue) { - if (req->fulfilled.load(std::memory_order_acquire)) continue; - req->cancelled.store(true, std::memory_order_release); - req->fulfilled.store(true, std::memory_order_release); - try { - req->promise.set_value(PoolContextHandle{}); - } catch (...) { - } - } - }; - cancelIn(interactivePending_); - cancelIn(metadataPending_); +std::vector ContextRequestQueue::takeForTask(const std::string& taskId) { + std::vector out; + for (auto* queue : {&interactivePending_, &metadataPending_}) { + auto matches = [&](const ContextRequestPtr& req) { return req->taskId == taskId; }; + std::copy_if(queue->begin(), queue->end(), std::back_inserter(out), matches); + queue->erase(std::remove_if(queue->begin(), queue->end(), matches), queue->end()); + } + return out; } -void ContextRequestQueue::removeCancelledFromHead() { - drainCancelledFromHead(interactivePending_); - drainCancelledFromHead(metadataPending_); +std::vector ContextRequestQueue::takeAll() { + std::vector out(interactivePending_.begin(), interactivePending_.end()); + out.insert(out.end(), metadataPending_.begin(), metadataPending_.end()); + interactivePending_.clear(); + metadataPending_.clear(); + return out; } } // namespace react_native_smb diff --git a/cpp/shared/connection/ContextRequestQueue.hpp b/cpp/shared/connection/ContextRequestQueue.hpp index dca062e..92b4812 100644 --- a/cpp/shared/connection/ContextRequestQueue.hpp +++ b/cpp/shared/connection/ContextRequestQueue.hpp @@ -3,24 +3,24 @@ #include #include #include +#include +#include #include "ContextRequest.hpp" namespace react_native_smb { +// Interactive-first FIFO of pending context requests. Not thread-safe; the pool guards it. class ContextRequestQueue { public: - ContextRequestPtr enqueue(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId); + void enqueue(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId, ContextCallbacks callbacks); ContextRequestPtr takeNext(); void requeueFront(ContextRequestPtr req); - void removeCancelledFromHead(); - void cancelForTask(const std::string& taskId); - void cancelAll(); + // Remove pending requests so the caller can reject them outside the lock. + std::vector takeForTask(const std::string& taskId); + std::vector takeAll(); private: - size_t pendingCount() const; - void drainCancelledFromHead(std::deque& queue); - std::deque interactivePending_; std::deque metadataPending_; uint64_t nextId_{1}; diff --git a/cpp/shared/connection/PoolSlot.cpp b/cpp/shared/connection/PoolSlot.cpp index 25536da..a3db4ec 100644 --- a/cpp/shared/connection/PoolSlot.cpp +++ b/cpp/shared/connection/PoolSlot.cpp @@ -4,11 +4,6 @@ namespace react_native_smb { PoolSlot::PoolSlot(size_t index) : index_(index), conn_(std::make_unique()) {} -bool PoolSlot::accepts(AcquireMode mode) const { - if (index_ == 0) return mode == AcquireMode::Interactive; - return true; -} - PoolSlotInfo PoolSlot::snapshot(size_t poolSize) const { PoolSlotInfo info; info.poolSize = poolSize; diff --git a/cpp/shared/connection/PoolSlot.hpp b/cpp/shared/connection/PoolSlot.hpp index c0a24a1..2869f4b 100644 --- a/cpp/shared/connection/PoolSlot.hpp +++ b/cpp/shared/connection/PoolSlot.hpp @@ -19,7 +19,6 @@ class PoolSlot { bool isInteractiveOnly() const { return index_ == 0; } bool isIdle() const { return state() == SlotState::Idle; } - bool accepts(AcquireMode mode) const; SmbConnectionManager* manager() { return conn_.get(); } const SmbConnectionManager* manager() const { return conn_.get(); } diff --git a/cpp/shared/connection/SlotReservation.cpp b/cpp/shared/connection/SlotReservation.cpp new file mode 100644 index 0000000..3e58680 --- /dev/null +++ b/cpp/shared/connection/SlotReservation.cpp @@ -0,0 +1,23 @@ +#include "SlotReservation.hpp" + +#include + +#include "SmbConnectionPool.hpp" + +namespace react_native_smb { + +SlotReservation::SlotReservation(SmbConnectionPool* pool, size_t slotIndex, std::shared_ptr request) + : pool_(pool), slotIndex_(slotIndex), request_(std::move(request)) {} + +SlotReservation::~SlotReservation() { + if (pool_) pool_->abandonReservation(slotIndex_, request_); +} + +SlotReservation::SlotReservation(SlotReservation&& o) noexcept + : pool_(std::exchange(o.pool_, nullptr)), slotIndex_(o.slotIndex_), request_(std::move(o.request_)) {} + +PoolContextHandle SlotReservation::activate() { + return std::exchange(pool_, nullptr)->activateReservation(slotIndex_, request_); +} + +} // namespace react_native_smb diff --git a/cpp/shared/connection/SlotReservation.hpp b/cpp/shared/connection/SlotReservation.hpp new file mode 100644 index 0000000..4e710a8 --- /dev/null +++ b/cpp/shared/connection/SlotReservation.hpp @@ -0,0 +1,44 @@ +#pragma once + +#include +#include +#include +#include + +#include "PoolContextHandle.hpp" + +namespace react_native_smb { + +class SmbConnectionPool; +struct ContextRequest; + +// A pool slot reserved for one request and marked Activating. The holder calls +// activate() on its own thread, so connecting a fresh slot never runs on the +// thread that queued or released work. Dropping it unactivated frees the slot. +class SlotReservation { + public: + SlotReservation(SmbConnectionPool* pool, size_t slotIndex, std::shared_ptr request); + ~SlotReservation(); + + SlotReservation(SlotReservation&& o) noexcept; + SlotReservation& operator=(SlotReservation&&) = delete; + SlotReservation(const SlotReservation&) = delete; + SlotReservation& operator=(const SlotReservation&) = delete; + + // Connects the slot if needed and assigns it. Throws when activation fails, + // the request was cancelled, or the pool is closing. + PoolContextHandle activate(); + + private: + SmbConnectionPool* pool_{nullptr}; + size_t slotIndex_{0}; + std::shared_ptr request_; +}; + +// Exactly one callback runs per request, never under the pool lock. +struct ContextCallbacks { + std::function onGranted; + std::function onRejected; +}; + +} // namespace react_native_smb diff --git a/cpp/shared/connection/SmbConnectionPool.cpp b/cpp/shared/connection/SmbConnectionPool.cpp index 0eea657..c6c7177 100644 --- a/cpp/shared/connection/SmbConnectionPool.cpp +++ b/cpp/shared/connection/SmbConnectionPool.cpp @@ -1,5 +1,6 @@ #include "SmbConnectionPool.hpp" +#include #include #include @@ -9,13 +10,9 @@ namespace react_native_smb { namespace { -bool fulfillRequest(const ContextRequestPtr& req, PoolContextHandle handle) { - if (!req || req->fulfilled.exchange(true, std::memory_order_acq_rel)) return false; - try { - req->promise.set_value(std::move(handle)); - return true; - } catch (...) { - return false; +void rejectRequests(const std::vector& requests, SmbErrorCode code, const std::string& message) { + for (const auto& req : requests) { + if (req->callbacks.onRejected) req->callbacks.onRejected(static_cast(code), message); } } } // namespace @@ -81,168 +78,139 @@ size_t SmbConnectionPool::maybeGrowSlot() { } void SmbConnectionPool::tryAssignNext() { - bool assigned = false; - for (;;) { - ContextRequestPtr req; - size_t slotIdx = SIZE_MAX; - bool needsActivate = false; - PoolConnectParams params; - std::string taskId; - - { - std::unique_lock lock(mutex_); - if (lifecycle_ != PoolLifecycle::Running) break; - queue_.removeCancelledFromHead(); - req = queue_.takeNext(); + std::vector> granted; + { + std::lock_guard lock(mutex_); + while (lifecycle_ == PoolLifecycle::Running) { + ContextRequestPtr req = queue_.takeNext(); if (!req) break; - - slotIdx = findIdleSlot(req->mode); + size_t slotIdx = findIdleSlot(req->mode); if (slotIdx == SIZE_MAX) slotIdx = maybeGrowSlot(); if (slotIdx == SIZE_MAX) { queue_.requeueFront(std::move(req)); break; } - - PoolSlot& slot = slots_[slotIdx]; - if (!slot.accepts(req->mode)) { - queue_.requeueFront(std::move(req)); - break; - } - - slot.markActivating(); + slots_[slotIdx].markActivating(); activating_[req->id] = req; - params.serverUrl = serverUrl_; - params.shareName = shareName_; - params.credentials = credentials_; - params.capabilities = capabilities_; - needsActivate = slotNeedsActivate(slot); - taskId = req->taskId; - - lock.unlock(); - - bool ok = true; - std::string activationError; - int activationCode = static_cast(SmbErrorCode::NotConnected); - try { - if (needsActivate) - slot.activate(params, taskId); - else - slot.ensureShare(shareName_, taskId); - } catch (const SmbException& e) { - ok = false; - activationError = e.what(); - activationCode = e.codeInt(); - } catch (const std::exception& e) { - ok = false; - activationError = e.what(); - activationCode = SmbErrorMapper::fromErrnoOrMessage(0, e.what()); - } catch (...) { - ok = false; - activationError = "context request failed"; - activationCode = static_cast(SmbErrorCode::NotConnected); - } + granted.emplace_back(std::move(req), slotIdx); + } + } + if (granted.empty()) return; + notifyObservers(); + for (auto& [req, slotIdx] : granted) req->callbacks.onGranted(SlotReservation(this, slotIdx, req)); +} - lock.lock(); - activating_.erase(req->id); +void SmbConnectionPool::requestContext(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId, ContextCallbacks callbacks) { + bool accepted = false; + { + std::lock_guard lock(mutex_); + accepted = lifecycle_ == PoolLifecycle::Running; + if (accepted) queue_.enqueue(mode, kind, taskId, std::move(callbacks)); + } + if (!accepted) { + if (callbacks.onRejected) callbacks.onRejected(static_cast(SmbErrorCode::NotConnected), "SMB connection is closing or disconnected"); + return; + } + tryAssignNext(); +} - const bool wasCancelled = req->cancelled.load(std::memory_order_acquire); +PoolContextHandle SmbConnectionPool::activateReservation(size_t slotIndex, const ContextRequestPtr& req) { + PoolSlot& slot = slots_[slotIndex]; + PoolConnectParams params; + bool needsActivate = false; + bool live = false; + { + std::lock_guard lock(mutex_); + live = lifecycle_ == PoolLifecycle::Running && !req->cancelled.load(std::memory_order_acquire); + params.serverUrl = serverUrl_; + params.shareName = shareName_; + params.credentials = credentials_; + params.capabilities = capabilities_; + needsActivate = slotNeedsActivate(slot); + } - if (lifecycle_ != PoolLifecycle::Running || wasCancelled) { - slot.resetBroken(); - req->cancelled.store(true, std::memory_order_release); - fulfillRequest(req, PoolContextHandle{}); - assignCv_.notify_all(); - if (lifecycle_ != PoolLifecycle::Running) break; - continue; - } + // The slot is Activating, so no other thread touches it while it connects unlocked. + std::optional failure; + if (live) { + try { + if (needsActivate) + slot.activate(params, req->taskId); + else + slot.ensureShare(params.shareName, req->taskId); + } catch (const SmbException& e) { + failure.emplace(e); + } catch (const std::exception& e) { + failure.emplace(static_cast(SmbErrorMapper::fromErrnoOrMessage(0, e.what())), e.what()); + } catch (...) { + failure.emplace(SmbErrorCode::NotConnected, "context request failed"); + } + } - if (!ok) { - SMB_LOG_ERROR("Pool could not activate a context for task %s (%s)", req->taskId.c_str(), operationName(req->kind)); + std::optional handle; + { + std::lock_guard lock(mutex_); + activating_.erase(req->id); + if (lifecycle_ != PoolLifecycle::Running || req->cancelled.load(std::memory_order_acquire)) { + if (failure) { slot.resetBroken(); - req->errorMessage = activationError.empty() ? "context request failed" : std::move(activationError); - req->errorCode = activationCode; - fulfillRequest(req, PoolContextHandle{}); - assignCv_.notify_all(); - continue; + } else { + slot.release(); } - + failure.emplace(SmbErrorCode::Cancelled, "context request cancelled"); + } else if (failure) { + slot.resetBroken(); + } else { slot.assign(req->id, req->taskId, req->kind); slot.manager()->setCapabilities(params.capabilities); - PoolContextHandle handle(this, slotIdx, slot.manager()); - if (!fulfillRequest(req, std::move(handle))) { - // The unconsumed handle releases the slot when it leaves scope. - assignCv_.notify_all(); - continue; - } - assigned = true; + handle.emplace(this, slotIndex, slot.manager()); } - } - { - std::lock_guard lock(mutex_); assignCv_.notify_all(); } - if (assigned) notifyObservers(); + notifyObservers(); + + if (handle) return std::move(*handle); + if (failure->code() != SmbErrorCode::Cancelled) { + SMB_LOG_ERROR("Pool could not activate a context for task %s (%s)", req->taskId.c_str(), operationName(req->kind)); + } + tryAssignNext(); + throw *failure; } -PoolContextHandle SmbConnectionPool::requestContext(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId) { - ContextRequestPtr req; - std::future fut; +void SmbConnectionPool::abandonReservation(size_t slotIndex, const ContextRequestPtr& req) { { std::lock_guard lock(mutex_); - if (lifecycle_ != PoolLifecycle::Running) { - SmbException::raise(SmbErrorCode::NotConnected, "SMB connection is closing or disconnected"); - } - req = queue_.enqueue(mode, kind, taskId); - fut = req->promise.get_future(); + activating_.erase(req->id); + slots_[slotIndex].release(); + assignCv_.notify_all(); } + notifyObservers(); tryAssignNext(); - - std::unique_lock lock(mutex_); - assignCv_.wait(lock, [&] { - return req->fulfilled.load(std::memory_order_acquire) || req->cancelled.load(std::memory_order_acquire); - }); - - if (req->cancelled.load(std::memory_order_acquire)) { - SmbException::raise(SmbErrorCode::Cancelled, "context request cancelled"); - } - - PoolContextHandle handle = fut.get(); - if (!handle.valid()) { - const std::string msg = req->errorMessage.empty() ? "context request failed" : req->errorMessage; - SmbException::raise(req->errorCode == 0 ? static_cast(SmbErrorCode::NotConnected) : req->errorCode, msg); - } - return handle; } void SmbConnectionPool::releaseContext(const PoolContextHandle& handle) { - bool shouldAssign = false; bool released = false; { std::lock_guard lock(mutex_); if (handle.valid() && handle.slotIndex() < slots_.size()) { - const size_t idx = handle.slotIndex(); - slots_[idx].release(); + slots_[handle.slotIndex()].release(); released = true; } - shouldAssign = lifecycle_ == PoolLifecycle::Running; assignCv_.notify_all(); } if (released) notifyObservers(); - if (shouldAssign) { - tryAssignNext(); - } + tryAssignNext(); } void SmbConnectionPool::cancelRequestsForTask(const std::string& taskId) { - std::lock_guard lock(mutex_); - queue_.cancelForTask(taskId); - for (auto& [id, req] : activating_) { - if (!req || req->taskId != taskId) continue; - if (req->fulfilled.load(std::memory_order_acquire)) continue; - req->cancelled.store(true, std::memory_order_release); - // Do not fulfill here — tryAssignNext owns the promise once activation returns. + std::vector rejected; + { + std::lock_guard lock(mutex_); + rejected = queue_.takeForTask(taskId); + for (auto& [id, req] : activating_) { + if (req->taskId == taskId) req->cancelled.store(true, std::memory_order_release); + } } - assignCv_.notify_all(); + rejectRequests(rejected, SmbErrorCode::Cancelled, "context request cancelled"); } size_t SmbConnectionPool::addObserver(const PoolObserver& observer) { @@ -267,12 +235,13 @@ std::vector SmbConnectionPool::getPoolStatus() const { void SmbConnectionPool::drainCurrentWork(const std::string& excludeTaskId, const CancellationToken& cancel) { if (cancel.cancelled()) SmbException::raise(SmbErrorCode::Cancelled, "connection transition cancelled"); + std::vector rejected; { std::lock_guard lock(mutex_); lifecycle_ = PoolLifecycle::Closing; - queue_.cancelAll(); - assignCv_.notify_all(); + rejected = queue_.takeAll(); } + rejectRequests(rejected, SmbErrorCode::Cancelled, "context request cancelled"); if (cancelTasksExcept_) cancelTasksExcept_(excludeTaskId); std::unique_lock lock(mutex_); assignCv_.wait(lock, [&] { diff --git a/cpp/shared/connection/SmbConnectionPool.hpp b/cpp/shared/connection/SmbConnectionPool.hpp index 8d6ea3a..ab9be74 100644 --- a/cpp/shared/connection/SmbConnectionPool.hpp +++ b/cpp/shared/connection/SmbConnectionPool.hpp @@ -15,6 +15,7 @@ #include "PoolContextHandle.hpp" #include "PoolSlot.hpp" #include "PoolTypes.hpp" +#include "SlotReservation.hpp" #include "SmbConnection.hpp" namespace react_native_smb { @@ -25,7 +26,10 @@ namespace react_native_smb { * slot[0] — Interactive-only * slot[1..N-1] — General (any AcquireMode; Interactive may overflow here) * - * Op::requestContext → Interactive-first FIFO queue → exclusive slot assignment + * requestContext → Interactive-first FIFO queue → SlotReservation → activate → PoolContextHandle + * + * Requests never block: a queued request holds no thread, and the caller's + * onGranted starts the work once a slot is reserved. */ class SmbConnectionPool { public: @@ -43,7 +47,8 @@ class SmbConnectionPool { void resetPool(); // [context] - PoolContextHandle requestContext(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId = ""); + // Queues a request and returns at once. Rejects immediately unless the pool is running. + void requestContext(AcquireMode mode, SmbOperatorKind kind, const std::string& taskId, ContextCallbacks callbacks); void releaseContext(const PoolContextHandle& handle); void cancelRequestsForTask(const std::string& taskId); @@ -64,6 +69,8 @@ class SmbConnectionPool { void removeObserver(size_t id); private: + friend class SlotReservation; + enum class PoolLifecycle { Running, Closing, Disconnected }; // Request scheduling @@ -71,6 +78,8 @@ class SmbConnectionPool { size_t findIdleSlot(AcquireMode mode) const; size_t maybeGrowSlot(); bool slotNeedsActivate(const PoolSlot& slot) const; + PoolContextHandle activateReservation(size_t slotIndex, const ContextRequestPtr& req); + void abandonReservation(size_t slotIndex, const ContextRequestPtr& req); // Lifecycle void drainCurrentWork(const std::string& excludeTaskId, const CancellationToken& cancel); @@ -97,7 +106,7 @@ class SmbConnectionPool { // Pending context requests ContextRequestQueue queue_; - // Requests outside queue_ while a slot is activating. Cancellation must see them. + // Reserved requests whose slot is activating. Cancellation must see them. std::unordered_map activating_; // Connection configuration diff --git a/cpp/shared/core/LifecycleSerialExecutor.hpp b/cpp/shared/core/LifecycleSerialExecutor.hpp index 053d626..574f05a 100644 --- a/cpp/shared/core/LifecycleSerialExecutor.hpp +++ b/cpp/shared/core/LifecycleSerialExecutor.hpp @@ -9,8 +9,8 @@ namespace react_native_smb { // Single-worker FIFO queue for connection lifecycle tasks (initialize / connect / -// connectShare / disconnect). Keeps those transitions off Nitro's shared -// Promise::async pool so bulk Metadata work cannot starve logout/reconnect. +// connectShare / disconnect). They need no pool slot, so they never queue behind +// bulk work waiting for one; the task runs inline on this worker. class LifecycleSerialExecutor { public: LifecycleSerialExecutor(); diff --git a/cpp/shared/core/SmbTask.cpp b/cpp/shared/core/SmbTask.cpp index bcadaaa..719ae09 100644 --- a/cpp/shared/core/SmbTask.cpp +++ b/cpp/shared/core/SmbTask.cpp @@ -1,7 +1,5 @@ #include "SmbTask.hpp" -#include - #include "../connection/SmbConnectionPool.hpp" #include "../operators/OperatorBase.hpp" #include "../util/SmbErrorMapper.hpp" @@ -25,38 +23,62 @@ void SmbTask::cancel() { if (auto pool = pool_.lock()) pool->cancelRequestsForTask(getId()); } -void SmbTask::run() { - markRunning(); +bool SmbTask::prepare() { auto pool = pool_.lock(); if (!pool) { - if (!cancel_.cancelled()) { - settle(SmbTaskStatus::Error, "SMB connection pool is unavailable", static_cast(SmbErrorCode::NotConnected)); - } - } else if (!cancel_.cancelled()) { + settle(SmbTaskStatus::Error, "SMB connection pool is unavailable", static_cast(SmbErrorCode::NotConnected)); + return false; + } + op_->attach(this, pool.get(), cancel_); + try { + op_->prepare(); + return true; + } catch (...) { + settleFromCurrentException(); + } + maybeSettle(); + return false; +} + +std::optional SmbTask::acquireMode() const { return op_->acquireMode(); } + +void SmbTask::run(std::optional reservation) { + if (!cancel_.cancelled()) { try { - op_->attach(this, pool.get(), cancel_); - op_->prepare(); std::optional context; - if (const auto mode = op_->acquireMode()) { - markPending(); - context = pool->requestContext(*mode, getKind(), getId()); - markRunning(); - } + if (reservation) context = reservation->activate(); + markRunning(); op_->start(context ? &*context : nullptr); - } catch (const SmbException& e) { - if (e.code() == SmbErrorCode::Cancelled) { - SmbTaskCore::cancel(); - } else { - settle(SmbTaskStatus::Error, e.what(), e.codeInt()); - } - } catch (const std::exception& e) { - const int code = SmbErrorMapper::fromErrnoOrMessage(0, e.what()); - settle(SmbTaskStatus::Error, e.what(), code); } catch (...) { - settle(SmbTaskStatus::Error, "unknown error", static_cast(SmbErrorCode::Unknown)); + settleFromCurrentException(); } } maybeSettle(); } +void SmbTask::reject(int code, const std::string& message) { + if (code == static_cast(SmbErrorCode::Cancelled)) { + SmbTaskCore::cancel(); + } else { + settle(SmbTaskStatus::Error, message, code); + } + maybeSettle(); +} + +void SmbTask::settleFromCurrentException() { + try { + throw; + } catch (const SmbException& e) { + if (e.code() == SmbErrorCode::Cancelled) { + SmbTaskCore::cancel(); + } else { + settle(SmbTaskStatus::Error, e.what(), e.codeInt()); + } + } catch (const std::exception& e) { + settle(SmbTaskStatus::Error, e.what(), SmbErrorMapper::fromErrnoOrMessage(0, e.what())); + } catch (...) { + settle(SmbTaskStatus::Error, "unknown error", static_cast(SmbErrorCode::Unknown)); + } +} + } // namespace react_native_smb diff --git a/cpp/shared/core/SmbTask.hpp b/cpp/shared/core/SmbTask.hpp index e9e6af6..ae83b59 100644 --- a/cpp/shared/core/SmbTask.hpp +++ b/cpp/shared/core/SmbTask.hpp @@ -1,8 +1,11 @@ #pragma once #include +#include #include +#include "../connection/PoolTypes.hpp" +#include "../connection/SlotReservation.hpp" #include "SmbTaskCore.hpp" namespace react_native_smb { @@ -16,8 +19,14 @@ class SmbTask : public SmbTaskCore { SmbTask(std::string id, std::unique_ptr op, std::shared_ptr pool); ~SmbTask(); - // Runs the operator on the calling thread and settles the task. - void run(); + // Binds the operator and runs its prepare step. False when that settled the task. + bool prepare(); + std::optional acquireMode() const; + // Activates the reserved slot (none for lifecycle tasks), runs the operator + // on the calling thread, and settles the task. + void run(std::optional reservation); + // Settles a task whose slot request was rejected. + void reject(int code, const std::string& message); using SmbTaskCore::getState; using SmbTaskCore::subscribe; @@ -32,6 +41,9 @@ class SmbTask : public SmbTaskCore { std::unique_ptr op_; std::weak_ptr pool_; std::shared_ptr entries_; // non-null only for ListDirectory + + // Call from a catch block: settles from the in-flight exception. + void settleFromCurrentException(); }; } // namespace react_native_smb From 1090d71cebd17fb0288e599593b76989a8e75652 Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:26:16 +0800 Subject: [PATCH 8/9] docs(architecture): document task admission and threading Describe the single admission point, the one-task-one-slot rule, the thread bounds, and when a task reports Pending. - add a Task admission section to ARCHITECTURE - note that every request may open a slot; drop the PoolSlot::accepts snippet - TASK_MODEL: status is Pending while queued for a slot --- docs/ARCHITECTURE.md | 28 +++++++++++++++++++--------- docs/TASK_MODEL.md | 2 +- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 33c4d15..fbe398f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -6,7 +6,7 @@ TCP → NEGOTIATE → SESSION SETUP → TREE CONNECT ``` -Tasks call `requestContext(mode)`, hold a slot for the operator's lifetime, then release via `PoolContextHandle`. One operator per slot (mutex on the context). Work on different slots runs concurrently. +Each task is granted one slot before its operator runs, holds it for the operator's lifetime, then releases it via `PoolContextHandle`. One operator per slot (mutex on the context). Work on different slots runs concurrently. From `SmbConnectionPool.hpp`: @@ -20,13 +20,6 @@ slot[1..N-1] — General (any AcquireMode; Interactive may overflow here) | `slot[0]` | `Interactive` only | `listDirectory`, `getPathInfo`, rename, move | | `slot[1..3]` | Any | Download, upload, copy, delete; grows on demand | -```cpp -bool PoolSlot::accepts(AcquireMode mode) const { - if (index_ == 0) return mode == AcquireMode::Interactive; - return true; -} -``` - Metadata never uses slot 0. Interactive work can overflow to slots 1–3 when slot 0 is busy. ### Acquire modes @@ -36,7 +29,24 @@ Metadata never uses slot 0. Interactive work can overflow to slots 1–3 when sl | `Interactive` | `getPathInfo`, `listDirectory` (`maxDepth: 0`), `moveItem`, `renameItem`, `createDirectory`, `getSecurityDescriptor`, `listShares` | | `Metadata` | `downloadFile`, `uploadFile`, `copyItem`, `duplicateItem`, `deleteItem`, `listDirectory` (`maxDepth != 0`) | -FIFO queue per mode. +FIFO queue per mode; queued Interactive requests are assigned before Metadata. Every request may open a new slot up to the pool size. + +### Task admission + +The pool queue is the only place a work task waits. Starting a task does not block the calling thread or use Nitro's `Promise::async` pool: + +``` +JS call → prepare() validate arguments, record paths (no SMB) + → requestContext(mode) queue; status Pending + → slot reserved start one thread for the task + → activate() connect the slot if needed, on that thread + → run() status Running; slot released when it returns +``` + +- A queued task holds no thread. At most one thread per pool slot runs work, plus the lifecycle thread. +- A task acquires exactly one slot, once, before `run()`; operators never request another one. +- `initialize`, `connect`, `connectShare`, and `disconnect` take no slot. They run one at a time on a dedicated lifecycle thread, so they never wait behind queued work; a transition cancels queued and running tasks before it changes the connection. +- Cancelling a queued task settles it at once without starting a thread. Grant and rejection callbacks run outside the pool lock. The server sees each active slot as a separate client connection — multiple full sessions to the same host/share, not channels bound to one session. SMB3 multichannel is the protocol-level alternative: extra TCP links attach to an existing session via `SMB2_SESSION_FLAG_BINDING` and share one `SessionId`. libsmb2 does not implement that; each `smb2_context` maps to one `fd`, so the pool uses independent contexts instead. diff --git a/docs/TASK_MODEL.md b/docs/TASK_MODEL.md index 40f68c6..a6a5132 100644 --- a/docs/TASK_MODEL.md +++ b/docs/TASK_MODEL.md @@ -85,7 +85,7 @@ function DownloadBar({ task }) { | Field | Description | | ----- | ----------- | | `progress` | `0–1` (determinate for transfers) | -| `status` | `TaskStatus` enum | +| `status` | `TaskStatus` enum; `Pending` while queued for a connection slot | | `bytesDone` / `totalBytes` | Raw byte counts | | `bytesPerSecond` / `etaSeconds` | Throughput estimate | | `determinate` | `true` for download/upload/copy | From 703d38dcb910c10f6ca3a08b6a2d22ced7097a9e Mon Sep 17 00:00:00 2001 From: yfcyrus <79596426+yfcyrus@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:47:00 +0800 Subject: [PATCH 9/9] feat(example): clarify transfer tray for pool admission Pending/Running need clear labels. - Active/Waiting badges - Running before Pending - In progress / Finished --- example/components/TransferTrayPanel.js | 391 ++++++++++++------------ 1 file changed, 196 insertions(+), 195 deletions(-) diff --git a/example/components/TransferTrayPanel.js b/example/components/TransferTrayPanel.js index 9ad277a..d373f92 100644 --- a/example/components/TransferTrayPanel.js +++ b/example/components/TransferTrayPanel.js @@ -7,6 +7,7 @@ import { SmbOperatorKind, TaskStatus, formatFileSize, + isTerminalStatus, operationLabel, useTransferActions, useTransfers, @@ -14,38 +15,26 @@ import { import { useSmb } from '../contexts/SmbContext'; -const statusBadge = { - running: { text: '', color: '#9EC5FF' }, - pending: { text: 'Waiting', color: '#C5B89A' }, - completed: { text: 'Done', color: '#7BE495' }, - failed: { text: 'Failed', color: '#FF6B6B' }, - cancelled: { text: 'Cancelled', color: '#BDBDBD' }, -}; +const SPEED_DEBOUNCE_MS = 1500; -const shareFile = async (uri) => { - if (!uri) return; - try { - const file = new File(uri); - if (!file.exists) return; - await Sharing.shareAsync(uri); - } catch {} +const BADGE = { + [TaskStatus.Running]: { text: 'Active', color: '#9EC5FF' }, + [TaskStatus.Pending]: { text: 'Waiting', color: '#C5B89A' }, + [TaskStatus.Success]: { text: 'Done', color: '#7BE495' }, + [TaskStatus.Error]: { text: 'Failed', color: '#FF6B6B' }, + [TaskStatus.Cancelled]: { text: 'Cancelled', color: '#BDBDBD' }, }; -const shareAll = async (uris) => { - for (const uri of uris) { - // eslint-disable-next-line no-await-in-loop - await shareFile(uri); - } -}; +const unsettledRank = (s) => + s === TaskStatus.Running ? 0 : s === TaskStatus.Pending ? 1 : s === TaskStatus.Idle ? 2 : 3; -const formatDuration = (seconds) => { - if (!isFinite(seconds) || seconds < 0) return '--'; - if (seconds < 60) return `${Math.ceil(seconds)}s`; - const m = Math.floor(seconds / 60); - const s = Math.ceil(seconds % 60); +const formatDuration = (sec) => { + if (!isFinite(sec) || sec < 0) return '--'; + if (sec < 60) return `${Math.ceil(sec)}s`; + const m = Math.floor(sec / 60); + const s = Math.ceil(sec % 60); if (m < 60) return `${m}m ${s}s`; - const h = Math.floor(m / 60); - return `${h}h ${m % 60}m`; + return `${Math.floor(m / 60)}h ${m % 60}m`; }; const computeRate = (t, now) => { @@ -58,197 +47,187 @@ const computeRate = (t, now) => { const done = t.bytesDone || t.progress * t.totalBytes; const speed = done / elapsed; if (!isFinite(speed) || speed <= 0) return null; - const remaining = t.totalBytes - done; - const eta = remaining > 0 ? remaining / speed : 0; - return { speed, eta }; + return { speed, eta: Math.max(0, (t.totalBytes - done) / speed) }; }; -const getTaskDisplayName = (task) => { - const path = task.destinationPath || task.sourcePath; - if (!path) return ''; - const parts = path.split('/'); - return parts[parts.length - 1]; -}; +const fileName = (t) => (t.destinationPath || t.sourcePath || '').split('/').pop() || ''; -const badgeKey = (status) => { - if (status === TaskStatus.Success) return 'completed'; - if (status === TaskStatus.Error) return 'failed'; - if (status === TaskStatus.Cancelled) return 'cancelled'; - if (status === TaskStatus.Running) return 'running'; - if (status === TaskStatus.Pending) return 'pending'; - return 'pending'; +const shareFile = async (uri) => { + if (!uri) return; + try { + const file = new File(uri); + if (file.exists) await Sharing.shareAsync(uri); + } catch {} }; -const TransferTrayPanel = () => { +function TaskRow({ task, onCancel, onRemove }) { + const badge = BADGE[task.status] ?? BADGE[TaskStatus.Pending]; + const pct = Math.round(task.progress * 100); + const now = Date.now(); + const rate = task.status === TaskStatus.Running ? computeRate(task, now) : null; + const speedSig = `${task.bytesPerSecond}:${task.bytesDone}:${task.progress}`; + const [speedBps, setSpeedBps] = useState(() => rate?.speed ?? 0); + const timer = useRef(null); + + useEffect(() => { + if (task.status !== TaskStatus.Running) { + clearTimeout(timer.current); + return undefined; + } + clearTimeout(timer.current); + timer.current = setTimeout(() => { + const r = computeRate(task, Date.now()); + if (r?.speed > 0) setSpeedBps(r.speed); + }, SPEED_DEBOUNCE_MS); + return () => clearTimeout(timer.current); + }, [task.taskId, speedSig, task.status]); + + let meta = badge.text || `${pct}%`; + if (rate) { + const speed = speedBps > 0 ? speedBps : rate.speed; + meta = `${pct}% · ${formatFileSize(speed)}/s · ${formatDuration(rate.eta)} left`; + } + + const isDone = task.status === TaskStatus.Success; + const isDownload = task.kind === SmbOperatorKind.DownloadFile; + const shareUri = isDownload ? task.destinationPath : ''; + const active = !isTerminalStatus(task.status); + + return ( + isDone && shareUri && shareFile(shareUri)} + style={styles.row}> + + + {operationLabel(task.kind)} {fileName(task)} + + + + + {meta} + {task.errorMessage ? ( + + {task.errorMessage} + + ) : null} + + (active ? onCancel(task.taskId) : onRemove(task.taskId))}> + {active ? 'Cancel' : 'Clear'} + + + ); +} + +export default function TransferTrayPanel() { const { smb } = useSmb(); const transferTasks = useTransfers(smb); const { clearCompleted, hide } = useTransferActions(smb); - const displayOrderRef = useRef(new Map()); - const nextDisplayOrderRef = useRef(0); + const orderRef = useRef(new Map()); + const orderNext = useRef(0); + const [expanded, setExpanded] = useState(false); + const [openActive, setOpenActive] = useState(true); + const [openDone, setOpenDone] = useState(true); + const tasks = useMemo(() => { for (const t of transferTasks) { - if (!displayOrderRef.current.has(t.taskId)) { - displayOrderRef.current.set(t.taskId, nextDisplayOrderRef.current++); - } + if (!orderRef.current.has(t.taskId)) orderRef.current.set(t.taskId, orderNext.current++); } - return [...transferTasks].sort( - (a, b) => displayOrderRef.current.get(a.taskId) - displayOrderRef.current.get(b.taskId), - ); + return transferTasks; }, [transferTasks]); - const runningTasks = useMemo( - () => - tasks.filter( - (t) => - t.status === TaskStatus.Running || t.status === TaskStatus.Pending, - ), - [tasks], - ); - const completedTasks = useMemo( - () => - tasks.filter( - (t) => - t.status === TaskStatus.Success || - t.status === TaskStatus.Error || - t.status === TaskStatus.Cancelled, - ), + + const order = orderRef.current; + const byUnsettled = (a, b) => unsettledRank(a.status) - unsettledRank(b.status) || order.get(a.taskId) - order.get(b.taskId); + const bySettled = (a, b) => (b.endedAt || 0) - (a.endedAt || 0) || order.get(a.taskId) - order.get(b.taskId); + + const activeTasks = useMemo( + () => tasks.filter((t) => !isTerminalStatus(t.status)).sort(byUnsettled), [tasks], ); - const totalProgress = useMemo(() => { - if (runningTasks.length === 0) return 100; - const sum = runningTasks.reduce((acc, t) => acc + t.progress * 100, 0); - return Math.round(sum / runningTasks.length); - }, [runningTasks]); - const shareableUris = useMemo(() => { - return completedTasks - .filter((t) => t.status === TaskStatus.Success && t.kind === SmbOperatorKind.DownloadFile && t.destinationPath) - .map((t) => t.destinationPath); - }, [completedTasks]); + const settledTasks = useMemo(() => tasks.filter((t) => isTerminalStatus(t.status)).sort(bySettled), [tasks]); - const cancelTask = (taskId) => smb?.cancelTask(taskId); - const cancelAll = () => smb?.cancelTransferTasks(); - const removeTask = (taskId) => hide(taskId); - const [expanded, setExpanded] = useState(false); + const inFlight = activeTasks.filter((t) => t.status === TaskStatus.Running || t.status === TaskStatus.Pending); + const totalPct = + inFlight.length === 0 + ? 100 + : Math.round(inFlight.reduce((n, t) => n + Math.round(t.progress * 100), 0) / inFlight.length); - const [, setTick] = useState(0); - useEffect(() => { - if (runningTasks.length === 0) return undefined; - const h = setInterval(() => setTick((x) => x + 1), 1000); - return () => clearInterval(h); - }, [runningTasks]); + const shareUris = settledTasks + .filter((t) => t.status === TaskStatus.Success && t.kind === SmbOperatorKind.DownloadFile && t.destinationPath) + .map((t) => t.destinationPath); if (!smb || tasks.length === 0) return null; - const showShareAll = runningTasks.length === 0 && shareableUris.length >= 2; - const now = Date.now(); + const n = (c) => `${c} transfer${c === 1 ? '' : 's'}`; + const pill = activeTasks.length > 0 ? `${n(activeTasks.length)} · ${totalPct}%` : `${n(tasks.length)} complete`; + + const section = (title, items, open, toggle) => + items.length === 0 ? null : ( + + + {open ? '\u25BE' : '\u25B8'} + {title} + {items.length} + + {open ? items.map((t) => ( + smb.cancelTask(id)} + onRemove={hide} + /> + )) : null} + + ); return ( - - setExpanded((v) => !v)} - style={styles.pill}> - {runningTasks.length > 0 ? `${runningTasks.length} transfer${runningTasks.length === 1 ? '' : 's'} · ${totalProgress}%` : `${tasks.length} transfer${tasks.length === 1 ? '' : 's'} complete`} + + setExpanded((v) => !v)}> + {pill} {expanded ? '\u2193' : '\u2191'} - {expanded && ( Transfers - - {runningTasks.length > 0 && ( - - Cancel all + + {activeTasks.length > 0 && ( + smb.cancelTransferTasks()} style={styles.hdrBtn}> + Cancel all )} - {showShareAll && ( + {activeTasks.length === 0 && shareUris.length >= 2 && ( shareAll(shareableUris)} - style={styles.headerBtn}> - Share all ({shareableUris.length}) + onPress={async () => { + for (const u of shareUris) { + // eslint-disable-next-line no-await-in-loop + await shareFile(u); + } + }} + style={styles.hdrBtn}> + Share all ({shareUris.length}) )} - {completedTasks.length > 0 && ( - - Clear done + {settledTasks.length > 0 && ( + + Clear done )} - {tasks.map((t) => { - const progress = Math.round(t.progress * 100); - const badge = statusBadge[badgeKey(t.status)] || statusBadge.running; - const isDone = t.status === TaskStatus.Success; - const isDownload = t.kind === SmbOperatorKind.DownloadFile; - const isActive = - t.status === TaskStatus.Running || t.status === TaskStatus.Pending; - const isRunning = t.status === TaskStatus.Running; - const shareUri = isDownload ? t.destinationPath : ''; - const rate = isRunning ? computeRate(t, now) : null; - - let metaText = badge.text || `${progress}%`; - if (isRunning && rate) { - metaText = `${progress}% · ${formatFileSize(rate.speed)}/s · ${formatDuration(rate.eta)} left`; - } - - return ( - { - if (isDone && isDownload && shareUri) shareFile(shareUri); - }} - style={styles.row}> - - - {operationLabel(t.kind)} {getTaskDisplayName(t)} - - - - - {metaText} - {t.errorMessage ? ( - - {t.errorMessage} - - ) : null} - - (isActive ? cancelTask(t.taskId) : removeTask(t.taskId))}> - {isActive ? 'Cancel' : 'Clear'} - - - ); - })} + {section('In progress', activeTasks, openActive, () => setOpenActive((v) => !v))} + {section('Finished', settledTasks, openDone, () => setOpenDone((v) => !v))} )} ); -}; +} const styles = StyleSheet.create({ - wrap: { - position: 'absolute', - right: 12, - bottom: 96, - width: 340, - maxWidth: '92%', - alignItems: 'flex-end', - }, + wrap: { position: 'absolute', right: 12, bottom: 96, width: 340, maxWidth: '92%', alignItems: 'flex-end' }, pill: { flexDirection: 'row', alignItems: 'center', @@ -256,9 +235,6 @@ const styles = StyleSheet.create({ paddingHorizontal: 12, paddingVertical: 6, borderRadius: 999, - shadowColor: '#000', - shadowOpacity: 0.2, - shadowRadius: 4, elevation: 4, }, pillText: { color: '#fff', fontWeight: '600', marginRight: 6, fontSize: 12 }, @@ -269,27 +245,52 @@ const styles = StyleSheet.create({ borderRadius: 12, width: '100%', maxHeight: 360, - shadowColor: '#000', - shadowOpacity: 0.25, - shadowRadius: 8, elevation: 6, overflow: 'hidden', }, - header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingHorizontal: 12, paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: 'rgba(255,255,255,0.12)' }, - headerText: { fontWeight: '700', color: '#FFFFFF' }, - headerBtn: { paddingHorizontal: 8, paddingVertical: 4, marginLeft: 4 }, - headerBtnText: { color: '#CFE2FF', fontSize: 12, fontWeight: '600' }, - headerBtnAccent: { color: '#7BE495' }, - headerBtnDestructive: { color: '#FF6B6B' }, + header: { + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'center', + paddingHorizontal: 12, + paddingVertical: 10, + borderBottomWidth: 1, + borderBottomColor: 'rgba(255,255,255,0.12)', + }, + headerText: { fontWeight: '700', color: '#fff' }, + headerRow: { flexDirection: 'row' }, + hdrBtn: { paddingHorizontal: 8, paddingVertical: 4, marginLeft: 4 }, + hdrBtnText: { color: '#CFE2FF', fontSize: 12, fontWeight: '600' }, + ok: { color: '#7BE495' }, + danger: { color: '#FF6B6B' }, list: { paddingHorizontal: 8, paddingVertical: 4 }, - row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8, paddingHorizontal: 6, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: 'rgba(255,255,255,0.1)' }, - rowTitle: { fontSize: 13, color: '#FFFFFF', fontWeight: '500' }, - progressTrack: { height: 4, backgroundColor: 'rgba(255,255,255,0.18)', borderRadius: 2, marginTop: 4, overflow: 'hidden' }, - progressFill: { height: 4, borderRadius: 2 }, - rowMeta: { fontSize: 11, marginTop: 3 }, - rowError: { fontSize: 11, color: '#FF8A8A', marginTop: 2 }, - rowAction: { paddingHorizontal: 8, paddingVertical: 4, marginLeft: 8 }, - rowActionText: { color: '#CFE2FF', fontSize: 12, fontWeight: '600' }, + section: { marginBottom: 4 }, + secHead: { + flexDirection: 'row', + alignItems: 'center', + paddingVertical: 8, + paddingHorizontal: 6, + marginTop: 4, + borderRadius: 6, + backgroundColor: 'rgba(255,255,255,0.06)', + }, + secChevron: { color: 'rgba(255,255,255,0.7)', fontSize: 14, width: 16, marginRight: 4 }, + secTitle: { flex: 1, fontSize: 11, fontWeight: '700', color: 'rgba(255,255,255,0.85)', textTransform: 'uppercase' }, + secCount: { fontSize: 11, fontWeight: '700', color: '#CFE2FF' }, + row: { + flexDirection: 'row', + alignItems: 'center', + paddingVertical: 8, + paddingHorizontal: 6, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: 'rgba(255,255,255,0.1)', + }, + rowBody: { flex: 1 }, + rowTitle: { fontSize: 13, color: '#fff', fontWeight: '500' }, + track: { height: 4, backgroundColor: 'rgba(255,255,255,0.18)', borderRadius: 2, marginTop: 4, overflow: 'hidden' }, + fill: { height: 4, borderRadius: 2 }, + meta: { fontSize: 11, marginTop: 3 }, + err: { fontSize: 11, color: '#FF8A8A', marginTop: 2 }, + rowBtn: { paddingHorizontal: 8, paddingVertical: 4, marginLeft: 8 }, + rowBtnText: { color: '#CFE2FF', fontSize: 12, fontWeight: '600' }, }); - -export default TransferTrayPanel; \ No newline at end of file