Skip to content

Commit f5141be

Browse files
committed
dev: refactor torrent/repository
1 parent 2bc2bff commit f5141be

File tree

8 files changed

+158
-150
lines changed

8 files changed

+158
-150
lines changed

cSpell.json

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"alekitto",
66
"appuser",
77
"Arvid",
8+
"asyn",
89
"autoclean",
910
"AUTOINCREMENT",
1011
"automock",

packages/torrent-repository-benchmarks/src/benches/asyn.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ use std::time::Duration;
33

44
use clap::Parser;
55
use futures::stream::FuturesUnordered;
6-
use torrust_tracker::core::torrent::repository::TRepositoryAsync;
6+
use torrust_tracker::core::torrent::repository_asyn::RepositoryAsync;
77
use torrust_tracker::shared::bit_torrent::info_hash::InfoHash;
88

99
use crate::args::Args;
1010
use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER};
1111

12-
pub async fn async_add_one_torrent<T: TRepositoryAsync + Send + Sync + 'static>(samples: usize) -> (Duration, Duration) {
12+
pub async fn async_add_one_torrent<T: RepositoryAsync + Send + Sync + 'static>(samples: usize) -> (Duration, Duration) {
1313
let mut results: Vec<Duration> = Vec::with_capacity(samples);
1414

1515
for _ in 0..samples {
@@ -32,7 +32,7 @@ pub async fn async_add_one_torrent<T: TRepositoryAsync + Send + Sync + 'static>(
3232
}
3333

3434
// Add one torrent ten thousand times in parallel (depending on the set worker threads)
35-
pub async fn async_update_one_torrent_in_parallel<T: TRepositoryAsync + Send + Sync + 'static>(
35+
pub async fn async_update_one_torrent_in_parallel<T: RepositoryAsync + Send + Sync + 'static>(
3636
runtime: &tokio::runtime::Runtime,
3737
samples: usize,
3838
) -> (Duration, Duration) {
@@ -81,7 +81,7 @@ pub async fn async_update_one_torrent_in_parallel<T: TRepositoryAsync + Send + S
8181
}
8282

8383
// Add ten thousand torrents in parallel (depending on the set worker threads)
84-
pub async fn async_add_multiple_torrents_in_parallel<T: TRepositoryAsync + Send + Sync + 'static>(
84+
pub async fn async_add_multiple_torrents_in_parallel<T: RepositoryAsync + Send + Sync + 'static>(
8585
runtime: &tokio::runtime::Runtime,
8686
samples: usize,
8787
) -> (Duration, Duration) {
@@ -125,7 +125,7 @@ pub async fn async_add_multiple_torrents_in_parallel<T: TRepositoryAsync + Send
125125
}
126126

127127
// Async update ten thousand torrents in parallel (depending on the set worker threads)
128-
pub async fn async_update_multiple_torrents_in_parallel<T: TRepositoryAsync + Send + Sync + 'static>(
128+
pub async fn async_update_multiple_torrents_in_parallel<T: RepositoryAsync + Send + Sync + 'static>(
129129
runtime: &tokio::runtime::Runtime,
130130
samples: usize,
131131
) -> (Duration, Duration) {

packages/torrent-repository-benchmarks/src/benches/sync.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@ use std::time::Duration;
33

44
use clap::Parser;
55
use futures::stream::FuturesUnordered;
6-
use torrust_tracker::core::torrent::repository::Repository;
6+
use torrust_tracker::core::torrent::repository_sync::RepositorySync;
77
use torrust_tracker::shared::bit_torrent::info_hash::InfoHash;
88

99
use crate::args::Args;
1010
use crate::benches::utils::{generate_unique_info_hashes, get_average_and_adjusted_average_from_results, DEFAULT_PEER};
1111

1212
// Simply add one torrent
1313
#[must_use]
14-
pub fn add_one_torrent<T: Repository + Send + Sync + 'static>(samples: usize) -> (Duration, Duration) {
14+
pub fn add_one_torrent<T: RepositorySync + Send + Sync + 'static>(samples: usize) -> (Duration, Duration) {
1515
let mut results: Vec<Duration> = Vec::with_capacity(samples);
1616

1717
for _ in 0..samples {
@@ -32,7 +32,7 @@ pub fn add_one_torrent<T: Repository + Send + Sync + 'static>(samples: usize) ->
3232
}
3333

3434
// Add one torrent ten thousand times in parallel (depending on the set worker threads)
35-
pub async fn update_one_torrent_in_parallel<T: Repository + Send + Sync + 'static>(
35+
pub async fn update_one_torrent_in_parallel<T: RepositorySync + Send + Sync + 'static>(
3636
runtime: &tokio::runtime::Runtime,
3737
samples: usize,
3838
) -> (Duration, Duration) {
@@ -77,7 +77,7 @@ pub async fn update_one_torrent_in_parallel<T: Repository + Send + Sync + 'stati
7777
}
7878

7979
// Add ten thousand torrents in parallel (depending on the set worker threads)
80-
pub async fn add_multiple_torrents_in_parallel<T: Repository + Send + Sync + 'static>(
80+
pub async fn add_multiple_torrents_in_parallel<T: RepositorySync + Send + Sync + 'static>(
8181
runtime: &tokio::runtime::Runtime,
8282
samples: usize,
8383
) -> (Duration, Duration) {
@@ -119,7 +119,7 @@ pub async fn add_multiple_torrents_in_parallel<T: Repository + Send + Sync + 'st
119119
}
120120

121121
// Update ten thousand torrents in parallel (depending on the set worker threads)
122-
pub async fn update_multiple_torrents_in_parallel<T: Repository + Send + Sync + 'static>(
122+
pub async fn update_multiple_torrents_in_parallel<T: RepositorySync + Send + Sync + 'static>(
123123
runtime: &tokio::runtime::Runtime,
124124
samples: usize,
125125
) -> (Duration, Duration) {

packages/torrent-repository-benchmarks/src/main.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ use torrust_torrent_repository_benchmarks::benches::asyn::{
77
use torrust_torrent_repository_benchmarks::benches::sync::{
88
add_multiple_torrents_in_parallel, add_one_torrent, update_multiple_torrents_in_parallel, update_one_torrent_in_parallel,
99
};
10-
use torrust_tracker::core::torrent::repository::{AsyncSync, RepositoryAsync, RepositoryAsyncSingle, Sync, SyncSingle};
10+
use torrust_tracker::core::torrent::repository_asyn::{Async, AsyncSync, RepositoryAsyncSingle};
11+
use torrust_tracker::core::torrent::repository_sync::{Sync, SyncSingle};
1112

1213
#[allow(clippy::too_many_lines)]
1314
#[allow(clippy::print_literal)]
@@ -118,22 +119,22 @@ fn main() {
118119
println!(
119120
"{}: Avg/AdjAvg: {:?}",
120121
"add_one_torrent",
121-
rt.block_on(async_add_one_torrent::<RepositoryAsync>(1_000_000))
122+
rt.block_on(async_add_one_torrent::<Async>(1_000_000))
122123
);
123124
println!(
124125
"{}: Avg/AdjAvg: {:?}",
125126
"update_one_torrent_in_parallel",
126-
rt.block_on(async_update_one_torrent_in_parallel::<RepositoryAsync>(&rt, 10))
127+
rt.block_on(async_update_one_torrent_in_parallel::<Async>(&rt, 10))
127128
);
128129
println!(
129130
"{}: Avg/AdjAvg: {:?}",
130131
"add_multiple_torrents_in_parallel",
131-
rt.block_on(async_add_multiple_torrents_in_parallel::<RepositoryAsync>(&rt, 10))
132+
rt.block_on(async_add_multiple_torrents_in_parallel::<Async>(&rt, 10))
132133
);
133134
println!(
134135
"{}: Avg/AdjAvg: {:?}",
135136
"update_multiple_torrents_in_parallel",
136-
rt.block_on(async_update_multiple_torrents_in_parallel::<RepositoryAsync>(&rt, 10))
137+
rt.block_on(async_update_multiple_torrents_in_parallel::<Async>(&rt, 10))
137138
);
138139
}
139140
}

src/core/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ use torrust_tracker_primitives::TrackerMode;
455455
use self::auth::Key;
456456
use self::error::Error;
457457
use self::peer::Peer;
458-
use self::torrent::repository::{RepositoryAsyncSingle, TRepositoryAsync};
458+
use self::torrent::repository_asyn::{RepositoryAsync, RepositoryAsyncSingle};
459459
use crate::core::databases::Database;
460460
use crate::core::torrent::{SwarmMetadata, SwarmStats};
461461
use crate::shared::bit_torrent::info_hash::InfoHash;

src/core/torrent/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@
2828
//! Peer that don not have a full copy of the torrent data are called "leechers".
2929
//!
3030
//! > **NOTICE**: that both [`SwarmMetadata`] and [`SwarmStats`] contain the same information. [`SwarmMetadata`] is using the names used on [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html).
31-
pub mod repository;
31+
pub mod repository_asyn;
32+
pub mod repository_sync;
3233

3334
use std::time::Duration;
3435

src/core/torrent/repository.rs src/core/torrent/repository_asyn.rs

+6-133
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,7 @@ use crate::core::peer;
44
use crate::core::torrent::{Entry, SwarmStats};
55
use crate::shared::bit_torrent::info_hash::InfoHash;
66

7-
pub trait Repository {
8-
fn new() -> Self;
9-
fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool);
10-
}
11-
12-
pub trait TRepositoryAsync {
7+
pub trait RepositoryAsync {
138
fn new() -> Self;
149
fn update_torrent_with_peer_and_get_stats(
1510
&self,
@@ -18,135 +13,13 @@ pub trait TRepositoryAsync {
1813
) -> impl std::future::Future<Output = (SwarmStats, bool)> + Send;
1914
}
2015

21-
/// Structure that holds all torrents. Using `std::sync` locks.
22-
pub struct Sync {
23-
torrents: std::sync::RwLock<std::collections::BTreeMap<InfoHash, Arc<std::sync::Mutex<Entry>>>>,
24-
}
25-
26-
impl Sync {
27-
/// Returns the get torrents of this [`Sync`].
28-
///
29-
/// # Panics
30-
///
31-
/// Panics if unable to read the torrent.
32-
pub fn get_torrents(
33-
&self,
34-
) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap<InfoHash, Arc<std::sync::Mutex<Entry>>>> {
35-
self.torrents.read().expect("unable to get torrent list")
36-
}
37-
38-
/// Returns the mutable get torrents of this [`Sync`].
39-
///
40-
/// # Panics
41-
///
42-
/// Panics if unable to write to the torrents list.
43-
pub fn get_torrents_mut(
44-
&self,
45-
) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap<InfoHash, Arc<std::sync::Mutex<Entry>>>> {
46-
self.torrents.write().expect("unable to get writable torrent list")
47-
}
48-
}
49-
50-
impl Repository for Sync {
51-
fn new() -> Self {
52-
Self {
53-
torrents: std::sync::RwLock::new(std::collections::BTreeMap::new()),
54-
}
55-
}
56-
57-
fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) {
58-
let maybe_existing_torrent_entry = self.get_torrents().get(info_hash).cloned();
59-
60-
let torrent_entry: Arc<std::sync::Mutex<Entry>> = if let Some(existing_torrent_entry) = maybe_existing_torrent_entry {
61-
existing_torrent_entry
62-
} else {
63-
let mut torrents_lock = self.get_torrents_mut();
64-
let entry = torrents_lock
65-
.entry(*info_hash)
66-
.or_insert(Arc::new(std::sync::Mutex::new(Entry::new())));
67-
entry.clone()
68-
};
69-
70-
let (stats, stats_updated) = {
71-
let mut torrent_entry_lock = torrent_entry.lock().unwrap();
72-
let stats_updated = torrent_entry_lock.insert_or_update_peer(peer);
73-
let stats = torrent_entry_lock.get_stats();
74-
75-
(stats, stats_updated)
76-
};
77-
78-
(
79-
SwarmStats {
80-
downloaded: stats.1,
81-
complete: stats.0,
82-
incomplete: stats.2,
83-
},
84-
stats_updated,
85-
)
86-
}
87-
}
88-
89-
/// Structure that holds all torrents. Using `std::sync` locks.
90-
pub struct SyncSingle {
91-
torrents: std::sync::RwLock<std::collections::BTreeMap<InfoHash, Entry>>,
92-
}
93-
94-
impl SyncSingle {
95-
/// Returns the get torrents of this [`SyncSingle`].
96-
///
97-
/// # Panics
98-
///
99-
/// Panics if unable to get torrent list.
100-
pub fn get_torrents(&self) -> std::sync::RwLockReadGuard<'_, std::collections::BTreeMap<InfoHash, Entry>> {
101-
self.torrents.read().expect("unable to get torrent list")
102-
}
103-
104-
/// Returns the get torrents of this [`SyncSingle`].
105-
///
106-
/// # Panics
107-
///
108-
/// Panics if unable to get writable torrent list.
109-
pub fn get_torrents_mut(&self) -> std::sync::RwLockWriteGuard<'_, std::collections::BTreeMap<InfoHash, Entry>> {
110-
self.torrents.write().expect("unable to get writable torrent list")
111-
}
112-
}
113-
114-
impl Repository for SyncSingle {
115-
fn new() -> Self {
116-
Self {
117-
torrents: std::sync::RwLock::new(std::collections::BTreeMap::new()),
118-
}
119-
}
120-
121-
fn update_torrent_with_peer_and_get_stats(&self, info_hash: &InfoHash, peer: &peer::Peer) -> (SwarmStats, bool) {
122-
let mut torrents = self.torrents.write().unwrap();
123-
124-
let torrent_entry = match torrents.entry(*info_hash) {
125-
std::collections::btree_map::Entry::Vacant(vacant) => vacant.insert(Entry::new()),
126-
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
127-
};
128-
129-
let stats_updated = torrent_entry.insert_or_update_peer(peer);
130-
let stats = torrent_entry.get_stats();
131-
132-
(
133-
SwarmStats {
134-
downloaded: stats.1,
135-
complete: stats.0,
136-
incomplete: stats.2,
137-
},
138-
stats_updated,
139-
)
140-
}
141-
}
142-
14316
/// Structure that holds all torrents. Using `tokio::sync` locks.
14417
#[allow(clippy::module_name_repetitions)]
145-
pub struct RepositoryAsync {
18+
pub struct Async {
14619
torrents: tokio::sync::RwLock<std::collections::BTreeMap<InfoHash, Arc<tokio::sync::Mutex<Entry>>>>,
14720
}
14821

149-
impl TRepositoryAsync for RepositoryAsync {
22+
impl RepositoryAsync for Async {
15023
fn new() -> Self {
15124
Self {
15225
torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()),
@@ -185,7 +58,7 @@ impl TRepositoryAsync for RepositoryAsync {
18558
}
18659
}
18760

188-
impl RepositoryAsync {
61+
impl Async {
18962
pub async fn get_torrents(
19063
&self,
19164
) -> tokio::sync::RwLockReadGuard<'_, std::collections::BTreeMap<InfoHash, Arc<tokio::sync::Mutex<Entry>>>> {
@@ -204,7 +77,7 @@ pub struct AsyncSync {
20477
torrents: tokio::sync::RwLock<std::collections::BTreeMap<InfoHash, Arc<std::sync::Mutex<Entry>>>>,
20578
}
20679

207-
impl TRepositoryAsync for AsyncSync {
80+
impl RepositoryAsync for AsyncSync {
20881
fn new() -> Self {
20982
Self {
21083
torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()),
@@ -262,7 +135,7 @@ pub struct RepositoryAsyncSingle {
262135
torrents: tokio::sync::RwLock<std::collections::BTreeMap<InfoHash, Entry>>,
263136
}
264137

265-
impl TRepositoryAsync for RepositoryAsyncSingle {
138+
impl RepositoryAsync for RepositoryAsyncSingle {
266139
fn new() -> Self {
267140
Self {
268141
torrents: tokio::sync::RwLock::new(std::collections::BTreeMap::new()),

0 commit comments

Comments
 (0)