Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ members = [
"packages/component-derive",
"packages/minecraft-meta-manifest",
"packages/minecraft-meta-model",
"packages/modrinth-app-analytics-sdk",
"packages/modrinth-app-analytics-types",
"packages/modrinth-content-management",
"packages/modrinth-log",
"packages/modrinth-skin-rendering",
Expand Down Expand Up @@ -150,6 +152,7 @@ lz4_flex = { version = "0.14.0", default-features = false, features = [
] }
minecraft-meta-manifest = { path = "packages/minecraft-meta-manifest" }
minecraft-meta-model = { path = "packages/minecraft-meta-model" }
modrinth-app-analytics-types = { path = "packages/modrinth-app-analytics-types" }
modrinth-content-management = { path = "packages/modrinth-content-management" }
modrinth-log = { path = "packages/modrinth-log" }
modrinth-skin-rendering = { path = "packages/modrinth-skin-rendering" }
Expand Down Expand Up @@ -221,6 +224,7 @@ sha1_smol = { version = "1.0.1", features = ["std"] }
sha2 = "0.11.1"
shlex = "2.0.1"
smallvec = "1.16.3"
smol_str = "0.3.7"
spdx = "0.13.6"
sqlx = { version = "0.9.0", default-features = false }
sqlx-tracing = { path = "packages/sqlx-tracing" }
Expand Down
2 changes: 2 additions & 0 deletions _typos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ extend-exclude = [
# contains payment card IDs like `IY1VMST1MOXS` which are flagged
"apps/labrinth/src/queue/payouts/mod.rs",
"apps/app-frontend/src/features/settings/syncing/game-settings-modal/languages.ts",
# ISO 3166-1 alpha-2 country codes like `BA` and `FO`
"packages/modrinth-app-analytics-types/src/iso3166_1_alpha_2.rs",
# vendored
"packages/toasty",
]
Expand Down
44 changes: 44 additions & 0 deletions apps/labrinth/src/clickhouse/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::queue::server_ping;
pub const DOWNLOADS: &str = "downloads";
pub const PLAYTIME: &str = "playtime";
pub const MINECRAFT_SERVER_PLAYS: &str = "minecraft_server_plays";
pub const APP_EVENTS: &str = "app_events";

pub async fn init_client() -> clickhouse::error::Result<clickhouse::Client> {
init_client_with_database(&ENV.CLICKHOUSE_DATABASE).await
Expand Down Expand Up @@ -73,13 +74,25 @@ pub async fn run_migrations_on_database(
"MergeTree()"
};

let replacing_engine = if clickhouse_replicated {
"ReplicatedReplacingMergeTree('/clickhouse/{installation}/{cluster}/tables/{shard}/{database}/{table}', '{replica}', recorded_ts)"
} else {
"ReplacingMergeTree(recorded_ts)"
};

// For the Clickhouse database on the staging environment, set a TTL to avoid accumulating too much data
let ttl = if database == "staging_analytics" {
"TTL toDateTime(recorded) + INTERVAL 1 DAY"
} else {
""
};

let app_events_ttl = if database == "staging_analytics" {
"TTL toDateTime(recorded_ts) + INTERVAL 3 DAY"
} else {
""
};

client
.query(&format!(
"
Expand Down Expand Up @@ -208,6 +221,37 @@ pub async fn run_migrations_on_database(
.execute()
.await?;

// Duplicate events are merged eventually, and only when their corrected
// timestamps fall on the same UTC day, so rows may still be duplicated.
client
.query(&format!(
"
CREATE TABLE IF NOT EXISTS {database}.{APP_EVENTS} {cluster_line}
(
event_id UUID COMMENT 'Client-controlled event ID',
client_installation_id UUID COMMENT 'Client-controlled installation ID',
event_type LowCardinality(String) COMMENT 'Type of event, validated at ingest',
event_ts DateTime64(6, 'UTC') COMMENT 'Event timestamp, corrected for client clock skew',
client_ts DateTime64(6, 'UTC') COMMENT 'Informational, client-side event timestamp',
recorded_ts DateTime64(6, 'UTC') COMMENT 'Informational, server receive timestamp',
source LowCardinality(String) COMMENT 'Where in the app the event was initiated from, validated at ingest',
app_version LowCardinality(String) COMMENT 'App version, validated at ingest',
os LowCardinality(String) COMMENT 'Client operating system, validated at ingest',
arch LowCardinality(String) COMMENT 'Client CPU architecture, validated at ingest',
ip_country FixedString(2) COMMENT 'ISO 3166-1 alpha-2 client country, XX for unknown and T1 for Tor',
metadata JSON(max_dynamic_paths = 256) COMMENT 'Event metadata, schema validated at ingest'
)
ENGINE = {replacing_engine}
PARTITION BY toYYYYMM(event_ts)
ORDER BY (toDate(event_ts), event_type, cityHash64(client_installation_id), event_id)
SAMPLE BY cityHash64(client_installation_id)
{app_events_ttl}
SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1
"
))
.execute()
.await?;

client
.query(&format!(
"
Expand Down
6 changes: 6 additions & 0 deletions apps/meta-generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ cargo run -p meta-generator -- import
cargo run -p meta-generator -- export
```

Both commands apply pending database migrations first. To only apply migrations and exit:

```sh
cargo run -p meta-generator -- migrate
```

Without upstream flags, all upstreams are selected. Put flags before the command to select specific upstreams:

```sh
Expand Down
7 changes: 7 additions & 0 deletions apps/meta-generator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ enum Command {
/// Take processed information from the database, produce JSON manifests
/// from them, and upload them to the public file store
Export,
/// Apply pending database migrations, then exit
Migrate,
}

pub fn main() -> Result<()> {
Expand Down Expand Up @@ -130,6 +132,10 @@ async fn main_(config: Config) -> Result<()> {
.await?;
info!("applied {} migrations", report.applied());

if matches!(cli.command, Command::Migrate) {
return Ok(());
}

let fastly = if let Some(config) = config.fastly {
fastly::Client::builder()
.http(http.clone())
Expand Down Expand Up @@ -192,6 +198,7 @@ async fn main_(config: Config) -> Result<()> {
.context(info_span!("export"))
.await
}
Command::Migrate => Ok(()),
}
}

Expand Down
17 changes: 17 additions & 0 deletions packages/modrinth-app-analytics-sdk/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "modrinth-app-analytics-sdk"
edition.workspace = true

[dependencies]
arc-swap = { workspace = true }
chrono = { workspace = true }
modrinth-app-analytics-types = { workspace = true }
parking_lot = { workspace = true }
reqwest = { workspace = true, features = ["json", "rustls-no-provider"] }
smol_str = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
tracing = { workspace = true }
uuid = { workspace = true, features = ["v7"] }

[lints]
workspace = true
33 changes: 33 additions & 0 deletions packages/modrinth-app-analytics-sdk/src/backend.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::time::Duration;

#[derive(Debug)]
pub(crate) enum AnalyticsBackend {
OptedOut,
Enabled { http_pool: reqwest::Client },
}

impl AnalyticsBackend {
pub(crate) fn clone_pool(&self) -> Option<reqwest::Client> {
match self {
AnalyticsBackend::OptedOut => None,
AnalyticsBackend::Enabled { http_pool } => Some(http_pool.clone()),
}
}

pub(crate) fn is_enabled(&self) -> bool {
matches!(self, AnalyticsBackend::Enabled { .. })
}
}

#[track_caller]
pub(crate) fn init_pool(user_agent: &str) -> reqwest::Client {
reqwest::Client::builder()
.user_agent(user_agent)
.timeout(Duration::from_secs(10))
.read_timeout(Duration::from_secs(10))
.connect_timeout(Duration::from_secs(10))
// we try to flush events every 10 seconds
.pool_idle_timeout(Duration::from_secs(30))
.build()
.expect("reqwest::Client failed to build")
}
Loading
Loading