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
8 changes: 8 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ on:
env:
CARGO_TERM_COLOR: always
RUSTFLAGS: "-Dwarnings"
PROXY_CANISTER_VERSION: "v0.1.0"

jobs:
lint:
Expand Down Expand Up @@ -75,6 +76,13 @@ jobs:
echo "JSON_RPC_CANISTER_WASM_PATH=$GITHUB_WORKSPACE/target/wasm32-unknown-unknown/release/json_rpc_canister.wasm" >> "$GITHUB_ENV"
echo "MULTI_CANISTER_WASM_PATH=$GITHUB_WORKSPACE/target/wasm32-unknown-unknown/release/multi_canister.wasm" >> "$GITHUB_ENV"

- name: 'Download proxy canister WASM'
run: |
PROXY_CANISTER_WASM_PATH=$GITHUB_WORKSPACE/target/test-artifacts
mkdir -p $PROXY_CANISTER_WASM_PATH
curl -L "https://github.com/dfinity/proxy-canister/releases/download/${PROXY_CANISTER_VERSION}/proxy.wasm" -o "${PROXY_CANISTER_WASM_PATH}/proxy.wasm"
echo "PROXY_CANISTER_WASM_PATH=${PROXY_CANISTER_WASM_PATH}/proxy.wasm" >> $GITHUB_ENV

- name: 'Install PocketIC server'
uses: dfinity/pocketic@main
with:
Expand Down
4 changes: 3 additions & 1 deletion Cargo.lock

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

2 changes: 2 additions & 0 deletions examples/http_canister/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ ic-cdk = { workspace = true }
tower = { workspace = true }

[dev-dependencies]
assert_matches = { workspace = true }
ic-canister-runtime = { workspace = true }
ic-management-canister-types = { workspace = true }
ic-test-utilities-load-wasm = { workspace = true }
pocket-ic = { workspace = true }
Expand Down
34 changes: 26 additions & 8 deletions examples/http_canister/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
//! Example of a canister using `canhttp` to issue HTTP requests.

use canhttp::{
cycles::{ChargeMyself, CyclesAccountingServiceBuilder},
cycles::{ChargeCaller, ChargeMyself, CyclesAccountingServiceBuilder, CyclesChargingPolicy},
http::HttpConversionLayer,
observability::ObservabilityLayer,
CanisterReadyLayer, Client, MaxResponseBytesRequestExtension,
};
use http::Request;
use ic_cdk::update;
use tower::{BoxError, Service, ServiceBuilder, ServiceExt};

/// Make an HTTP POST request.
#[update]
pub async fn make_http_post_request() -> String {
let response = http_client()
let response = http_client(ChargeMyself::default())
.ready()
.await
.expect("Client should be ready")
.call(request())
.await
.expect("Request should succeed");

assert_eq!(response.status(), http::StatusCode::OK);

String::from_utf8_lossy(response.body()).to_string()
}

/// Make an HTTP POST request and charge the user cycles for it.
#[update]
pub async fn make_http_post_request_and_charge_user_cycles() -> String {
// Use cycles attached by the caller to pay for HTTPs outcalls and charge an additional flat
// fee of 1M cycles.
let response = http_client(ChargeCaller::new(|_request, cost| cost + 1_000_000))
.ready()
.await
.expect("Client should be ready")
Expand All @@ -32,7 +49,7 @@ pub async fn make_http_post_request() -> String {
pub async fn infinite_loop_make_http_post_request() -> String {
let mut client = ServiceBuilder::new()
.layer(CanisterReadyLayer)
.service(http_client());
.service(http_client(ChargeMyself::default()));

loop {
match client.ready().await {
Expand All @@ -45,7 +62,8 @@ pub async fn infinite_loop_make_http_post_request() -> String {
}
}

fn http_client(
fn http_client<C: CyclesChargingPolicy<Error: Into<BoxError>> + Clone>(
cycles_charging_policy: C,
) -> impl Service<http::Request<Vec<u8>>, Response = http::Response<Vec<u8>>, Error = BoxError> {
ServiceBuilder::new()
// Print request, response and errors to the console
Expand All @@ -61,13 +79,13 @@ fn http_client(
)
// Only deal with types from the http crate.
.layer(HttpConversionLayer)
// Use cycles from the canister to pay for HTTPs outcalls
.cycles_accounting(ChargeMyself::default())
// The strategy to use to charge cycles for the request
.cycles_accounting(cycles_charging_policy)
// The actual client
.service(Client::new_with_box_error())
}

fn request() -> Request<Vec<u8>> {
fn request() -> http::Request<Vec<u8>> {
fn httpbin_base_url() -> String {
option_env!("HTTPBIN_URL")
.unwrap_or_else(|| "https://httpbin.org")
Expand Down
33 changes: 31 additions & 2 deletions examples/http_canister/tests/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use assert_matches::assert_matches;
use candid::{Decode, Encode, Principal};
use ic_management_canister_types::CanisterIdRecord;
use ic_management_canister_types::CanisterSettings;
use ic_canister_runtime::IcError;
use ic_management_canister_types::{CanisterIdRecord, CanisterSettings};
use pocket_ic::common::rest::{
CanisterHttpReply, CanisterHttpResponse, MockCanisterHttpResponse, RawEffectivePrincipal,
};
Expand All @@ -20,6 +21,34 @@ async fn should_make_http_post_request() {
assert!(http_request_result.contains("\"X-Id\": \"42\""));
}

#[tokio::test]
async fn should_attach_cycles_to_canister_call() {
const REQUIRED_CYCLES: u128 = 1_000_000;

let setup = Setup::new("http_canister").await.with_proxy().await;

let http_request_result = setup
.canister()
.try_update_call_with_cycles::<_, String>(
"make_http_post_request_and_charge_user_cycles",
(),
REQUIRED_CYCLES - 1,
)
.await;
assert_matches!(http_request_result, Err(IcError::CallRejected { code: _, message }) if message.contains("InsufficientCyclesError"));

let http_request_result = setup
.canister()
.update_call_with_cycles::<_, String>(
"make_http_post_request_and_charge_user_cycles",
(),
REQUIRED_CYCLES,
)
.await;
assert!(http_request_result.contains("Hello, World!"));
assert!(http_request_result.contains("\"X-Id\": \"42\""));
}

#[test]
fn should_not_make_http_request_when_stopping() {
let env = PocketIc::new();
Expand Down
1 change: 0 additions & 1 deletion ic-canister-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ repository.workspace = true
documentation = "https://docs.rs/ic-canister-runtime"

[features]
proxy = ["dep:serde_bytes"]
wallet = ["dep:regex-lite", "dep:serde_bytes"]

[dependencies]
Expand Down
4 changes: 0 additions & 4 deletions ic-canister-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,12 @@ use async_trait::async_trait;
use candid::{utils::ArgumentEncoder, CandidType, Principal};
use ic_cdk::call::{Call, CallFailed, CandidDecodeFailed};
use ic_error_types::RejectCode;
#[cfg(feature = "proxy")]
pub use proxy::ProxyRuntime;
use serde::de::DeserializeOwned;
pub use stub::StubRuntime;
use thiserror::Error;
#[cfg(feature = "wallet")]
pub use wallet::CyclesWalletRuntime;

#[cfg(feature = "proxy")]
mod proxy;
mod stub;
#[cfg(feature = "wallet")]
mod wallet;
Expand Down
155 changes: 0 additions & 155 deletions ic-canister-runtime/src/proxy.rs

This file was deleted.

1 change: 1 addition & 0 deletions ic-pocket-canister-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ ic-cdk = { workspace = true }
ic-error-types = { workspace = true }
pocket-ic = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
url = { workspace = true }
Loading