Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
[workspace]
members = ["canhttp", "examples/http_canister", "ic-canister-runtime"]
members = [
"canhttp",
"examples/http_canister",
"ic-canister-runtime",
"ic-mock-http-canister-runtime",
]
resolver = "2"

[workspace.package]
Expand All @@ -14,10 +19,12 @@ readme = "README.md"
assert_matches = "1.5.0"
async-trait = "0.1.88"
candid = { version = "0.10.13" }
canhttp = { path = "canhttp" }
ciborium = "0.2.2"
futures-channel = "0.3.31"
futures-util = "0.3.31"
http = "1.3.1"
ic-canister-runtime = { path = "ic-canister-runtime" }
ic-cdk = "0.18.7"
ic-error-types = "0.2"
ic-management-canister-types = "0.3.3"
Expand All @@ -38,6 +45,7 @@ thiserror = "2.0.12"
tokio = "1.44.1"
tower = "0.5.2"
tower-layer = "0.3.3"
url = "2.5.7"

[profile.release]
debug = false
Expand Down
8 changes: 8 additions & 0 deletions ic-mock-http-canister-runtime/CHANGELOG.md
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
26 changes: 26 additions & 0 deletions ic-mock-http-canister-runtime/Cargo.toml
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]
1 change: 1 addition & 0 deletions ic-mock-http-canister-runtime/LICENSE
1 change: 1 addition & 0 deletions ic-mock-http-canister-runtime/NOTICE
192 changes: 192 additions & 0 deletions ic-mock-http-canister-runtime/src/lib.rs
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
}
Loading