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
4 changes: 2 additions & 2 deletions nix/sources.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
"type": "git"
},
"dfinity": {
"ref": "v0.5.2",
"ref": "v0.5.4",
"repo": "ssh://git@github.com/dfinity-lab/dfinity",
"rev": "a847ecc0bb8a1893f2cfb8d26dd31d69cb019eb6",
"rev": "a77551d2c630c2f30d18860bfb556ce46a0e8b08",
"type": "git"
},
"motoko": {
Expand Down
8 changes: 4 additions & 4 deletions src/dfx/src/actors/replica.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl Replica {
"Replica Configuration (TOML):\n-----\n{}-----\n", config_toml
);

let use_port = config.http_handler.use_port;
let port = config.http_handler.port;
let write_port_to = config.http_handler.write_port_to.clone();
let replica_path = self.config.replica_path.to_path_buf();

Expand All @@ -123,7 +123,7 @@ impl Replica {
let handle = replica_start_thread(
logger,
config_toml,
use_port,
port,
write_port_to,
replica_path,
addr,
Expand Down Expand Up @@ -216,7 +216,7 @@ fn wait_for_child_or_receiver(
fn replica_start_thread(
logger: Logger,
config_toml: String,
use_port: Option<u16>,
port: Option<u16>,
write_port_to: Option<PathBuf>,
replica_path: PathBuf,
addr: Addr<Replica>,
Expand Down Expand Up @@ -246,7 +246,7 @@ fn replica_start_thread(
debug!(logger, "Starting replica...");
let mut child = cmd.spawn().expect("Could not start replica.");

let port = use_port.unwrap_or_else(|| {
let port = port.unwrap_or_else(|| {
Replica::wait_for_port_file(write_port_to.as_ref().unwrap()).unwrap()
});
addr.do_send(signals::ReplicaRestarted { port });
Expand Down
7 changes: 3 additions & 4 deletions src/dfx/src/commands/canister/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,9 @@ pub fn exec(env: &dyn Environment, args: &ArgMatches<'_>) -> DfxResult {
.ok_or(DfxError::CommandMustBeRunInAProject)?;
let mut runtime = Runtime::new().expect("Unable to create a runtime");
if is_query {
if let Some(blob) = runtime.block_on(client.query(&canister_id, method_name, &arg_value))? {
print_idl_blob(&blob)
.map_err(|e| DfxError::InvalidData(format!("Invalid IDL blob: {}", e)))?;
}
let blob = runtime.block_on(client.query(&canister_id, method_name, &arg_value))?;
print_idl_blob(&blob)
.map_err(|e| DfxError::InvalidData(format!("Invalid IDL blob: {}", e)))?;
} else if args.is_present("async") {
let request_id = runtime.block_on(client.call(&canister_id, method_name, &arg_value))?;

Expand Down
6 changes: 2 additions & 4 deletions src/dfx/src/commands/canister/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,8 @@ pub fn exec(env: &dyn Environment, args: &ArgMatches<'_>) -> DfxResult {
.get_agent()
.ok_or(DfxError::CommandMustBeRunInAProject)?;
let mut runtime = Runtime::new().expect("Unable to create a runtime");
if let Some(blob) = runtime.block_on(agent.query(&canister_id, method_name, &arg_value))? {
print_idl_blob(&blob)
.map_err(|e| DfxError::InvalidData(format!("Invalid IDL blob: {}", e)))?;
}
let blob = runtime.block_on(agent.query(&canister_id, method_name, &arg_value))?;
print_idl_blob(&blob).map_err(|e| DfxError::InvalidData(format!("Invalid IDL blob: {}", e)))?;

Ok(())
}
2 changes: 1 addition & 1 deletion src/dfx/src/commands/replica.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ fn get_config(env: &dyn Environment, args: &ArgMatches<'_>) -> DfxResult<Replica
let file = env.get_temp_dir().join("config").join("port.txt");
http_handler.write_port_to = Some(file);
} else {
http_handler.use_port = Some(port);
http_handler.port = Some(port);
};
let message_gas_limit = get_message_gas_limit(&config, args)?;
let round_gas_limit = get_round_gas_limit(&config, args)?;
Expand Down
8 changes: 4 additions & 4 deletions src/dfx/src/lib/replica_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct HttpHandlerConfig {
/// Instructs the HTTP handler to use the specified port
pub use_port: Option<u16>,
pub port: Option<u16>,

/// Instructs the HTTP handler to bind to any open port and report the port
/// to the specified file.
Expand Down Expand Up @@ -62,7 +62,7 @@ impl ReplicaConfig {
ReplicaConfig {
http_handler: HttpHandlerConfig {
write_port_to: None,
use_port: None,
port: None,
},
scheduler: SchedulerConfig {
exec_gas: None,
Expand All @@ -82,13 +82,13 @@ impl ReplicaConfig {

#[allow(dead_code)]
pub fn with_port(&mut self, port: u16) -> &mut Self {
self.http_handler.use_port = Some(port);
self.http_handler.port = Some(port);
self.http_handler.write_port_to = None;
self
}

pub fn with_random_port(&mut self, write_port_to: &Path) -> &mut Self {
self.http_handler.use_port = None;
self.http_handler.port = None;
self.http_handler.write_port_to = Some(write_port_to.to_path_buf());
self
}
Expand Down
32 changes: 18 additions & 14 deletions src/ic_http_agent/src/agent/agent_test.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::agent::replica_api::{QueryResponseReply, ReadResponse};
use crate::agent::response::RequestStatusResponse;
use crate::agent::response::{Replied, RequestStatusResponse};
use crate::{Agent, AgentConfig, AgentError, Blob, CanisterId};
use delay::Delay;
use mockito::mock;
Expand All @@ -9,7 +9,7 @@ use std::time::Duration;
fn query() -> Result<(), AgentError> {
let blob = Blob(Vec::from("Hello World"));
let response = ReadResponse::Replied {
reply: Some(QueryResponseReply { arg: blob.clone() }),
reply: QueryResponseReply { arg: blob.clone() },
};

let read_mock = mock("POST", "/api/v1/read")
Expand All @@ -31,7 +31,7 @@ fn query() -> Result<(), AgentError> {

read_mock.assert();

assert_eq!(result?, Some(blob));
assert_eq!(result?, blob);

Ok(())
}
Expand All @@ -46,7 +46,7 @@ fn query_error() -> Result<(), AgentError> {
})?;
let mut runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime");

let result: Result<Option<Blob>, AgentError> = runtime.block_on(async {
let result: Result<Blob, AgentError> = runtime.block_on(async {
agent
.query(&CanisterId::from_bytes(&[2u8]), "greet", &Blob::empty())
.await
Expand All @@ -61,7 +61,7 @@ fn query_error() -> Result<(), AgentError> {

#[test]
fn query_rejected() -> Result<(), AgentError> {
let response: ReadResponse<u8> = ReadResponse::Rejected {
let response: ReadResponse = ReadResponse::Rejected {
reject_code: 1234,
reject_message: "Rejected Message".to_string(),
};
Expand All @@ -78,7 +78,7 @@ fn query_rejected() -> Result<(), AgentError> {
})?;
let mut runtime = tokio::runtime::Runtime::new().expect("Unable to create a runtime");

let result: Result<Option<Blob>, AgentError> = runtime.block_on(async {
let result: Result<Blob, AgentError> = runtime.block_on(async {
agent
.query(&CanisterId::from_bytes(&[3u8]), "greet", &Blob::empty())
.await
Expand All @@ -101,7 +101,7 @@ fn query_rejected() -> Result<(), AgentError> {
fn call() -> Result<(), AgentError> {
let blob = Blob(Vec::from("Hello World"));
let response = ReadResponse::Replied {
reply: Some(QueryResponseReply { arg: blob.clone() }),
reply: QueryResponseReply { arg: blob.clone() },
};

let submit_mock = mock("POST", "/api/v1/submit").with_status(200).create();
Expand Down Expand Up @@ -129,7 +129,9 @@ fn call() -> Result<(), AgentError> {

assert_eq!(
result?,
RequestStatusResponse::Replied { reply: Some(blob) }
RequestStatusResponse::Replied {
reply: Replied::CodeCallReplied { arg: blob }
}
);

Ok(())
Expand Down Expand Up @@ -160,7 +162,7 @@ fn call_error() -> Result<(), AgentError> {

#[test]
fn call_rejected() -> Result<(), AgentError> {
let response: ReadResponse<u8> = ReadResponse::Rejected {
let response: ReadResponse = ReadResponse::Rejected {
reject_code: 1234,
reject_message: "Rejected Message".to_string(),
};
Expand Down Expand Up @@ -208,7 +210,7 @@ fn install() -> Result<(), AgentError> {

let blob = Blob(Vec::from("Hello World"));
let response = ReadResponse::Replied {
reply: Some(QueryResponseReply { arg: blob.clone() }),
reply: QueryResponseReply { arg: blob.clone() },
};

let submit_mock = mock("POST", "/api/v1/submit").with_status(200).create();
Expand All @@ -234,15 +236,17 @@ fn install() -> Result<(), AgentError> {

assert_eq!(
result?,
RequestStatusResponse::Replied { reply: Some(blob) }
RequestStatusResponse::Replied {
reply: Replied::CodeCallReplied { arg: blob }
}
);

Ok(())
}

#[test]
fn ping() -> Result<(), AgentError> {
let read_mock = mock("GET", "/api/v1/read").with_status(200).create();
let read_mock = mock("GET", "/api/v1/status").with_status(200).create();

let agent = Agent::new(AgentConfig {
url: &mockito::server_url(),
Expand All @@ -260,7 +264,7 @@ fn ping() -> Result<(), AgentError> {

#[test]
fn ping_okay() -> Result<(), AgentError> {
let read_mock = mock("GET", "/api/v1/read").with_status(405).create();
let read_mock = mock("GET", "/api/v1/status").with_status(200).create();

let agent = Agent::new(AgentConfig {
url: &mockito::server_url(),
Expand All @@ -284,7 +288,7 @@ fn ping_okay() -> Result<(), AgentError> {
fn ping_error() -> Result<(), AgentError> {
// This mock is never asserted as we don't know (nor do we need to know) how many times
// it is called.
let _read_mock = mock("GET", "/api/v1/read").with_status(500).create();
let _read_mock = mock("GET", "/api/v1/status").with_status(500).create();

let agent = Agent::new(AgentConfig {
url: &mockito::server_url(),
Expand Down
38 changes: 20 additions & 18 deletions src/ic_http_agent/src/agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub(crate) mod public {
pub use super::agent_error::AgentError;
pub use super::nonce::NonceFactory;
pub use super::replica_api::{MessageWithSender, ReadRequest, Request, SignedMessage};
pub use super::response::RequestStatusResponse;
pub use super::response::{Replied, RequestStatusResponse};
pub use super::signer::Signer;
pub use super::Agent;
}
Expand All @@ -19,9 +19,7 @@ mod agent_test;

pub mod signer;

use crate::agent::replica_api::{
QueryResponseReply, ReadRequest, ReadResponse, Request, SubmitRequest,
};
use crate::agent::replica_api::{ReadRequest, ReadResponse, Request, SubmitRequest};
use crate::agent::signer::Signer;
use crate::{Blob, CanisterAttributes, CanisterId, RequestId};

Expand Down Expand Up @@ -56,11 +54,13 @@ impl Agent {
})
}

async fn read<A>(&self, request: ReadRequest<'_>) -> Result<ReadResponse<A>, AgentError>
async fn read<A>(&self, request: ReadRequest<'_>) -> Result<A, AgentError>
where
A: serde::de::DeserializeOwned,
{
let record = serde_cbor::to_vec(&request)?;
let request = Request::Query(request);
let (_, signed_request) = self.signer.sign(request)?;
let record = serde_cbor::to_vec(&signed_request)?;
let url = self.url.join("read")?;

let mut http_request = reqwest::Request::new(Method::POST, url);
Expand Down Expand Up @@ -110,15 +110,15 @@ impl Agent {
canister_id: &'a CanisterId,
method_name: &'a str,
arg: &'a Blob,
) -> Result<Option<Blob>, AgentError> {
self.read::<QueryResponseReply>(ReadRequest::Query {
) -> Result<Blob, AgentError> {
self.read::<ReadResponse>(ReadRequest::Query {
canister_id,
method_name,
arg,
})
.await
.and_then(|response| match response {
ReadResponse::Replied { reply } => Ok(reply.map(|r| r.arg)),
ReadResponse::Replied { reply } => Ok(reply.arg),
ReadResponse::Rejected {
reject_code,
reject_message,
Expand All @@ -132,9 +132,7 @@ impl Agent {
&self,
request_id: &RequestId,
) -> Result<RequestStatusResponse, AgentError> {
self.read(ReadRequest::RequestStatus { request_id })
.await
.and_then(|response| Ok(RequestStatusResponse::from(response)))
self.read(ReadRequest::RequestStatus { request_id }).await
}

pub async fn request_status_and_wait<W: delay::Waiter>(
Expand All @@ -146,10 +144,14 @@ impl Agent {

loop {
match self.request_status(request_id).await? {
RequestStatusResponse::Replied { reply } => return Ok(reply),
RequestStatusResponse::Rejected { code, message } => {
return Err(AgentError::ClientError(code, message))
}
RequestStatusResponse::Replied { reply } => match reply {
Replied::CodeCallReplied { arg } => return Ok(Some(arg)),
Replied::Empty {} => return Ok(None),
},
RequestStatusResponse::Rejected {
reject_code,
reject_message,
} => return Err(AgentError::ClientError(reject_code, reject_message)),
RequestStatusResponse::Unknown => (),
RequestStatusResponse::Pending => (),
};
Expand Down Expand Up @@ -225,11 +227,11 @@ impl Agent {
}

pub async fn ping_once(&self) -> Result<(), AgentError> {
let url = self.url.join("read")?;
let url = self.url.join("status")?;
let http_request = reqwest::Request::new(Method::GET, url);
let response = self.client.execute(http_request).await?;

if response.status().as_u16() == 405 {
if response.status().as_u16() == 200 {
Ok(())
} else {
// Verify the error is 2XX.
Expand Down
8 changes: 4 additions & 4 deletions src/ic_http_agent/src/agent/replica_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub enum ReadRequest<'a> {
},
}

#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub(crate) struct QueryResponseReply {
pub arg: Blob,
Expand All @@ -26,9 +26,9 @@ pub(crate) struct QueryResponseReply {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "status")]
pub(crate) enum ReadResponse<A> {
pub(crate) enum ReadResponse {
Replied {
reply: Option<A>,
reply: QueryResponseReply,
},
Rejected {
reject_code: u16,
Expand Down Expand Up @@ -75,7 +75,7 @@ pub struct MessageWithSender<T: Serialize> {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SignedMessage<'a> {
#[serde(flatten)]
#[serde(rename = "content")]
pub request_with_sender: Request<'a>,
pub sender_pubkey: Blob,
#[serde(rename = "sender_sig")]
Expand Down
Loading