44 using JobResult = std::invoke_result_t<Fn&, SqliteConnection&>;
57 void Disconnect(std::chrono::milliseconds stopDeadline = std::chrono::seconds(5));
65 Enqueue(MakeJob(std::move(name), std::move(fn), {}));
69 std::move(name), std::move(fn), [
this, onDone = std::move(onDone)](
Result<
JobResult<Fn>> result)
mutable {
71 [onDone = std::move(onDone), result = std::move(result)]()
mutable { onDone(std::move(result)); });
76 template <
class Fn,
class OnValue>
77 requires(!std::is_void_v<JobResult<Fn>> && std::invocable<OnValue&, JobResult<Fn>> &&
78 !std::invocable<OnValue&, Result<JobResult<Fn>>>)
83 RunAsync(std::move(name), std::move(fn));
86 RunAsync(std::move(name), std::move(fn),
91 onValue(std::move(*result));
101 auto promise = std::make_shared<std::promise<Result<JobResult<Fn>>>>();
102 std::future<Result<JobResult<Fn>>> answer = promise->get_future();
103 Enqueue(MakeJob(std::move(name), std::move(fn),
112 auto result =
Run(std::move(name), std::move(fn));
113 return result ? std::move(*result) : std::move(fallback);
120 bool IsConnected()
const {
return _connected.load(std::memory_order_relaxed); }
130 std::move_only_function<void(
Error)> Fail;
143 static Job MakeJob(std::string name, Fn fn, std::move_only_function<
void(
Result<
JobResult<Fn>>)> deliver)
145 static_assert(std::same_as<std::invoke_result_t<Fn&, PostgresConnection&>,
JobResult<Fn>> &&
146 std::same_as<std::invoke_result_t<Fn&, MariaDbConnection&>,
JobResult<Fn>>,
147 "a database job must return the same type for every driver");
151 .Name = std::move(name),
152 .Run = [fn = std::move(fn)](
AnyConnection& conn)
mutable { Invoke(conn, fn); },
153 .Fail = [](
Error) {},
157 auto shared = std::make_shared<decltype(deliver)>(std::move(deliver));
159 .Name = std::move(name),
162 if constexpr (std::is_void_v<JobResult<Fn>>)
172 .Fail = [shared](
Error error) { (*shared)(std::unexpected(std::move(error))); },
182 if constexpr (std::same_as<std::remove_cvref_t<
decltype(open)>, std::monostate>)
184 throw std::logic_error(
"no database connection");
195 static bool IsSet(
const auto& callback)
197 if constexpr (
requires {
static_cast<bool>(callback); })
199 return static_cast<bool>(callback);
207 void Enqueue(Job job);
210 std::optional<Job> TakeJob();
211 void RunJob(Job& job);
215 void DropConnection();
217 Scheduler& _scheduler;
218 DatabaseConfig _config;
221 std::mutex _queueMutex;
222 std::condition_variable _queueCv;
223 std::deque<Job> _queue;
224 State _state = State::Stopped;
225 std::chrono::steady_clock::time_point _stopDeadline{};
227 GameThreadQueue _completions;
229 Subscription _onFrame;
232 std::atomic<bool> _connected{
false};
236 std::chrono::steady_clock::time_point _retryAt{};