tpex_api/server/
mod.rs

1use std::fmt::Debug;
2
3use crate::{shared::*, state_type};
4pub mod tokens;
5pub mod state;
6
7use axum::{extract::{ws::rejection::WebSocketUpgradeRejection, FromRequestParts}, response::IntoResponse, serve::Listener, Router};
8use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncSeek, AsyncSeekExt, AsyncWrite};
9use tokio_util::sync::CancellationToken;
10use tower_http::trace::TraceLayer;
11use tpex::StateSync;
12#[derive(clap::Parser)]
13pub struct Args {
14    pub trades: std::path::PathBuf,
15    pub db: String,
16    pub endpoint: String,
17}
18
19#[derive(Debug)]
20enum Error {
21    TPEx(tpex::Error),
22    UncontrolledUser,
23    TokenTooLowLevel,
24    TokenInvalid,
25    NotNextId{next_id: u64}
26}
27impl From<tpex::Error> for Error {
28    fn from(value: tpex::Error) -> Self {
29        Self::TPEx(value)
30    }
31}
32impl axum::response::IntoResponse for Error {
33    fn into_response(self) -> axum::response::Response {
34        let (code,err) = match self {
35            Self::TPEx(err) => (409, ErrorInfo{error:err.to_string()}),
36            Self::UncontrolledUser => (403, ErrorInfo{error:"This action would act on behalf of a different user.".to_owned()}),
37            Self::TokenTooLowLevel => (403, ErrorInfo{error:"This action requires a higher permission level".to_owned()}),
38            Self::NotNextId{next_id} => (409, ErrorInfo{error:format!("The requested ID was not the next, which is {next_id}")}),
39            Self::TokenInvalid => (409, ErrorInfo{error:"The given token does not exist".to_owned()})
40        };
41
42        let body = serde_json::to_vec(&err).expect("Unable to serialise error");
43
44        let body = axum::body::Body::from(body);
45
46        axum::response::Response::builder()
47        .status(code)
48        .header("Content-Type", "application/json")
49        .body(body)
50        .expect("Unable to create error response")
51    }
52}
53
54async fn state_patch(
55    axum::extract::State(state): axum::extract::State<state_type!()>,
56    token: TokenInfo,
57    axum_extra::extract::OptionalQuery(args): axum_extra::extract::OptionalQuery<StatePatchArgs>,
58    axum::extract::Json(action): axum::extract::Json<tpex::Action>
59) -> Result<axum::response::Json<u64>, Error> {
60    match token.level {
61        TokenLevel::ReadOnly => return Err(Error::TokenTooLowLevel),
62        TokenLevel::ProxyOne => {
63            let perms = state.tpex.read().await.state().perms(&action)?;
64            if perms.player != token.user {
65                return Err(Error::UncontrolledUser);
66            }
67        }
68        // Apply catches all banker perm mismatches, assuming that upstream has verified their action:
69        TokenLevel::ProxyAll => ()
70    }
71    let mut tpex_state = state.tpex.write().await;
72    let id =
73        if let Some(expected_id) = args.and_then(|i| i.id) {
74            let next_id = tpex_state.state().get_next_id();
75            if next_id != expected_id {
76                return Err(Error::NotNextId{next_id});
77            }
78            let id = tpex_state.apply(action).await?;
79            assert_eq!(id, next_id, "Somehow got ID mismatch");
80            id
81        }
82        else {
83            tpex_state.apply(action).await?
84        };
85    // We patched, so update the id
86    //
87    // We use send_replace so that we don't have to worry about if anyone's listening
88    state.updated.send_replace(id);
89    Ok(axum::Json(id))
90}
91
92struct OptionalWebSocket(pub Option<axum::extract::ws::WebSocketUpgrade>);
93impl<S : Send + Sync> FromRequestParts<S> for OptionalWebSocket {
94    #[doc = " If the extractor fails it\'ll use this \"rejection\" type. A rejection is"]
95    #[doc = " a kind of error that can be converted into a response."]
96    type Rejection = WebSocketUpgradeRejection;
97
98    async fn from_request_parts(parts: &mut axum::http::request::Parts,state: &S,) -> Result<Self,Self::Rejection> {
99        match axum::extract::ws::WebSocketUpgrade::from_request_parts(parts, state).await {
100            Ok(x) => Ok(Self(Some(x))),
101            Err(WebSocketUpgradeRejection::MethodNotGet(_)) |
102            Err(WebSocketUpgradeRejection::MethodNotConnect(_)) |
103            Err(WebSocketUpgradeRejection::InvalidConnectionHeader(_)) |
104            Err(WebSocketUpgradeRejection::InvalidUpgradeHeader(_)) => Ok(Self(None)),
105            Err(e) => Err(e)
106        }
107    }
108}
109
110async fn state_get(
111    axum::extract::State(state): axum::extract::State<state_type!()>,
112    // must extract token to auth
113    _token: TokenInfo,
114    axum_extra::extract::OptionalQuery(args): axum_extra::extract::OptionalQuery<StateGetArgs>,
115    OptionalWebSocket(upgrade): OptionalWebSocket
116) -> axum::response::Response {
117    let mut from = args.unwrap_or_default().from.unwrap_or(0);
118    if let Some(upgrade) = upgrade {
119        upgrade.on_upgrade(move |mut sock: axum::extract::ws::WebSocket| async move {
120            let mut subscription = state.updated.subscribe();
121            loop {
122                subscription.wait_for(|i| *i >= from).await.expect("Failed to poll updated_recv");
123
124                let tpex_state_handle = state.tpex.read().await;
125                // It's better to clone these out than hold state
126                let res =
127                    tpex_state_handle.cache().iter()
128                    .skip(from as usize)
129                    .map(Into::into)
130                    .map(axum::extract::ws::Message::Text)
131                    .collect::<Vec<_>>();
132                // rechecking the id prevents a race condition
133                from = tpex_state_handle.state().get_next_id() - 1;
134                // We have extracted all we need
135                drop(tpex_state_handle);
136                // Send it off
137                for i in res {
138                    if sock.send(i).await.is_err() {
139                        break;
140                    }
141                }
142            }
143        })
144    }
145    else {
146        let data =
147            state.tpex.read().await.cache().iter()
148            .skip(from as usize)
149            .fold(String::new(), |a, b| a + b);
150        let body = axum::body::Body::from(data);
151        axum::response::Response::builder()
152        .header("Content-Type", "text/plain")
153        .body(body)
154        .expect("Unable to create state_get response")
155    }
156}
157
158async fn token_get(
159    axum::extract::State(_state): axum::extract::State<state_type!()>,
160    token: TokenInfo
161) -> axum::Json<TokenInfo> {
162    axum::Json(token)
163}
164
165async fn token_post(
166    axum::extract::State(state): axum::extract::State<state_type!()>,
167    token: TokenInfo,
168    axum::extract::Json(args): axum::extract::Json<TokenPostArgs>,
169) -> Result<axum::Json<Token>, Error> {
170    if args.level > token.level {
171        return Err(Error::TokenTooLowLevel)
172    }
173    if args.user != token.user && token.level < TokenLevel::ProxyAll {
174        return Err(Error::UncontrolledUser)
175    }
176
177    Ok(axum::Json(state.tokens.create_token(args.level, args.user).await.expect("Cannot access DB")))
178}
179
180async fn token_delete(
181    axum::extract::State(state): axum::extract::State<state_type!()>,
182    token: TokenInfo,
183    axum::extract::Json(args): axum::extract::Json<TokenDeleteArgs>
184) -> Result<axum::Json<()>, Error> {
185    let target = args.token.unwrap_or(token.token);
186    // We only need perms to delete other tokens
187    if target != token.token && token.level < TokenLevel::ProxyOne {
188        return Err(Error::TokenTooLowLevel);
189    }
190    state.tokens.delete_token(&token.token).await
191    .map_or(Err(Error::TokenInvalid), |_| Ok(axum::Json(())))
192}
193
194async fn fastsync_get(
195    axum::extract::State(state): axum::extract::State<state_type!()>,
196    _token: TokenInfo,
197    OptionalWebSocket(upgrade): OptionalWebSocket
198) -> axum::response::Response {
199    if let Some(upgrade) = upgrade {
200        upgrade.on_upgrade(move |mut sock: axum::extract::ws::WebSocket| async move {
201            let mut subscription = state.updated.subscribe();
202            subscription.mark_changed();
203            loop {
204                subscription.changed().await.expect("Failed to poll updated_recv");
205                let res = StateSync::from(state.tpex.read().await.state());
206                if sock.send(axum::extract::ws::Message::Text(serde_json::to_string(&res).expect("Could not serialise state sync").into())).await.is_err() {
207                    break;
208                }
209            }
210        })
211    }
212    else {
213        let res = StateSync::from(state.tpex.read().await.state());
214        axum::Json(res).into_response()
215    }
216}
217
218async fn inspect_balance_get(
219    axum::extract::State(state): axum::extract::State<state_type!()>,
220    _token: TokenInfo,
221    axum::extract::Query(args): axum::extract::Query<InspectBalanceGetArgs>
222) -> axum::response::Response {
223    axum::Json(state.tpex.read().await.state().get_bal(&args.player)).into_response()
224}
225
226async fn inspect_assets_get(
227    axum::extract::State(state): axum::extract::State<state_type!()>,
228    _token: TokenInfo,
229    axum::extract::Query(args): axum::extract::Query<InspectAssetsGetArgs>
230) -> axum::response::Response {
231    axum::Json(state.tpex.read().await.state().get_assets(&args.player)).into_response()
232}
233
234async fn inspect_audit_get(
235    axum::extract::State(state): axum::extract::State<state_type!()>,
236    _token: TokenInfo
237) -> axum::response::Response {
238    axum::Json(state.tpex.read().await.state().itemised_audit()).into_response()
239}
240
241pub async fn run_server<L: Listener>(
242    cancel: CancellationToken,
243    mut trade_log: impl AsyncWrite + AsyncBufRead + AsyncSeek + Unpin + Send + Sync + 'static,
244    token_handler: tokens::TokenHandler,
245    listener: L) where L::Addr : Debug
246{
247    // Load cache
248    let mut cache = Vec::new();
249    {
250        let mut lines = trade_log.lines();
251        while let Some(mut line) = lines.next_line().await.expect("Could not read trade file") {
252            line.push('\n');
253            cache.push(line);
254        }
255        trade_log = lines.into_inner();
256        trade_log.rewind().await.expect("Could not rewind trade file");
257    }
258
259    let mut tpex_state = tpex::State::new();
260    tpex_state.replay(&mut trade_log, true).await.expect("Could not replay trades");
261
262    let (updated, _) = tokio::sync::watch::channel(tpex_state.get_next_id().checked_sub(1).expect("Poll counter underflow"));
263    let state = state::StateStruct {
264        tpex: tokio::sync::RwLock::new(state::TPExState::new(tpex_state, trade_log, cache)),
265        tokens: token_handler,
266        updated
267    };
268
269    let cors = tower_http::cors::CorsLayer::new()
270        .allow_headers(tower_http::cors::Any)
271        .allow_origin(tower_http::cors::Any)
272        .allow_methods(tower_http::cors::Any);
273
274
275    let app = Router::new()
276        .route("/state", axum::routing::get(state_get))
277        .route("/state", axum::routing::connect(state_get))
278        .route("/state", axum::routing::patch(state_patch))
279
280        .route("/token", axum::routing::get(token_get))
281        .route("/token", axum::routing::post(token_post))
282        .route("/token", axum::routing::delete(token_delete))
283
284        .route("/fastsync", axum::routing::get(fastsync_get))
285
286        .route("/inspect/balance", axum::routing::get(inspect_balance_get))
287        .route("/inspect/assets", axum::routing::get(inspect_assets_get))
288        .route("/inspect/audit", axum::routing::get(inspect_audit_get))
289
290        .with_state(std::sync::Arc::new(state))
291
292        .layer(TraceLayer::new_for_http())
293
294        .route_layer(cors);
295
296    axum::serve(listener, app).with_graceful_shutdown(async move { cancel.cancelled().await }).await.expect("Failed to serve");
297}
298
299pub async fn run_server_with_args(args: Args, cancel: CancellationToken) {
300    run_server(
301        cancel,
302        tokio::io::BufStream::with_capacity(16<<20, 16<<20,
303            tokio::fs::File::options()
304            .read(true)
305            .write(true)
306            .truncate(false)
307            .create(true)
308            .open(args.trades).await.expect("Unable to open trade list")),
309        tokens::TokenHandler::new(&args.db).await.expect("Could not connect to DB"),
310        tokio::net::TcpListener::bind(args.endpoint).await.expect("Could not bind to endpoint")
311    ).await
312}