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
impl DocValidator {
/// Creates a new validator with default configuration
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn new(config: ValidatorConfig) -> Self {
#[cfg(feature = "http-client")]
let http_client = if config.http_timeout_ms > 0 {
Some(
reqwest::Client::builder()
.timeout(Duration::from_millis(config.http_timeout_ms))
.user_agent(&config.user_agent)
.redirect(if config.follow_redirects {
reqwest::redirect::Policy::limited(10)
} else {
reqwest::redirect::Policy::none()
})
.build()
.expect("Failed to create HTTP client"),
)
} else {
None
};
Self {
config,
#[cfg(feature = "http-client")]
http_client,
}
}
/// Validates a single link
///
/// # Examples
///
/// ```no_run
/// use pmat::services::doc_validator::{DocValidator, Link, LinkType, ValidatorConfig};
/// use std::path::PathBuf;
///
/// #[tokio::main]
/// async fn main() {
/// let validator = DocValidator::new(ValidatorConfig::default());
/// let link = Link {
/// text: "Example".to_string(),
/// target: "https://example.com".to_string(),
/// source_file: PathBuf::from("test.md"),
/// line_number: 1,
/// link_type: LinkType::ExternalHttp,
/// };
///
/// let result = validator.validate_link(&link).await;
/// assert!(result.is_ok());
/// }
/// ```
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub async fn validate_link(&self, link: &Link) -> Result<ValidationResult> {
let start = Instant::now();
let (status, error_message, http_status) = match &link.link_type {
LinkType::Internal => self.validate_internal_link(link).await,
LinkType::ExternalHttp => self.validate_http_link(link).await,
LinkType::Anchor => self.validate_anchor_link(link).await,
LinkType::Email => (ValidationStatus::Valid, None, None), // Don't validate emails
LinkType::Other(_) => (ValidationStatus::Skipped, None, None),
};
Ok(ValidationResult {
link: link.clone(),
status,
error_message,
http_status_code: http_status,
response_time_ms: Some(start.elapsed().as_millis() as u64),
})
}
/// Validates an internal file link
async fn validate_internal_link(
&self,
link: &Link,
) -> (ValidationStatus, Option<String>, Option<u16>) {
// Remove anchor from target
let target = link
.target
.split('#')
.next()
.expect("split should have at least one element");
// Skip empty targets (pure anchors)
if target.is_empty() {
return (ValidationStatus::Valid, None, None);
}
// Resolve relative path
let base_dir = link.source_file.parent().unwrap_or_else(|| Path::new("."));
let target_path = base_dir.join(target);
let normalized_path = normalize_path(&target_path);
if normalized_path.exists() {
(ValidationStatus::Valid, None, None)
} else {
(
ValidationStatus::NotFound,
Some(format!("File not found: {}", normalized_path.display())),
None,
)
}
}
/// Validates an HTTP/HTTPS link with retry logic
#[cfg(feature = "http-client")]
async fn validate_http_link(
&self,
link: &Link,
) -> (ValidationStatus, Option<String>, Option<u16>) {
let client = match &self.http_client {
Some(c) => c,
None => {
return (
ValidationStatus::NetworkError,
Some("HTTP client not configured".to_string()),
None,
)
}
};
// Issue #101: Handle crates.io URLs specially - they block programmatic access
// Use the crates.io API instead of scraping the web page
if let Some(crate_name) = Self::extract_crates_io_crate_name(&link.target) {
return self.validate_crates_io_crate(client, &crate_name).await;
}
let mut retries = 0;
loop {
match client.head(&link.target).send().await {
Ok(response) => {
let status_code = response.status().as_u16();
return if status_code == 404 {
(
ValidationStatus::NotFound,
Some(format!("HTTP 404: {}", link.target)),
Some(status_code),
)
} else if (200..300).contains(&status_code) {
(ValidationStatus::Valid, None, Some(status_code))
} else {
(
ValidationStatus::HttpError(status_code),
Some(format!("HTTP {}: {}", status_code, link.target)),
Some(status_code),
)
};
}
Err(e) => {
retries += 1;
if retries >= self.config.max_retries {
return (
ValidationStatus::NetworkError,
Some(format!("Network error: {}", e)),
None,
);
}
tokio::time::sleep(Duration::from_millis(
self.config.retry_delay_ms * 2_u64.pow(retries - 1),
))
.await;
}
}
}
}
/// Extract crate name from crates.io URL (Issue #101)
/// Handles: https://crates.io/crates/{crate_name}
#[cfg(feature = "http-client")]
fn extract_crates_io_crate_name(url: &str) -> Option<String> {
// Match patterns like:
// - https://crates.io/crates/trueno
// - http://crates.io/crates/trueno
// - https://crates.io/crates/trueno/versions
let patterns = ["https://crates.io/crates/", "http://crates.io/crates/"];
for pattern in patterns {
if let Some(rest) = url.strip_prefix(pattern) {
// Get the crate name (up to the next / or end)
let crate_name = rest.split('/').next()?;
if !crate_name.is_empty() {
return Some(crate_name.to_string());
}
}
}
None
}
/// Fallback when http-client feature is disabled
#[cfg(not(feature = "http-client"))]
async fn validate_http_link(
&self,
_link: &Link,
) -> (ValidationStatus, Option<String>, Option<u16>) {
(
ValidationStatus::Skipped,
Some("HTTP validation requires http-client feature".to_string()),
None,
)
}
/// Validate a crate exists using the crates.io API (Issue #101)
#[cfg(feature = "http-client")]
async fn validate_crates_io_crate(
&self,
client: &reqwest::Client,
crate_name: &str,
) -> (ValidationStatus, Option<String>, Option<u16>) {
// Use the crates.io API which accepts programmatic access
let api_url = format!("https://crates.io/api/v1/crates/{}", crate_name);
match client
.get(&api_url)
.header("User-Agent", "pmat-doc-validator/1.0")
.send()
.await
{
Ok(response) => {
let status_code = response.status().as_u16();
if status_code == 200 {
(ValidationStatus::Valid, None, Some(status_code))
} else if status_code == 404 {
(
ValidationStatus::NotFound,
Some(format!("Crate not found on crates.io: {}", crate_name)),
Some(status_code),
)
} else {
(
ValidationStatus::HttpError(status_code),
Some(format!(
"crates.io API error {}: {}",
status_code, crate_name
)),
Some(status_code),
)
}
}
Err(e) => (
ValidationStatus::NetworkError,
Some(format!("crates.io API error: {}", e)),
None,
),
}
}
/// Validates an anchor link
async fn validate_anchor_link(
&self,
_link: &Link,
) -> (ValidationStatus, Option<String>, Option<u16>) {
// Anchor validation not yet implemented; assumes valid
(ValidationStatus::Valid, None, None)
}
/// Checks if a path should be excluded
fn should_exclude(&self, path: &Path) -> bool {
let path_str = path.to_string_lossy();
for pattern in &self.config.exclude_patterns {
if path_str.contains(pattern) {
return true;
}
}
false
}
/// Validates all links in a directory
///
/// # Examples
///
/// ```no_run
/// use pmat::services::doc_validator::{DocValidator, ValidatorConfig};
/// use std::path::PathBuf;
///
/// #[tokio::main]
/// async fn main() {
/// let validator = DocValidator::new(ValidatorConfig::default());
/// let summary = validator.validate_directory(&PathBuf::from("docs")).await.unwrap();
///
/// if summary.broken_links > 0 {
/// eprintln!("Found {} broken links", summary.broken_links);
/// std::process::exit(1);
/// }
/// }
/// ```
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn validate_directory(&self, root: &Path) -> Result<ValidationSummary> {
let start = Instant::now();
let mut all_links = Vec::new();
let mut file_count = 0;
// Find all markdown files, skipping excluded directories
for entry in WalkDir::new(root)
.into_iter()
.filter_entry(|e| !self.should_exclude(e.path()))
.filter_map(|e| e.ok())
.filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "md"))
{
file_count += 1;
let content = tokio::fs::read_to_string(entry.path())
.await
.context(format!("Failed to read {}", entry.path().display()))?;
let links = extract_links(&content, entry.path());
all_links.extend(links);
}
// Validate all links concurrently
let results = self.validate_links_concurrent(&all_links).await?;
// Compute summary
let valid_count = results
.iter()
.filter(|r| r.status == ValidationStatus::Valid)
.count();
let broken_count = results
.iter()
.filter(|r| {
matches!(
r.status,
ValidationStatus::NotFound | ValidationStatus::HttpError(_)
)
})
.count();
let skipped_count = results
.iter()
.filter(|r| r.status == ValidationStatus::Skipped)
.count();
Ok(ValidationSummary {
total_files: file_count,
total_links: all_links.len(),
valid_links: valid_count,
broken_links: broken_count,
skipped_links: skipped_count,
duration_ms: start.elapsed().as_millis() as u64,
results,
})
}
/// Validates multiple links concurrently
async fn validate_links_concurrent(&self, links: &[Link]) -> Result<Vec<ValidationResult>> {
use futures::stream::{self, StreamExt};
let results = stream::iter(links)
.map(|link| async move { self.validate_link(link).await })
.buffer_unordered(self.config.max_concurrent_requests)
.collect::<Vec<_>>()
.await;
results.into_iter().collect()
}
}
impl Default for DocValidator {
fn default() -> Self {
Self::new(ValidatorConfig::default())
}
}