summaryrefslogtreecommitdiff
path: root/libs/tdlib/td/td/telegram/files/ResourceManager.h
blob: 48a32f18f6bd8ab7c7e0fce3b8f2a45b113153ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once

#include "td/actor/actor.h"
#include "td/actor/PromiseFuture.h"

#include "td/telegram/files/FileLoaderActor.h"
#include "td/telegram/files/ResourceState.h"

#include "td/utils/Container.h"
#include "td/utils/Heap.h"

#include <utility>

namespace td {
class ResourceManager : public Actor {
 public:
  enum class Mode { Baseline, Greedy };
  explicit ResourceManager(Mode mode) : mode_(mode) {
  }
  // use through ActorShared
  void update_priority(int8 priority);
  void update_resources(const ResourceState &resource_state);

  void register_worker(ActorShared<FileLoaderActor> callback, int8 priority);

 private:
  Mode mode_;
  using NodeId = uint64;
  struct Node : public HeapNode {
    NodeId node_id;

    ResourceState resource_state_;
    ActorShared<FileLoaderActor> callback_;

    HeapNode *as_heap_node() {
      return static_cast<HeapNode *>(this);
    }
    static Node *from_heap_node(HeapNode *heap_node) {
      return static_cast<Node *>(heap_node);
    }
  };

  Container<std::unique_ptr<Node>> nodes_container_;
  vector<std::pair<int8, NodeId>> to_xload_;
  KHeap<int64> by_estimated_extra_;
  ResourceState resource_state_;

  ActorShared<> parent_;
  bool stop_flag_ = false;

  void hangup_shared() override;

  void loop() override;

  void add_to_heap(Node *node);
  bool satisfy_node(NodeId file_node_id);
  void add_node(NodeId node_id, int8 priority);
  bool remove_node(NodeId node_id);
};
}  // namespace td