| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- #pragma once
- #include <chrono>
- #include <cstdint>
- #include <functional>
- /// Waiting for the database at startup, bounded by WALL TIME.
- ///
- /// This exists because the previous version bounded the wait by an ATTEMPT
- /// COUNT - `for (i = 0; i < 30 && !db.connect(); ++i) sleep(1s)` - and that
- /// count carried an unstated assumption about how long one attempt costs.
- /// Database client 2.13.0 and earlier returned from connect() immediately on an
- /// unreachable server, because it only built the gRPC stub, so 30 attempts cost
- /// about 30 seconds. In 2.13.1 connect() WAITS up to its configured timeout
- /// (5 s for us) before answering, so the same loop costs up to 180 seconds.
- ///
- /// Our units are `Type=notify` with systemd's default `TimeoutStartSec` of 90
- /// seconds, so that loop would be SIGTERMed partway through. A clean
- /// "database not reachable" plus exit 1 - diagnosable, and restarted 3 seconds
- /// later - would become "start operation timed out", killed mid-loop, with
- /// restart churn. Not a rare path either: the package postinst starts the
- /// service while the database is still down on every upgrade.
- ///
- /// So the bound is a deadline. Swapping 30 for a smaller number would have been
- /// the same bug waiting for the next change in what an attempt costs.
- ///
- /// Pure and clock-injected so the property that broke - "returns within its
- /// budget however slow one attempt is" - can be tested without a database and
- /// without really sleeping.
- namespace svapi {
- /// Call `tryConnect` until it succeeds or `budget` has elapsed.
- ///
- /// Always attempts at least ONCE, even with a zero budget: a caller asking to
- /// connect wants one honest try, and a zero budget is a configuration choice
- /// about waiting rather than an instruction to skip the work.
- ///
- /// `sleepFor` is only called when there is budget left for it, so the function
- /// cannot overshoot by sleeping past its own deadline.
- inline bool awaitConnectable(const std::function<bool()>& tryConnect,
- const std::function<std::chrono::steady_clock::time_point()>& now,
- const std::function<void(std::chrono::milliseconds)>& sleepFor,
- std::chrono::milliseconds budget,
- std::chrono::milliseconds betweenAttempts) {
- const auto deadline = now() + budget;
- for (;;) {
- if (tryConnect()) return true;
- const auto remaining = deadline - now();
- // No time for another attempt's pause, so no point starting one: the
- // attempt itself may cost more than everything left.
- if (remaining <= betweenAttempts) return false;
- if (betweenAttempts > std::chrono::milliseconds::zero()) sleepFor(betweenAttempts);
- }
- }
- } // namespace svapi
|