arch-toolkit 0.3.0

Complete Rust toolkit for Arch Linux package management
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! AUR package info/details functionality.

use crate::aur::utils::{arrs, s, u64_of};
use crate::aur::validation::validate_package_names;
use crate::cache::cache_key_info;
use crate::client::{
    ArchClient, extract_retry_after, is_archlinux_url, rate_limit_archlinux,
    reset_archlinux_backoff, retry_with_policy,
};
use crate::error::{ArchToolkitError, Result};
use crate::types::AurPackageDetails;
use reqwest::Client;
use serde_json::Value;
use tracing::{debug, warn};

/// Maximum accepted AUR info response body size in bytes.
const MAX_AUR_INFO_RESPONSE_BYTES: usize = 10 * 1024 * 1024;

/// What: Fetch detailed information for one or more AUR packages.
///
/// Inputs:
/// - `client`: `ArchClient` to use for requests.
/// - `names`: Slice of package names to fetch info for.
///
/// Output:
/// - `Result<Vec<AurPackageDetails>>` containing package details, or an error.
///
/// Details:
/// - Uses AUR RPC v5 info endpoint.
/// - Fetches info for all packages in a single request (more efficient).
/// - Returns empty vector if no packages found (not an error).
/// - Applies rate limiting for archlinux.org requests.
/// - Uses retry policy if enabled for info operations.
/// - Checks cache before making network request if caching is enabled.
///
/// # Errors
/// - Returns `Err(ArchToolkitError::Network)` if the HTTP request fails
/// - Returns `Err(ArchToolkitError::InvalidInput)` if the URL is not from archlinux.org
/// - Returns `Err(ArchToolkitError::EmptyInput)` if names slice is empty and strict mode is enabled
/// - Returns `Err(ArchToolkitError::InvalidPackageName)` if any package name is invalid
/// - Returns `Err(ArchToolkitError::InputTooLong)` if any package name exceeds maximum length
pub async fn info(client: &ArchClient, names: &[&str]) -> Result<Vec<AurPackageDetails>> {
    // Validate input
    let validation_config = client.validation_config();
    validate_package_names(names, Some(validation_config))?;

    // In lenient mode, empty slice returns empty results
    if names.is_empty() {
        return Ok(Vec::new());
    }

    // Check cache if enabled
    if let Some(cache_config) = client.cache_config()
        && cache_config.enable_info
        && let Some(cache) = client.cache()
    {
        let cache_key = cache_key_info(names);
        if let Some(cached) = cache.get::<Vec<AurPackageDetails>>(&cache_key) {
            debug!(names = ?names, "cache hit for info");
            return Ok(cached);
        }
    }

    // Build URL with multiple arg parameters using array notation
    // AUR RPC v5 requires arg[]=name1&arg[]=name2 format for multiple packages.
    // Names must be percent-encoded: a raw `+` (valid in package names) would
    // otherwise be decoded as a space by the server.
    let mut url = String::from("https://aur.archlinux.org/rpc/v5/info?");
    for (i, name) in names.iter().enumerate() {
        if i > 0 {
            url.push('&');
        }
        url.push_str("arg[]=");
        url.push_str(&crate::aur::utils::percent_encode(name));
    }

    debug!(names = ?names, url = %url, "fetching AUR package info");

    // Apply rate limiting for archlinux.org
    let _permit = if is_archlinux_url(&url) {
        rate_limit_archlinux().await
    } else {
        return Err(ArchToolkitError::InvalidInput(format!(
            "Unexpected URL domain: {url}"
        )));
    };

    let retry_policy = client.retry_policy();
    let http_client = client.http_client();

    // Wrap the request in retry logic if enabled
    let result = if retry_policy.enabled && retry_policy.retry_info {
        retry_with_policy(retry_policy, "info", &names.join(", "), || async {
            perform_info_request(http_client, &url, names).await
        })
        .await
    } else {
        perform_info_request(http_client, &url, names).await
    }?;

    // Store in cache if enabled
    if let Some(cache_config) = client.cache_config()
        && cache_config.enable_info
        && let Some(cache) = client.cache()
    {
        let cache_key = cache_key_info(names);
        let _ = cache.set(&cache_key, &result, cache_config.info_ttl);
    }

    Ok(result)
}

/// What: Perform the actual info request without retry logic.
///
/// Inputs:
/// - `client`: HTTP client to use for requests.
/// - `url`: URL to request.
/// - `package_names`: Package names retained in every operation error.
///
/// Output:
/// - `Result<Vec<AurPackageDetails>>` containing package details, or an error.
///
/// Details:
/// - Internal helper function that performs the HTTP request and parsing
/// - Used by both retry and non-retry code paths
async fn perform_info_request(
    client: &Client,
    url: &str,
    package_names: &[&str],
) -> Result<Vec<AurPackageDetails>> {
    let response = match client.get(url).send().await {
        Ok(resp) => {
            reset_archlinux_backoff();
            resp
        }
        Err(e) => {
            warn!(error = %e, packages = ?package_names, "AUR info request failed");
            return Err(ArchToolkitError::info_failed(package_names, e));
        }
    };

    // Check for Retry-After header before consuming response
    let _retry_after = extract_retry_after(&response);

    let response = match response.error_for_status() {
        Ok(resp) => resp,
        Err(e) => {
            warn!(error = %e, packages = ?package_names, "AUR info returned non-success status");
            return Err(ArchToolkitError::info_failed(package_names, e));
        }
    };

    let resource_label = format!("AUR info for packages [{}]", package_names.join(", "));
    let text = crate::http::read_bounded_response_text(
        response,
        MAX_AUR_INFO_RESPONSE_BYTES,
        &resource_label,
        |error| ArchToolkitError::info_failed(package_names, error),
    )
    .await?;
    let json: Value = serde_json::from_str(&text).map_err(|error| {
        ArchToolkitError::Parse(format!("failed to parse {resource_label} JSON: {error}"))
    })?;

    let mut packages = Vec::new();

    if let Some(results) = json.get("results").and_then(Value::as_array) {
        for pkg in results {
            let name = s(pkg, "Name");
            if name.is_empty() {
                continue;
            }

            let version = s(pkg, "Version");
            let description = s(pkg, "Description");
            let url = s(pkg, "URL");

            // Extract arrays
            let licenses = arrs(pkg, &["License", "Licenses"]);
            let groups = arrs(pkg, &["Groups", "Group"]);
            let provides = arrs(pkg, &["Provides"]);
            let depends = arrs(pkg, &["Depends"]);
            let make_depends = arrs(pkg, &["MakeDepends"]);
            let opt_depends = arrs(pkg, &["OptDepends"]);
            let conflicts = arrs(pkg, &["Conflicts"]);
            let replaces = arrs(pkg, &["Replaces"]);

            // Extract maintainer
            let maintainer_str = s(pkg, "Maintainer");
            let maintainer = if maintainer_str.is_empty() {
                None
            } else {
                Some(maintainer_str)
            };

            // Extract timestamps
            let first_submitted = pkg
                .get("FirstSubmitted")
                .and_then(Value::as_i64)
                .filter(|&ts| ts > 0);
            let last_modified = pkg
                .get("LastModified")
                .and_then(Value::as_i64)
                .filter(|&ts| ts > 0);

            // Extract popularity and votes
            let popularity = pkg.get("Popularity").and_then(Value::as_f64);
            let num_votes = u64_of(pkg, &["NumVotes", "Votes"]);

            // Extract out-of-date timestamp
            let out_of_date = pkg
                .get("OutOfDate")
                .and_then(Value::as_i64)
                .and_then(|ts| u64::try_from(ts).ok())
                .filter(|&ts| ts > 0);

            let orphaned = maintainer.is_none();

            packages.push(AurPackageDetails {
                name,
                version,
                description,
                url,
                licenses,
                groups,
                provides,
                depends,
                make_depends,
                opt_depends,
                conflicts,
                replaces,
                maintainer,
                first_submitted,
                last_modified,
                popularity,
                num_votes,
                out_of_date,
                orphaned,
            });
        }
    }

    debug!(found = packages.len(), "AUR info fetch completed");

    Ok(packages)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ArchToolkitError;
    use serde_json::json;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn test_info_error_includes_package_context() {
        // Test that InfoFailed error includes the package names
        let packages = &["yay", "paru"];
        let mock_error = crate::aur::utils::mock_reqwest_error();
        let error = ArchToolkitError::info_failed(packages, mock_error);
        let error_msg = format!("{error}");
        assert!(
            error_msg.contains("yay"),
            "Error message should include package names: {error_msg}"
        );
        assert!(
            error_msg.contains("paru"),
            "Error message should include all package names: {error_msg}"
        );
        assert!(
            error_msg.contains("AUR info fetch failed"),
            "Error message should indicate info operation: {error_msg}"
        );
    }

    #[tokio::test]
    /// What: Verify an oversized AUR info body is rejected before JSON parsing.
    ///
    /// Inputs:
    /// - A local response declaring a body one byte above the approved 10 MiB ceiling.
    ///
    /// Output:
    /// - `InputTooLong` retaining AUR info and package context.
    ///
    /// Details:
    /// - This regression test uses a deterministic wiremock endpoint and no live service.
    async fn oversized_aur_info_response_is_rejected() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/info"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![
                b'x';
                MAX_AUR_INFO_RESPONSE_BYTES
                    + 1
            ]))
            .mount(&server)
            .await;

        let error =
            perform_info_request(&Client::new(), &format!("{}/info", server.uri()), &["yay"])
                .await
                .expect_err("oversized AUR info response must fail");
        let message = error.to_string();

        assert!(matches!(
            error,
            ArchToolkitError::InputTooLong {
                max_length: MAX_AUR_INFO_RESPONSE_BYTES,
                ..
            }
        ));
        assert!(message.contains("info"));
        assert!(message.contains("yay"));
    }

    #[tokio::test]
    /// What: Preserve operation and package context for empty or malformed AUR info JSON.
    ///
    /// Inputs:
    /// - Local empty and syntactically malformed successful responses.
    ///
    /// Output:
    /// - Contextual `Parse` errors for both bodies.
    ///
    /// Details:
    /// - Explicit serde JSON parsing occurs only after the bounded UTF-8 read.
    async fn empty_and_malformed_aur_info_bodies_are_contextual() {
        for (path_value, body) in [("/empty", ""), ("/malformed", "{")] {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path(path_value))
                .respond_with(ResponseTemplate::new(200).set_body_string(body))
                .mount(&server)
                .await;

            let error = perform_info_request(
                &Client::new(),
                &format!("{}{path_value}", server.uri()),
                &["yay"],
            )
            .await
            .expect_err("invalid AUR info JSON must fail");
            let message = error.to_string();

            assert!(matches!(error, ArchToolkitError::Parse(_)));
            assert!(message.contains("AUR info"));
            assert!(message.contains("yay"));
        }
    }

    #[tokio::test]
    /// What: Preserve info-operation context for a non-success status.
    ///
    /// Inputs:
    /// - A local HTTP 503 response for package `yay`.
    ///
    /// Output:
    /// - Existing `InfoFailed` with status and package context.
    ///
    /// Details:
    /// - Status handling remains ahead of bounded body consumption.
    async fn non_success_aur_info_status_is_contextual() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/info"))
            .respond_with(ResponseTemplate::new(503))
            .mount(&server)
            .await;

        let error =
            perform_info_request(&Client::new(), &format!("{}/info", server.uri()), &["yay"])
                .await
                .expect_err("non-success AUR info status must fail");
        let message = error.to_string();

        assert!(matches!(error, ArchToolkitError::InfoFailed { .. }));
        assert!(message.contains("yay"));
        assert!(message.contains("503"));
    }

    #[tokio::test]
    /// What: Parse a normal bounded AUR info fixture through the request path.
    ///
    /// Inputs:
    /// - One valid AUR RPC result from a local HTTP server.
    ///
    /// Output:
    /// - One populated `AurPackageDetails` entry.
    ///
    /// Details:
    /// - Covers the explicit JSON parser after streamed response reading.
    async fn normal_aur_info_fixture_is_parsed() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/info"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "results": [{
                    "Name": "yay",
                    "Version": "12.3.4-1",
                    "Description": "AUR helper",
                    "Depends": ["git"]
                }]
            })))
            .mount(&server)
            .await;

        let packages =
            perform_info_request(&Client::new(), &format!("{}/info", server.uri()), &["yay"])
                .await
                .expect("normal AUR info fixture");

        assert_eq!(packages.len(), 1);
        assert_eq!(packages[0].name, "yay");
        assert_eq!(packages[0].depends, ["git"]);
    }

    #[test]
    fn test_info_parses_valid_response() {
        let json = json!({
            "results": [
                {
                    "Name": "yay",
                    "Version": "12.3.4-1",
                    "Description": "AUR helper",
                    "URL": "https://github.com/Jguer/yay",
                    "License": ["MIT"],
                    "Groups": [],
                    "Provides": [],
                    "Depends": ["git", "go"],
                    "MakeDepends": ["git"],
                    "OptDepends": ["sudo: privilege escalation"],
                    "Conflicts": [],
                    "Replaces": [],
                    "Maintainer": "someuser",
                    "FirstSubmitted": 1_234_567_890,
                    "LastModified": 1_234_567_891,
                    "Popularity": 3.0,
                    "NumVotes": 100,
                    "OutOfDate": null
                }
            ]
        });

        let results = json
            .get("results")
            .and_then(Value::as_array)
            .expect("test JSON should have results array");
        let mut packages = Vec::new();

        for pkg in results {
            let name = s(pkg, "Name");
            if name.is_empty() {
                continue;
            }

            let version = s(pkg, "Version");
            let description = s(pkg, "Description");
            let url = s(pkg, "URL");

            let licenses = arrs(pkg, &["License", "Licenses"]);
            let groups = arrs(pkg, &["Groups", "Group"]);
            let provides = arrs(pkg, &["Provides"]);
            let depends = arrs(pkg, &["Depends"]);
            let make_depends = arrs(pkg, &["MakeDepends"]);
            let opt_depends = arrs(pkg, &["OptDepends"]);
            let conflicts = arrs(pkg, &["Conflicts"]);
            let replaces = arrs(pkg, &["Replaces"]);

            let maintainer_str = s(pkg, "Maintainer");
            let maintainer = if maintainer_str.is_empty() {
                None
            } else {
                Some(maintainer_str)
            };

            let first_submitted = pkg
                .get("FirstSubmitted")
                .and_then(Value::as_i64)
                .filter(|&ts| ts > 0);
            let last_modified = pkg
                .get("LastModified")
                .and_then(Value::as_i64)
                .filter(|&ts| ts > 0);

            let popularity = pkg.get("Popularity").and_then(Value::as_f64);
            let num_votes = u64_of(pkg, &["NumVotes", "Votes"]);

            let out_of_date = pkg
                .get("OutOfDate")
                .and_then(Value::as_i64)
                .and_then(|ts| u64::try_from(ts).ok())
                .filter(|&ts| ts > 0);

            let orphaned = maintainer.is_none();

            packages.push(AurPackageDetails {
                name,
                version,
                description,
                url,
                licenses,
                groups,
                provides,
                depends,
                make_depends,
                opt_depends,
                conflicts,
                replaces,
                maintainer,
                first_submitted,
                last_modified,
                popularity,
                num_votes,
                out_of_date,
                orphaned,
            });
        }

        assert_eq!(packages.len(), 1);
        assert_eq!(packages[0].name, "yay");
        assert_eq!(packages[0].version, "12.3.4-1");
        assert_eq!(packages[0].depends, vec!["git", "go"]);
        assert_eq!(packages[0].opt_depends, vec!["sudo: privilege escalation"]);
        assert_eq!(packages[0].num_votes, Some(100));
    }
}