aboutsummaryrefslogtreecommitdiff
path: root/planetwars-server/src/modules/bot_api.rs
blob: 2face62901b853b077bb15af9c552f320b04894b (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
pub mod pb {
    tonic::include_proto!("grpc.planetwars.bot_api");
}

use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use runner::match_context::{EventBus, PlayerHandle, RequestMessage};
use runner::match_log::MatchLogger;
use tokio::sync::{mpsc, oneshot};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tonic;
use tonic::transport::Server;
use tonic::{Request, Response, Status, Streaming};

use planetwars_matchrunner as runner;

use crate::db;
use crate::{ConnectionPool, MAPS_DIR, MATCHES_DIR};

use super::matches::code_bundle_to_botspec;

pub struct BotApiServer {
    router: PlayerRouter,
}

/// Routes players to their handler
#[derive(Clone)]
struct PlayerRouter {
    routing_table: Arc<Mutex<HashMap<String, SyncThingData>>>,
}

impl PlayerRouter {
    pub fn new() -> Self {
        PlayerRouter {
            routing_table: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

// TODO: implement a way to expire entries
impl PlayerRouter {
    fn put(&self, player_id: String, entry: SyncThingData) {
        let mut routing_table = self.routing_table.lock().unwrap();
        routing_table.insert(player_id, entry);
    }

    fn get(&self, player_id: &str) -> Option<SyncThingData> {
        // TODO: this design does not allow for reconnects. Is this desired?
        let mut routing_table = self.routing_table.lock().unwrap();
        routing_table.remove(player_id)
    }
}

#[tonic::async_trait]
impl pb::bot_api_service_server::BotApiService for BotApiServer {
    type ConnectBotStream = UnboundedReceiverStream<Result<pb::PlayerRequest, Status>>;

    async fn connect_bot(
        &self,
        req: Request<Streaming<pb::PlayerRequestResponse>>,
    ) -> Result<Response<Self::ConnectBotStream>, Status> {
        println!("bot connected");
        let stream = req.into_inner();
        // TODO: return error when player does not exist
        let sync_data = self.router.get("test_player").unwrap();
        sync_data.tx.send(stream).unwrap();
        Ok(Response::new(UnboundedReceiverStream::new(
            sync_data.server_messages,
        )))
    }
}

struct SyncThingData {
    tx: oneshot::Sender<Streaming<pb::PlayerRequestResponse>>,
    server_messages: mpsc::UnboundedReceiver<Result<pb::PlayerRequest, Status>>,
}

struct RemoteBotSpec {
    router: PlayerRouter,
}

#[tonic::async_trait]
impl runner::BotSpec for RemoteBotSpec {
    async fn run_bot(
        &self,
        player_id: u32,
        event_bus: Arc<Mutex<EventBus>>,
        _match_logger: MatchLogger,
    ) -> Box<dyn PlayerHandle> {
        let (tx, rx) = oneshot::channel();
        let (server_msg_snd, server_msg_recv) = mpsc::unbounded_channel();
        self.router.put(
            "test_player".to_string(),
            SyncThingData {
                tx,
                server_messages: server_msg_recv,
            },
        );

        let client_messages = rx.await.unwrap();
        tokio::spawn(handle_bot_messages(player_id, event_bus, client_messages));

        Box::new(RemoteBotHandle {
            sender: server_msg_snd,
        })
    }
}

async fn handle_bot_messages(
    player_id: u32,
    event_bus: Arc<Mutex<EventBus>>,
    mut messages: Streaming<pb::PlayerRequestResponse>,
) {
    while let Some(message) = messages.message().await.unwrap() {
        let request_id = (player_id, message.request_id as u32);
        event_bus
            .lock()
            .unwrap()
            .resolve_request(request_id, Ok(message.content));
    }
}

struct RemoteBotHandle {
    sender: mpsc::UnboundedSender<Result<pb::PlayerRequest, Status>>,
}

impl PlayerHandle for RemoteBotHandle {
    fn send_request(&mut self, r: RequestMessage) {
        self.sender
            .send(Ok(pb::PlayerRequest {
                request_id: r.request_id as i32,
                content: r.content,
            }))
            .unwrap();
    }
}

async fn run_match(router: PlayerRouter, pool: ConnectionPool) {
    let conn = pool.get().await.unwrap();

    let opponent = db::bots::find_bot_by_name("simplebot", &conn).unwrap();
    let opponent_code_bundle = db::bots::active_code_bundle(opponent.id, &conn).unwrap();

    let log_file_name = "remote_match.log";

    let remote_bot_spec = RemoteBotSpec { router };

    let match_config = runner::MatchConfig {
        map_path: PathBuf::from(MAPS_DIR).join("hex.json"),
        map_name: "hex".to_string(),
        log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name),
        players: vec![
            runner::MatchPlayer {
                bot_spec: Box::new(remote_bot_spec),
            },
            runner::MatchPlayer {
                bot_spec: code_bundle_to_botspec(&opponent_code_bundle),
            },
        ],
    };

    runner::run_match(match_config).await;
}

pub async fn run_bot_api(pool: ConnectionPool) {
    let router = PlayerRouter::new();
    tokio::spawn(run_match(router.clone(), pool));
    let server = BotApiServer { router };

    let addr = SocketAddr::from(([127, 0, 0, 1], 50051));
    Server::builder()
        .add_service(pb::bot_api_service_server::BotApiServiceServer::new(server))
        .serve(addr)
        .await
        .unwrap()
}