Branch data Line data Source code
1 : : // Copyright 2026 HPActor Contributors
2 : : //
3 : : // Licensed under the Apache License, Version 2.0 (the "License");
4 : : // you may not use this file except in compliance with the License.
5 : : // You may obtain a copy of the License at
6 : : //
7 : : // http://www.apache.org/licenses/LICENSE-2.0
8 : : //
9 : : // Unless required by applicable law or agreed to in writing, software
10 : : // distributed under the License is distributed on an "AS IS" BASIS,
11 : : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : : // See the License for the specific language governing permissions and
13 : : // limitations under the License.
14 : :
15 : : #include <hpactor/net/actor_location_cache.hpp>
16 : :
17 : : #include <mutex>
18 : :
19 : : namespace hpactor::net {
20 : :
21 : 9 : std::optional<EndPoint> ActorLocationCache::get(ActorId id) const {
22 : 9 : std::shared_lock lock(mutex_);
23 : 9 : auto it = cache_.find(id);
24 : 9 : if (it == cache_.end())
25 : 4 : return std::nullopt;
26 : 5 : if (it->second.expires_at <= std::chrono::steady_clock::now())
27 : 1 : return std::nullopt; // expired, deferred eviction via purge_expired()
28 : 4 : return it->second.endpoint;
29 : 9 : }
30 : :
31 : 8 : void ActorLocationCache::put(ActorId id, EndPoint ep, std::chrono::seconds ttl) {
32 : 8 : std::unique_lock lock(mutex_);
33 : 8 : cache_[id] = {ep, std::chrono::steady_clock::now() + ttl};
34 : 8 : }
35 : :
36 : 1 : void ActorLocationCache::evict(ActorId id) {
37 : 1 : std::unique_lock lock(mutex_);
38 : 1 : cache_.erase(id);
39 : 1 : }
40 : :
41 : 1 : void ActorLocationCache::evict_node(EndPoint ep) {
42 : 1 : std::unique_lock lock(mutex_);
43 : 4 : for (auto it = cache_.begin(); it != cache_.end();) {
44 : 3 : if (it->second.endpoint == ep)
45 : 2 : it = cache_.erase(it);
46 : : else
47 : 1 : ++it;
48 : : }
49 : 1 : }
50 : :
51 : 1 : void ActorLocationCache::purge_expired() {
52 : 1 : std::unique_lock lock(mutex_);
53 : 1 : auto now = std::chrono::steady_clock::now();
54 : 3 : for (auto it = cache_.begin(); it != cache_.end();) {
55 : 2 : if (it->second.expires_at <= now)
56 : 1 : it = cache_.erase(it);
57 : : else
58 : 1 : ++it;
59 : : }
60 : 1 : }
61 : :
62 : : } // namespace hpactor::net
|