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
use bytes::Bytes;
use reqwest::{Client, RequestBuilder};
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Reqwest(#[from] reqwest::Error),
#[error("did not find a runtime token in the ACTIONS_RUNTIME_TOKEN environment variable")]
NoRuntimeToken,
#[error("did not find the endpoint URL in the ACTIONS_CACHE_URL environment variable")]
NoEndpointUrl,
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Deserialize, Debug)]
pub struct CacheHit {
#[serde(rename = "cacheKey")]
pub key: String,
pub scope: String,
}
pub struct Cache {
client: Client,
token: String,
endpoint: String,
}
impl Cache {
pub fn new() -> Result<Self> {
let token = std::env::var("ACTIONS_RUNTIME_TOKEN").map_err(|_| Error::NoRuntimeToken)?;
let endpoint = format!(
"{}/_apis/artifactcache",
std::env::var("ACTIONS_CACHE_URL")
.map_err(|_| Error::NoEndpointUrl)?
.trim_end_matches('/')
);
let client = Client::builder().build()?;
Ok(Self {
client,
token,
endpoint,
})
}
fn api_request(&self, builder: RequestBuilder) -> RequestBuilder {
builder.bearer_auth(&self.token).header(
reqwest::header::ACCEPT,
"application/json;api-version=6.0-preview.1",
)
}
pub async fn get_url(
&self,
key_space: &str,
key_prefixes: &[&str],
) -> Result<Option<(CacheHit, String)>> {
#[derive(Deserialize)]
pub struct GetResponse {
#[serde(flatten)]
hit: CacheHit,
#[serde(rename = "archiveLocation")]
location: String,
}
let response = self
.api_request(self.client.get(format!("{}/cache", self.endpoint)))
.query(&[("keys", &*key_prefixes.join(",")), ("version", key_space)])
.send()
.await?;
tracing::debug!(response_headers = ?response.headers());
if response.status() == reqwest::StatusCode::NO_CONTENT {
Ok(None)
} else {
let response: GetResponse = response.error_for_status()?.json().await?;
Ok(Some((response.hit, response.location)))
}
}
pub async fn get_bytes(
&self,
key_space: &str,
keys: &[&str],
) -> Result<Option<(CacheHit, Bytes)>> {
if let Some((hit, location)) = self.get_url(key_space, keys).await? {
let response = self.client.get(location).send().await?;
tracing::debug!(response_headers = ?response.headers());
Ok(Some((hit, response.bytes().await?)))
} else {
Ok(None)
}
}
pub async fn put_bytes(&self, key_space: &str, key: &str, data: Bytes) -> Result<()> {
#[derive(Serialize)]
struct ReserveRequest<'a> {
key: &'a str,
version: &'a str,
}
#[derive(Deserialize)]
struct ReserveResponse {
#[serde(rename = "cacheId")]
cache_id: i64,
}
let response = self
.api_request(self.client.post(format!("{}/caches", self.endpoint)))
.json(&ReserveRequest {
key,
version: key_space,
})
.send()
.await?;
tracing::debug!(response_headers = ?response.headers());
let ReserveResponse { cache_id } = response.error_for_status()?.json().await?;
let response = self
.api_request(
self.client
.patch(format!("{}/caches/{}", self.endpoint, cache_id)),
)
.header(
reqwest::header::CONTENT_RANGE,
format!("bytes {}-{}/*", 0, data.len()),
)
.header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
.body(data.clone())
.send()
.await?;
tracing::debug!(response_headers = ?response.headers());
response.error_for_status()?;
#[derive(Serialize)]
struct RequestBody<'a> {
key: &'a str,
version: &'a str,
}
#[derive(Serialize)]
struct FinalizeRequest {
size: usize,
}
let response = self
.api_request(
self.client
.post(format!("{}/caches/{}", self.endpoint, cache_id)),
)
.json(&FinalizeRequest { size: data.len() })
.send()
.await?;
tracing::debug!(response_headers = ?response.headers());
response.error_for_status()?;
Ok(())
}
}