-
Notifications
You must be signed in to change notification settings - Fork 2
feat: add ic-mock-http-canister-runtime crate
#38
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| # Changelog | ||
|
|
||
| All notable changes to this project will be documented in this file. | ||
|
|
||
| The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), | ||
| and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). | ||
|
|
||
| ## Unreleased | ||
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,26 @@ | ||
| [package] | ||
| name = "ic-mock-http-canister-runtime" | ||
| version = "0.1.0" | ||
| description = "Mock HTTP outcalls with Pocket IC" | ||
| license.workspace = true | ||
| readme.workspace = true | ||
| homepage.workspace = true | ||
| authors.workspace = true | ||
| edition.workspace = true | ||
| include = ["src", "Cargo.toml", "CHANGELOG.md", "LICENSE", "README.md"] | ||
| repository.workspace = true | ||
| documentation = "https://docs.rs/ic-mock-http-canister-runtime" | ||
|
|
||
| [dependencies] | ||
| async-trait = { workspace = true } | ||
| candid = { workspace = true } | ||
| canhttp = { workspace = true, features = ["json", "http"] } | ||
| ic-canister-runtime = { workspace = true } | ||
| ic-cdk = { workspace = true } | ||
| ic-error-types = { workspace = true } | ||
| pocket-ic = { workspace = true } | ||
| serde = { workspace = true } | ||
| serde_json = { workspace = true } | ||
| url = { workspace = true } | ||
|
|
||
| [dev-dependencies] |
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 @@ | ||
| ../LICENSE |
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 @@ | ||
| ../NOTICE |
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,192 @@ | ||
| //! Library to mock HTTP outcalls on the Internet Computer leveraging the [`ic_canister_runtime`] crate's | ||
| //! [`Runtime`] trait as well as [`PocketIc`]. | ||
|
|
||
| #![forbid(unsafe_code)] | ||
| #![forbid(missing_docs)] | ||
|
|
||
| mod mock; | ||
|
|
||
| use async_trait::async_trait; | ||
| use candid::{decode_one, encode_args, utils::ArgumentEncoder, CandidType, Principal}; | ||
| use ic_canister_runtime::{IcError, Runtime}; | ||
| use ic_cdk::call::{CallFailed, CallRejected}; | ||
| use ic_error_types::RejectCode; | ||
| pub use mock::{ | ||
| json::{JsonRpcRequestMatcher, JsonRpcResponse}, | ||
| CanisterHttpReject, CanisterHttpReply, CanisterHttpRequestMatcher, MockHttpOutcall, | ||
| MockHttpOutcallBuilder, MockHttpOutcalls, MockHttpOutcallsBuilder, | ||
| }; | ||
| use pocket_ic::{ | ||
| common::rest::{CanisterHttpRequest, CanisterHttpResponse, MockCanisterHttpResponse}, | ||
| nonblocking::PocketIc, | ||
| RejectResponse, | ||
| }; | ||
| use serde::de::DeserializeOwned; | ||
| use std::{ | ||
| sync::{Arc, Mutex}, | ||
| time::Duration, | ||
| }; | ||
|
|
||
| const DEFAULT_MAX_RESPONSE_BYTES: u64 = 2_000_000; | ||
| const MAX_TICKS: usize = 10; | ||
|
|
||
| /// [`Runtime`] using [`PocketIc`] to mock HTTP outcalls. | ||
| /// | ||
| /// This runtime allows making calls to canisters through Pocket IC while verifying the HTTP | ||
| /// outcalls made and mocking their responses. | ||
| pub struct MockHttpRuntime { | ||
| env: Arc<PocketIc>, | ||
| caller: Principal, | ||
| mocks: Mutex<MockHttpOutcalls>, | ||
| } | ||
|
|
||
| impl MockHttpRuntime { | ||
| /// Create a new [`MockHttpRuntime`] with the given [`PocketIc`] and [`MockHttpOutcalls`]. | ||
| /// All calls to canisters are made using the given caller identity. | ||
| pub fn new(env: Arc<PocketIc>, caller: Principal, mocks: impl Into<MockHttpOutcalls>) -> Self { | ||
| Self { | ||
| env: env.clone(), | ||
| caller, | ||
| mocks: Mutex::new(mocks.into()), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[async_trait] | ||
| impl Runtime for MockHttpRuntime { | ||
| async fn update_call<In, Out>( | ||
| &self, | ||
| id: Principal, | ||
| method: &str, | ||
| args: In, | ||
| _cycles: u128, | ||
| ) -> Result<Out, IcError> | ||
| where | ||
| In: ArgumentEncoder + Send, | ||
| Out: CandidType + DeserializeOwned, | ||
| { | ||
| let message_id = self | ||
| .env | ||
| .submit_call( | ||
| id, | ||
| self.caller, | ||
| method, | ||
| encode_args(args).unwrap_or_else(panic_when_encode_fails), | ||
| ) | ||
| .await | ||
| .unwrap(); | ||
| self.execute_mocks().await; | ||
| self.env | ||
| .await_call(message_id) | ||
| .await | ||
| .map(decode_call_response) | ||
| .map_err(parse_reject_response)? | ||
| } | ||
|
|
||
| async fn query_call<In, Out>( | ||
| &self, | ||
| id: Principal, | ||
| method: &str, | ||
| args: In, | ||
| ) -> Result<Out, IcError> | ||
| where | ||
| In: ArgumentEncoder + Send, | ||
| Out: CandidType + DeserializeOwned, | ||
| { | ||
| self.env | ||
| .query_call( | ||
| id, | ||
| self.caller, | ||
| method, | ||
| encode_args(args).unwrap_or_else(panic_when_encode_fails), | ||
| ) | ||
| .await | ||
| .map(decode_call_response) | ||
| .map_err(parse_reject_response)? | ||
| } | ||
| } | ||
|
|
||
| impl MockHttpRuntime { | ||
| async fn execute_mocks(&self) { | ||
| loop { | ||
| let pending_requests = tick_until_http_requests(self.env.as_ref()).await; | ||
| if let Some(request) = pending_requests.first() { | ||
| let maybe_mock = { | ||
| let mut mocks = self.mocks.lock().unwrap(); | ||
| mocks.pop_matching(request) | ||
| }; | ||
| match maybe_mock { | ||
| Some(mock) => { | ||
| let mock_response = MockCanisterHttpResponse { | ||
| subnet_id: request.subnet_id, | ||
| request_id: request.request_id, | ||
| response: check_response_size(request, mock.response), | ||
| additional_responses: vec![], | ||
| }; | ||
| self.env.mock_canister_http_response(mock_response).await; | ||
| } | ||
| None => { | ||
| panic!("No mocks matching the request: {:?}", request); | ||
| } | ||
| } | ||
| } else { | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn check_response_size( | ||
| request: &CanisterHttpRequest, | ||
| response: CanisterHttpResponse, | ||
| ) -> CanisterHttpResponse { | ||
| if let CanisterHttpResponse::CanisterHttpReply(reply) = &response { | ||
| let max_response_bytes = request | ||
| .max_response_bytes | ||
| .unwrap_or(DEFAULT_MAX_RESPONSE_BYTES); | ||
| if reply.body.len() as u64 > max_response_bytes { | ||
| // Approximate replica behavior since headers are not accounted for. | ||
| return CanisterHttpResponse::CanisterHttpReject( | ||
| pocket_ic::common::rest::CanisterHttpReject { | ||
| reject_code: RejectCode::SysFatal as u64, | ||
| message: format!("Http body exceeds size limit of {max_response_bytes} bytes.",), | ||
| }, | ||
| ); | ||
| } | ||
| } | ||
| response | ||
| } | ||
|
|
||
| fn parse_reject_response(response: RejectResponse) -> IcError { | ||
| CallFailed::CallRejected(CallRejected::with_rejection( | ||
| response.reject_code as u32, | ||
| response.reject_message, | ||
| )) | ||
| .into() | ||
| } | ||
|
|
||
| fn decode_call_response<Out>(bytes: Vec<u8>) -> Result<Out, IcError> | ||
| where | ||
| Out: CandidType + DeserializeOwned, | ||
| { | ||
| decode_one(&bytes).map_err(|e| IcError::CandidDecodeFailed { | ||
| message: e.to_string(), | ||
| }) | ||
| } | ||
|
|
||
| fn panic_when_encode_fails(err: candid::error::Error) -> Vec<u8> { | ||
| panic!("failed to encode args: {err}") | ||
| } | ||
|
|
||
| async fn tick_until_http_requests(env: &PocketIc) -> Vec<CanisterHttpRequest> { | ||
| let mut requests = Vec::new(); | ||
| for _ in 0..MAX_TICKS { | ||
| requests = env.get_canister_http().await; | ||
| if !requests.is_empty() { | ||
| break; | ||
| } | ||
| env.tick().await; | ||
| env.advance_time(Duration::from_nanos(1)).await; | ||
| } | ||
| requests | ||
| } |
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.