Skip to content
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

Greet bot sample phase 1 WIP #7113

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft
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
94 changes: 67 additions & 27 deletions Cargo.lock

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

7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
[workspace]
members = [
"backend/bots/api",
"backend/bots/c2c_client",
"backend/bots/examples/greet",
"backend/canisters/airdrop_bot/api",
"backend/canisters/airdrop_bot/client",
"backend/canisters/airdrop_bot/impl",
Expand Down Expand Up @@ -106,6 +105,8 @@ members = [
"backend/external_canisters/sonic/api",
"backend/external_canisters/sonic/c2c_client",
"backend/integration_tests",
"backend/legacy_bots/api",
"backend/legacy_bots/c2c_client",
"backend/libraries/activity_notification_state",
"backend/libraries/candid_gen",
"backend/libraries/canister_agent_utils",
Expand Down Expand Up @@ -186,6 +187,7 @@ futures = "0.3.30"
getrandom = { version = "0.2.15", features = ["custom"] }
hex = "0.4.3"
hmac-sha256 = { version = "1.1.7", features = ["traits010"] }
http = "1.1.0"
ic-agent = "0.39.1"
ic-canister-sig-creation = "1.1.0"
ic-captcha = "1.0.0"
Expand All @@ -195,6 +197,7 @@ ic-cdk-macros = "0.17.0"
ic-cdk-timers = "0.11.0"
ic-certificate-verification = "2.4.0"
ic-certification = "2.5.0"
ic-http-certification = "2.5.0"
ic-ledger-types = "0.14.0"
ic_principal = "0.1.1"
ic-stable-structures = "0.6.7"
Expand Down
29 changes: 29 additions & 0 deletions backend/bots/examples/greet/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[package]
name = "greet_bot_canister_impl"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]

[dependencies]
candid = { workspace = true }
canister_client = { path = "../../../libraries/canister_client" }
getrandom = { workspace = true }
http = { workspace = true }
ic-cdk = { workspace = true }
ic-cdk-timers = { workspace = true }
ic-http-certification = { workspace = true }
ic_principal = { workspace = true }
ic-stable-structures = { workspace = true }
jwt = { path = "../../../libraries/jwt" }
local_user_index_canister = { path = "../../../canisters/local_user_index/api" }
local_user_index_canister_c2c_client = { path = "../../../canisters/local_user_index/c2c_client" }
msgpack = { path = "../../../libraries/msgpack" }
rmp-serde = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
types = { path = "../../../libraries/types" }
2 changes: 2 additions & 0 deletions backend/bots/examples/greet/can.did
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
service : {
};
52 changes: 52 additions & 0 deletions backend/bots/examples/greet/src/commands/greet.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use local_user_index_canister::execute_bot_command::{self, BotApiCallError};
use types::{
bot_actions::{BotMessageAction, MessageContent},
BotAction, BotCommandClaims, CanisterId, TextContent,
};

use crate::execute_command::{execute_bot_command, InternalError, Message, SuccessResult};

pub async fn greet(bot: BotCommandClaims, access_token: &str) -> Result<SuccessResult, InternalError> {
let user_id = bot.initiator;
let content = MessageContent::Text(TextContent {
text: format!("hello @UserId({user_id})"),
});

let args = execute_bot_command::Args {
action: BotAction::SendMessage(BotMessageAction {
content: content.clone(),
finalised: true,
}),
jwt: access_token.to_string(),
};

// Send the message to the OC chat but don't wait for the response
send_message_to_oc_chat(bot.bot_api_gateway, args);

Ok(SuccessResult {
message: Some(Message {
id: bot.message_id,
content,
}),
})
}

fn send_message_to_oc_chat(bot_api_gateway: CanisterId, args: execute_bot_command::Args) {
ic_cdk::spawn(call_oc_bot_action_inner(bot_api_gateway, args));

async fn call_oc_bot_action_inner(bot_api_gateway: CanisterId, args: execute_bot_command::Args) {
let result = match execute_bot_command(bot_api_gateway, &args).await {
Ok(Ok(_)) => Ok(()),
Ok(Err(error)) => match error {
BotApiCallError::C2CError(code, message) => Err(InternalError::C2CError(code, message)),
BotApiCallError::CanisterError(canister_error) => Err(InternalError::CanisterError(canister_error)),
BotApiCallError::Invalid(text) => Err(InternalError::Invalid(text)),
},
Err((code, message)) => Err(InternalError::C2CError(code as i32, message)),
};

if let Some(error) = result.err() {
ic_cdk::println!("Failed to call OC bot action: {:?}", error);
}
}
}
1 change: 1 addition & 0 deletions backend/bots/examples/greet/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod greet;
16 changes: 16 additions & 0 deletions backend/bots/examples/greet/src/env.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use candid::Principal;
use types::{Nanoseconds, TimestampMillis, TimestampNanos};

const NANOS_PER_MILLISECOND: Nanoseconds = 1_000_000;

pub fn now() -> TimestampMillis {
now_nanos() / NANOS_PER_MILLISECOND
}

pub fn now_nanos() -> TimestampNanos {
ic_cdk::api::time()
}

pub fn canister_id() -> Principal {
ic_cdk::id()
}
78 changes: 78 additions & 0 deletions backend/bots/examples/greet/src/execute_command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use canister_client::generate_candid_c2c_call;
use jwt::{verify_jwt, Claims};
use local_user_index_canister::execute_bot_command;
use serde::Serialize;
use types::{bot_actions::MessageContent, BotCommandClaims, HandleBotActionsError, MessageId};

use crate::{
commands::greet::greet,
env,
state::{self, State},
};

pub enum ExecuteCommandResponse {
Success(SuccessResult),
BadRequest(BadRequest),
InternalError(InternalError),
}

#[derive(Serialize)]
pub struct SuccessResult {
pub message: Option<Message>,
}

#[derive(Serialize)]
pub struct Message {
pub id: MessageId,
pub content: MessageContent,
}

#[derive(Serialize)]
pub enum BadRequest {
AccessTokenNotFound,
AccessTokenInvalid,
AccessTokenExpired,
CommandNotFound,
ArgsInvalid,
}

#[derive(Serialize, Debug)]
pub enum InternalError {
Invalid(String),
CanisterError(HandleBotActionsError),
C2CError(i32, String),
}

pub async fn execute_command(access_token: &str) -> ExecuteCommandResponse {
let bot = match state::read(|state| prepare(access_token, state)) {
Ok(c) => c,
Err(bad_request) => return ExecuteCommandResponse::BadRequest(bad_request),
};

let result = match bot.command_name.as_str() {
"greet" => greet(bot, access_token).await,
_ => return ExecuteCommandResponse::BadRequest(BadRequest::CommandNotFound),
};

match result {
Ok(success) => ExecuteCommandResponse::Success(success),
Err(internal_error) => ExecuteCommandResponse::InternalError(internal_error),
}
}

fn prepare(access_token: &str, state: &State) -> Result<BotCommandClaims, BadRequest> {
let oc_public_key_pem = state.oc_public_key();

let claims = verify_jwt::<Claims<BotCommandClaims>>(access_token, oc_public_key_pem).map_err(|error| {
ic_cdk::println!("Access token invalid: {:?}, error: {:?}", access_token, error);
BadRequest::AccessTokenInvalid
})?;

if claims.exp_ms() < env::now() {
return Err(BadRequest::AccessTokenExpired);
}

Ok(claims.into_custom())
}

generate_candid_c2c_call!(execute_bot_command);
Loading
Loading