-
-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathmod.rs
More file actions
2531 lines (2275 loc) · 76.2 KB
/
mod.rs
File metadata and controls
2531 lines (2275 loc) · 76.2 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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module implements the API access to the Sentry API as well
//! as some other APIs we interact with. In particular it can talk
//! to the GitHub API to figure out if there are new releases of the
//! sentry-cli tool.
pub mod envelopes_api;
mod connection_manager;
mod data_types;
mod encoding;
mod errors;
mod pagination;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::ffi::OsStr;
use std::fmt;
use std::fs::File;
use std::io::{self, Read as _, Write};
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::{Context as _, Result};
use backoff::backoff::Backoff as _;
use brotli::enc::BrotliEncoderParams;
use brotli::CompressorWriter;
#[cfg(target_os = "macos")]
use chrono::Duration;
use chrono::{DateTime, FixedOffset, Utc};
use clap::ArgMatches;
use flate2::write::GzEncoder;
use if_chain::if_chain;
use lazy_static::lazy_static;
use log::{debug, info, warn};
use parking_lot::Mutex;
use regex::{Captures, Regex};
use secrecy::ExposeSecret as _;
use sentry::protocol::{Exception, Values};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sha1_smol::Digest;
use symbolic::common::DebugId;
use symbolic::debuginfo::ObjectKind;
use uuid::Uuid;
use crate::api::errors::ProjectRenamedError;
use crate::config::{Auth, Config};
use crate::constants::{ARCH, DEFAULT_URL, EXT, PLATFORM, RELEASE_REGISTRY_LATEST_URL, VERSION};
use crate::utils::file_upload::LegacyUploadContext;
use crate::utils::http::{self, is_absolute_url};
use crate::utils::progress::{ProgressBar, ProgressBarMode};
use crate::utils::retry::{get_default_backoff, DurationAsMilliseconds as _};
use crate::utils::sourcemaps::get_sourcemap_reference_from_headers;
use crate::utils::ui::{capitalize_string, make_byte_progress_bar};
use self::pagination::Pagination;
use connection_manager::CurlConnectionManager;
use encoding::{PathArg, QueryArg};
use errors::{ApiError, ApiErrorKind, ApiResult, SentryError};
pub use self::data_types::*;
lazy_static! {
static ref API: Mutex<Option<Arc<Api>>> = Mutex::new(None);
}
const RETRY_STATUS_CODES: &[u32] = &[
http::HTTP_STATUS_502_BAD_GATEWAY,
http::HTTP_STATUS_503_SERVICE_UNAVAILABLE,
http::HTTP_STATUS_504_GATEWAY_TIMEOUT,
http::HTTP_STATUS_507_INSUFFICIENT_STORAGE,
http::HTTP_STATUS_524_CLOUDFLARE_TIMEOUT,
];
/// Helper for the API access.
/// Implements the low-level API access methods, and provides high-level implementations for interacting
/// with portions of the API that do not require authentication via an auth token.
pub struct Api {
config: Arc<Config>,
pool: r2d2::Pool<CurlConnectionManager>,
}
/// Wrapper for Api that ensures Auth is provided. AuthenticatedApi provides implementations of high-level
/// functions that make API requests requiring authentication via auth token.
pub struct AuthenticatedApi<'a> {
api: &'a Api,
}
pub struct RegionSpecificApi<'a> {
api: &'a AuthenticatedApi<'a>,
org: &'a str,
region_url: Option<Box<str>>,
}
/// Represents an HTTP method that is used by the API.
#[derive(Eq, PartialEq, Debug)]
pub enum Method {
Get,
Post,
Put,
Delete,
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Method::Get => write!(f, "GET"),
Method::Post => write!(f, "POST"),
Method::Put => write!(f, "PUT"),
Method::Delete => write!(f, "DELETE"),
}
}
}
/// Represents an API request. This can be customized before
/// sending but only sent once.
pub struct ApiRequest {
handle: r2d2::PooledConnection<CurlConnectionManager>,
headers: curl::easy::List,
is_authenticated: bool,
body: Option<Vec<u8>>,
progress_bar_mode: ProgressBarMode,
}
/// Represents an API response.
#[derive(Clone, Debug)]
pub struct ApiResponse {
status: u32,
headers: Vec<String>,
body: Option<Vec<u8>>,
}
impl<'a> TryFrom<&'a Api> for AuthenticatedApi<'a> {
type Error = ApiError;
fn try_from(api: &'a Api) -> ApiResult<AuthenticatedApi<'a>> {
match api.config.get_auth() {
Some(_) => Ok(AuthenticatedApi { api }),
None => Err(ApiErrorKind::AuthMissing.into()),
}
}
}
impl Api {
/// Returns the current api for the thread.
pub fn current() -> Arc<Api> {
let mut api_opt = API.lock();
if let Some(ref api) = *api_opt {
api.clone()
} else {
let api = Arc::new(Api::with_config(Config::current()));
*api_opt = Some(api.clone());
api
}
}
/// Similar to `new` but uses a specific config.
pub fn with_config(config: Arc<Config>) -> Api {
Api {
config,
#[expect(clippy::unwrap_used, reason = "legacy code")]
pool: r2d2::Pool::builder()
.max_size(16)
.build(CurlConnectionManager)
.unwrap(),
}
}
/// Utility method that unbinds the current api.
pub fn dispose_pool() {
*API.lock() = None;
}
/// Creates an AuthenticatedApi referencing this Api instance if an auth token is available.
/// If an auth token is not available, returns an error.
pub fn authenticated(&self) -> ApiResult<AuthenticatedApi<'_>> {
self.try_into()
}
// Low Level Methods
/// Create a new `ApiRequest` for the given HTTP method and URL. If the
/// URL is just a path then it's relative to the configured API host
/// and authentication is automatically enabled.
fn request(
&self,
method: Method,
url: &str,
region_url: Option<&str>,
) -> ApiResult<ApiRequest> {
let (url, auth) = self.resolve_base_url_and_auth(url, region_url)?;
self.construct_api_request(method, &url, auth)
}
fn resolve_base_url_and_auth(
&self,
url: &str,
region_url: Option<&str>,
) -> ApiResult<(String, Option<&Auth>)> {
if is_absolute_url(url) && region_url.is_some() {
return Err(ApiErrorKind::InvalidRegionRequest.into());
}
let (url, auth) = if is_absolute_url(url) {
(Cow::Borrowed(url), None)
} else {
(
Cow::Owned(match self.config.get_api_endpoint(url, region_url) {
Ok(rv) => rv,
Err(err) => return Err(ApiError::with_source(ApiErrorKind::BadApiUrl, err)),
}),
self.config.get_auth(),
)
};
Ok((url.into_owned(), auth))
}
fn construct_api_request(
&self,
method: Method,
url: &str,
auth: Option<&Auth>,
) -> ApiResult<ApiRequest> {
let mut handle = self
.pool
.get()
.map_err(|e| ApiError::with_source(ApiErrorKind::RequestFailed, e))?;
handle.reset();
if !self.config.allow_keepalive() {
handle.forbid_reuse(true).ok();
}
let mut ssl_opts = curl::easy::SslOpt::new();
if self.config.disable_ssl_revocation_check() {
ssl_opts.no_revoke(true);
}
handle.ssl_options(&ssl_opts)?;
if let Some(proxy_url) = self.config.get_proxy_url() {
handle.proxy(&proxy_url)?;
}
if let Some(proxy_username) = self.config.get_proxy_username() {
handle.proxy_username(proxy_username)?;
}
if let Some(proxy_password) = self.config.get_proxy_password() {
handle.proxy_password(proxy_password)?;
}
handle.ssl_verify_host(self.config.should_verify_ssl())?;
handle.ssl_verify_peer(self.config.should_verify_ssl())?;
// This toggles gzipping, useful for uploading large files
handle.transfer_encoding(self.config.allow_transfer_encoding())?;
let env = self.config.get_pipeline_env();
let headers = self.config.get_headers();
ApiRequest::create(handle, &method, url, auth, env, headers)
}
/// Convenience method that performs a `GET` request.
fn get(&self, path: &str) -> ApiResult<ApiResponse> {
self.request(Method::Get, path, None)?.send()
}
/// Convenience method that performs a `DELETE` request.
fn delete(&self, path: &str) -> ApiResult<ApiResponse> {
self.request(Method::Delete, path, None)?.send()
}
/// Convenience method that performs a `POST` request with JSON data.
fn post<S: Serialize>(&self, path: &str, body: &S) -> ApiResult<ApiResponse> {
self.request(Method::Post, path, None)?
.with_json_body(body)?
.send()
}
/// Convenience method that performs a `PUT` request with JSON data.
fn put<S: Serialize>(&self, path: &str, body: &S) -> ApiResult<ApiResponse> {
self.request(Method::Put, path, None)?
.with_json_body(body)?
.send()
}
/// Convenience method that downloads a file into the given file object.
pub fn download(&self, url: &str, dst: &mut File) -> ApiResult<ApiResponse> {
self.request(Method::Get, url, None)?
.follow_location(true)?
.send_into(dst)
}
/// Convenience method that downloads a file into the given file object
/// and show a progress bar
#[cfg(not(feature = "managed"))]
pub fn download_with_progress(&self, url: &str, dst: &mut File) -> ApiResult<ApiResponse> {
self.request(Method::Get, url, None)?
.follow_location(true)?
.progress_bar_mode(ProgressBarMode::Response)
.send_into(dst)
}
/// Convenience method that waits for a few seconds until a resource
/// becomes available. We only use this in the macOS binary.
#[cfg(target_os = "macos")]
pub fn wait_until_available(&self, url: &str, duration: Duration) -> ApiResult<bool> {
let started = Utc::now();
loop {
match self.request(Method::Get, url, None)?.send() {
Ok(_) => return Ok(true),
Err(err) => {
if err.kind() != ApiErrorKind::RequestFailed {
return Err(err);
}
}
}
std::thread::sleep(
Duration::milliseconds(500)
.to_std()
.expect("500ms is valid, as it is non-negative"),
);
if Utc::now() - duration > started {
return Ok(false);
}
}
}
// High Level Methods
/// Finds the latest release for sentry-cli on GitHub.
pub fn get_latest_sentrycli_release(&self) -> ApiResult<Option<SentryCliRelease>> {
let resp = self.get(RELEASE_REGISTRY_LATEST_URL)?;
// Prefer universal binary on macOS
let arch = match PLATFORM {
"darwin" => "universal",
_ => ARCH,
};
let ref_name = format!("sentry-cli-{}-{arch}{EXT}", capitalize_string(PLATFORM));
info!("Looking for file named: {ref_name}");
if resp.status() == 200 {
let info: RegistryRelease = resp.convert()?;
for (filename, _download_url) in info.file_urls {
info!("Found asset {filename}");
if filename == ref_name {
return Ok(Some(SentryCliRelease {
version: info.version,
#[cfg(not(feature = "managed"))]
download_url: _download_url,
}));
}
}
warn!("Unable to find release file");
Ok(None)
} else {
info!("Release registry returned {}", resp.status());
Ok(None)
}
}
/// Compresses a file with the given compression.
fn compress(data: &[u8], compression: ChunkCompression) -> Result<Vec<u8>, io::Error> {
Ok(match compression {
ChunkCompression::Brotli => {
let mut encoder = CompressorWriter::with_params(
Vec::new(),
0,
&BrotliEncoderParams {
quality: 6,
..Default::default()
},
);
encoder.write_all(data)?;
encoder.flush()?;
encoder.into_inner()
}
ChunkCompression::Gzip => {
let mut encoder = GzEncoder::new(Vec::new(), Default::default());
encoder.write_all(data)?;
encoder.finish()?
}
ChunkCompression::Uncompressed => data.into(),
})
}
/// Upload a batch of file chunks.
pub fn upload_chunks<'data, I, T>(
&self,
url: &str,
chunks: I,
progress_bar_mode: ProgressBarMode,
compression: ChunkCompression,
) -> ApiResult<()>
where
I: IntoIterator<Item = &'data T>,
T: AsRef<(Digest, &'data [u8])> + 'data,
{
// Curl stores a raw pointer to the stringified checksum internally. We first
// transform all checksums to string and keep them in scope until the request
// has completed. The original iterator is not needed anymore after this.
let stringified_chunks = chunks
.into_iter()
.map(T::as_ref)
.map(|&(checksum, data)| (checksum.to_string(), data));
let mut form = curl::easy::Form::new();
for (ref checksum, data) in stringified_chunks {
let name = compression.field_name();
let buffer = Api::compress(data, compression)
.map_err(|err| ApiError::with_source(ApiErrorKind::CompressionFailed, err))?;
form.part(name).buffer(&checksum, buffer).add()?
}
let request = self
.request(Method::Post, url, None)?
.with_form_data(form)?
.progress_bar_mode(progress_bar_mode);
// The request is performed to an absolute URL. Thus, `Self::request()` will
// not add the authorization header, by default. Since the URL is guaranteed
// to be a Sentry-compatible endpoint, we force the Authorization header at
// this point.
let request = match Config::current().get_auth() {
// Make sure that we don't authenticate a request
// that has been already authenticated
Some(auth) if !request.is_authenticated => request.with_auth(auth)?,
_ => request,
};
// Handle 301 or 302 requests as a missing project
let resp = request.send()?;
match resp.status() {
301 | 302 => Err(ApiErrorKind::ProjectNotFound.into()),
_ => {
resp.into_result()?;
Ok(())
}
}
}
}
impl<'a> AuthenticatedApi<'a> {
// Pass through low-level methods to API.
/// Convenience method to call self.api.get.
fn get(&self, path: &str) -> ApiResult<ApiResponse> {
self.api.get(path)
}
/// Convenience method to call self.api.delete.
fn delete(&self, path: &str) -> ApiResult<ApiResponse> {
self.api.delete(path)
}
/// Convenience method to call self.api.post.
fn post<S: Serialize>(&self, path: &str, body: &S) -> ApiResult<ApiResponse> {
self.api.post(path, body)
}
/// Convenience method to call self.api.put.
fn put<S: Serialize>(&self, path: &str, body: &S) -> ApiResult<ApiResponse> {
self.api.put(path, body)
}
/// Convenience method to call self.api.request.
fn request(&self, method: Method, url: &str) -> ApiResult<ApiRequest> {
self.api.request(method, url, None)
}
// High-level method implementations
/// Performs an API request to verify the authentication status of the
/// current token.
pub fn get_auth_info(&self) -> ApiResult<AuthInfo> {
self.get("/")?.convert()
}
/// Lists release files for the given `release`, filtered by a set of checksums.
/// When empty checksums list is provided, fetches all possible artifacts.
pub fn list_release_files_by_checksum(
&self,
org: &str,
project: Option<&str>,
release: &str,
checksums: &[String],
) -> ApiResult<Vec<Artifact>> {
let mut rv = vec![];
let mut cursor = "".to_owned();
loop {
let mut path = if let Some(project) = project {
format!(
"/projects/{}/{}/releases/{}/files/?cursor={}",
PathArg(org),
PathArg(project),
PathArg(release),
QueryArg(&cursor),
)
} else {
format!(
"/organizations/{}/releases/{}/files/?cursor={}",
PathArg(org),
PathArg(release),
QueryArg(&cursor),
)
};
let mut checksums_qs = String::new();
for checksum in checksums.iter() {
checksums_qs.push_str(&format!("&checksum={}", QueryArg(checksum)));
}
// We have a 16kb buffer for reach request configured in nginx,
// so do not even bother trying if it's too long.
// (16_384 limit still leaves us with 384 bytes for the url itself).
if !checksums_qs.is_empty() && checksums_qs.len() <= 16_000 {
path.push_str(&checksums_qs);
}
let resp = self.get(&path)?;
if resp.status() == 404 || (resp.status() == 400 && !cursor.is_empty()) {
if rv.is_empty() {
return Err(ApiErrorKind::ReleaseNotFound.into());
} else {
break;
}
}
let pagination = resp.pagination();
rv.extend(resp.convert::<Vec<Artifact>>()?);
if let Some(next) = pagination.into_next_cursor() {
cursor = next;
} else {
break;
}
}
Ok(rv)
}
/// Lists all the release files for the given `release`.
pub fn list_release_files(
&self,
org: &str,
project: Option<&str>,
release: &str,
) -> ApiResult<Vec<Artifact>> {
self.list_release_files_by_checksum(org, project, release, &[])
}
/// Get a single release file and store it inside provided descriptor.
pub fn get_release_file(
&self,
org: &str,
project: Option<&str>,
version: &str,
file_id: &str,
file_desc: &mut File,
) -> Result<(), ApiError> {
let path = if let Some(project) = project {
format!(
"/projects/{}/{}/releases/{}/files/{}/?download=1",
PathArg(org),
PathArg(project),
PathArg(version),
PathArg(file_id)
)
} else {
format!(
"/organizations/{}/releases/{}/files/{}/?download=1",
PathArg(org),
PathArg(version),
PathArg(file_id)
)
};
let resp = self.api.download(&path, file_desc)?;
if resp.status() == 404 {
resp.convert_rnf(ApiErrorKind::ResourceNotFound)
} else {
Ok(())
}
}
/// Get a single release file metadata.
pub fn get_release_file_metadata(
&self,
org: &str,
project: Option<&str>,
version: &str,
file_id: &str,
) -> ApiResult<Option<Artifact>> {
let path = if let Some(project) = project {
format!(
"/projects/{}/{}/releases/{}/files/{}/",
PathArg(org),
PathArg(project),
PathArg(version),
PathArg(file_id)
)
} else {
format!(
"/organizations/{}/releases/{}/files/{}/",
PathArg(org),
PathArg(version),
PathArg(file_id)
)
};
let resp = self.get(&path)?;
if resp.status() == 404 {
Ok(None)
} else {
resp.convert()
}
}
/// Deletes a single release file. Returns `true` if the file was
/// deleted or `false` otherwise.
pub fn delete_release_file(
&self,
org: &str,
project: Option<&str>,
version: &str,
file_id: &str,
) -> ApiResult<bool> {
let path = if let Some(project) = project {
format!(
"/projects/{}/{}/releases/{}/files/{}/",
PathArg(org),
PathArg(project),
PathArg(version),
PathArg(file_id)
)
} else {
format!(
"/organizations/{}/releases/{}/files/{}/",
PathArg(org),
PathArg(version),
PathArg(file_id)
)
};
let resp = self.delete(&path)?;
if resp.status() == 404 {
Ok(false)
} else {
resp.into_result().map(|_| true)
}
}
/// Deletes all release files. Returns `true` if files were
/// deleted or `false` otherwise.
pub fn delete_release_files(
&self,
org: &str,
project: Option<&str>,
version: &str,
) -> ApiResult<()> {
let path = if let Some(project) = project {
format!(
"/projects/{}/{}/files/source-maps/?name={}",
PathArg(org),
PathArg(project),
PathArg(version)
)
} else {
format!(
"/organizations/{}/files/source-maps/?name={}",
PathArg(org),
PathArg(version)
)
};
self.delete(&path)?.into_result().map(|_| ())
}
/// Creates a new release.
pub fn new_release(&self, org: &str, release: &NewRelease) -> ApiResult<ReleaseInfo> {
// for single project releases use the legacy endpoint that is project bound.
// This means we can support both old and new servers.
if release.projects.len() == 1 {
let path = format!(
"/projects/{}/{}/releases/",
PathArg(org),
PathArg(&release.projects[0])
);
self.post(&path, release)?
.convert_rnf(ApiErrorKind::ProjectNotFound)
} else {
let path = format!("/organizations/{}/releases/", PathArg(org));
self.post(&path, release)?
.convert_rnf(ApiErrorKind::OrganizationNotFound)
}
}
/// Updates a release.
pub fn update_release(
&self,
org: &str,
version: &str,
release: &UpdatedRelease,
) -> ApiResult<ReleaseInfo> {
if_chain! {
if let Some(ref projects) = release.projects;
if projects.len() == 1;
then {
let path = format!("/projects/{}/{}/releases/{}/",
PathArg(org),
PathArg(&projects[0]),
PathArg(version)
);
self.put(&path, release)?.convert_rnf(ApiErrorKind::ReleaseNotFound)
} else {
if release.version.is_some() {
let path = format!("/organizations/{}/releases/",
PathArg(org));
return self.post(&path, release)?.convert_rnf(ApiErrorKind::ReleaseNotFound)
}
let path = format!("/organizations/{}/releases/{}/",
PathArg(org),
PathArg(version));
self.put(&path, release)?.convert_rnf(ApiErrorKind::ReleaseNotFound)
}
}
}
/// Sets release commits
pub fn set_release_refs(
&self,
org: &str,
version: &str,
refs: Vec<Ref>,
) -> ApiResult<ReleaseInfo> {
let update = UpdatedRelease {
refs: Some(refs),
..Default::default()
};
let path = format!(
"/organizations/{}/releases/{}/",
PathArg(org),
PathArg(version)
);
self.put(&path, &update)?
.convert_rnf(ApiErrorKind::ReleaseNotFound)
}
/// Deletes an already existing release. Returns `true` if it was deleted
/// or `false` if not. The project is needed to support the old deletion
/// API.
pub fn delete_release(
&self,
org: &str,
project: Option<&str>,
version: &str,
) -> ApiResult<bool> {
let resp = if let Some(project) = project {
self.delete(&format!(
"/projects/{}/{}/releases/{}/",
PathArg(org),
PathArg(project),
PathArg(version)
))?
} else {
self.delete(&format!(
"/organizations/{}/releases/{}/",
PathArg(org),
PathArg(version)
))?
};
if resp.status() == 404 {
Ok(false)
} else {
resp.into_result().map(|_| true)
}
}
/// Looks up a release and returns it. If it does not exist `None`
/// will be returned.
pub fn get_release(
&self,
org: &str,
project: Option<&str>,
version: &str,
) -> ApiResult<Option<ReleaseInfo>> {
let path = if let Some(project) = project {
format!(
"/projects/{}/{}/releases/{}/",
PathArg(org),
PathArg(project),
PathArg(version)
)
} else {
format!(
"/organizations/{}/releases/{}/",
PathArg(org),
PathArg(version)
)
};
let resp = self.get(&path)?;
if resp.status() == 404 {
Ok(None)
} else {
resp.convert()
}
}
/// Returns a list of releases for a given project. This is currently a
/// capped list by what the server deems an acceptable default limit.
pub fn list_releases(&self, org: &str, project: Option<&str>) -> ApiResult<Vec<ReleaseInfo>> {
if let Some(project) = project {
let path = format!("/projects/{}/{}/releases/", PathArg(org), PathArg(project));
self.get(&path)?
.convert_rnf::<Vec<ReleaseInfo>>(ApiErrorKind::ProjectNotFound)
} else {
let path = format!("/organizations/{}/releases/", PathArg(org));
self.get(&path)?
.convert_rnf::<Vec<ReleaseInfo>>(ApiErrorKind::OrganizationNotFound)
}
}
/// Looks up a release commits and returns it. If it does not exist `None`
/// will be returned.
pub fn get_release_commits(
&self,
org: &str,
project: Option<&str>,
version: &str,
) -> ApiResult<Option<Vec<ReleaseCommit>>> {
let path = if let Some(project) = project {
format!(
"/projects/{}/{}/releases/{}/commits/",
PathArg(org),
PathArg(project),
PathArg(version)
)
} else {
format!(
"/organizations/{}/releases/{}/commits/",
PathArg(org),
PathArg(version)
)
};
let resp = self.get(&path)?;
if resp.status() == 404 {
Ok(None)
} else {
resp.convert()
}
}
// Finds the most recent release with commits and returns it.
// If it does not exist `None` will be returned.
pub fn get_previous_release_with_commits(
&self,
org: &str,
version: &str,
) -> ApiResult<OptionalReleaseInfo> {
let path = format!(
"/organizations/{}/releases/{}/previous-with-commits/",
PathArg(org),
PathArg(version)
);
let resp = self.get(&path)?;
if resp.status() == 404 {
Ok(OptionalReleaseInfo::None(NoneReleaseInfo {}))
} else {
resp.convert()
}
}
/// Creates a new deploy for a release.
pub fn create_deploy(
&self,
org: &str,
version: &str,
deploy: &Deploy,
) -> ApiResult<Deploy<'_>> {
let path = format!(
"/organizations/{}/releases/{}/deploys/",
PathArg(org),
PathArg(version)
);
self.post(&path, deploy)?
.convert_rnf(ApiErrorKind::ReleaseNotFound)
}
/// Lists all deploys for a release
pub fn list_deploys(&self, org: &str, version: &str) -> ApiResult<Vec<Deploy<'_>>> {
let path = format!(
"/organizations/{}/releases/{}/deploys/",
PathArg(org),
PathArg(version)
);
self.get(&path)?.convert_rnf(ApiErrorKind::ReleaseNotFound)
}
/// Updates a bunch of issues within a project that match a provided filter
/// and performs `changes` changes.
pub fn bulk_update_issue(
&self,
org: &str,
project: &str,
filter: &IssueFilter,
changes: &IssueChanges,
) -> ApiResult<bool> {
let qs = match filter.get_query_string() {
None => {
return Ok(false);
}
Some(qs) => qs,
};
self.put(
&format!(
"/projects/{}/{}/issues/?{qs}",
PathArg(org),
PathArg(project)
),
changes,
)?
.into_result()
.map(|_| true)
}
/// Given a list of checksums for DIFs, this returns a list of those
/// that do not exist for the project yet.
pub fn find_missing_dif_checksums<I>(
&self,
org: &str,
project: &str,
checksums: I,
) -> ApiResult<HashSet<Digest>>
where
I: IntoIterator<Item = Digest>,
{
let mut url = format!(
"/projects/{}/{}/files/dsyms/unknown/?",
PathArg(org),
PathArg(project)
);
for (idx, checksum) in checksums.into_iter().enumerate() {
if idx > 0 {
url.push('&');
}
url.push_str("checksums=");
url.push_str(&checksum.to_string());
}
let state: MissingChecksumsResponse = self.get(&url)?.convert()?;
Ok(state.missing)
}
/// Get the server configuration for chunked file uploads.
pub fn get_chunk_upload_options(&self, org: &str) -> ApiResult<Option<ChunkServerOptions>> {
let url = format!("/organizations/{}/chunk-upload/", PathArg(org));
match self
.get(&url)?
.convert_rnf::<ChunkServerOptions>(ApiErrorKind::ChunkUploadNotSupported)
{
Ok(options) => Ok(Some(options)),
Err(error) => {
if error.kind() == ApiErrorKind::ChunkUploadNotSupported {
Ok(None)
} else {
Err(error)
}
}
}
}
/// Request DIF assembling and processing from chunks.
pub fn assemble_difs(
&self,
org: &str,
project: &str,
request: &AssembleDifsRequest<'_>,
) -> ApiResult<AssembleDifsResponse> {
let url = format!(
"/projects/{}/{}/files/difs/assemble/",
PathArg(org),
PathArg(project)
);
self.request(Method::Post, &url)?
.with_json_body(request)?
.send()?
.convert_rnf(ApiErrorKind::ProjectNotFound)
}
pub fn assemble_release_artifacts(
&self,
org: &str,
release: &str,
checksum: Digest,
chunks: &[Digest],
) -> ApiResult<AssembleArtifactsResponse> {