an http based roguelike rpg about jelqing
| 1 | //! The resources under `/runs/{id}`. |
| 2 | |
| 3 | use std::{convert::Infallible, fmt::Write as _}; |
| 4 | |
| 5 | use axum::{ |
| 6 | Json, |
| 7 | body::{Body, Bytes}, |
| 8 | http::{StatusCode, header}, |
| 9 | response::{IntoResponse, Response}, |
| 10 | }; |
| 11 | use serde_json::{Value, json}; |
| 12 | |
| 13 | use super::{ |
| 14 | ctx::Ctx, |
| 15 | resource::{Resource, Verb}, |
| 16 | response::respond, |
| 17 | run::{Greeting, RunResource, Scope}, |
| 18 | }; |
| 19 | use crate::{ |
| 20 | game::{ |
| 21 | Cause, Floor, Grip, Item, LUBRICANTS, Lube, PatchOp, Run, Technique, |
| 22 | balance::{EQ_BAND, MM_PER_INCH}, |
| 23 | shaft, |
| 24 | }, |
| 25 | headers::ACCEPT_PATCH, |
| 26 | problem::Problem, |
| 27 | }; |
| 28 | |
| 29 | const fn home(verbs: &'static [Verb<Run>]) -> RunResource { |
| 30 | RunResource { |
| 31 | scope: Scope::Home, |
| 32 | resource: Resource::new(verbs), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | const fn pockets(verbs: &'static [Verb<Run>]) -> RunResource { |
| 37 | RunResource { |
| 38 | scope: Scope::Pockets, |
| 39 | resource: Resource::new(verbs), |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | fn not_in_clinic(run: &Run) -> bool { |
| 44 | run.floor != Floor::Clinic |
| 45 | } |
| 46 | |
| 47 | fn never(_: &Run) -> bool { |
| 48 | false |
| 49 | } |
| 50 | |
| 51 | fn unreachable_handler(_: &mut Run, _: &Ctx) -> Response { |
| 52 | StatusCode::METHOD_NOT_ALLOWED.into_response() |
| 53 | } |
| 54 | |
| 55 | pub static RUN: RunResource = RunResource { |
| 56 | scope: Scope::Home, |
| 57 | resource: Resource { |
| 58 | verbs: &[ |
| 59 | Verb::new("GET", get_run), |
| 60 | Verb::new("JELQ", jelq) |
| 61 | .only_when(not_in_clinic, "JELQ is not performed in the clinic."), |
| 62 | Verb::new("PUT", put_run), |
| 63 | Verb::new("PATCH", patch_run), |
| 64 | Verb::new("DELETE", delete_run), |
| 65 | Verb::new("TRACE", trace_run), |
| 66 | ], |
| 67 | accept_patch: true, |
| 68 | }, |
| 69 | }; |
| 70 | pub static LENGTH: RunResource = home(&[Verb::new("GET", get_length)]); |
| 71 | pub static FORESKIN: RunResource = home(&[ |
| 72 | Verb::new("GET", get_foreskin), |
| 73 | Verb::new("DELETE", delete_foreskin), |
| 74 | ]); |
| 75 | pub static INVENTORY: RunResource = pockets(&[Verb::new("GET", get_inventory)]); |
| 76 | pub static ITEM: RunResource = |
| 77 | pockets(&[Verb::new("GET", get_item), Verb::new("DELETE", delete_item)]); |
| 78 | pub static TECHNIQUES: RunResource = home(&[Verb::new("GET", get_techniques)]); |
| 79 | pub static DRAWER: RunResource = home(&[Verb::new("POST", search_drawer)]); |
| 80 | pub static BRANCH: RunResource = home(&[Verb::new("POST", choose_branch)]); |
| 81 | pub static FLOOR: RunResource = |
| 82 | home(&[Verb::new("GET", get_floor), Verb::new("POST", leave_floor)]); |
| 83 | pub static SHOP: RunResource = home(&[Verb::new("GET", get_shop)]); |
| 84 | pub static BUY: RunResource = home(&[Verb::new("POST", buy)]); |
| 85 | pub static PORTAL: RunResource = pockets(&[ |
| 86 | Verb::new("GET", get_portal), |
| 87 | Verb::new("POST", accept_portal), |
| 88 | ]); |
| 89 | pub static ELDER: RunResource = home(&[Verb::new("GET", get_elder)]); |
| 90 | pub static GRIP: RunResource = home(&[Verb::new("GET", get_grip)]); |
| 91 | pub static DIAGNOSIS: RunResource = pockets(&[Verb::new("GET", get_diagnosis)]); |
| 92 | pub static FOOTAGE: RunResource = pockets(&[ |
| 93 | Verb::new("GET", get_footage), |
| 94 | Verb::new("DELETE", unreachable_handler).only_when( |
| 95 | never, |
| 96 | "The footage has been cached by intermediaries. It cannot be deleted.", |
| 97 | ), |
| 98 | ]); |
| 99 | |
| 100 | fn get_run(run: &mut Run, ctx: &Ctx) -> Response { |
| 101 | if ctx |
| 102 | .header(header::ACCEPT) |
| 103 | .is_some_and(|accept| accept.contains("reassurance")) |
| 104 | { |
| 105 | return Problem::new( |
| 106 | StatusCode::NOT_ACCEPTABLE, |
| 107 | "no-reassurance", |
| 108 | "The server does not produce reassurance.", |
| 109 | ) |
| 110 | .into_response(); |
| 111 | } |
| 112 | ( |
| 113 | StatusCode::OK, |
| 114 | [(header::ETAG, run.etag())], |
| 115 | Json(run.view()), |
| 116 | ) |
| 117 | .into_response() |
| 118 | } |
| 119 | |
| 120 | fn parse_techniques(run: &Run, ctx: &Ctx) -> Result<Vec<Technique>, Problem> { |
| 121 | let required = || { |
| 122 | Problem::new( |
| 123 | StatusCode::BAD_REQUEST, |
| 124 | "technique-required", |
| 125 | "No technique was specified.", |
| 126 | ) |
| 127 | .with("techniques", run.path("/techniques")) |
| 128 | }; |
| 129 | let names = ctx |
| 130 | .query("technique") |
| 131 | .filter(|n| !n.trim().is_empty()) |
| 132 | .ok_or_else(required)?; |
| 133 | names |
| 134 | .split(',') |
| 135 | .map(str::trim) |
| 136 | .filter(|n| !n.is_empty()) |
| 137 | .map(|name| { |
| 138 | Technique::parse(name).ok_or_else(|| { |
| 139 | Problem::new( |
| 140 | StatusCode::BAD_REQUEST, |
| 141 | "unknown-technique", |
| 142 | format!("{name} is not a technique."), |
| 143 | ) |
| 144 | .with("techniques", run.path("/techniques")) |
| 145 | }) |
| 146 | }) |
| 147 | .collect() |
| 148 | } |
| 149 | |
| 150 | fn parse_intensity(ctx: &Ctx) -> Result<i32, Problem> { |
| 151 | match ctx.query("intensity").map(str::parse::<i32>) { |
| 152 | None => Ok(5), |
| 153 | Some(Ok(i)) if (1..=10).contains(&i) => Ok(i), |
| 154 | Some(_) => Err(Problem::new( |
| 155 | StatusCode::BAD_REQUEST, |
| 156 | "intensity-out-of-range", |
| 157 | "Intensity is measured from 1 to 10.", |
| 158 | )), |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | fn jelq(run: &mut Run, ctx: &Ctx) -> Response { |
| 163 | let parsed = parse_techniques(run, ctx).and_then(|techniques| { |
| 164 | let intensity = parse_intensity(ctx)?; |
| 165 | let lube = Lube::from_content_type(ctx.header(header::CONTENT_TYPE))?; |
| 166 | Ok((techniques, intensity, lube)) |
| 167 | }); |
| 168 | match parsed { |
| 169 | Ok((techniques, intensity, lube)) => { |
| 170 | respond(run.jelq(&techniques, intensity, lube, ctx.now)) |
| 171 | } |
| 172 | Err(problem) => problem.into_response(), |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | fn put_run(run: &mut Run, _: &Ctx) -> Response { |
| 177 | run.put().into_response() |
| 178 | } |
| 179 | |
| 180 | fn patch_run(run: &mut Run, ctx: &Ctx) -> Response { |
| 181 | let is_patch = ctx |
| 182 | .header(header::CONTENT_TYPE) |
| 183 | .is_some_and(|ct| ct.starts_with("application/json-patch+json")); |
| 184 | if !is_patch { |
| 185 | return Problem::new( |
| 186 | StatusCode::UNSUPPORTED_MEDIA_TYPE, |
| 187 | "patch-format", |
| 188 | "Patches are accepted as application/json-patch+json.", |
| 189 | ) |
| 190 | .header(ACCEPT_PATCH, "application/json-patch+json") |
| 191 | .into_response(); |
| 192 | } |
| 193 | match serde_json::from_slice::<Vec<PatchOp>>(&ctx.body) { |
| 194 | Ok(ops) => respond(run.patch(&ops)), |
| 195 | Err(_) => Problem::new( |
| 196 | StatusCode::BAD_REQUEST, |
| 197 | "malformed-patch", |
| 198 | "The patch could not be parsed.", |
| 199 | ) |
| 200 | .into_response(), |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | fn delete_run(run: &mut Run, _: &Ctx) -> Response { |
| 205 | run.end(Cause::Abandoned); |
| 206 | StatusCode::NO_CONTENT.into_response() |
| 207 | } |
| 208 | |
| 209 | fn trace_run(run: &mut Run, ctx: &Ctx) -> Response { |
| 210 | run.shame += 1; |
| 211 | let mut message = format!("{} {} {:?}\r\n", ctx.method, ctx.uri, ctx.version); |
| 212 | for (name, value) in &ctx.headers { |
| 213 | let _ = write!( |
| 214 | message, |
| 215 | "{name}: {}\r\n", |
| 216 | value.to_str().unwrap_or("<binary>") |
| 217 | ); |
| 218 | } |
| 219 | message.push_str("\r\n"); |
| 220 | ( |
| 221 | StatusCode::OK, |
| 222 | [(header::CONTENT_TYPE, "message/http")], |
| 223 | message, |
| 224 | ) |
| 225 | .into_response() |
| 226 | } |
| 227 | |
| 228 | fn millimetres(inches: f64) -> usize { |
| 229 | (inches * MM_PER_INCH).round() as usize |
| 230 | } |
| 231 | |
| 232 | enum InchRange { |
| 233 | Satisfiable(f64, f64), |
| 234 | Unsatisfiable, |
| 235 | } |
| 236 | |
| 237 | /// `None` means the header is not a valid range, which RFC 9110 §14.2 says to ignore rather than refuse. |
| 238 | fn parse_inch_range(range: &str, total: f64) -> Option<InchRange> { |
| 239 | let (start, end) = range.strip_prefix("inches=")?.split_once('-')?; |
| 240 | let number = |text: &str| { |
| 241 | text.parse::<f64>() |
| 242 | .ok() |
| 243 | .filter(|n| n.is_finite() && *n >= 0.0) |
| 244 | }; |
| 245 | let (start, end) = match (start.trim(), end.trim()) { |
| 246 | ("", "") => return None, |
| 247 | ("", suffix) => ((total - number(suffix)?).max(0.0), total), |
| 248 | (start, "") => (number(start)?, total), |
| 249 | (start, end) => { |
| 250 | let (start, end) = (number(start)?, number(end)?); |
| 251 | if start > end { |
| 252 | return None; |
| 253 | } |
| 254 | (start, end) |
| 255 | } |
| 256 | }; |
| 257 | Some(if start < total { |
| 258 | InchRange::Satisfiable(start, end.min(total)) |
| 259 | } else { |
| 260 | InchRange::Unsatisfiable |
| 261 | }) |
| 262 | } |
| 263 | |
| 264 | fn get_length(run: &mut Run, ctx: &Ctx) -> Response { |
| 265 | let inches = if run.items.ruler { |
| 266 | run.current_length() |
| 267 | } else { |
| 268 | run.self_reported() |
| 269 | }; |
| 270 | let body = shaft(millimetres(inches)); |
| 271 | let content_type = ( |
| 272 | header::CONTENT_TYPE, |
| 273 | "text/plain; charset=us-ascii".to_owned(), |
| 274 | ); |
| 275 | let accept_ranges = (header::ACCEPT_RANGES, "inches".to_owned()); |
| 276 | |
| 277 | if let Some(range) = ctx |
| 278 | .header(header::RANGE) |
| 279 | .and_then(|range| parse_inch_range(range, inches)) |
| 280 | { |
| 281 | let InchRange::Satisfiable(start, end) = range else { |
| 282 | return Problem::new( |
| 283 | StatusCode::RANGE_NOT_SATISFIABLE, |
| 284 | "range-not-satisfiable", |
| 285 | format!("The requested range is not available. {inches:.2} inches are."), |
| 286 | ) |
| 287 | .header(header::CONTENT_RANGE, format!("inches */{inches:.2}")) |
| 288 | .into_response(); |
| 289 | }; |
| 290 | let from = millimetres(start).min(body.len() - 1); |
| 291 | let to = millimetres(end).clamp(from + 1, body.len()); |
| 292 | let content_range = ( |
| 293 | header::CONTENT_RANGE, |
| 294 | format!("inches {start:.2}-{end:.2}/{inches:.2}"), |
| 295 | ); |
| 296 | return ( |
| 297 | StatusCode::PARTIAL_CONTENT, |
| 298 | [content_type, accept_ranges, content_range], |
| 299 | body[from..to].to_owned(), |
| 300 | ) |
| 301 | .into_response(); |
| 302 | } |
| 303 | |
| 304 | if run.items.ruler { |
| 305 | return (StatusCode::OK, [content_type, accept_ranges], body).into_response(); |
| 306 | } |
| 307 | let chunks: Vec<Result<Bytes, Infallible>> = body |
| 308 | .into_bytes() |
| 309 | .chunks(16) |
| 310 | .map(|c| Ok(Bytes::copy_from_slice(c))) |
| 311 | .collect(); |
| 312 | let body = Body::from_stream(futures_util::stream::iter(chunks)); |
| 313 | (StatusCode::OK, [content_type, accept_ranges], body).into_response() |
| 314 | } |
| 315 | |
| 316 | fn get_foreskin(run: &mut Run, _: &Ctx) -> Response { |
| 317 | if run.foreskin.is_none() { |
| 318 | return Problem::new( |
| 319 | StatusCode::GONE, |
| 320 | "foreskin-gone", |
| 321 | "The foreskin is gone. It will not be returning.", |
| 322 | ) |
| 323 | .into_response(); |
| 324 | } |
| 325 | (StatusCode::NO_CONTENT, [(header::ETAG, run.etag())]).into_response() |
| 326 | } |
| 327 | |
| 328 | fn delete_foreskin(run: &mut Run, ctx: &Ctx) -> Response { |
| 329 | respond(run.delete_foreskin(ctx.header(header::IF_MATCH))) |
| 330 | } |
| 331 | |
| 332 | fn get_inventory(run: &mut Run, _: &Ctx) -> Response { |
| 333 | let items: Vec<Value> = run |
| 334 | .items |
| 335 | .owned() |
| 336 | .into_iter() |
| 337 | .map(|item| { |
| 338 | json!({ |
| 339 | "name": item.slug(), |
| 340 | "href": run.path(&format!("/inventory/{}", item.slug())), |
| 341 | }) |
| 342 | }) |
| 343 | .collect(); |
| 344 | Json(json!({ |
| 345 | "items": items, |
| 346 | "ice_packs": run.items.ice_packs, |
| 347 | "supplements": run.items.supplements, |
| 348 | "excuses": run.excuses(), |
| 349 | })) |
| 350 | .into_response() |
| 351 | } |
| 352 | |
| 353 | fn owned_item(run: &Run, ctx: &Ctx) -> Result<Item, Problem> { |
| 354 | Item::parse(ctx.param("item")) |
| 355 | .filter(|&item| run.items.has(item)) |
| 356 | .ok_or_else(|| { |
| 357 | Problem::new( |
| 358 | StatusCode::NOT_FOUND, |
| 359 | "no-such-item", |
| 360 | "You do not have that.", |
| 361 | ) |
| 362 | }) |
| 363 | } |
| 364 | |
| 365 | fn get_item(run: &mut Run, ctx: &Ctx) -> Response { |
| 366 | match owned_item(run, ctx) { |
| 367 | Ok(item) => { |
| 368 | Json(json!({ "name": item.slug(), "description": item.description() })).into_response() |
| 369 | } |
| 370 | Err(problem) => problem.into_response(), |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | fn delete_item(run: &mut Run, ctx: &Ctx) -> Response { |
| 375 | match owned_item(run, ctx) { |
| 376 | Ok(item) => respond(run.drop_item(item)), |
| 377 | Err(problem) => problem.into_response(), |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | fn get_techniques(run: &mut Run, _: &Ctx) -> Response { |
| 382 | let listed: Vec<Value> = Technique::ALL |
| 383 | .into_iter() |
| 384 | .map(|t| t.describe(run.forum_read())) |
| 385 | .collect(); |
| 386 | Json(json!({ |
| 387 | "usage": format!("JELQ {}?technique=<name>[,<name>]&intensity=<1-10>", run.path("")), |
| 388 | "lubricant": "Declared with Content-Type.", |
| 389 | "lubricants": LUBRICANTS, |
| 390 | "eq_band": [EQ_BAND.start(), EQ_BAND.end()], |
| 391 | "techniques": listed, |
| 392 | })) |
| 393 | .into_response() |
| 394 | } |
| 395 | |
| 396 | fn search_drawer(run: &mut Run, _: &Ctx) -> Response { |
| 397 | respond(run.search_drawer()) |
| 398 | } |
| 399 | |
| 400 | fn choose_branch(run: &mut Run, ctx: &Ctx) -> Response { |
| 401 | respond(run.choose(ctx.param("choice"))) |
| 402 | } |
| 403 | |
| 404 | fn get_floor(run: &mut Run, _: &Ctx) -> Response { |
| 405 | Json(run.floor_view()).into_response() |
| 406 | } |
| 407 | |
| 408 | fn leave_floor(run: &mut Run, _: &Ctx) -> Response { |
| 409 | respond(run.advance()) |
| 410 | } |
| 411 | |
| 412 | fn get_shop(run: &mut Run, _: &Ctx) -> Response { |
| 413 | respond(run.shop_view().map(Json)) |
| 414 | } |
| 415 | |
| 416 | fn buy(run: &mut Run, ctx: &Ctx) -> Response { |
| 417 | respond(run.buy(ctx.param("item"))) |
| 418 | } |
| 419 | |
| 420 | fn get_portal(run: &mut Run, _: &Ctx) -> Response { |
| 421 | Json(json!({ |
| 422 | "terms": "By connecting you agree that the hotel is not responsible for anything that happens in this room, and that it does not want to know.", |
| 423 | "accept": { "href": run.path("/portal"), "method": "POST" }, |
| 424 | })) |
| 425 | .into_response() |
| 426 | } |
| 427 | |
| 428 | fn accept_portal(run: &mut Run, _: &Ctx) -> Response { |
| 429 | respond(run.accept_terms()) |
| 430 | } |
| 431 | |
| 432 | fn get_elder(run: &mut Run, ctx: &Ctx) -> Response { |
| 433 | respond(run.elder( |
| 434 | ctx.header(header::PROXY_AUTHORIZATION), |
| 435 | ctx.header(header::IF_MODIFIED_SINCE), |
| 436 | )) |
| 437 | } |
| 438 | |
| 439 | fn requested_grip(ctx: &Ctx) -> Option<Grip> { |
| 440 | let connection = ctx.header(header::CONNECTION)?.to_ascii_lowercase(); |
| 441 | if !connection.split(',').any(|token| token.trim() == "upgrade") { |
| 442 | return None; |
| 443 | } |
| 444 | ctx.header(header::UPGRADE)? |
| 445 | .split(',') |
| 446 | .find_map(|protocol| Grip::parse(protocol.trim())) |
| 447 | } |
| 448 | |
| 449 | fn get_grip(run: &mut Run, ctx: &Ctx) -> Response { |
| 450 | if let Some(grip) = requested_grip(ctx) { |
| 451 | run.set_grip(grip); |
| 452 | let mut response = ( |
| 453 | StatusCode::SWITCHING_PROTOCOLS, |
| 454 | [ |
| 455 | (header::UPGRADE, grip.name()), |
| 456 | (header::CONNECTION, "upgrade"), |
| 457 | ], |
| 458 | ) |
| 459 | .into_response(); |
| 460 | response.extensions_mut().insert(Greeting(format!( |
| 461 | "You are now jelqing {}.\r\n", |
| 462 | grip.name() |
| 463 | ))); |
| 464 | return response; |
| 465 | } |
| 466 | let detail = match ctx.header(header::UPGRADE) { |
| 467 | Some(protocol) => { |
| 468 | format!("The server does not know the {protocol} grip. Grips are protocols.") |
| 469 | } |
| 470 | None => "Grips are protocols. Change grip by upgrading the connection.".to_owned(), |
| 471 | }; |
| 472 | ( |
| 473 | StatusCode::OK, |
| 474 | [(header::UPGRADE, "overhand, underhand")], |
| 475 | Json(json!({ "grip": run.grip.name(), "detail": detail })), |
| 476 | ) |
| 477 | .into_response() |
| 478 | } |
| 479 | |
| 480 | fn get_diagnosis(run: &mut Run, ctx: &Ctx) -> Response { |
| 481 | respond(run.diagnose( |
| 482 | ctx.header(header::AUTHORIZATION), |
| 483 | ctx.header(header::IF_NONE_MATCH), |
| 484 | )) |
| 485 | } |
| 486 | |
| 487 | fn get_footage(run: &mut Run, _: &Ctx) -> Response { |
| 488 | let Some((filmed, age)) = run.footage() else { |
| 489 | return Problem::new( |
| 490 | StatusCode::NOT_FOUND, |
| 491 | "no-footage", |
| 492 | "There is no footage. Yet.", |
| 493 | ) |
| 494 | .into_response(); |
| 495 | }; |
| 496 | ( |
| 497 | [ |
| 498 | ( |
| 499 | header::CACHE_CONTROL, |
| 500 | "public, max-age=31536000, immutable".to_owned(), |
| 501 | ), |
| 502 | (header::AGE, age.to_string()), |
| 503 | (header::LAST_MODIFIED, httpdate::fmt_http_date(filmed)), |
| 504 | ], |
| 505 | Json(json!({ |
| 506 | "detail": "A recording. It is grainy. It is unmistakably you. It has been shared.", |
| 507 | "views": 1 + age * 37, |
| 508 | })), |
| 509 | ) |
| 510 | .into_response() |
| 511 | } |