rattler_upload 0.4.15

A crate to Upload conda packages to various channels.
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
use std::borrow::Cow;

use fs_err::tokio as fs;
use miette::{miette, IntoDiagnostic};
use rattler_conda_types::package::AboutJson;
use rattler_conda_types::utils::url_with_trailing_slash::UrlWithTrailingSlash;
use rattler_conda_types::PackageName;
use reqwest::multipart::Form;
use reqwest::multipart::Part;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use tracing::debug;
use tracing::info;
use url::Url;

use crate::upload::opt::ForceOverwrite;

use super::package::ExtractedPackage;
use super::VERSION;

pub struct Anaconda {
    client: Client,
    url: UrlWithTrailingSlash,
}

#[derive(Serialize, Deserialize, Debug)]
struct PackageAttrs<'a> {
    package_types: Vec<String>,
    name: Cow<'a, PackageName>,
    #[serde(flatten)]
    about: Cow<'a, AboutJson>,
}

#[derive(Serialize, Deserialize, Debug)]
struct ReleaseCreationArgs<'a> {
    requirements: Vec<String>,
    announce: bool,
    description: Option<String>,
    #[serde(flatten)]
    about: Cow<'a, AboutJson>,
}

#[derive(Serialize, Deserialize, Debug)]
struct FileStageResponse {
    post_url: Url,
    form_data: serde_json::Map<String, serde_json::Value>,
    dist_id: String,
}

impl Anaconda {
    pub fn new(token: String, url: UrlWithTrailingSlash) -> Self {
        let mut default_headers = reqwest::header::HeaderMap::new();

        default_headers.append(
            "Accept",
            "application/json".parse().expect("failed to parse"),
        );
        default_headers.append(
            "Authorization",
            format!("token {token}").parse().expect("failed to parse"),
        );

        default_headers.append(
            "x-binstar-api-version",
            "1.12.2".parse().expect("failed to parse"),
        );

        let client = Client::builder()
            .no_gzip()
            .user_agent(format!("rattler-build/{VERSION}"))
            .default_headers(default_headers)
            .build()
            .expect("failed to create client");

        Self { client, url }
    }
}

impl Anaconda {
    pub async fn create_or_update_package(
        &self,
        owner: &str,
        package: &ExtractedPackage<'_>,
    ) -> miette::Result<()> {
        let package_name = package.package_name();
        debug!("getting package {}/{}", owner, package_name.as_normalized(),);

        let url = self
            .url
            .join(&format!(
                "package/{}/{}",
                owner,
                package_name.as_normalized(),
            ))
            .into_diagnostic()?;

        let response = self
            .client
            .get(url)
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?;

        let exists = match response.status() {
            reqwest::StatusCode::OK => true,
            reqwest::StatusCode::NOT_FOUND => false,
            _ => {
                return Err(miette!(
                    "failed to get existing package: {}",
                    response.status()
                ));
            }
        };

        let url = self
            .url
            .join(&format!(
                "package/{}/{}",
                owner,
                package_name.as_normalized(),
            ))
            .into_diagnostic()?;

        // See inspect_conda_info_dir in anaconda-client
        // https://github.com/Anaconda-Platform/anaconda-client/blob/master/binstar_client/inspect_package/conda.py#L81-L150
        // dumping the entire about.json as public_attrs seems to work fine
        let payload = serde_json::json!({
            "public": true,
            "publish": false,
            "public_attrs": PackageAttrs {
                package_types: vec!["conda".to_string()],
                name: Cow::Borrowed(package_name),
                about: Cow::Borrowed(package.about_json()),
            },
        });

        let req = if exists {
            debug!(
                "updating package {}/{}",
                owner,
                package_name.as_normalized(),
            );
            self.client.patch(url)
        } else {
            debug!(
                "creating package {}/{}",
                owner,
                package_name.as_normalized(),
            );
            self.client.post(url)
        };

        req.json(&payload)
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?
            .error_for_status()
            .into_diagnostic()
            .map_err(|e| miette!("failed to create package: {}", e))?;

        Ok(())
    }

    pub async fn create_or_update_release(
        &self,
        owner: &str,
        package: &ExtractedPackage<'_>,
    ) -> miette::Result<()> {
        let package_name = package.package_name();
        let package_version = package.package_version();
        debug!(
            "getting release {}/{}/{}",
            owner,
            package_name.as_normalized(),
            package_version
        );

        let url = self
            .url
            .join(&format!(
                "release/{}/{}/{}",
                owner,
                package_name.as_normalized(),
                package_version,
            ))
            .into_diagnostic()?;

        let response = self
            .client
            .get(url)
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?;

        let exists = match response.status() {
            reqwest::StatusCode::OK => true,
            reqwest::StatusCode::NOT_FOUND => false,
            _ => {
                return Err(miette!(
                    "failed to get existing release: {}",
                    response.status()
                ));
            }
        };

        let url = self
            .url
            .join(&format!(
                "release/{}/{}/{}",
                owner,
                package_name.as_normalized(),
                package_version,
            ))
            .into_diagnostic()?;

        let req = if exists {
            debug!(
                "updating release {}/{}/{}",
                owner,
                package_name.as_normalized(),
                package_version
            );
            self.client.patch(url).json(&serde_json::json!({
                "requirements": [],
                "announce": false,
                "description": null,
                "public_attrs": Cow::Borrowed(package.about_json())
            }))
        } else {
            debug!(
                "creating release {}/{}/{}",
                owner,
                package_name.as_normalized(),
                package_version
            );
            self.client.post(url).json(&ReleaseCreationArgs {
                requirements: vec![],
                announce: false,
                description: None,
                about: Cow::Borrowed(package.about_json()),
            })
        };

        req.send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?
            .error_for_status()
            .into_diagnostic()
            .map_err(|e| miette!("failed to create release: {}", e))?;

        Ok(())
    }

    pub async fn remove_file(
        &self,
        owner: &str,
        package: &ExtractedPackage<'_>,
    ) -> miette::Result<()> {
        let package_name = package.package_name();
        let package_version = package.package_version();
        let subdir = package
            .subdir()
            .ok_or(miette!("missing subdir in index.json"))?;
        let filename = package
            .filename()
            .ok_or(miette!("missing filename in index.json"))?;

        debug!(
            "removing file {}/{}/{}/{}/{}",
            owner,
            package_name.as_normalized(),
            package_version,
            subdir,
            filename,
        );

        let url = self
            .url
            .join(&format!(
                "dist/{}/{}/{}/{}/{}",
                owner,
                package_name.as_normalized(),
                package_version,
                subdir,
                filename,
            ))
            .into_diagnostic()?;

        self.client
            .delete(url)
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?
            .error_for_status()
            .into_diagnostic()
            .map_err(|e| miette!("failed to remove file: {}", e))?;

        Ok(())
    }

    pub async fn upload_file(
        &self,
        owner: &str,
        channels: &[String],
        force: ForceOverwrite,
        package: &ExtractedPackage<'_>,
    ) -> miette::Result<bool> {
        if channels.is_empty() {
            return Err(miette!(
                "No channel selected - please specify at least one channel for upload to Anaconda.org"
            ));
        }

        let sha256 = package.sha256().into_diagnostic()?;

        let package_name = package.package_name();
        let version = package.package_version();

        let index_json = &package.index_json();

        let subdir = index_json
            .subdir
            .as_deref()
            .ok_or(miette!("missing subdir in index.json"))?;

        let filename = package.filename().ok_or(miette!("missing filename"))?;

        debug!(
            "uploading file {}/{}/{}/{}/{}",
            owner,
            package_name.as_normalized(),
            version,
            subdir,
            filename,
        );

        let url = self
            .url
            .join(&format!(
                "stage/{}/{}/{}/{}/{}",
                owner,
                package_name.as_normalized(),
                version,
                subdir,
                filename,
            ))
            .into_diagnostic()?;

        let payload = serde_json::json!({
            "distribution_type": "conda",
            "description": null,
            "attrs": index_json,
            "channels": channels,
            "sha256": sha256,
        });

        let resp = self
            .client
            .post(url)
            .json(&payload)
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?;

        match resp.status() {
            reqwest::StatusCode::OK => (),
            reqwest::StatusCode::CONFLICT => {
                if force.is_enabled() {
                    info!(
                        "file {} already exists, running with --force, removing file and retrying",
                        filename
                    );
                    self.remove_file(owner, package).await?;

                    // We cannot just retry the staging request here, because
                    // Anaconda might have garbage collected the release /
                    // package after the deletion of the file.
                    return Ok(false);
                } else {
                    return Err(miette!(
                        "file {} already exists, use --force to overwrite",
                        filename
                    ));
                }
            }
            _ => {
                return Err(miette!(
                    "failed to stage file, server replied with: {}",
                    resp.status()
                ));
            }
        }

        let parsed_response: FileStageResponse = resp
            .json()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to parse response: {}", e))?;

        debug!("Uploading file to S3 Bucket {}", parsed_response.post_url);

        let base64_md5 = package.base64_md5().into_diagnostic()?;
        let file_size = package.file_size().into_diagnostic()?;

        let mut form_data = Form::new();

        for (key, value) in parsed_response.form_data {
            let serde_json::Value::String(value) = value else {
                Err(miette!("invalid value in form data: {}", value))?
            };

            form_data = form_data.text(key, value);
        }

        let content = fs::read(package.path()).await.into_diagnostic()?;

        form_data = form_data.text("Content-Length", file_size.to_string());
        form_data = form_data.text("Content-MD5", base64_md5);
        form_data = form_data.part("file", Part::bytes(content));

        reqwest::Client::new()
            .post(parsed_response.post_url)
            .multipart(form_data)
            .header("Accept", "application/json")
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send request: {}", e))?
            .error_for_status()
            .into_diagnostic()
            .map_err(|e| miette!("failed to upload file, server replied with: {}", e))?;

        debug!("Committing file {}", filename);

        let url = self
            .url
            .join(&format!(
                "commit/{}/{}/{}/{}/{}",
                owner,
                package_name.as_normalized(),
                version,
                subdir,
                filename,
            ))
            .into_diagnostic()?;

        self.client
            .post(url)
            .json(&serde_json::json!({
                "dist_id": parsed_response.dist_id,
            }))
            .send()
            .await
            .into_diagnostic()
            .map_err(|e| miette!("failed to send commit: {}", e))?
            .error_for_status()
            .into_diagnostic()
            .map_err(|e| miette!("failed to commit file, server replied with: {}", e))?;

        debug!("File {} uploaded successfully", filename);

        Ok(true)
    }
}