Skip to content
Repos

DevPlaceApp

C++ 3.5 KB103 lines Opens in site

Directory Raw Download

#pragma once
// Spec: SPEC.md UX-IMG-02. Remote bitmap loader: network fetch on NetworkService, decode on a 2 thread pool,
// byte capped LRU, in-flight de-duplication, failure memo with a retry cooldown. UI thread API only.
// Mirrors CachedAsyncImage / AsyncSVGImage (NetworkImage cache) of the iOS app.
#include <chrono>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <functional>
#include <list>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>

#include "net/HttpTypes.hpp"
#include "ui/Bitmap.hpp"

namespace dp::ui {

class RemoteImages {
 public:
  using Fetcher = std::function<void(const std::string& url, std::function<void(Result<HttpResponse>)> done)>;

  struct Config {
    Fetcher fetcher;                  // empty: NetworkService::instance().send
    double cooldownSeconds = -1;      // < 0: spec value
    std::size_t cacheBytes = 0;       // 0: spec value; always clamped to the spec ceiling
    std::size_t maxEntries = 0;       // 0: spec value; always clamped to the spec ceiling
  };

  static RemoteImages& instance();

  // UI thread. nullptr while loading or failed. Starts a load on first use. rasterPx only matters for vector
  // sources (SVG), it is clamped and rounded up to a bucket; a larger later request re-rasterizes vectors.
  BitmapPtr get(const std::string& url, int rasterPx);
  bool isLoading(const std::string& url) const;
  bool failed(const std::string& url) const;
  void retry(const std::string& url);
  // Increments whenever a load finishes (success or failure), so the host knows to redraw.
  std::uint64_t version() const { return version_; }

  // Test and tuning hooks.
  void configure(Config config);
  void clear();  // drops cache and memo; results of loads started earlier are ignored
  std::size_t cachedBytes() const { return bytes_; }
  std::size_t entryCount() const { return entries_.size(); }
  int inFlight() const { return inFlight_; }

  RemoteImages(const RemoteImages&) = delete;
  RemoteImages& operator=(const RemoteImages&) = delete;

 private:
  enum class State { Queued, Loading, Ready, Failed };
  struct Entry {
    State state = State::Queued;
    BitmapPtr bitmap;
    int raster = 0;
    bool vector = false;
    std::size_t bytes = 0;
    std::uint64_t generation = 0;
    std::chrono::steady_clock::time_point failedAt;
    std::list<std::string>::iterator lru;
  };
  struct Job {
    std::string url;
    std::string body;
    int raster = 0;
    std::uint64_t generation = 0;
  };

  RemoteImages();
  ~RemoteImages();

  static int bucket(int rasterPx);
  Entry& touch(const std::string& url, bool& created);
  bool start(const std::string& url, Entry& e);  // false: wait queue full, nothing changed
  void pump();
  void onFetched(const std::string& url, std::uint64_t generation, Result<HttpResponse> r);
  void finish(const std::string& url, std::uint64_t generation, BitmapPtr bmp, bool vector);
  void fail(const std::string& url, Entry& e);
  void evict(std::size_t reserve = 0);
  std::size_t byteCap() const;
  void workerLoop();

  Config config_;
  std::unordered_map<std::string, Entry> entries_;
  std::list<std::string> lru_;  // front = most recent
  std::deque<std::string> waiting_;
  std::size_t bytes_ = 0;
  int inFlight_ = 0;
  std::uint64_t generation_ = 1;
  std::uint64_t version_ = 0;

  std::mutex mutex_;
  std::condition_variable cv_;
  std::deque<Job> jobs_;
  bool stop_ = false;
  std::vector<std::thread> workers_;
};

}  // namespace dp::ui
33.2ms