Skip to content

Commit 1f5d18f

Browse files
committed
refactor: [#1491] remove duplicate code
1 parent 09bbef7 commit 1f5d18f

File tree

6 files changed

+46
-97
lines changed

6 files changed

+46
-97
lines changed

packages/torrent-repository/src/lib.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
pub mod entry;
22
pub mod repository;
33

4-
use std::sync::{Arc, Mutex};
4+
use std::sync::{Arc, Mutex, MutexGuard};
55

66
use torrust_tracker_clock::clock;
77

@@ -19,6 +19,16 @@ pub(crate) type CurrentClock = clock::Working;
1919
#[allow(dead_code)]
2020
pub(crate) type CurrentClock = clock::Stopped;
2121

22+
pub trait LockTrackedTorrent {
23+
fn lock_or_panic(&self) -> MutexGuard<'_, TrackedTorrent>;
24+
}
25+
26+
impl LockTrackedTorrent for Arc<Mutex<TrackedTorrent>> {
27+
fn lock_or_panic(&self) -> MutexGuard<'_, TrackedTorrent> {
28+
self.lock().expect("can't acquire lock for tracked torrent handle")
29+
}
30+
}
31+
2232
#[cfg(test)]
2333
pub(crate) mod tests {
2434
use std::net::{IpAddr, Ipv4Addr, SocketAddr};

packages/torrent-repository/src/repository.rs

Lines changed: 13 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PersistentTorrent
99

1010
use crate::entry::peer_list::PeerList;
1111
use crate::entry::torrent::TrackedTorrent;
12-
use crate::TrackedTorrentHandle;
12+
use crate::{LockTrackedTorrent, TrackedTorrentHandle};
1313

1414
#[derive(Default, Debug)]
1515
pub struct TorrentRepository {
@@ -46,11 +46,7 @@ impl TorrentRepository {
4646
if let Some(existing_entry) = self.torrents.get(info_hash) {
4747
tracing::debug!("Torrent already exists: {:?}", info_hash);
4848

49-
existing_entry
50-
.value()
51-
.lock()
52-
.expect("can't acquire lock for tracked torrent handle")
53-
.upsert_peer(peer)
49+
existing_entry.value().lock_or_panic().upsert_peer(peer)
5450
} else {
5551
tracing::debug!("Inserting new torrent: {:?}", info_hash);
5652

@@ -68,10 +64,7 @@ impl TorrentRepository {
6864

6965
let inserted_entry = self.torrents.get_or_insert(*info_hash, new_entry);
7066

71-
let mut torrent_guard = inserted_entry
72-
.value()
73-
.lock()
74-
.expect("can't acquire lock for tracked torrent handle");
67+
let mut torrent_guard = inserted_entry.value().lock_or_panic();
7568

7669
torrent_guard.upsert_peer(peer)
7770
}
@@ -97,11 +90,7 @@ impl TorrentRepository {
9790
/// This function panics if the lock for the entry cannot be obtained.
9891
pub fn remove_inactive_peers(&self, current_cutoff: DurationSinceUnixEpoch) {
9992
for entry in &self.torrents {
100-
entry
101-
.value()
102-
.lock()
103-
.expect("can't acquire lock for tracked torrent handle")
104-
.remove_inactive_peers(current_cutoff);
93+
entry.value().lock_or_panic().remove_inactive_peers(current_cutoff);
10594
}
10695
}
10796

@@ -154,13 +143,9 @@ impl TorrentRepository {
154143
/// This function panics if the lock for the entry cannot be obtained.
155144
#[must_use]
156145
pub fn get_swarm_metadata(&self, info_hash: &InfoHash) -> Option<SwarmMetadata> {
157-
self.torrents.get(info_hash).map(|entry| {
158-
entry
159-
.value()
160-
.lock()
161-
.expect("can't acquire lock for tracked torrent handle")
162-
.get_swarm_metadata()
163-
})
146+
self.torrents
147+
.get(info_hash)
148+
.map(|entry| entry.value().lock_or_panic().get_swarm_metadata())
164149
}
165150

166151
/// Retrieves swarm metadata for a given torrent.
@@ -196,10 +181,7 @@ impl TorrentRepository {
196181
pub fn get_peers_for(&self, info_hash: &InfoHash, peer: &peer::Peer, limit: usize) -> Vec<Arc<peer::Peer>> {
197182
match self.get(info_hash) {
198183
None => vec![],
199-
Some(entry) => entry
200-
.lock()
201-
.expect("can't acquire lock for tracked torrent handle")
202-
.get_peers_for_client(&peer.peer_addr, Some(limit)),
184+
Some(entry) => entry.lock_or_panic().get_peers_for_client(&peer.peer_addr, Some(limit)),
203185
}
204186
}
205187

@@ -220,10 +202,7 @@ impl TorrentRepository {
220202
pub fn get_torrent_peers(&self, info_hash: &InfoHash, limit: usize) -> Vec<Arc<peer::Peer>> {
221203
match self.get(info_hash) {
222204
None => vec![],
223-
Some(entry) => entry
224-
.lock()
225-
.expect("can't acquire lock for tracked torrent handle")
226-
.get_peers(Some(limit)),
205+
Some(entry) => entry.lock_or_panic().get_peers(Some(limit)),
227206
}
228207
}
229208

@@ -237,12 +216,7 @@ impl TorrentRepository {
237216
/// This function panics if the lock for the entry cannot be obtained.
238217
pub fn remove_peerless_torrents(&self, policy: &TrackerPolicy) {
239218
for entry in &self.torrents {
240-
if entry
241-
.value()
242-
.lock()
243-
.expect("can't acquire lock for tracked torrent handle")
244-
.meets_retaining_policy(policy)
245-
{
219+
if entry.value().lock_or_panic().meets_retaining_policy(policy) {
246220
continue;
247221
}
248222

@@ -293,11 +267,7 @@ impl TorrentRepository {
293267
let mut metrics = AggregateSwarmMetadata::default();
294268

295269
for entry in &self.torrents {
296-
let stats = entry
297-
.value()
298-
.lock()
299-
.expect("can't acquire lock for tracked torrent handle")
300-
.get_swarm_metadata();
270+
let stats = entry.value().lock_or_panic().get_swarm_metadata();
301271
metrics.total_complete += u64::from(stats.complete);
302272
metrics.total_downloaded += u64::from(stats.downloaded);
303273
metrics.total_incomplete += u64::from(stats.incomplete);
@@ -584,7 +554,7 @@ mod tests {
584554

585555
use crate::repository::TorrentRepository;
586556
use crate::tests::{sample_info_hash, sample_peer};
587-
use crate::TrackedTorrentHandle;
557+
use crate::{LockTrackedTorrent, TrackedTorrentHandle};
588558

589559
/// `TorrentEntry` data is not directly accessible. It's only
590560
/// accessible through the trait methods. We need this temporary
@@ -599,7 +569,7 @@ mod tests {
599569
#[allow(clippy::from_over_into)]
600570
impl Into<TorrentEntryInfo> for TrackedTorrentHandle {
601571
fn into(self) -> TorrentEntryInfo {
602-
let torrent_guard = self.lock().expect("can't acquire lock for tracked torrent handle");
572+
let torrent_guard = self.lock_or_panic();
603573

604574
let torrent_entry_info = TorrentEntryInfo {
605575
swarm_metadata: torrent_guard.get_swarm_metadata(),

packages/torrent-repository/tests/common/torrent.rs

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::sync::Arc;
44
use torrust_tracker_configuration::TrackerPolicy;
55
use torrust_tracker_primitives::swarm_metadata::SwarmMetadata;
66
use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch};
7-
use torrust_tracker_torrent_repository::{entry, TrackedTorrentHandle};
7+
use torrust_tracker_torrent_repository::{entry, LockTrackedTorrent, TrackedTorrentHandle};
88

99
#[derive(Debug, Clone)]
1010
pub(crate) enum Torrent {
@@ -16,68 +16,56 @@ impl Torrent {
1616
pub(crate) fn get_stats(&self) -> SwarmMetadata {
1717
match self {
1818
Torrent::Single(entry) => entry.get_swarm_metadata(),
19-
Torrent::MutexStd(entry) => entry
20-
.lock()
21-
.expect("can't acquire lock for torrent entry")
22-
.get_swarm_metadata(),
19+
Torrent::MutexStd(entry) => entry.lock_or_panic().get_swarm_metadata(),
2320
}
2421
}
2522

2623
pub(crate) fn meets_retaining_policy(&self, policy: &TrackerPolicy) -> bool {
2724
match self {
2825
Torrent::Single(entry) => entry.meets_retaining_policy(policy),
29-
Torrent::MutexStd(entry) => entry
30-
.lock()
31-
.expect("can't acquire lock for torrent entry")
32-
.meets_retaining_policy(policy),
26+
Torrent::MutexStd(entry) => entry.lock_or_panic().meets_retaining_policy(policy),
3327
}
3428
}
3529

3630
pub(crate) fn peers_is_empty(&self) -> bool {
3731
match self {
3832
Torrent::Single(entry) => entry.peers_is_empty(),
39-
Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").peers_is_empty(),
33+
Torrent::MutexStd(entry) => entry.lock_or_panic().peers_is_empty(),
4034
}
4135
}
4236

4337
pub(crate) fn get_peers_len(&self) -> usize {
4438
match self {
4539
Torrent::Single(entry) => entry.get_peers_len(),
46-
Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").get_peers_len(),
40+
Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers_len(),
4741
}
4842
}
4943

5044
pub(crate) fn get_peers(&self, limit: Option<usize>) -> Vec<Arc<peer::Peer>> {
5145
match self {
5246
Torrent::Single(entry) => entry.get_peers(limit),
53-
Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").get_peers(limit),
47+
Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers(limit),
5448
}
5549
}
5650

5751
pub(crate) fn get_peers_for_client(&self, client: &SocketAddr, limit: Option<usize>) -> Vec<Arc<peer::Peer>> {
5852
match self {
5953
Torrent::Single(entry) => entry.get_peers_for_client(client, limit),
60-
Torrent::MutexStd(entry) => entry
61-
.lock()
62-
.expect("can't acquire lock for torrent entry")
63-
.get_peers_for_client(client, limit),
54+
Torrent::MutexStd(entry) => entry.lock_or_panic().get_peers_for_client(client, limit),
6455
}
6556
}
6657

6758
pub(crate) fn upsert_peer(&mut self, peer: &peer::Peer) -> bool {
6859
match self {
6960
Torrent::Single(entry) => entry.upsert_peer(peer),
70-
Torrent::MutexStd(entry) => entry.lock().expect("can't acquire lock for torrent entry").upsert_peer(peer),
61+
Torrent::MutexStd(entry) => entry.lock_or_panic().upsert_peer(peer),
7162
}
7263
}
7364

7465
pub(crate) fn remove_inactive_peers(&mut self, current_cutoff: DurationSinceUnixEpoch) {
7566
match self {
7667
Torrent::Single(entry) => entry.remove_inactive_peers(current_cutoff),
77-
Torrent::MutexStd(entry) => entry
78-
.lock()
79-
.expect("can't acquire lock for torrent entry")
80-
.remove_inactive_peers(current_cutoff),
68+
Torrent::MutexStd(entry) => entry.lock_or_panic().remove_inactive_peers(current_cutoff),
8169
}
8270
}
8371
}

packages/tracker-core/src/announce_handler.rs

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,7 @@ mod tests {
594594

595595
use aquatic_udp_protocol::AnnounceEvent;
596596
use torrust_tracker_test_helpers::configuration;
597+
use torrust_tracker_torrent_repository::LockTrackedTorrent;
597598

598599
use crate::announce_handler::tests::the_announce_handler::peer_ip;
599600
use crate::announce_handler::{AnnounceHandler, PeersWanted};
@@ -656,20 +657,10 @@ mod tests {
656657
.expect("it should be able to get entry");
657658

658659
// It persists the number of completed peers.
659-
assert_eq!(
660-
torrent_entry
661-
.lock()
662-
.expect("can't acquire lock for torrent entry")
663-
.get_swarm_metadata()
664-
.downloaded,
665-
1
666-
);
660+
assert_eq!(torrent_entry.lock_or_panic().get_swarm_metadata().downloaded, 1);
667661

668662
// It does not persist the peers
669-
assert!(torrent_entry
670-
.lock()
671-
.expect("can't acquire lock for torrent entry")
672-
.peers_is_empty());
663+
assert!(torrent_entry.lock_or_panic().peers_is_empty());
673664
}
674665
}
675666

packages/tracker-core/src/torrent/manager.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ mod tests {
110110
use std::sync::Arc;
111111

112112
use torrust_tracker_configuration::Core;
113+
use torrust_tracker_torrent_repository::LockTrackedTorrent;
113114

114115
use super::{DatabasePersistentTorrentRepository, TorrentsManager};
115116
use crate::databases::setup::initialize_database;
@@ -163,8 +164,7 @@ mod tests {
163164
.in_memory_torrent_repository
164165
.get(&infohash)
165166
.unwrap()
166-
.lock()
167-
.expect("can't acquire lock for torrent entry")
167+
.lock_or_panic()
168168
.get_swarm_metadata()
169169
.downloaded,
170170
1

packages/tracker-core/src/torrent/services.rs

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use std::sync::Arc;
1717
use bittorrent_primitives::info_hash::InfoHash;
1818
use torrust_tracker_primitives::pagination::Pagination;
1919
use torrust_tracker_primitives::peer;
20+
use torrust_tracker_torrent_repository::LockTrackedTorrent;
2021

2122
use crate::torrent::repository::in_memory::InMemoryTorrentRepository;
2223

@@ -98,15 +99,9 @@ pub fn get_torrent_info(in_memory_torrent_repository: &Arc<InMemoryTorrentReposi
9899

99100
let torrent_entry = torrent_entry_option?;
100101

101-
let stats = torrent_entry
102-
.lock()
103-
.expect("can't acquire lock for torrent entry")
104-
.get_swarm_metadata();
102+
let stats = torrent_entry.lock_or_panic().get_swarm_metadata();
105103

106-
let peers = torrent_entry
107-
.lock()
108-
.expect("can't acquire lock for torrent entry")
109-
.get_peers(None);
104+
let peers = torrent_entry.lock_or_panic().get_peers(None);
110105

111106
let peers = Some(peers.iter().map(|peer| (**peer)).collect());
112107

@@ -148,10 +143,7 @@ pub fn get_torrents_page(
148143
let mut basic_infos: Vec<BasicInfo> = vec![];
149144

150145
for (info_hash, torrent_entry) in in_memory_torrent_repository.get_paginated(pagination) {
151-
let stats = torrent_entry
152-
.lock()
153-
.expect("can't acquire lock for torrent entry")
154-
.get_swarm_metadata();
146+
let stats = torrent_entry.lock_or_panic().get_swarm_metadata();
155147

156148
basic_infos.push(BasicInfo {
157149
info_hash,
@@ -190,12 +182,10 @@ pub fn get_torrents(in_memory_torrent_repository: &Arc<InMemoryTorrentRepository
190182
let mut basic_infos: Vec<BasicInfo> = vec![];
191183

192184
for info_hash in info_hashes {
193-
if let Some(stats) = in_memory_torrent_repository.get(info_hash).map(|torrent_entry| {
194-
torrent_entry
195-
.lock()
196-
.expect("can't acquire lock for torrent entry")
197-
.get_swarm_metadata()
198-
}) {
185+
if let Some(stats) = in_memory_torrent_repository
186+
.get(info_hash)
187+
.map(|torrent_entry| torrent_entry.lock_or_panic().get_swarm_metadata())
188+
{
199189
basic_infos.push(BasicInfo {
200190
info_hash: *info_hash,
201191
seeders: u64::from(stats.complete),

0 commit comments

Comments
 (0)