Skip to content
This repository was archived by the owner on Dec 24, 2025. It is now read-only.

Commit e30879a

Browse files
committed
Cache Limit Bytes
1 parent 4b60077 commit e30879a

File tree

3 files changed

+47
-13
lines changed

3 files changed

+47
-13
lines changed

flake.nix

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,18 @@
6060
description = "File containing notes to be returned by the Api.";
6161
default = null;
6262
};
63+
64+
domainName = mkOption {
65+
type = types.nullOr types.str;
66+
description = "Domain Name the API is hosted on";
67+
default = null;
68+
};
69+
70+
cacheLimitBytes = mkOption {
71+
type = types.nullOr types.ints.unsigned;
72+
description = "Cache Size Limits in Bytes";
73+
default = null;
74+
};
6375
};
6476

6577
config = mkIf cfg.enable {
@@ -89,7 +101,9 @@
89101
${optionalString (cfg.postgresUrlFile != null) "--postgres-url-file ${cfg.postgresUrlFile}"} \
90102
${optionalString (cfg.hypixelApiKey != null) "--hypixel-api-key ${cfg.hypixelApiKey}"} \
91103
${optionalString (cfg.hypixelApiKeyFile != null) "--hypixel-api-key-file ${cfg.hypixelApiKeyFile}"} \
92-
${optionalString (cfg.notesFile != null) "--notes-file ${cfg.notesFile}"}
104+
${optionalString (cfg.notesFile != null) "--notes-file ${cfg.notesFile}"} \
105+
${optionalString (cfg.domainName != null) "--domain-name ${cfg.domainName}"} \
106+
${optionalString (cfg.cacheLimitBytes != null) "--cache-limit-bytes ${cfg.cacheLimitBytes}"}
93107
'';
94108

95109
# Why can't this shit just be the default?

src/endpoints/hypixel.rs

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
1-
use crate::ClArgs;
2-
use crate::{errors::ApiError, extractors::Authentication, ApiState};
3-
use axum::response::IntoResponse;
4-
use axum::{body::Body, extract::State, response::Response, Json};
1+
use crate::{errors::ApiError, extractors::Authentication, ApiState, ClArgs};
2+
use axum::{body::Body, extract::State, response::IntoResponse, response::Response, Json};
53
use chrono::Utc;
64
use log::warn;
75
use mini_moka::sync::{Cache, CacheBuilder};
86
use reqwest::{Client, StatusCode};
97
use serde::Deserialize;
108
use serde_json::{json, Value};
11-
use std::fs::read_to_string;
12-
use std::sync::Arc;
13-
use std::time::Duration;
9+
use std::{collections::VecDeque, fs::read_to_string, sync::Arc};
1410
use tokio::sync::RwLock;
1511
use uuid::Uuid;
1612

@@ -27,11 +23,32 @@ struct Ratelimits {
2723
reset: u64,
2824
}
2925

30-
impl Default for HypixelApiProxyState {
31-
fn default() -> Self {
26+
impl HypixelApiProxyState {
27+
pub fn new(cache_limit_bytes: u64) -> Self {
3228
Self {
33-
cache: CacheBuilder::new(10_000)
34-
.time_to_live(Duration::from_secs(2 * 24 * 60 * 60))
29+
cache: CacheBuilder::new(cache_limit_bytes)
30+
.weigher(|_, value| {
31+
let mut size = size_of::<Uuid>() as u32 + size_of::<Value>() as u32;
32+
let mut recursive_search = VecDeque::from([value]);
33+
while let Some(value) = recursive_search.pop_front() {
34+
match value {
35+
Value::String(string) => size += string.capacity() as u32,
36+
Value::Array(vec) => {
37+
size += (vec.capacity() * size_of::<Value>()) as u32;
38+
recursive_search.extend(vec);
39+
}
40+
Value::Object(map) => {
41+
size += map.keys().map(String::len).sum::<usize>() as u32;
42+
size += ((size_of::<String>() + size_of::<Value>()) * map.len()) as u32; // Capacity isn't available?
43+
recursive_search.extend(map.values());
44+
}
45+
_ => {}
46+
};
47+
}
48+
size
49+
})
50+
// Disable Time to Live for now
51+
// .time_to_live(Duration::from_secs(2 * 24 * 60 * 60))
3552
.build(),
3653
ratelimits: RwLock::new(Ratelimits {
3754
limit: 10,

src/main.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ pub struct ClArgs {
3939

4040
#[arg(long)]
4141
pub domain_name: Option<String>,
42+
43+
#[arg(long, default_value = "1073741824")]
44+
pub cache_limit_bytes: u64,
4245
}
4346

4447
#[derive(Args)]
@@ -154,14 +157,14 @@ async fn main() -> anyhow::Result<()> {
154157
.fallback(not_found)
155158
.with_state(ApiState {
156159
database,
160+
hypixel_api_state: Arc::new(HypixelApiProxyState::new(cl_args.cache_limit_bytes)),
157161
cl_args,
158162
client: Client::builder()
159163
.user_agent(concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")))
160164
.build()?,
161165
online_users: Default::default(),
162166
socket_sender: Default::default(),
163167
global_data: Default::default(),
164-
hypixel_api_state: Default::default(),
165168
});
166169

167170
let listener = tokio::net::TcpListener::bind("[::]:8000").await?;

0 commit comments

Comments
 (0)