forked from rust-lang/docs.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepackage.rs
More file actions
475 lines (412 loc) · 14.4 KB
/
repackage.rs
File metadata and controls
475 lines (412 loc) · 14.4 KB
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
use anyhow::Result;
use docs_rs_storage::{AsyncStorage, FileEntry, rustdoc_archive_path, source_archive_path};
use docs_rs_types::{CompressionAlgorithm, KrateName, ReleaseId, Version};
use docs_rs_utils::{retry_async, spawn_blocking};
use futures_util::TryStreamExt as _;
use sqlx::Acquire as _;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::{fs, io};
use tracing::{debug, info, instrument};
/// repackage old rustdoc / source content.
///
/// New releases are storaged as ZIP files for quite some time already,
/// from the current 1.9 million releases, only 363k are old non-archive
/// releases, where we store all the single files on the storage.
///
/// Since I don't want to rebuild all of these,
/// and I don't even know if stuff that old can be rebuilt with current toolchains,
/// I'll just repackage the old file.
///
/// So
/// 1. download all files for rustdoc / source from storage
/// 2. create a ZIP archive containing all these files
/// 3. upload the zip
/// 4. update database entries accordingly
/// 5. delete old files
///
/// When that's done, I can remove all the logic in the codebase related to
/// non-archive storage.
#[instrument(skip_all, fields(rid=%rid, name=%name, version=%version))]
pub async fn repackage(
conn: &mut sqlx::PgConnection,
storage: &AsyncStorage,
rid: ReleaseId,
name: &KrateName,
version: &Version,
) -> Result<()> {
info!("repackaging");
let mut transaction = conn.begin().await?;
let rustdoc_prefix = format!("rustdoc/{name}/{version}/");
let rustdoc_archive_path = rustdoc_archive_path(name, version);
let sources_prefix = format!("sources/{name}/{version}/");
let source_archive_path = source_archive_path(name, version);
let mut algs: HashSet<CompressionAlgorithm> = HashSet::new();
if let Some((_rustdoc_file_list, alg)) =
repackage_path(storage, &rustdoc_prefix, &rustdoc_archive_path).await?
{
algs.insert(alg);
}
if let Some((_source_file_list, alg)) =
repackage_path(storage, &sources_prefix, &source_archive_path).await?
{
algs.insert(alg);
};
let affected = sqlx::query!(
r#"
UPDATE releases
SET archive_storage = TRUE
WHERE id = $1;
"#,
rid as _,
)
.execute(&mut *transaction)
.await?
.rows_affected();
debug_assert!(
affected > 0,
"release not found in database. Can't update archive_storage"
);
sqlx::query!("DELETE FROM compression_rels WHERE release = $1;", rid as _)
.execute(&mut *transaction)
.await?;
for alg in algs {
sqlx::query!(
"INSERT INTO compression_rels (release, algorithm)
VALUES ($1, $2)
ON CONFLICT DO NOTHING;",
rid as _,
&(alg as i32)
)
.execute(&mut *transaction)
.await?;
}
transaction.commit().await?;
// only delete the old files when we were able to update database with `archive_storage=true`,
// and were able to validate the zip file.
info!("removing legacy files from storage...");
storage.delete_prefix(&rustdoc_prefix).await?;
storage.delete_prefix(&sources_prefix).await?;
Ok(())
}
/// repackage contents of a S3 path prefix into a single archive file.
///
/// Not performance optimized, for now it just tries to be simple.
async fn repackage_path(
storage: &AsyncStorage,
prefix: &str,
target_archive: &str,
) -> Result<Option<(Vec<FileEntry>, CompressionAlgorithm)>> {
const DOWNLOAD_CONCURRENCY: usize = 8;
info!("repackage path");
let tempdir = spawn_blocking(|| tempfile::tempdir().map_err(Into::into)).await?;
let tempdir_path = tempdir.path().to_path_buf();
let files = Arc::new(AtomicUsize::new(0));
storage
.list_prefix(prefix)
.await
.try_for_each_concurrent(DOWNLOAD_CONCURRENCY, {
|entry| {
let tempdir_path = tempdir_path.clone();
let files = files.clone();
async move {
debug!(path=%entry, "downloading file");
let mut stream = storage.get_stream(&entry).await?;
let target_path = tempdir_path.join(stream.path.trim_start_matches(prefix));
if let Some(parent) = target_path.parent() {
fs::create_dir_all(parent).await?;
}
let mut output_file = fs::File::create(&target_path).await?;
io::copy(&mut stream.content, &mut output_file).await?;
output_file.sync_all().await?;
files.fetch_add(1, Ordering::Relaxed);
Ok(())
}
}
})
.await?;
let files = files.load(Ordering::Relaxed);
if files > 0 {
info!("creating zip file...");
let (file_list, alg) = retry_async(
|| {
let path = tempdir.path().to_path_buf();
async move { storage.store_all_in_archive(target_archive, &path).await }
},
3,
)
.await?;
info!("removing temp-dir...");
fs::remove_dir_all(&tempdir).await?;
Ok(Some((file_list, alg)))
} else {
Ok(None)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::TestEnvironment;
use docs_rs_storage::{PathNotFoundError, StorageKind, source_archive_path};
use docs_rs_types::testing::{KRATE, V1};
use futures_util::StreamExt as _;
use pretty_assertions::assert_eq;
use test_case::test_case;
async fn ls(storage: &AsyncStorage) -> Vec<String> {
storage
.list_prefix("")
.await
.filter_map(|path| async {
let Ok(path) = path else { return None };
if path.starts_with("rustdoc-json/") || path.starts_with("build-logs/") {
return None;
}
Some(path.clone())
})
.collect::<Vec<String>>()
.await
}
#[test_case(StorageKind::S3)]
#[test_case(StorageKind::Memory)]
#[tokio::test(flavor = "multi_thread")]
async fn test_repackage_normal(kind: StorageKind) -> Result<()> {
let env = TestEnvironment::builder()
.storage_config(docs_rs_storage::Config::test_config_with_kind(kind)?)
.build()
.await?;
const HTML_PATH: &str = "some/path.html";
const HTML_CONTENT: &str = "<html>content</html>";
const SOURCE_PATH: &str = "another/source.rs";
const SOURCE_CONTENT: &str = "fn main() {}";
let rid = env
.fake_release()
.await
.name(&KRATE)
.archive_storage(false)
.rustdoc_file_with(HTML_PATH, HTML_CONTENT.as_bytes())
.source_file(SOURCE_PATH, SOURCE_CONTENT.as_bytes())
.version(V1)
.create()
.await?;
let storage = env.storage()?;
// confirm we can fetch the files via old file-based storage.
assert_eq!(
storage
.stream_rustdoc_file(&KRATE, &V1, None, HTML_PATH, false)
.await?
.materialize(usize::MAX)
.await?
.content,
HTML_CONTENT.as_bytes()
);
assert_eq!(
storage
.stream_source_file(&KRATE, &V1, None, SOURCE_PATH, false)
.await?
.materialize(usize::MAX)
.await?
.content,
SOURCE_CONTENT.as_bytes()
);
assert_eq!(
ls(storage).await,
vec![
"rustdoc/krate/1.0.0/krate/index.html",
"rustdoc/krate/1.0.0/some/path.html",
"sources/krate/1.0.0/Cargo.toml",
"sources/krate/1.0.0/another/source.rs",
]
);
// confirm the target archives really don't exist
for path in &[
&rustdoc_archive_path(&KRATE, &V1),
&source_archive_path(&KRATE, &V1),
] {
assert!(!storage.exists(path).await?);
}
let mut conn = env.async_conn().await?;
repackage(&mut conn, storage, rid, &KRATE, &V1).await?;
// afterwards it works with rustdoc archives.
assert_eq!(
&storage
.stream_rustdoc_file(&KRATE, &V1, None, HTML_PATH, true)
.await?
.materialize(usize::MAX)
.await?
.content,
HTML_CONTENT.as_bytes(),
);
// also with source archives.
assert_eq!(
&storage
.stream_source_file(&KRATE, &V1, None, SOURCE_PATH, true)
.await?
.materialize(usize::MAX)
.await?
.content,
SOURCE_CONTENT.as_bytes(),
);
// all new files are these (`.zip`, `.zip.index`), old files are gone.
assert_eq!(
ls(storage).await,
vec![
"rustdoc/krate/1.0.0.zip",
"rustdoc/krate/1.0.0.zip.index",
"sources/krate/1.0.0.zip",
"sources/krate/1.0.0.zip.index",
]
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_repackage_without_rustdoc() -> Result<()> {
let env = TestEnvironment::builder()
.storage_config(docs_rs_storage::Config::test_config_with_kind(
StorageKind::S3,
)?)
.build()
.await?;
const HTML_PATH: &str = "some/path.html";
const SOURCE_PATH: &str = "another/source.rs";
const SOURCE_CONTENT: &str = "fn main() {}";
let rid = env
.fake_release()
.await
.name(&KRATE)
.archive_storage(false)
.rustdoc_file(HTML_PATH) // will be deleted
.source_file(SOURCE_PATH, SOURCE_CONTENT.as_bytes())
.version(V1)
.create()
.await?;
let storage = env.storage()?;
storage
.delete_prefix(&format!("rustdoc/{KRATE}/{V1}/"))
.await?;
// confirm we can fetch the files via old file-based storage.
assert!(
!storage
.rustdoc_file_exists(&KRATE, &V1, None, HTML_PATH, false)
.await?
);
assert_eq!(
storage
.stream_source_file(&KRATE, &V1, None, SOURCE_PATH, false)
.await?
.materialize(usize::MAX)
.await?
.content,
SOURCE_CONTENT.as_bytes()
);
assert_eq!(
ls(storage).await,
vec![
"sources/krate/1.0.0/Cargo.toml",
"sources/krate/1.0.0/another/source.rs",
]
);
// confirm the target archives really don't exist
for path in &[
&rustdoc_archive_path(&KRATE, &V1),
&source_archive_path(&KRATE, &V1),
] {
assert!(!storage.exists(path).await?);
}
let mut conn = env.async_conn().await?;
repackage(&mut conn, storage, rid, &KRATE, &V1).await?;
// but source archive works
assert_eq!(
&storage
.stream_source_file(&KRATE, &V1, None, SOURCE_PATH, true)
.await?
.materialize(usize::MAX)
.await?
.content,
SOURCE_CONTENT.as_bytes(),
);
// all new files are these (`.zip`, `.zip.index`), old files are gone.
assert_eq!(
ls(storage).await,
vec!["sources/krate/1.0.0.zip", "sources/krate/1.0.0.zip.index",]
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn test_repackage_without_source() -> Result<()> {
let env = TestEnvironment::builder()
.storage_config(docs_rs_storage::Config::test_config_with_kind(
StorageKind::S3,
)?)
.build()
.await?;
const HTML_PATH: &str = "some/path.html";
const HTML_CONTENT: &str = "<html>content</html>";
const SOURCE_PATH: &str = "another/source.rs";
const SOURCE_CONTENT: &str = "fn main() {}";
let rid = env
.fake_release()
.await
.name(&KRATE)
.archive_storage(false)
.rustdoc_file_with(HTML_PATH, HTML_CONTENT.as_bytes())
.source_file(SOURCE_PATH, SOURCE_CONTENT.as_bytes())
.version(V1)
.create()
.await?;
let storage = env.storage()?;
storage
.delete_prefix(&format!("sources/{KRATE}/{V1}/"))
.await?;
// confirm we can fetch the files via old file-based storage.
assert_eq!(
storage
.stream_rustdoc_file(&KRATE, &V1, None, HTML_PATH, false)
.await?
.materialize(usize::MAX)
.await?
.content,
HTML_CONTENT.as_bytes()
);
// source file doesn't exist
assert!(
storage
.stream_source_file(&KRATE, &V1, None, SOURCE_PATH, false)
.await
.unwrap_err()
.is::<PathNotFoundError>()
);
assert_eq!(
ls(storage).await,
vec![
"rustdoc/krate/1.0.0/krate/index.html",
"rustdoc/krate/1.0.0/some/path.html",
]
);
// confirm the target archives really don't exist
for path in &[
&rustdoc_archive_path(&KRATE, &V1),
&source_archive_path(&KRATE, &V1),
] {
assert!(!storage.exists(path).await?);
}
let mut conn = env.async_conn().await?;
repackage(&mut conn, storage, rid, &KRATE, &V1).await?;
// afterwards it works with rustdoc archives.
assert_eq!(
&storage
.stream_rustdoc_file(&KRATE, &V1, None, HTML_PATH, true)
.await?
.materialize(usize::MAX)
.await?
.content,
HTML_CONTENT.as_bytes(),
);
// all new files are these (`.zip`, `.zip.index`), old files are gone.
assert_eq!(
ls(storage).await,
vec!["rustdoc/krate/1.0.0.zip", "rustdoc/krate/1.0.0.zip.index",]
);
Ok(())
}
}