aboutsummaryrefslogtreecommitdiff
path: root/planetwars-client/src/main.rs
blob: 5c9ee44acc9ea1ff613ab0e6feed263d4fd674d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
pub mod pb {
    tonic::include_proto!("grpc.planetwars.client_api");

    pub use player_api_client_message::ClientMessage as PlayerApiClientMessageType;
    pub use player_api_server_message::ServerMessage as PlayerApiServerMessageType;
}

use clap::Parser;
use pb::client_api_service_client::ClientApiServiceClient;
use planetwars_matchrunner::bot_runner::{Bot, BotProcess};
use serde::Deserialize;
use std::{
    collections::VecDeque,
    path::PathBuf,
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::{
    io::{AsyncWriteExt, BufReader, Lines},
    process::{ChildStdin, ChildStdout},
    sync::mpsc::{self, UnboundedSender},
};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tonic::{metadata::MetadataValue, transport::Channel, Request, Status, Streaming};

#[derive(clap::Parser)]
struct PlayMatch {
    #[clap(value_parser)]
    bot_config_path: String,

    #[clap(value_parser)]
    opponent_name: String,

    #[clap(value_parser, long = "map")]
    map_name: Option<String>,

    #[clap(
        value_parser,
        long,
        default_value = "https://planetwars.dev:7492",
        env = "PLANETWARS_GRPC_SERVER_URL"
    )]
    grpc_server_url: String,
}

#[derive(Deserialize)]
struct BotConfig {
    #[allow(dead_code)]
    name: Option<String>,
    command: Command,
    working_directory: Option<String>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum Command {
    String(String),
    Argv(Vec<String>),
}

impl Command {
    pub fn to_argv(&self) -> Vec<String> {
        match self {
            Command::Argv(vec) => vec.clone(),
            Command::String(s) => shlex::split(s).expect("invalid command string"),
        }
    }
}

#[tokio::main]
async fn main() {
    let play_match = PlayMatch::parse();

    let content = std::fs::read_to_string(play_match.bot_config_path).unwrap();
    let bot_config: BotConfig = toml::from_str(&content).unwrap();

    let uri = play_match
        .grpc_server_url
        .parse()
        .expect("invalid grpc url");

    let channel = Channel::builder(uri).connect().await.unwrap();

    let created_match = create_match(
        channel.clone(),
        play_match.opponent_name,
        play_match.map_name,
    )
    .await
    .unwrap();
    match run_player(bot_config, created_match.player_key, channel).await {
        Ok(()) => (),
        Err(RunPlayerError::RunBotError(err)) => {
            println!("Error running bot: {}", err)
        }
    }
    println!(
        "Match completed. Watch the replay at {}",
        created_match.match_url
    );
    tokio::time::sleep(Duration::from_secs(1)).await;
}

async fn create_match(
    channel: Channel,
    opponent_name: String,
    map_name: Option<String>,
) -> Result<pb::CreateMatchResponse, Status> {
    let mut client = ClientApiServiceClient::new(channel);
    let res = client
        .create_match(Request::new(pb::CreateMatchRequest {
            opponent_name,
            map_name: map_name.unwrap_or_default(),
        }))
        .await;
    res.map(|response| response.into_inner())
}

#[derive(thiserror::Error, Debug)]
enum RunPlayerError {
    #[error("error running bot")]
    RunBotError(std::io::Error),
}

async fn run_player(
    bot_config: BotConfig,
    player_key: String,
    channel: Channel,
) -> Result<(), RunPlayerError> {
    let mut client = ClientApiServiceClient::with_interceptor(channel, |mut req: Request<()>| {
        let player_key: MetadataValue<_> = player_key.parse().unwrap();
        req.metadata_mut().insert("player_key", player_key);
        Ok(req)
    });

    let BotProcess {
        child: _child,
        stdin,
        stdout,
    } = Bot {
        working_dir: PathBuf::from(
            bot_config
                .working_directory
                .unwrap_or_else(|| ".".to_string()),
        ),
        argv: bot_config.command.to_argv(),
    }
    .spawn_process();

    let state = Arc::new(Mutex::new(BotRunnerState {
        request_queue: VecDeque::new(),
    }));

    let (tx, rx) = mpsc::unbounded_channel();
    let stream = client
        .connect_player(UnboundedReceiverStream::new(rx))
        .await
        .unwrap()
        .into_inner();

    let output_handle = tokio::spawn(handle_bot_output(state.clone(), tx, stdout));
    let input_handle = tokio::spawn(handle_server_messages(state.clone(), stream, stdin));

    output_handle
        .await
        .unwrap()
        .map_err(RunPlayerError::RunBotError)?;
    input_handle
        .await
        .unwrap()
        .map_err(RunPlayerError::RunBotError)?;

    Ok(())
}

struct BotRunnerState {
    request_queue: VecDeque<i32>,
}

async fn handle_server_messages(
    runner_state: Arc<Mutex<BotRunnerState>>,
    mut stream: Streaming<pb::PlayerApiServerMessage>,
    mut stdin: ChildStdin,
) -> io::Result<()> {
    while let Some(message) = stream.message().await.unwrap() {
        match message.server_message {
            Some(pb::PlayerApiServerMessageType::ActionRequest(req)) => {
                {
                    let mut state = runner_state.lock().unwrap();
                    if !state.request_queue.is_empty() {
                        eprintln!("[WARN] new turn started before bot output was received");
                        eprintln!(
                            "[WARN] this could be due to your bot taking too long, \
                                    or failing to flush output buffers."
                        );
                    }
                    state.request_queue.push_back(req.action_request_id);
                }
                stdin.write_all(&req.content).await?;
                stdin.write_u8(b'\n').await?;
            }
            _ => {} // pass
        }
    }

    Ok(())
}

use std::io;

async fn handle_bot_output(
    runner_state: Arc<Mutex<BotRunnerState>>,
    tx: UnboundedSender<pb::PlayerApiClientMessage>,
    mut bot_stdout: Lines<BufReader<ChildStdout>>,
) -> io::Result<()> {
    while let Some(line) = bot_stdout.next_line().await? {
        if let Some(request_id) = runner_state.lock().unwrap().request_queue.pop_front() {
            let action = pb::PlayerAction {
                action_request_id: request_id,
                content: line.as_bytes().to_vec(),
            };
            let msg = pb::PlayerApiClientMessage {
                client_message: Some(pb::PlayerApiClientMessageType::Action(action)),
            };
            tx.send(msg).unwrap();
        } else {
            eprintln!("[WARN] bot issued commands before a gamestate was received");
        }
    }

    Ok(())
}