-
Notifications
You must be signed in to change notification settings - Fork 11
[EPROD-1041] Non-replicated http outcalls #241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 10 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
8225f8c
http outcall libs
F3kilo 04cc9e9
packages renamed + outcall impl for Rc RefCell
F3kilo 0325f59
proxy client
F3kilo fb78f0d
fmt
F3kilo d455702
better callback in non-replicated responses
F3kilo f3b2496
doc comments
F3kilo 38b1c57
build fix
F3kilo 0863084
Merge branch 'main' into non_replicated_http_outcalls
F3kilo e631ef9
proxy canister test
F3kilo b7c72e4
more tests, just scripts
F3kilo 32a086e
readme
F3kilo 0a431ec
typo
F3kilo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| [package] | ||
| name = "ic-http-outcall-api" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
|
|
||
| [dependencies] | ||
| ic-exports = { path = "../../ic-exports" } | ||
| ic-helpers = { path = "../../ic-helpers", features = ["management_canister"] } | ||
| ic-canister = { path = "../../ic-canister/ic-canister", optional = true } | ||
|
|
||
| candid = { workspace = true } | ||
| serde = { workspace = true } | ||
| futures = { workspace = true } | ||
|
|
||
| [features] | ||
| proxy-api = [] | ||
| non-replicated = ["proxy-api", "ic-canister"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| //! This crate provides an abstraction over different implementations of IC | ||
| //! Http outcall mechanism. | ||
| //! | ||
| //! The absraction is described as `HttpOutcall` trait. It has the | ||
| //! following implementations: | ||
| //! - `NonReplicatedHttpOutcall` - performs non-replicated call. | ||
| //! Details: `https://forum.dfinity.org/t/non-replicated-https-outcalls/26627`; | ||
| //! | ||
| //! - `ReplicatedHttpOutcall` - perform replicated calls using basic `http_outcall` | ||
| //! method in IC API. | ||
|
|
||
| #[cfg(feature = "non-replicated")] | ||
| mod non_replicated; | ||
| #[cfg(feature = "proxy-api")] | ||
| mod proxy_types; | ||
|
|
||
| mod outcall; | ||
| mod replicated; | ||
|
|
||
| #[cfg(feature = "non-replicated")] | ||
| pub use non_replicated::NonReplicatedHttpOutcall; | ||
| pub use outcall::HttpOutcall; | ||
| #[cfg(feature = "proxy-api")] | ||
| pub use proxy_types::{InitArgs, RequestArgs, RequestId, ResponseResult, REQUEST_METHOD_NAME}; | ||
| pub use replicated::ReplicatedHttpOutcall; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| use std::cell::RefCell; | ||
| use std::collections::HashMap; | ||
| use std::rc::Rc; | ||
| use std::time::Duration; | ||
|
|
||
| use candid::Principal; | ||
| use futures::channel::oneshot; | ||
| use ic_canister::virtual_canister_call; | ||
| use ic_exports::ic_cdk::api::management_canister::http_request::{ | ||
| CanisterHttpRequestArgument, HttpResponse, | ||
| }; | ||
| use ic_exports::ic_kit::{ic, CallResult, RejectionCode}; | ||
|
|
||
| use crate::outcall::HttpOutcall; | ||
| use crate::proxy_types::{RequestArgs, RequestId, REQUEST_METHOD_NAME}; | ||
| use crate::ResponseResult; | ||
|
|
||
| /// Callback type, which should be called to make the `HttpOutcall::request` function return. | ||
| pub type OnResponse = Box<dyn Fn(Vec<ResponseResult>)>; | ||
|
|
||
| /// Non-replicated http outcall implementation, which works together with ProxyCanister and ProxyCanisterClient. | ||
| /// | ||
| /// # Workflow | ||
| /// 1. Client code calls `HttpOutcall::request(params)`. `Self` sends request params to ProxyCanister | ||
| /// and awaits a Waker, which will be awaken, once the ProxyCanister will call the given callback, | ||
| /// or when the timeout reached. | ||
| /// | ||
| /// 2. ProxyCanister stores request params, and waits until ProxyCanisterClient query and execute the request. | ||
| /// | ||
| /// 3. ProxyCanister notifies the current canister about the reponse, by calling the `callback_api_fn_name` API endpoint. | ||
| /// The notification should be forwarded to the `OnResponse` callback, returned from `Self::new(...)`. | ||
| #[derive(Debug)] | ||
| pub struct NonReplicatedHttpOutcall { | ||
| requests: Rc<RefCell<HashMap<RequestId, DeferredResponse>>>, | ||
| callback_api_fn_name: &'static str, | ||
| proxy_canister: Principal, | ||
| request_timeout: Duration, | ||
| } | ||
|
|
||
| impl NonReplicatedHttpOutcall { | ||
| /// Crates a new instance of NonReplicatedHttpOutcall and a callback, which should be called | ||
| /// from canister API `callback_api_fn_name` function for response processing. | ||
| /// | ||
| /// The `callback_api_fn_name` expected to | ||
| /// - have a name equal to `callback_api_fn_name` value, | ||
| /// - be a canister API update endpoint, | ||
| /// - have the following signature: `fn(Vec<ResponseResult>) -> ()` | ||
| /// - call the returned `OnResponse` callback. | ||
| pub fn new( | ||
| proxy_canister: Principal, | ||
| callback_api_fn_name: &'static str, | ||
| request_timeout: Duration, | ||
| ) -> (Self, OnResponse) { | ||
| let s = Self { | ||
| requests: Default::default(), | ||
| callback_api_fn_name, | ||
| proxy_canister, | ||
| request_timeout, | ||
| }; | ||
|
|
||
| let requests = Rc::clone(&s.requests); | ||
| let callback = Box::new(move |responses: Vec<ResponseResult>| { | ||
| for response in responses { | ||
| if let Some(deferred) = requests.borrow_mut().remove(&response.id) { | ||
| let _ = deferred.notify.send(response.result); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| (s, callback) | ||
| } | ||
|
|
||
| /// Checks if some requests are expired, and, if so, finishs them with timeout error. | ||
| pub fn check_requests_timeout(&self) { | ||
| let now = ic::time(); | ||
| self.requests | ||
| .borrow_mut() | ||
| .retain(|_, deffered| deffered.expired_at > now); | ||
| } | ||
| } | ||
|
|
||
| impl HttpOutcall for NonReplicatedHttpOutcall { | ||
| async fn request(&self, request: CanisterHttpRequestArgument) -> CallResult<HttpResponse> { | ||
| self.check_requests_timeout(); | ||
|
|
||
| let proxy_canister = self.proxy_canister; | ||
| let request = RequestArgs { | ||
| callback_name: self.callback_api_fn_name.into(), | ||
| request, | ||
| }; | ||
| let id: RequestId = | ||
| virtual_canister_call!(proxy_canister, REQUEST_METHOD_NAME, (request,), RequestId) | ||
| .await?; | ||
|
|
||
| let (notify, waker) = oneshot::channel(); | ||
| let expired_at = ic::time() + self.request_timeout.as_nanos() as u64; | ||
| let response = DeferredResponse { expired_at, notify }; | ||
| self.requests.borrow_mut().insert(id, response); | ||
|
|
||
| waker | ||
| .await | ||
| .map_err(|_| { | ||
| // if proxy canister doesn't respond | ||
| ( | ||
| RejectionCode::SysTransient, | ||
| "timeout waiting HTTP request callback.".into(), | ||
| ) | ||
| })? | ||
| .map_err(|e| { | ||
| // if request failed | ||
| ( | ||
| RejectionCode::SysFatal, | ||
| format!("failed to send HTTP request: {e}"), | ||
| ) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| struct DeferredResponse { | ||
| pub expired_at: u64, | ||
| pub notify: oneshot::Sender<Result<HttpResponse, String>>, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| //! Abstraction over Http outcalls. | ||
|
|
||
| use ic_exports::ic_cdk::api::management_canister::http_request::{ | ||
| CanisterHttpRequestArgument, HttpResponse, | ||
| }; | ||
| use ic_exports::ic_kit::CallResult; | ||
|
|
||
| /// Abstraction over Http outcalls. | ||
| #[allow(async_fn_in_trait)] | ||
| pub trait HttpOutcall { | ||
| async fn request(&self, args: CanisterHttpRequestArgument) -> CallResult<HttpResponse>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| use candid::Principal; | ||
| use ic_exports::candid::CandidType; | ||
| use ic_exports::ic_cdk::api::management_canister::http_request::{ | ||
| CanisterHttpRequestArgument, HttpResponse, | ||
| }; | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| pub const REQUEST_METHOD_NAME: &str = "http_outcall"; | ||
|
|
||
| /// Params for proxy canister initialization. | ||
| #[derive(Debug, Serialize, Deserialize, CandidType)] | ||
| pub struct InitArgs { | ||
| /// Off-chain proxy agent, allowed to perform http requests. | ||
| pub allowed_proxy: Principal, | ||
| } | ||
|
|
||
| /// ID of a request. | ||
| #[derive( | ||
| Debug, Clone, Copy, Serialize, Deserialize, CandidType, PartialEq, Eq, PartialOrd, Ord, Hash, | ||
| )] | ||
| pub struct RequestId(u64); | ||
|
|
||
| impl RequestId { | ||
| /// Returns inner representation of the Id. | ||
| pub fn inner(&self) -> u64 { | ||
| self.0 | ||
| } | ||
| } | ||
|
|
||
| impl From<u64> for RequestId { | ||
| fn from(value: u64) -> Self { | ||
| Self(value) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Deserialize, CandidType)] | ||
| pub struct RequestArgs { | ||
| pub callback_name: String, | ||
| pub request: CanisterHttpRequestArgument, | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Serialize, Deserialize, CandidType)] | ||
| pub struct ResponseResult { | ||
| pub id: RequestId, | ||
| pub result: Result<HttpResponse, String>, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| use candid::Principal; | ||
| use ic_exports::ic_cdk::api::management_canister::http_request::{ | ||
| CanisterHttpRequestArgument, HttpResponse, | ||
| }; | ||
| use ic_exports::ic_kit::CallResult; | ||
| use ic_helpers::principal::management::ManagementPrincipalExt; | ||
|
|
||
| use crate::outcall::HttpOutcall; | ||
|
|
||
| pub struct ReplicatedHttpOutcall; | ||
|
|
||
| impl HttpOutcall for ReplicatedHttpOutcall { | ||
| async fn request(&self, args: CanisterHttpRequestArgument) -> CallResult<HttpResponse> { | ||
| Principal::management_canister().http_request(args).await | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| [package] | ||
| name = "ic-http-outcall-proxy-canister" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
|
|
||
| [features] | ||
| default = [] | ||
| export-api = [] | ||
|
|
||
| [dependencies] | ||
| ic-canister = { path = "../../ic-canister/ic-canister" } | ||
| ic-exports = { path = "../../ic-exports" } | ||
| ic-http-outcall-api = { path = "../api", features = ["proxy-api"] } | ||
|
|
||
| candid = { workspace = true } | ||
| serde = { workspace = true } | ||
|
|
||
| [dev-dependencies] | ||
| tokio = { workspace = true, features = ["full"] } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.