-
-
Notifications
You must be signed in to change notification settings - Fork 271
/
lib.rs
1701 lines (1525 loc) · 58.6 KB
/
lib.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
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
//! # Octocrab: A modern, extensible GitHub API client.
//! Octocrab is an third party GitHub API client, allowing you to easily build
//! your own GitHub integrations or bots. `octocrab` comes with two primary
//! set of APIs for communicating with GitHub, a high level strongly typed
//! semantic API, and a lower level HTTP API for extending behaviour.
//!
//! ## Semantic API
//! The semantic API provides strong typing around GitHub's API, as well as a
//! set of [`models`] that maps to GitHub's types. Currently the following
//! modules are available.
//!
//! - [`activity`] GitHub Activity
//! - [`actions`] GitHub Actions
//! - [`apps`] GitHub Apps
//! - [`current`] Information about the current user.
//! - [`gitignore`] Gitignore templates
//! - [`Octocrab::graphql`] GraphQL.
//! - [`issues`] Issues and related items, e.g. comments, labels, etc.
//! - [`licenses`] License Metadata.
//! - [`markdown`] Rendering Markdown with GitHub
//! - [`orgs`] GitHub Organisations
//! - [`projects`] GitHub Projects
//! - [`pulls`] Pull Requests
//! - [`repos`] Repositories
//! - [`repos::forks`] Repositories
//! - [`repos::releases`] Repositories
//! - [`search`] Using GitHub's search.
//! - [`teams`] Teams
//! - [`users`] Users
//!
//! #### Getting a Pull Request
//! ```no_run
//! # async fn run() -> octocrab::Result<()> {
//! // Get pull request #404 from `octocrab/repo`.
//! let pr = octocrab::instance().pulls("octocrab", "repo").get(404).await?;
//! # Ok(())
//! # }
//! ```
//!
//! All methods with multiple optional parameters are built as `Builder`
//! structs, allowing you to easily specify parameters.
//!
//! #### Listing issues
//! ```no_run
//! # async fn run() -> octocrab::Result<()> {
//! use octocrab::{models, params};
//!
//! let octocrab = octocrab::instance();
//! // Returns the first page of all issues.
//! let mut page = octocrab.issues("octocrab", "repo")
//! .list()
//! // Optional Parameters
//! .creator("octocrab")
//! .state(params::State::All)
//! .per_page(50)
//! .send()
//! .await?;
//!
//! // Go through every page of issues. Warning: There's no rate limiting so
//! // be careful.
//! let results = octocrab.all_pages::<models::issues::Issue>(page).await?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## HTTP API
//! The typed API currently doesn't cover all of GitHub's API at this time, and
//! even if it did GitHub is in active development and this library will
//! likely always be somewhat behind GitHub at some points in time. However that
//! shouldn't mean that in order to use those features that you have to now fork
//! or replace `octocrab` with your own solution.
//!
//! Instead `octocrab` exposes a suite of HTTP methods allowing you to easily
//! extend `Octocrab`'s existing behaviour. Using these HTTP methods allows you
//! to keep using the same authentication and configuration, while having
//! control over the request and response. There is a method for each HTTP
//! method `get`, `post`, `patch`, `put`, `delete`, all of which accept a
//! relative route and a optional body.
//!
//! ```no_run
//! # async fn run() -> octocrab::Result<()> {
//! let user: octocrab::models::Author = octocrab::instance()
//! .get("/user", None::<&()>)
//! .await?;
//! # Ok(())
//! # }
//! ```
//!
//! Each of the HTTP methods expects a body, formats the URL with the base
//! URL, and errors if GitHub doesn't return a successful status, but this isn't
//! always desired when working with GitHub's API, sometimes you need to check
//! the response status or headers. As such there are companion methods `_get`,
//! `_post`, etc. that perform no additional pre or post-processing to
//! the request.
//!
//! ```no_run
//! # use http::Uri;
//! # async fn run() -> octocrab::Result<()> {
//! let octocrab = octocrab::instance();
//! let response = octocrab
//! ._get("https://api.github.com/organizations")
//! .await?;
//!
//! // You can also use `Uri::builder().authority("<my custom base>").path_and_query("<my custom path>")` if you want to customize the base uri and path.
//! let response = octocrab
//! ._get(Uri::builder().path_and_query("/organizations").build().expect("valid uri"))
//! .await?;
//! # Ok(())
//! # }
//! ```
//!
//! You can use the those HTTP methods to easily create your own extensions to
//! `Octocrab`'s typed API. (Requires `async_trait`).
//! ```
//! use octocrab::{Octocrab, Page, Result, models};
//!
//! #[async_trait::async_trait]
//! trait OrganisationExt {
//! async fn list_every_organisation(&self) -> Result<Page<models::orgs::Organization>>;
//! }
//!
//! #[async_trait::async_trait]
//! impl OrganisationExt for Octocrab {
//! async fn list_every_organisation(&self) -> Result<Page<models::orgs::Organization>> {
//! self.get("organizations", None::<&()>).await
//! }
//! }
//! ```
//!
//! You can also easily access new properties that aren't available in the
//! current models using `serde`.
//!
//! ## Static API
//! `octocrab` also provides a statically reference count version of its API,
//! allowing you to easily plug it into existing systems without worrying
//! about having to integrate and pass around the client.
//!
//! ```
//! // Initialises the static instance with your configuration and returns an
//! // instance of the client.
//! # use octocrab::Octocrab;
//! tokio_test::block_on(async {
//! octocrab::initialise(Octocrab::default());
//! // Gets a instance of `Octocrab` from the static API. If you call this
//! // without first calling `octocrab::initialise` a default client will be
//! // initialised and returned instead.
//! octocrab::instance();
//! # })
//! ```
//!
//! ## GitHub webhook application support
//!
//! `octocrab` provides [deserializable datatypes](crate::models::webhook_events)
//! for the payloads received by a GitHub application [responding to
//! webhooks](https://docs.github.com/en/apps/creating-github-apps/writing-code-for-a-github-app/building-a-github-app-that-responds-to-webhook-events).
//! This allows you to write a typesafe application using Rust with
//! pattern-matching/enum-dispatch to respond to events.
//!
//! **Note**: Webhook support in `octocrab` is still beta, not all known webhook events are
//! strongly typed.
//!
//! ```no_run
//! # use http::request::Request;
//! # use tracing::{warn, info};
//! # use octocrab::models::webhook_events::*;
//! # let request_from_github = Request::post("https://my-webhook-url.com").body(vec![0_u8]).unwrap();
//! // request_from_github is the HTTP request your webhook handler received
//! let (parts, body) = request_from_github.into_parts();
//! let header = parts.headers.get("X-GitHub-Event").unwrap().to_str().unwrap();
//!
//! let event = WebhookEvent::try_from_header_and_body(header, &body).unwrap();
//! // Now you can match on event type and call any specific handling logic
//! match event.kind {
//! WebhookEventType::Ping => info!("Received a ping"),
//! WebhookEventType::PullRequest => info!("Received a pull request event"),
//! // ...
//! _ => warn!("Ignored event"),
//! };
//! ```
#![cfg_attr(test, recursion_limit = "512")]
mod api;
mod error;
mod from_response;
mod page;
pub mod auth;
pub mod etag;
pub mod models;
pub mod params;
pub mod service;
use chrono::{DateTime, Utc};
use http::{HeaderMap, HeaderValue, Method, Uri};
use http_body_util::combinators::BoxBody;
use http_body_util::BodyExt;
use service::middleware::auth_header::AuthHeaderLayer;
use std::convert::{Infallible, TryInto};
use std::fmt;
use std::io::Write;
use std::marker::PhantomData;
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use http::{header::HeaderName, StatusCode};
use hyper::{Request, Response};
use once_cell::sync::Lazy;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use snafu::*;
use tower::{buffer::Buffer, util::BoxService, BoxError, Layer, Service, ServiceExt};
use bytes::Bytes;
use http::header::USER_AGENT;
use http::request::Builder;
#[cfg(feature = "opentls")]
use hyper_tls::HttpsConnector;
#[cfg(feature = "rustls")]
use hyper_rustls::HttpsConnectorBuilder;
#[cfg(feature = "retry")]
use tower::retry::{Retry, RetryLayer};
#[cfg(feature = "timeout")]
use hyper_timeout::TimeoutConnector;
use tower_http::{classify::ServerErrorsFailureClass, map_response_body::MapResponseBodyLayer};
#[cfg(feature = "tracing")]
use {tower_http::trace::TraceLayer, tracing::Span};
use crate::error::{
HttpSnafu, HyperSnafu, InvalidUtf8Snafu, SerdeSnafu, SerdeUrlEncodedSnafu, ServiceSnafu,
UriParseError, UriParseSnafu, UriSnafu,
};
use crate::service::middleware::base_uri::BaseUriLayer;
use crate::service::middleware::extra_headers::ExtraHeadersLayer;
#[cfg(feature = "retry")]
use crate::service::middleware::retry::RetryConfig;
use crate::api::users;
use auth::{AppAuth, Auth};
use models::{AppId, InstallationId, InstallationToken};
pub use self::{
api::{
actions, activity, apps, checks, commits, current, events, gists, gitignore, issues,
licenses, markdown, orgs, projects, pulls, ratelimit, repos, search, teams, workflows,
},
error::{Error, GitHubError},
from_response::FromResponse,
page::Page,
};
/// A convenience type with a default error type of [`Error`].
pub type Result<T, E = error::Error> = std::result::Result<T, E>;
const GITHUB_BASE_URI: &str = "https://api.github.com";
#[cfg(feature = "default-client")]
static STATIC_INSTANCE: Lazy<arc_swap::ArcSwap<Octocrab>> =
Lazy::new(|| arc_swap::ArcSwap::from_pointee(Octocrab::default()));
/// Formats a GitHub preview from it's name into the full value for the
/// `Accept` header.
/// ```
/// assert_eq!(octocrab::format_preview("machine-man"), "application/vnd.github.machine-man-preview");
/// ```
pub fn format_preview(preview: impl AsRef<str>) -> String {
format!("application/vnd.github.{}-preview", preview.as_ref())
}
/// Formats a media type from it's name into the full value for the
/// `Accept` header.
/// ```
/// assert_eq!(octocrab::format_media_type("html"), "application/vnd.github.v3.html+json");
/// assert_eq!(octocrab::format_media_type("json"), "application/vnd.github.v3.json");
/// assert_eq!(octocrab::format_media_type("patch"), "application/vnd.github.v3.patch");
/// ```
pub fn format_media_type(media_type: impl AsRef<str>) -> String {
let media_type = media_type.as_ref();
let json_suffix = match media_type {
"raw" | "text" | "html" | "full" => "+json",
_ => "",
};
format!("application/vnd.github.v3.{media_type}{json_suffix}")
}
#[derive(Debug, Deserialize)]
struct GitHubErrorBody {
pub documentation_url: Option<String>,
pub errors: Option<Vec<serde_json::Value>>,
pub message: String,
}
/// Maps a GitHub error response into and `Err()` variant if the status is
/// not a success.
pub async fn map_github_error(
response: http::Response<BoxBody<Bytes, crate::Error>>,
) -> Result<http::Response<BoxBody<Bytes, crate::Error>>> {
if response.status().is_success() {
Ok(response)
} else {
let (parts, body) = response.into_parts();
let GitHubErrorBody {
documentation_url,
errors,
message,
} = serde_json::from_slice(body.collect().await?.to_bytes().as_ref())
.context(error::SerdeSnafu)?;
Err(error::Error::GitHub {
source: GitHubError {
status_code: parts.status,
documentation_url,
errors,
message,
},
backtrace: Backtrace::generate(),
})
}
}
/// Initialises the static instance using the configuration set by
/// `builder`.
/// ```
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let octocrab = octocrab::initialise(octocrab::Octocrab::default());
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "default-client")]
pub fn initialise(crab: Octocrab) -> Arc<Octocrab> {
STATIC_INSTANCE.swap(Arc::from(crab))
}
/// Returns a new instance of [`Octocrab`]. If it hasn't been previously
/// initialised it returns a default instance with no authentication set.
/// ```
/// #[tokio::main]
/// async fn main() -> () {
/// let octocrab = octocrab::instance();
/// }
/// ```
#[cfg(feature = "default-client")]
pub fn instance() -> Arc<Octocrab> {
STATIC_INSTANCE.load().clone()
}
/// A builder struct for `Octocrab`, allowing you to configure the client, such
/// as using GitHub previews, the github instance, authentication, etc.
/// ```
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let octocrab = octocrab::OctocrabBuilder::default()
/// .add_preview("machine-man")
/// .base_uri("https://github.example.com")?
/// .build()?;
/// # Ok(())
/// # }
/// ```
//Typed builder, thanks to https://www.greyblake.com/blog/builder-with-typestate-in-rust/ for explaining
/// A builder struct for `Octocrab`.
/// OctocrabBuilder can be extended with a custom config, see [DefaultOctocrabBuilderConfig] for an example
pub struct OctocrabBuilder<Svc, Config, Auth, LayerReady> {
service: Svc,
auth: Auth,
config: Config,
_layer_ready: PhantomData<LayerReady>,
}
//Indicates weather the builder supports config
pub struct NoConfig {}
//Indicates weather the builder supports service that is already inside builder
pub struct NoSvc {}
//Indicates weather builder supports with_layer(This is somewhat redundant given NoSvc exists, but we have to use this until specialization is stable)
pub struct NotLayerReady {}
pub struct LayerReady {}
//Indicates weather the builder supports auth
pub struct NoAuth {}
impl OctocrabBuilder<NoSvc, NoConfig, NoAuth, NotLayerReady> {
pub fn new_empty() -> Self {
OctocrabBuilder {
service: NoSvc {},
auth: NoAuth {},
config: NoConfig {},
_layer_ready: PhantomData,
}
}
}
impl OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady> {
pub fn new() -> Self {
OctocrabBuilder::default()
}
}
impl<Config, Auth> OctocrabBuilder<NoSvc, Config, Auth, NotLayerReady> {
pub fn with_service<Svc>(self, service: Svc) -> OctocrabBuilder<Svc, Config, Auth, LayerReady> {
OctocrabBuilder {
service,
auth: self.auth,
config: self.config,
_layer_ready: PhantomData,
}
}
}
impl<Svc, Config, Auth, B> OctocrabBuilder<Svc, Config, Auth, LayerReady>
where
Svc: Service<Request<String>, Response = Response<B>> + Send + 'static,
Svc::Future: Send + 'static,
Svc::Error: Into<BoxError>,
B: http_body::Body<Data = bytes::Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
/// Add a [`Layer`] to the current [`Service`] stack.
pub fn with_layer<L: Layer<Svc>>(
self,
layer: &L,
) -> OctocrabBuilder<L::Service, Config, Auth, LayerReady> {
let Self {
service: stack,
auth,
config,
..
} = self;
OctocrabBuilder {
service: layer.layer(stack),
auth,
config,
_layer_ready: PhantomData,
}
}
}
impl Default for OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady> {
fn default() -> OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady> {
OctocrabBuilder::new_empty().with_config(DefaultOctocrabBuilderConfig::default())
}
}
impl<Svc, Auth, LayerState> OctocrabBuilder<Svc, NoConfig, Auth, LayerState> {
fn with_config<Config>(self, config: Config) -> OctocrabBuilder<Svc, Config, Auth, LayerState> {
OctocrabBuilder {
service: self.service,
auth: self.auth,
config,
_layer_ready: PhantomData,
}
}
}
impl<Svc, B, LayerState> OctocrabBuilder<Svc, NoConfig, AuthState, LayerState>
where
Svc: Service<Request<String>, Response = Response<B>> + Send + 'static,
Svc::Future: Send + 'static,
Svc::Error: Into<BoxError>,
B: http_body::Body<Data = bytes::Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
/// Build a [`Client`] instance with the current [`Service`] stack.
pub fn build(self) -> Result<Octocrab, Infallible> {
// Transform response body to `BoxBody<Bytes, crate::Error>` and use type erased error to avoid type parameters.
let service = MapResponseBodyLayer::new(|b: B| {
b.map_err(|e| ServiceSnafu.into_error(e.into())).boxed()
})
.layer(self.service)
.map_err(|e| e.into());
Ok(Octocrab::new(service, self.auth))
}
}
impl<Svc, Config, LayerState> OctocrabBuilder<Svc, Config, NoAuth, LayerState> {
pub fn with_auth<Auth>(self, auth: Auth) -> OctocrabBuilder<Svc, Config, Auth, LayerState> {
OctocrabBuilder {
service: self.service,
auth,
config: self.config,
_layer_ready: PhantomData,
}
}
}
impl OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady> {
#[cfg(feature = "retry")]
pub fn add_retry_config(&mut self, retry_config: RetryConfig) -> &mut Self {
self.config.retry_config = retry_config;
self
}
/// Set the connect timeout.
#[cfg(feature = "timeout")]
pub fn set_connect_timeout(mut self, timeout: Option<Duration>) -> Self {
self.config.connect_timeout = timeout;
self
}
/// Set the read timeout.
#[cfg(feature = "timeout")]
pub fn set_read_timeout(mut self, timeout: Option<Duration>) -> Self {
self.config.read_timeout = timeout;
self
}
/// Set the write timeout.
#[cfg(feature = "timeout")]
pub fn set_write_timeout(mut self, timeout: Option<Duration>) -> Self {
self.config.write_timeout = timeout;
self
}
/// Enable a GitHub preview.
pub fn add_preview(mut self, preview: &'static str) -> Self {
self.config.previews.push(preview);
self
}
/// Add an additional header to include with every request.
pub fn add_header(mut self, key: HeaderName, value: String) -> Self {
self.config.extra_headers.push((key, value));
self
}
/// Add a personal token to use for authentication.
pub fn personal_token<S: Into<SecretString>>(mut self, token: S) -> Self {
self.config.auth = Auth::PersonalToken(token.into());
self
}
/// Authenticate as a Github App.
/// `key`: RSA private key in DER or PEM formats.
pub fn app(mut self, app_id: AppId, key: jsonwebtoken::EncodingKey) -> Self {
self.config.auth = Auth::App(AppAuth { app_id, key });
self
}
/// Authenticate as a Basic Auth
/// username and password
pub fn basic_auth(mut self, username: String, password: String) -> Self {
self.config.auth = Auth::Basic { username, password };
self
}
/// Authenticate with an OAuth token.
pub fn oauth(mut self, oauth: auth::OAuth) -> Self {
self.config.auth = Auth::OAuth(oauth);
self
}
/// Authenticate with a user access token.
pub fn user_access_token<S: Into<SecretString>>(mut self, token: S) -> Self {
self.config.auth = Auth::UserAccessToken(token.into());
self
}
/// Set the base url for `Octocrab`.
pub fn base_uri(mut self, base_uri: impl TryInto<Uri>) -> Result<Self> {
self.config.base_uri = Some(
base_uri
.try_into()
.map_err(|_| UriParseError {})
.context(UriParseSnafu)?,
);
Ok(self)
}
#[cfg(feature = "retry")]
pub fn set_connector_retry_service<S>(
&self,
connector: hyper_util::client::legacy::Client<S, String>,
) -> Retry<RetryConfig, hyper_util::client::legacy::Client<S, String>> {
let retry_layer = RetryLayer::new(self.config.retry_config.clone());
retry_layer.layer(connector)
}
#[cfg(feature = "timeout")]
pub fn set_connect_timeout_service<T>(&self, connector: T) -> TimeoutConnector<T>
where
T: Service<Uri> + Send,
T::Response: hyper::rt::Read + hyper::rt::Write + Send + Unpin,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
{
let mut connector = TimeoutConnector::new(connector);
// Set the timeouts for the client
connector.set_connect_timeout(self.config.connect_timeout);
connector.set_read_timeout(self.config.read_timeout);
connector.set_write_timeout(self.config.write_timeout);
connector
}
/// Build a [`Client`] instance with the current [`Service`] stack.
#[cfg(feature = "default-client")]
pub fn build(self) -> Result<Octocrab> {
let client: hyper_util::client::legacy::Client<_, String> = {
#[cfg(all(not(feature = "opentls"), not(feature = "rustls")))]
let mut connector = hyper::client::conn::http1::HttpConnector::new();
#[cfg(all(feature = "rustls", not(feature = "opentls")))]
let connector = {
let builder = HttpsConnectorBuilder::new();
#[cfg(feature = "rustls-webpki-tokio")]
let builder = builder.with_webpki_roots();
#[cfg(not(feature = "rustls-webpki-tokio"))]
let builder = builder
.with_native_roots()
.map_err(Into::into)
.context(error::OtherSnafu)?; // enabled the `rustls-native-certs` feature in hyper-rustls
builder
.https_or_http() // Disable .https_only() during tests until: https://github.com/LukeMathWalker/wiremock-rs/issues/58 is resolved. Alternatively we can use conditional compilation to only enable this feature in tests, but it becomes rather ugly with integration tests.
.enable_http1()
.build()
};
#[cfg(all(feature = "opentls", not(feature = "rustls")))]
let connector = HttpsConnector::new();
#[cfg(feature = "timeout")]
let connector = self.set_connect_timeout_service(connector);
hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
.build(connector)
};
#[cfg(feature = "retry")]
let client = self.set_connector_retry_service(client);
#[cfg(feature = "tracing")]
let client = TraceLayer::new_for_http()
.make_span_with(|req: &Request<String>| {
tracing::debug_span!(
"HTTP",
http.method = %req.method(),
http.url = %req.uri(),
http.status_code = tracing::field::Empty,
otel.name = req.extensions().get::<&'static str>().unwrap_or(&"HTTP"),
otel.kind = "client",
otel.status_code = tracing::field::Empty,
)
})
.on_request(|_req: &Request<String>, _span: &Span| {
tracing::debug!("requesting");
})
.on_response(
|res: &Response<hyper::body::Incoming>, _latency: Duration, span: &Span| {
let status = res.status();
span.record("http.status_code", status.as_u16());
if status.is_client_error() || status.is_server_error() {
span.record("otel.status_code", "ERROR");
}
},
)
// Explicitly disable `on_body_chunk`. The default does nothing.
.on_body_chunk(())
.on_eos(|_: Option<&HeaderMap>, _duration: Duration, _span: &Span| {
tracing::debug!("stream closed");
})
.on_failure(
|ec: ServerErrorsFailureClass, _latency: Duration, span: &Span| {
// Called when
// - Calling the inner service errored
// - Polling `Body` errored
// - the response was classified as failure (5xx)
// - End of stream was classified as failure
span.record("otel.status_code", "ERROR");
match ec {
ServerErrorsFailureClass::StatusCode(status) => {
span.record("http.status_code", status.as_u16());
tracing::error!("failed with status {}", status)
}
ServerErrorsFailureClass::Error(err) => {
tracing::error!("failed with error {}", err)
}
}
},
)
.layer(client);
#[cfg(feature = "follow-redirect")]
let client = tower_http::follow_redirect::FollowRedirectLayer::new().layer(client);
let mut hmap: Vec<(HeaderName, HeaderValue)> = vec![];
// Add the user agent header required by GitHub
hmap.push((USER_AGENT, HeaderValue::from_str("octocrab").unwrap()));
for preview in &self.config.previews {
hmap.push((
http::header::ACCEPT,
HeaderValue::from_str(crate::format_preview(preview).as_str()).unwrap(),
));
}
let (auth_header, auth_state): (Option<HeaderValue>, _) = match self.config.auth {
Auth::None => (None, AuthState::None),
Auth::Basic { username, password } => {
(None, AuthState::BasicAuth { username, password })
}
Auth::PersonalToken(token) => (
Some(format!("Bearer {}", token.expose_secret()).parse().unwrap()),
AuthState::None,
),
Auth::UserAccessToken(token) => (
Some(format!("Bearer {}", token.expose_secret()).parse().unwrap()),
AuthState::None,
),
Auth::App(app_auth) => (None, AuthState::App(app_auth)),
Auth::OAuth(device) => (
Some(
format!(
"{} {}",
device.token_type,
&device.access_token.expose_secret()
)
.parse()
.unwrap(),
),
AuthState::None,
),
};
for (key, value) in self.config.extra_headers.iter() {
hmap.push((
key.clone(),
HeaderValue::from_str(value.as_str())
.map_err(http::Error::from)
.context(HttpSnafu)?,
));
}
let client = ExtraHeadersLayer::new(Arc::new(hmap)).layer(client);
let client = MapResponseBodyLayer::new(|body| {
BodyExt::map_err(body, |e| HyperSnafu.into_error(e)).boxed()
})
.layer(client);
let uri = self
.config
.base_uri
.clone()
.unwrap_or_else(|| Uri::from_str(GITHUB_BASE_URI).unwrap());
let client = BaseUriLayer::new(uri.clone()).layer(client);
let client = AuthHeaderLayer::new(auth_header, uri).layer(client);
Ok(Octocrab::new(client, auth_state))
}
}
pub struct DefaultOctocrabBuilderConfig {
auth: Auth,
previews: Vec<&'static str>,
extra_headers: Vec<(HeaderName, String)>,
#[cfg(feature = "timeout")]
connect_timeout: Option<Duration>,
#[cfg(feature = "timeout")]
read_timeout: Option<Duration>,
#[cfg(feature = "timeout")]
write_timeout: Option<Duration>,
base_uri: Option<Uri>,
#[cfg(feature = "retry")]
retry_config: RetryConfig,
}
impl Default for DefaultOctocrabBuilderConfig {
fn default() -> Self {
Self {
auth: Auth::None,
previews: Vec::new(),
extra_headers: Vec::new(),
#[cfg(feature = "timeout")]
connect_timeout: None,
#[cfg(feature = "timeout")]
read_timeout: None,
#[cfg(feature = "timeout")]
write_timeout: None,
base_uri: None,
#[cfg(feature = "retry")]
retry_config: RetryConfig::Simple(3),
}
}
}
impl DefaultOctocrabBuilderConfig {
pub fn new() -> Self {
Self::default()
}
}
#[derive(Debug, Clone)]
struct CachedTokenInner {
expiration: Option<DateTime<Utc>>,
secret: SecretString,
}
impl CachedTokenInner {
fn new(secret: SecretString, expiration: Option<DateTime<Utc>>) -> Self {
Self { secret, expiration }
}
fn expose_secret(&self) -> &str {
self.secret.expose_secret()
}
}
/// A cached API access token (which may be None)
pub struct CachedToken(RwLock<Option<CachedTokenInner>>);
impl CachedToken {
fn clear(&self) {
*self.0.write().unwrap() = None;
}
/// Returns a valid token if it exists and is not expired or if there is no expiration date.
fn valid_token_with_buffer(&self, buffer: chrono::Duration) -> Option<SecretString> {
let inner = self.0.read().unwrap();
if let Some(token) = inner.as_ref() {
if let Some(exp) = token.expiration {
if exp - Utc::now() > buffer {
return Some(token.secret.clone());
}
} else {
return Some(token.secret.clone());
}
}
None
}
fn valid_token(&self) -> Option<SecretString> {
self.valid_token_with_buffer(chrono::Duration::seconds(30))
}
fn set<S: Into<SecretString>>(&self, token: S, expiration: Option<DateTime<Utc>>) {
*self.0.write().unwrap() = Some(CachedTokenInner::new(token.into(), expiration));
}
}
impl fmt::Debug for CachedToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.read().unwrap().fmt(f)
}
}
impl fmt::Display for CachedToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let option = self.0.read().unwrap();
option
.as_ref()
.map(|s| s.expose_secret().fmt(f))
.unwrap_or_else(|| write!(f, "<none>"))
}
}
impl Clone for CachedToken {
fn clone(&self) -> CachedToken {
CachedToken(RwLock::new(self.0.read().unwrap().clone()))
}
}
impl Default for CachedToken {
fn default() -> CachedToken {
CachedToken(RwLock::new(None))
}
}
/// State used for authenticate to Github
#[derive(Debug, Clone)]
pub enum AuthState {
/// No state, although Auth::PersonalToken may have caused
/// an Authorization HTTP header to be set to provide authentication.
None,
/// Basic Auth HTTP. (username:password)
BasicAuth {
/// The username
username: String,
/// The password
password: String,
},
/// Github App authentication with the given app data
App(AppAuth),
/// Authentication via a Github App repo-specific installation
Installation {
/// The app authentication data (app ID and private key)
app: AppAuth,
/// The installation ID
installation: InstallationId,
/// The cached access token, if any
token: CachedToken,
},
}
pub type OctocrabService = Buffer<
BoxService<http::Request<String>, http::Response<BoxBody<Bytes, Error>>, BoxError>,
http::Request<String>,
>;
/// The GitHub API client.
#[derive(Clone)]
pub struct Octocrab {
client: OctocrabService,
auth_state: AuthState,
}
impl fmt::Debug for Octocrab {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Octocrab")
.field("auth_state", &self.auth_state)
.finish()
}
}
/// Defaults for Octocrab:
/// - `base_uri`: `https://api.github.com`
/// - `auth`: `None`
/// - `client`: http client with the `octocrab` user agent.
#[cfg(feature = "default-client")]
impl Default for Octocrab {
fn default() -> Self {
OctocrabBuilder::default().build().unwrap()
}
}
/// # Constructors
impl Octocrab {
/// Returns a new `OctocrabBuilder`.
pub fn builder() -> OctocrabBuilder<NoSvc, DefaultOctocrabBuilderConfig, NoAuth, NotLayerReady>
{
OctocrabBuilder::new_empty().with_config(DefaultOctocrabBuilderConfig::default())
}
/// Creates a new `Octocrab`.
fn new<S>(service: S, auth_state: AuthState) -> Self
where
S: Service<Request<String>, Response = Response<BoxBody<Bytes, crate::Error>>>
+ Send
+ 'static,
S::Future: Send + 'static,
S::Error: Into<BoxError>,
{
let service = Buffer::new(BoxService::new(service.map_err(Into::into)), 1024);
Self {
client: service,
auth_state,
}
}
/// Returns a new `Octocrab` based on the current builder but
/// authorizing via a specific installation ID.
/// Typically you will first construct an `Octocrab` using
/// `OctocrabBuilder::app` to authenticate as your Github App,
/// then obtain an installation ID, and then pass that here to
/// obtain a new `Octocrab` with which you can make API calls
/// with the permissions of that installation.
pub fn installation(&self, id: InstallationId) -> Octocrab {
let app_auth = if let AuthState::App(ref app_auth) = self.auth_state {
app_auth.clone()
} else {
panic!("Github App authorization is required to target an installation");
};
Octocrab {
client: self.client.clone(),
auth_state: AuthState::Installation {
app: app_auth,
installation: id,
token: CachedToken::default(),
},
}
}
/// Similar to `installation`, but also eagerly caches the installation
/// token and returns the token. The returned token can be used to make
/// https git requests to e.g. clone repositories that the installation
/// has access to.
///
/// See also https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#http-based-git-access-by-an-installation
pub async fn installation_and_token(
&self,