wme-models 0.1.3

Type definitions for the Wikimedia Enterprise API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Metadata types for the Wikimedia Enterprise API.
//!
//! This module provides types for reference data, snapshots, and event metadata
//! used across all Enterprise APIs. These types describe the context around
//! articles rather than article content itself.
//!
//! # Namespaces
//!
//! Wikimedia projects use namespaces to organize different types of pages:
//! - **0 (Main)**: Article content
//! - **6 (File)**: Media files
//! - **10 (Template)**: Reusable wikitext
//! - **14 (Category)**: Topic groupings
//!
//! See [`Namespace`] for namespace information.
//!
//! # Snapshots
//!
//! Snapshots provide complete dumps of Wikimedia projects. Use [`SnapshotInfo`]
//! to discover available snapshots and their download chunks.
//!
//! # Events
//!
//! The Realtime API uses event-based updates. See [`EventMetadata`] for
//! partition/offset tracking to enable resume functionality.

use crate::Article;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Event types for article changes.
///
/// The Realtime API streams events of these types as they happen.
/// Event types indicate what kind of change occurred to an article.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub enum EventType {
    /// Article was created or updated (content changed)
    #[serde(rename = "update")]
    Update,
    /// Article was deleted
    #[serde(rename = "delete")]
    Delete,
    /// Article visibility changed (content/editor/comment hidden)
    #[serde(rename = "visibility-change")]
    VisibilityChange,
}

/// Event metadata for articles.
///
/// Tracks events through the Wikimedia Enterprise system. The partition and
/// offset fields enable resuming streams after disconnections.
///
/// # Resuming Streams
///
/// ```ignore
/// // Store the last processed offset for each partition
/// let offsets: HashMap<u32, u64> = load_checkpoints();
///
/// // When reconnecting, pass these offsets
/// client.connect_with_offsets(offsets).await?;
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct EventMetadata {
    /// Event UUID (for tracking through the system)
    pub identifier: String,
    /// Event type (update, delete, visibility-change)
    #[serde(rename = "type")]
    pub event_type: EventType,
    /// Event creation timestamp (when entered Enterprise system)
    pub date_created: DateTime<Utc>,
    /// Event publication timestamp (Realtime API only)
    pub date_published: Option<DateTime<Utc>>,
    /// Partition number (Realtime API only, for resume)
    pub partition: Option<u32>,
    /// Offset within partition (Realtime API only, for resume)
    pub offset: Option<u64>,
}

/// Namespace information.
///
/// Namespaces organize different types of pages in Wikimedia projects.
/// The identifier is the namespace number (0, 6, 10, 14, etc.).
///
/// # Common Namespaces
///
/// - `0` - Main (article content)
/// - `6` - File (media uploads)
/// - `10` - Template (reusable wikitext)
/// - `14` - Category (topic groupings)
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Namespace {
    /// Namespace ID (0 = Main, 6 = File, 10 = Template, 14 = Category)
    pub identifier: u32,
    /// Namespace name
    pub name: Option<String>,
    /// Namespace description
    pub description: Option<String>,
}

/// Language information.
///
/// Describes a language supported by Wikimedia projects.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Language {
    /// Language code (e.g., "en", "de", "fr")
    pub identifier: Option<String>,
    /// Language name in English
    pub name: Option<String>,
    /// Alternate language name (native script)
    pub alternate_name: Option<String>,
    /// Text direction ("ltr" for left-to-right, "rtl" for right-to-left)
    pub direction: Option<String>,
}

/// Project information.
///
/// Simple project reference with basic metadata.
/// For full project metadata including language, see [`ProjectInfo`].
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Project {
    /// Project identifier (e.g., "enwiki")
    pub identifier: String,
    /// Project URL
    pub url: String,
    /// Project type (e.g., "Wikipedia")
    #[serde(rename = "type")]
    pub project_type: Option<String>,
}

/// Project info for discovery API.
///
/// Full project metadata returned by the metadata endpoints.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ProjectInfo {
    /// Project identifier (e.g., "enwiki")
    pub identifier: String,
    /// Project code (e.g., "wikipedia")
    pub code: Option<String>,
    /// Project name
    pub name: Option<String>,
    /// Project URL
    pub url: Option<String>,
    /// Project language
    pub in_language: Option<Language>,
}

/// Project type (code) information.
///
/// Describes project types like "wiki" (Wikipedia) or "wiktionary".
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ProjectType {
    /// Type identifier (e.g., "wiki", "wiktionary")
    pub identifier: String,
    /// Type name
    pub name: String,
    /// Type description
    pub description: Option<String>,
}

/// File size information with unit.
///
/// Used in snapshot and batch metadata to describe download sizes.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Size {
    /// Unit of measurement (e.g., "bytes", "MB", "GB")
    pub unit_text: String,
    /// Size value (can be fractional for small sizes)
    pub value: f64,
}

/// Snapshot information.
///
/// Metadata about available project snapshots including download chunks
/// for parallel downloading.
///
/// # Example
///
/// ```ignore
/// // Get snapshot info and download chunks in parallel
/// for chunk in snapshot.chunks {
///     let data = download_chunk(chunk.url).await?;
///     process_chunk(data).await?;
/// }
/// ```
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct SnapshotInfo {
    /// Snapshot identifier (e.g., "enwiki_namespace_0")
    pub identifier: String,
    /// Snapshot version
    pub version: String,
    /// Last modification timestamp
    pub date_modified: DateTime<Utc>,
    /// Language of the snapshot content
    pub in_language: Language,
    /// Project this snapshot belongs to
    pub is_part_of: ProjectInfo,
    /// Namespace of the snapshot
    pub namespace: Namespace,
    /// Snapshot size information
    pub size: Size,
    /// Downloadable chunk identifiers for parallel download
    pub chunks: Option<Vec<String>>,
}

/// Chunk information for parallel downloads.
///
/// Large snapshots are split into chunks for parallel downloading.
/// Each chunk can be downloaded independently and contains a subset
/// of the articles.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ChunkInfo {
    /// Chunk identifier (e.g., "enwiki_namespace_0_chunk_0")
    pub identifier: String,
    /// Chunk version
    pub version: String,
    /// Last modification timestamp
    pub date_modified: DateTime<Utc>,
    /// Language of the chunk content
    pub in_language: Language,
    /// Project this chunk belongs to
    pub is_part_of: ProjectInfo,
    /// Namespace of the chunk
    pub namespace: Namespace,
    /// Chunk size information
    pub size: Size,
    /// Download URL for the chunk
    pub url: Option<String>,
}

/// Simplified language information (used in Realtime API).
///
/// Realtime API uses a minimal language representation.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct SimplifiedLanguage {
    /// Language code (e.g., "en", "de")
    pub identifier: String,
    /// Language name
    pub name: String,
}

/// Realtime project information (used in streaming API).
///
/// Realtime API uses a different project structure with version
/// and size information for the stream.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct RealtimeProject {
    /// Project identifier (e.g., "enwiki")
    pub identifier: String,
    /// Project name
    pub name: String,
    /// Project URL
    pub url: String,
    /// Project version
    pub version: String,
    /// Last modification timestamp
    pub date_modified: DateTime<Utc>,
    /// Project size
    pub size: Size,
    /// Language information (simplified)
    pub in_language: SimplifiedLanguage,
}

/// Simplified namespace (used in Realtime API).
///
/// Realtime API uses minimal namespace representation.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct SimplifiedNamespace {
    /// Namespace ID
    pub identifier: u32,
    /// Namespace name
    pub name: Option<String>,
}

/// Realtime batch info (hourly batches).
///
/// Metadata for hourly batch files available through the Realtime API.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct RealtimeBatchInfo {
    /// Batch identifier
    pub identifier: String,
    /// Batch name
    pub name: String,
    /// Batch version
    pub version: String,
    /// Language information
    pub in_language: Language,
    /// Project this batch belongs to
    pub is_part_of: ProjectInfo,
    /// Namespace information
    pub namespace: Namespace,
    /// Batch size information
    pub size: Size,
}

/// Batch information for Realtime API.
///
/// Basic batch metadata with event count.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct BatchInfo {
    /// Batch identifier
    pub identifier: String,
    /// Batch creation timestamp
    pub date_created: DateTime<Utc>,
    /// Number of events in batch
    pub event_count: u64,
}

/// Article update event for Realtime API.
///
/// Combines article data with event metadata for Realtime streams.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ArticleUpdate {
    /// Event type
    pub event_type: EventType,
    /// Article data
    pub article: Article,
    /// Event metadata
    pub event_metadata: EventMetadata,
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;

    #[test]
    fn test_event_type_variants() {
        let update = EventType::Update;
        let delete = EventType::Delete;
        let visibility = EventType::VisibilityChange;

        assert!(matches!(update, EventType::Update));
        assert!(matches!(delete, EventType::Delete));
        assert!(matches!(visibility, EventType::VisibilityChange));
    }

    #[test]
    fn test_event_metadata() {
        let event = EventMetadata {
            identifier: "evt-12345".to_string(),
            event_type: EventType::Update,
            date_created: Utc::now(),
            date_published: Some(Utc::now()),
            partition: Some(4),
            offset: Some(3593806),
        };

        assert_eq!(event.identifier, "evt-12345");
        assert_eq!(event.partition, Some(4));
        assert_eq!(event.offset, Some(3593806));
    }

    #[test]
    fn test_namespace_creation() {
        let ns = Namespace {
            identifier: 0,
            name: Some("".to_string()),
            description: Some("Main namespace".to_string()),
        };

        assert_eq!(ns.identifier, 0);
        assert_eq!(ns.name, Some("".to_string()));
    }

    #[test]
    fn test_language_creation() {
        let lang = Language {
            identifier: Some("en".to_string()),
            name: Some("English".to_string()),
            alternate_name: None,
            direction: Some("ltr".to_string()),
        };

        assert_eq!(lang.identifier, Some("en".to_string()));
        assert_eq!(lang.direction, Some("ltr".to_string()));
    }

    #[test]
    fn test_rtl_language() {
        let lang = Language {
            identifier: Some("ar".to_string()),
            name: Some("Arabic".to_string()),
            alternate_name: Some("العربية".to_string()),
            direction: Some("rtl".to_string()),
        };

        assert_eq!(lang.identifier, Some("ar".to_string()));
        assert_eq!(lang.direction, Some("rtl".to_string()));
    }

    #[test]
    fn test_project_info() {
        let project = ProjectInfo {
            identifier: "enwiki".to_string(),
            code: Some("wikipedia".to_string()),
            name: Some("English Wikipedia".to_string()),
            url: Some("https://en.wikipedia.org".to_string()),
            in_language: Some(Language {
                identifier: Some("en".to_string()),
                name: Some("English".to_string()),
                alternate_name: None,
                direction: Some("ltr".to_string()),
            }),
        };

        assert_eq!(project.identifier, "enwiki");
        assert_eq!(project.code, Some("wikipedia".to_string()));
    }

    #[test]
    fn test_size() {
        let size = Size {
            unit_text: "MB".to_string(),
            value: 1500.0,
        };

        assert_eq!(size.value, 1500.0);
        assert_eq!(size.unit_text, "MB");
    }

    #[test]
    fn test_snapshot_info() {
        let snapshot = SnapshotInfo {
            identifier: "enwiki_namespace_0".to_string(),
            version: "2024-01-15".to_string(),
            date_modified: Utc::now(),
            in_language: Language {
                identifier: Some("en".to_string()),
                name: Some("English".to_string()),
                alternate_name: None,
                direction: Some("ltr".to_string()),
            },
            is_part_of: ProjectInfo {
                identifier: "enwiki".to_string(),
                code: Some("wikipedia".to_string()),
                name: Some("English Wikipedia".to_string()),
                url: Some("https://en.wikipedia.org".to_string()),
                in_language: Some(Language {
                    identifier: Some("en".to_string()),
                    name: Some("English".to_string()),
                    alternate_name: None,
                    direction: Some("ltr".to_string()),
                }),
            },
            namespace: Namespace {
                identifier: 0,
                name: Some("".to_string()),
                description: Some("Main namespace".to_string()),
            },
            size: Size {
                unit_text: "GB".to_string(),
                value: 25.0,
            },
            chunks: Some(vec![]),
        };

        assert_eq!(snapshot.identifier, "enwiki_namespace_0");
        assert_eq!(snapshot.chunks.as_ref().map(|v| v.len()).unwrap_or(0), 0);
    }
}