-
Notifications
You must be signed in to change notification settings - Fork 4
chore: add multi example canister #48
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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,23 @@ | ||
| [package] | ||
| name = "multi_canister" | ||
| version = "1.0.0" | ||
| edition.workspace = true | ||
|
|
||
| [[bin]] | ||
| name = "multi_canister" | ||
| path = "src/main.rs" | ||
|
|
||
| [dependencies] | ||
| candid = { workspace = true } | ||
| canhttp = { path = "../../canhttp", features = ["http", "json", "multi"] } | ||
| http = { workspace = true } | ||
| ic-cdk = { workspace = true } | ||
| serde_json = { workspace = true } | ||
| tower = { workspace = true } | ||
|
|
||
| [dev-dependencies] | ||
| ic-management-canister-types = { workspace = true } | ||
| ic-test-utilities-load-wasm = { workspace = true } | ||
| pocket-ic = { workspace = true } | ||
| serde = { workspace = true } | ||
| uuid = { workspace = true } |
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,78 @@ | ||
| //! Example of a canister using `canhttp` to issue multiple requests in parallel. | ||
|
|
||
| use canhttp::http::json::JsonResponseConverter; | ||
| use canhttp::http::HttpRequest; | ||
| use canhttp::multi::parallel_call; | ||
| use canhttp::{ | ||
| cycles::{ChargeMyself, CyclesAccountingServiceBuilder}, | ||
| http::HttpConversionLayer, | ||
| observability::ObservabilityLayer, | ||
| Client, ConvertServiceBuilder, | ||
| }; | ||
| use ic_cdk::update; | ||
| use std::iter; | ||
| use tower::{BoxError, Service, ServiceBuilder, ServiceExt}; | ||
|
|
||
| /// Make parallel HTTP requests. | ||
| #[update] | ||
| pub async fn make_parallel_http_requests() -> Vec<String> { | ||
| let request = http::Request::get(format!("{}/uuid", httpbin_base_url())) | ||
| .body(vec![]) | ||
| .unwrap(); | ||
|
|
||
| let mut client = http_client(); | ||
| client.ready().await.expect("Client should be ready"); | ||
|
|
||
| let (_client, results) = parallel_call(client, iter::repeat_n(request, 5).enumerate()).await; | ||
| let (results, errors) = results.into_inner(); | ||
| if !errors.is_empty() { | ||
| panic!( | ||
| "Requests should all succeed but received {} errors: {:?}", | ||
| errors.len(), | ||
| errors | ||
| ); | ||
| } | ||
|
|
||
| results | ||
| .into_values() | ||
| .map(|response| { | ||
| assert_eq!(response.status(), http::StatusCode::OK); | ||
| response.body()["uuid"] | ||
| .as_str() | ||
| .expect("Expected UUID in response") | ||
| .to_string() | ||
| }) | ||
| .collect() | ||
| } | ||
|
|
||
| fn http_client( | ||
| ) -> impl Service<HttpRequest, Response = http::Response<serde_json::Value>, Error = BoxError> { | ||
| ServiceBuilder::new() | ||
| // Print request, response and errors to the console | ||
| .layer( | ||
| ObservabilityLayer::new() | ||
| .on_request(|request: &http::Request<Vec<u8>>| ic_cdk::println!("{request:?}")) | ||
| .on_response(|_, response: &http::Response<serde_json::Value>| { | ||
| ic_cdk::println!("{response:?}"); | ||
| }) | ||
| .on_error(|_, error: &BoxError| { | ||
| ic_cdk::println!("Error {error:?}"); | ||
| }), | ||
| ) | ||
| // Parse the response as JSON | ||
| .convert_response(JsonResponseConverter::<serde_json::Value>::new()) | ||
| // Convert the request and responses to types from the `http` crate | ||
| .layer(HttpConversionLayer) | ||
| // Use cycles from the canister to pay for HTTPs outcalls | ||
| .cycles_accounting(ChargeMyself::default()) | ||
| // The actual client | ||
| .service(Client::new_with_box_error()) | ||
| } | ||
|
|
||
| fn httpbin_base_url() -> String { | ||
| option_env!("HTTPBIN_URL") | ||
| .unwrap_or_else(|| "https://httpbin.org") | ||
| .to_string() | ||
| } | ||
|
|
||
| fn main() {} |
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,115 @@ | ||
| use candid::{decode_args, encode_args, utils::ArgumentEncoder, CandidType, Encode, Principal}; | ||
| use ic_management_canister_types::{CanisterId, CanisterSettings}; | ||
| use pocket_ic::{PocketIc, PocketIcBuilder}; | ||
| use serde::de::DeserializeOwned; | ||
| use std::{env::var, path::PathBuf, sync::Arc}; | ||
| use uuid::Uuid; | ||
|
|
||
| #[test] | ||
| fn should_make_parallel_http_requests() { | ||
| let setup = Setup::default(); | ||
| let http_canister = setup.http_canister(); | ||
|
|
||
| let http_request_results = http_canister.update_call::<_, Vec<String>>( | ||
| Principal::anonymous(), | ||
| "make_parallel_http_requests", | ||
| (), | ||
| ); | ||
|
|
||
| for uuid in http_request_results { | ||
| assert!(Uuid::parse_str(uuid.as_str()).is_ok()); | ||
| } | ||
| } | ||
|
|
||
| pub struct Setup { | ||
| env: Arc<PocketIc>, | ||
| http_canister_id: CanisterId, | ||
| } | ||
| impl Setup { | ||
| pub const DEFAULT_CONTROLLER: Principal = Principal::from_slice(&[0x9d, 0xf7, 0x02]); | ||
|
|
||
| pub fn new() -> Self { | ||
| let env = PocketIcBuilder::new() | ||
| .with_nns_subnet() //make_live requires NNS subnet. | ||
| .with_fiduciary_subnet() | ||
| .build(); | ||
|
|
||
| let canister_id = env.create_canister_with_settings( | ||
| None, | ||
| Some(CanisterSettings { | ||
| controllers: Some(vec![Self::DEFAULT_CONTROLLER]), | ||
| ..CanisterSettings::default() | ||
| }), | ||
| ); | ||
| env.add_cycles(canister_id, u64::MAX as u128); | ||
|
|
||
| env.install_canister( | ||
| canister_id, | ||
| multi_canister_wasm(), | ||
| Encode!().unwrap(), | ||
| Some(Self::DEFAULT_CONTROLLER), | ||
| ); | ||
|
|
||
| let mut env = env; | ||
| let _endpoint = env.make_live(None); | ||
|
|
||
| Self { | ||
| env: Arc::new(env), | ||
| http_canister_id: canister_id, | ||
| } | ||
| } | ||
|
|
||
| fn http_canister(&self) -> Canister { | ||
| Canister { | ||
| env: self.env.clone(), | ||
| id: self.http_canister_id, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl Default for Setup { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| pub struct Canister { | ||
| env: Arc<PocketIc>, | ||
| id: CanisterId, | ||
| } | ||
|
|
||
| impl Canister { | ||
| pub fn update_call<In, Out>(&self, sender: Principal, method: &str, args: In) -> Out | ||
| where | ||
| In: ArgumentEncoder + Send, | ||
| Out: CandidType + DeserializeOwned, | ||
| { | ||
| let message_id = self | ||
| .env | ||
| .submit_call( | ||
| self.id, | ||
| sender, | ||
| method, | ||
| encode_args(args).unwrap_or_else(|e| { | ||
| panic!("Failed to encode arguments for method {method}: {e}") | ||
| }), | ||
| ) | ||
| .unwrap_or_else(|e| panic!("Failed to call method {method}: {e}")); | ||
| let response_bytes = self | ||
| .env | ||
| .await_call_no_ticks(message_id) | ||
| .unwrap_or_else(|e| panic!("Failed to await call for method {method}: {e}")); | ||
| let (res,) = decode_args(&response_bytes).unwrap_or_else(|e| { | ||
| panic!("Failed to decode canister response for method {method}: {e}") | ||
| }); | ||
| res | ||
| } | ||
| } | ||
|
|
||
| fn multi_canister_wasm() -> Vec<u8> { | ||
| ic_test_utilities_load_wasm::load_wasm( | ||
| PathBuf::from(var("CARGO_MANIFEST_DIR").unwrap()).join("."), | ||
| "multi_canister", | ||
| &[], | ||
| ) | ||
| } | ||
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.