-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
async_cache.rs
540 lines (468 loc) · 17.4 KB
/
async_cache.rs
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
528
529
530
531
532
533
534
535
536
537
538
539
540
use std::sync::{atomic::AtomicU8, Arc, Mutex};
use futures::{stream::FuturesUnordered, StreamExt};
use tokio::sync::{mpsc, oneshot, Semaphore};
use tracing::{warn, Instrument, Level};
use turbopath::{AbsoluteSystemPath, AbsoluteSystemPathBuf, AnchoredSystemPathBuf};
use turborepo_analytics::AnalyticsSender;
use turborepo_api_client::{APIAuth, APIClient};
use crate::{
http::UploadMap, multiplexer::CacheMultiplexer, CacheError, CacheHitMetadata, CacheOpts,
};
const WARNING_CUTOFF: u8 = 4;
#[derive(Clone)]
pub struct AsyncCache {
real_cache: Arc<CacheMultiplexer>,
writer_sender: mpsc::Sender<WorkerRequest>,
}
enum WorkerRequest {
WriteRequest {
anchor: AbsoluteSystemPathBuf,
key: String,
duration: u64,
files: Vec<AnchoredSystemPathBuf>,
},
Flush(oneshot::Sender<()>),
/// Shutdown the cache. The first oneshot notifies when shutdown starts and
/// allows the user to inspect the status of the uploads. The second
/// oneshot notifies when the shutdown is complete.
Shutdown(oneshot::Sender<Arc<Mutex<UploadMap>>>, oneshot::Sender<()>),
}
impl AsyncCache {
pub fn new(
opts: &CacheOpts,
repo_root: &AbsoluteSystemPath,
api_client: APIClient,
api_auth: Option<APIAuth>,
analytics_recorder: Option<AnalyticsSender>,
) -> Result<AsyncCache, CacheError> {
let max_workers = opts.workers.try_into().expect("usize is smaller than u32");
let real_cache = Arc::new(CacheMultiplexer::new(
opts,
repo_root,
api_client,
api_auth,
analytics_recorder,
)?);
let (writer_sender, mut write_consumer) = mpsc::channel(1);
// start a task to manage workers
let worker_real_cache = real_cache.clone();
tokio::spawn(async move {
let semaphore = Arc::new(Semaphore::new(max_workers));
let mut workers = FuturesUnordered::new();
let real_cache = worker_real_cache;
let warnings = Arc::new(AtomicU8::new(0));
let mut shutdown_callback = None;
while let Some(request) = write_consumer.recv().await {
match request {
WorkerRequest::WriteRequest {
anchor,
key,
duration,
files,
} => {
let permit = semaphore.clone().acquire_owned().await.unwrap();
let real_cache = real_cache.clone();
let warnings = warnings.clone();
let worker_span = tracing::span!(Level::TRACE, "cache worker: cache PUT");
workers.push(tokio::spawn(
async move {
if let Err(err) =
real_cache.put(&anchor, &key, &files, duration).await
{
let num_warnings =
warnings.load(std::sync::atomic::Ordering::Acquire);
if num_warnings <= WARNING_CUTOFF {
warnings.store(
num_warnings + 1,
std::sync::atomic::Ordering::Release,
);
warn!("{err}");
}
}
// Release permit once we're done with the write
drop(permit);
}
.instrument(worker_span),
))
}
WorkerRequest::Flush(callback) => {
// Wait on all workers to finish writing
while let Some(worker) = workers.next().await {
let _ = worker;
}
drop(callback);
}
WorkerRequest::Shutdown(closing, done) => {
shutdown_callback = Some((closing, done));
break;
}
};
}
// Drop write consumer to immediately notify callers that cache is shutting down
drop(write_consumer);
let shutdown_callback = if let Some((closing, done)) = shutdown_callback {
closing.send(real_cache.requests().unwrap_or_default()).ok();
Some(done)
} else {
None
};
// wait for all writers to finish
while let Some(worker) = workers.next().await {
let _ = worker;
}
if let Some(callback) = shutdown_callback {
callback.send(()).ok();
}
});
Ok(AsyncCache {
real_cache,
writer_sender,
})
}
#[tracing::instrument(skip_all)]
pub async fn put(
&self,
anchor: AbsoluteSystemPathBuf,
key: String,
files: Vec<AnchoredSystemPathBuf>,
duration: u64,
) -> Result<(), CacheError> {
if self
.writer_sender
.send(WorkerRequest::WriteRequest {
anchor,
key,
duration,
files,
})
.await
.is_err()
{
Err(CacheError::CacheShuttingDown)
} else {
Ok(())
}
}
#[tracing::instrument(skip_all)]
pub async fn exists(&self, key: &str) -> Result<Option<CacheHitMetadata>, CacheError> {
self.real_cache.exists(key).await
}
#[tracing::instrument(skip_all)]
pub async fn fetch(
&self,
anchor: &AbsoluteSystemPath,
key: &str,
) -> Result<Option<(CacheHitMetadata, Vec<AnchoredSystemPathBuf>)>, CacheError> {
self.real_cache.fetch(anchor, key).await
}
// Used for testing to ensure that the workers resolve
// before checking the cache.
#[tracing::instrument(skip_all)]
pub async fn wait(&self) -> Result<(), CacheError> {
let (tx, rx) = oneshot::channel();
self.writer_sender
.send(WorkerRequest::Flush(tx))
.await
.map_err(|_| CacheError::CacheShuttingDown)?;
// Wait until flush callback is finished
rx.await.ok();
Ok(())
}
/// Shut down the cache, waiting for all workers to finish writing.
/// This function returns as soon as the shut down has started,
/// returning a channel through which workers can report on their
/// progress.
#[tracing::instrument(skip_all)]
pub async fn start_shutdown(
&self,
) -> Result<(Arc<Mutex<UploadMap>>, oneshot::Receiver<()>), CacheError> {
let (closing_tx, closing_rx) = oneshot::channel::<Arc<Mutex<UploadMap>>>();
let (closed_tx, closed_rx) = oneshot::channel::<()>();
self.writer_sender
.send(WorkerRequest::Shutdown(closing_tx, closed_tx))
.await
.map_err(|_| CacheError::CacheShuttingDown)?;
Ok((closing_rx.await.unwrap(), closed_rx)) // todo
}
/// Shut down the cache, waiting for all workers to finish writing.
/// This function returns only when the last worker is complete.
/// It is a convenience wrapper around `start_shutdown`.
#[tracing::instrument(skip_all)]
pub async fn shutdown(&self) -> Result<(), CacheError> {
let (_, closed_rx) = self.start_shutdown().await?;
closed_rx.await.ok();
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::{assert_matches::assert_matches, time::Duration};
use anyhow::Result;
use camino::Utf8PathBuf;
use futures::future::try_join_all;
use tempfile::tempdir;
use turbopath::AbsoluteSystemPathBuf;
use turborepo_api_client::{APIAuth, APIClient};
use turborepo_vercel_api_mock::start_test_server;
use crate::{
test_cases::{get_test_cases, TestCase},
AsyncCache, CacheActions, CacheConfig, CacheHitMetadata, CacheOpts, CacheSource,
RemoteCacheOpts,
};
#[tokio::test]
async fn test_async_cache() -> Result<()> {
let port = port_scanner::request_open_port().unwrap();
let handle = tokio::spawn(start_test_server(port));
try_join_all(get_test_cases().into_iter().map(|test_case| async move {
round_trip_test_with_both_caches(&test_case, port).await?;
round_trip_test_without_remote_cache(&test_case).await?;
round_trip_test_without_fs(&test_case, port).await
}))
.await?;
handle.abort();
Ok(())
}
async fn round_trip_test_without_fs(test_case: &TestCase, port: u16) -> Result<()> {
let repo_root = tempdir()?;
let repo_root_path = AbsoluteSystemPathBuf::try_from(repo_root.path())?;
test_case.initialize(&repo_root_path)?;
let hash = format!("{}-no-fs", test_case.hash);
let opts = CacheOpts {
cache_dir: Utf8PathBuf::from(".turbo/cache"),
cache: CacheConfig {
local: CacheActions {
read: false,
write: false,
},
remote: CacheActions {
read: true,
write: true,
},
},
workers: 10,
remote_cache_opts: Some(RemoteCacheOpts {
unused_team_id: Some("my-team".to_string()),
signature: false,
}),
};
let api_client = APIClient::new(
format!("http://localhost:{}", port),
Some(Duration::from_secs(200)),
None,
"2.0.0",
true,
)?;
let api_auth = Some(APIAuth {
team_id: Some("my-team-id".to_string()),
token: "my-token".to_string(),
team_slug: None,
});
let async_cache = AsyncCache::new(&opts, &repo_root_path, api_client, api_auth, None)?;
// Ensure that the cache is empty
let response = async_cache.exists(&hash).await;
assert_matches!(response, Ok(None));
// Add test case
async_cache
.put(
repo_root_path.clone(),
hash.clone(),
test_case
.files
.iter()
.map(|f| f.path().to_owned())
.collect(),
test_case.duration,
)
.await
.unwrap();
// Wait for async cache to process
async_cache.wait().await.unwrap();
let fs_cache_path =
repo_root_path.join_components(&[".turbo", "cache", &format!("{}.tar.zst", hash)]);
// Confirm that fs cache file does *not* exist
assert!(!fs_cache_path.exists());
let response = async_cache.exists(&hash).await?;
// Confirm that we fetch from remote cache and not local.
assert_eq!(
response,
Some(CacheHitMetadata {
source: CacheSource::Remote,
time_saved: test_case.duration
})
);
async_cache.shutdown().await.unwrap();
assert!(
async_cache.shutdown().await.is_err(),
"second shutdown should error"
);
Ok(())
}
async fn round_trip_test_without_remote_cache(test_case: &TestCase) -> Result<()> {
let repo_root = tempdir()?;
let repo_root_path = AbsoluteSystemPathBuf::try_from(repo_root.path())?;
test_case.initialize(&repo_root_path)?;
let hash = format!("{}-no-remote", test_case.hash);
let opts = CacheOpts {
cache_dir: Utf8PathBuf::from(".turbo/cache"),
cache: CacheConfig {
local: CacheActions {
read: true,
write: true,
},
remote: CacheActions {
read: false,
write: false,
},
},
workers: 10,
remote_cache_opts: Some(RemoteCacheOpts {
unused_team_id: Some("my-team".to_string()),
signature: false,
}),
};
// Initialize client with invalid API url to ensure that we don't hit the
// network
let api_client = APIClient::new(
"http://example.com",
Some(Duration::from_secs(200)),
None,
"2.0.0",
true,
)?;
let api_auth = Some(APIAuth {
team_id: Some("my-team-id".to_string()),
token: "my-token".to_string(),
team_slug: None,
});
let async_cache = AsyncCache::new(&opts, &repo_root_path, api_client, api_auth, None)?;
// Ensure that the cache is empty
let response = async_cache.exists(&hash).await;
assert_matches!(response, Ok(None));
// Add test case
async_cache
.put(
repo_root_path.clone(),
hash.clone(),
test_case
.files
.iter()
.map(|f| f.path().to_owned())
.collect(),
test_case.duration,
)
.await
.unwrap();
// Wait for async cache to process
async_cache.wait().await.unwrap();
let fs_cache_path =
repo_root_path.join_components(&[".turbo", "cache", &format!("{}.tar.zst", hash)]);
// Confirm that fs cache file exists
assert!(fs_cache_path.exists());
let response = async_cache.exists(&hash).await?;
// Confirm that we fetch from local cache first.
assert_eq!(
response,
Some(CacheHitMetadata {
source: CacheSource::Local,
time_saved: test_case.duration
})
);
// Remove fs cache file
fs_cache_path.remove_file()?;
let response = async_cache.exists(&hash).await?;
// Confirm that we get a cache miss
assert!(response.is_none());
async_cache.shutdown().await.unwrap();
assert!(
async_cache.shutdown().await.is_err(),
"second shutdown should error"
);
Ok(())
}
async fn round_trip_test_with_both_caches(test_case: &TestCase, port: u16) -> Result<()> {
let repo_root = tempdir()?;
let repo_root_path = AbsoluteSystemPathBuf::try_from(repo_root.path())?;
test_case.initialize(&repo_root_path)?;
let hash = format!("{}-both", test_case.hash);
let opts = CacheOpts {
cache_dir: Utf8PathBuf::from(".turbo/cache"),
cache: CacheConfig {
local: CacheActions {
read: true,
write: true,
},
remote: CacheActions {
read: true,
write: true,
},
},
workers: 10,
remote_cache_opts: Some(RemoteCacheOpts {
unused_team_id: Some("my-team".to_string()),
signature: false,
}),
};
let api_client = APIClient::new(
format!("http://localhost:{}", port),
Some(Duration::from_secs(200)),
None,
"2.0.0",
true,
)?;
let api_auth = Some(APIAuth {
team_id: Some("my-team-id".to_string()),
token: "my-token".to_string(),
team_slug: None,
});
let async_cache = AsyncCache::new(&opts, &repo_root_path, api_client, api_auth, None)?;
// Ensure that the cache is empty
let response = async_cache.exists(&hash).await;
assert_matches!(response, Ok(None));
// Add test case
async_cache
.put(
repo_root_path.clone(),
hash.clone(),
test_case
.files
.iter()
.map(|f| f.path().to_owned())
.collect(),
test_case.duration,
)
.await
.unwrap();
// Wait for async cache to process
async_cache.wait().await.unwrap();
let fs_cache_path =
repo_root_path.join_components(&[".turbo", "cache", &format!("{}.tar.zst", hash)]);
// Confirm that fs cache file exists
assert!(fs_cache_path.exists());
let response = async_cache.exists(&hash).await?;
// Confirm that we fetch from local cache first.
assert_eq!(
response,
Some(CacheHitMetadata {
source: CacheSource::Local,
time_saved: test_case.duration
})
);
// Remove fs cache file
fs_cache_path.remove_file()?;
let response = async_cache.exists(&hash).await?;
// Confirm that we still can fetch from remote cache
assert_eq!(
response,
Some(CacheHitMetadata {
source: CacheSource::Remote,
time_saved: test_case.duration
})
);
async_cache.shutdown().await.unwrap();
assert!(
async_cache.shutdown().await.is_err(),
"second shutdown should error"
);
Ok(())
}
}