atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
a6caa2f9978665374ee51870e78151e4324328d0
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/runs.rsRust576 lines16.9 KB
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("HOLD", hold_run).only_when(
63
                Run::can_hold,
64
                "HOLD is only available above 70 EQ or at 2 stamina or less.",
65
            ),
66
            Verb::new("PUT", put_run),
67
            Verb::new("PATCH", patch_run),
68
            Verb::new("DELETE", delete_run),
69
            Verb::new("TRACE", trace_run),
70
        ],
71
        accept_patch: true,
72
    },
73
};
74
pub static LENGTH: RunResource = home(&[Verb::new("GET", get_length)]);
75
pub static FORESKIN: RunResource = home(&[
76
    Verb::new("GET", get_foreskin),
77
    Verb::new("DELETE", delete_foreskin),
78
]);
79
pub static INVENTORY: RunResource = pockets(&[Verb::new("GET", get_inventory)]);
80
pub static ITEM: RunResource =
81
    pockets(&[Verb::new("GET", get_item), Verb::new("DELETE", delete_item)]);
82
pub static TECHNIQUES: RunResource = home(&[Verb::new("GET", get_techniques)]);
83
pub static DRAWER: RunResource = home(&[Verb::new("POST", search_drawer)]);
84
pub static BRANCH: RunResource = home(&[Verb::new("POST", choose_branch)]);
85
pub static KITCHEN: RunResource = home(&[Verb::new("POST", raid_kitchen)]);
86
pub static MELON: RunResource = home(&[Verb::new("POST", commit_melon)]);
87
pub static REREAD: RunResource = pockets(&[Verb::new("POST", re_read)]);
88
pub static FLOOR: RunResource =
89
    home(&[Verb::new("GET", get_floor), Verb::new("POST", leave_floor)]);
90
pub static SHOP: RunResource = home(&[Verb::new("GET", get_shop)]);
91
pub static BUY: RunResource = home(&[Verb::new("POST", buy)]);
92
pub static PORTAL: RunResource = pockets(&[
93
    Verb::new("GET", get_portal),
94
    Verb::new("POST", accept_portal),
95
]);
96
pub static ELDER: RunResource = home(&[Verb::new("GET", get_elder)]);
97
pub static GRIP: RunResource = home(&[Verb::new("GET", get_grip)]);
98
pub static DIAGNOSIS: RunResource = pockets(&[Verb::new("GET", get_diagnosis)]);
99
pub static FOOTAGE: RunResource = pockets(&[
100
    Verb::new("GET", get_footage),
101
    Verb::new("DELETE", unreachable_handler).only_when(
102
        never,
103
        "The footage has been cached by intermediaries. It cannot be deleted.",
104
    ),
105
]);
106
107
fn get_run(run: &mut Run, ctx: &Ctx) -> Response {
108
    if ctx
109
        .header(header::ACCEPT)
110
        .is_some_and(|accept| accept.contains("reassurance"))
111
    {
112
        return Problem::new(
113
            StatusCode::NOT_ACCEPTABLE,
114
            "no-reassurance",
115
            "The server does not produce reassurance.",
116
        )
117
        .into_response();
118
    }
119
    (
120
        StatusCode::OK,
121
        [(header::ETAG, run.etag())],
122
        Json(run.view()),
123
    )
124
        .into_response()
125
}
126
127
fn parse_techniques(run: &Run, ctx: &Ctx) -> Result<Vec<Technique>, Problem> {
128
    let required = || {
129
        Problem::new(
130
            StatusCode::BAD_REQUEST,
131
            "technique-required",
132
            "No technique was specified.",
133
        )
134
        .with("techniques", run.path("/techniques"))
135
    };
136
    let names = ctx
137
        .query("technique")
138
        .filter(|n| !n.trim().is_empty())
139
        .ok_or_else(required)?;
140
    names
141
        .split(',')
142
        .map(str::trim)
143
        .filter(|n| !n.is_empty())
144
        .map(|name| {
145
            Technique::parse(name).ok_or_else(|| {
146
                Problem::new(
147
                    StatusCode::BAD_REQUEST,
148
                    "unknown-technique",
149
                    format!("{name} is not a technique."),
150
                )
151
                .with("techniques", run.path("/techniques"))
152
            })
153
        })
154
        .collect()
155
}
156
157
fn parse_intensity(ctx: &Ctx) -> Result<i32, Problem> {
158
    match ctx.query("intensity").map(str::parse::<i32>) {
159
        None => Ok(5),
160
        Some(Ok(i)) if (1..=10).contains(&i) => Ok(i),
161
        Some(_) => Err(Problem::new(
162
            StatusCode::BAD_REQUEST,
163
            "intensity-out-of-range",
164
            "Intensity is measured from 1 to 10.",
165
        )),
166
    }
167
}
168
169
fn jelq(run: &mut Run, ctx: &Ctx) -> Response {
170
    let parsed = parse_techniques(run, ctx).and_then(|techniques| {
171
        let intensity = parse_intensity(ctx)?;
172
        let lube = Lube::from_content_type(ctx.header(header::CONTENT_TYPE))?;
173
        Ok((techniques, intensity, lube))
174
    });
175
    match parsed {
176
        Ok((techniques, intensity, lube)) => respond(run.jelq(&techniques, intensity, lube)),
177
        Err(problem) => problem.into_response(),
178
    }
179
}
180
181
fn put_run(run: &mut Run, _: &Ctx) -> Response {
182
    run.put().into_response()
183
}
184
185
fn hold_run(run: &mut Run, _: &Ctx) -> Response {
186
    respond(run.hold())
187
}
188
189
fn patch_run(run: &mut Run, ctx: &Ctx) -> Response {
190
    let is_patch = ctx
191
        .header(header::CONTENT_TYPE)
192
        .is_some_and(|ct| ct.starts_with("application/json-patch+json"));
193
    if !is_patch {
194
        return Problem::new(
195
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
196
            "patch-format",
197
            "Patches are accepted as application/json-patch+json.",
198
        )
199
        .header(ACCEPT_PATCH, "application/json-patch+json")
200
        .into_response();
201
    }
202
    match serde_json::from_slice::<Vec<PatchOp>>(&ctx.body) {
203
        Ok(ops) => respond(run.patch(&ops)),
204
        Err(_) => Problem::new(
205
            StatusCode::BAD_REQUEST,
206
            "malformed-patch",
207
            "The patch could not be parsed.",
208
        )
209
        .into_response(),
210
    }
211
}
212
213
fn delete_run(run: &mut Run, _: &Ctx) -> Response {
214
    run.end(Cause::Abandoned);
215
    StatusCode::NO_CONTENT.into_response()
216
}
217
218
fn trace_run(run: &mut Run, ctx: &Ctx) -> Response {
219
    run.shame += 1;
220
    let mut message = format!("{} {} {:?}\r\n", ctx.method, ctx.uri, ctx.version);
221
    for (name, value) in &ctx.headers {
222
        let _ = write!(
223
            message,
224
            "{name}: {}\r\n",
225
            value.to_str().unwrap_or("<binary>")
226
        );
227
    }
228
    message.push_str("\r\n");
229
    (
230
        StatusCode::OK,
231
        [(header::CONTENT_TYPE, "message/http")],
232
        message,
233
    )
234
        .into_response()
235
}
236
237
fn millimetres(inches: f64) -> usize {
238
    (inches * MM_PER_INCH).round() as usize
239
}
240
241
enum InchRange {
242
    Satisfiable(f64, f64),
243
    Unsatisfiable,
244
}
245
246
/// `None` means the header is not a valid range, which RFC 9110 §14.2 says to ignore rather than refuse.
247
fn parse_inch_range(range: &str, total: f64) -> Option<InchRange> {
248
    let (start, end) = range.strip_prefix("inches=")?.split_once('-')?;
249
    let number = |text: &str| {
250
        text.parse::<f64>()
251
            .ok()
252
            .filter(|n| n.is_finite() && *n >= 0.0)
253
    };
254
    let (start, end) = match (start.trim(), end.trim()) {
255
        ("", "") => return None,
256
        ("", suffix) => ((total - number(suffix)?).max(0.0), total),
257
        (start, "") => (number(start)?, total),
258
        (start, end) => {
259
            let (start, end) = (number(start)?, number(end)?);
260
            if start > end {
261
                return None;
262
            }
263
            (start, end)
264
        }
265
    };
266
    Some(if start < total {
267
        InchRange::Satisfiable(start, end.min(total))
268
    } else {
269
        InchRange::Unsatisfiable
270
    })
271
}
272
273
fn unsatisfied_range(inches: f64) -> Response {
274
    Problem::new(
275
        StatusCode::RANGE_NOT_SATISFIABLE,
276
        "range-not-satisfiable",
277
        format!("The requested range is not available. {inches:.2} inches are."),
278
    )
279
    .header(header::CONTENT_RANGE, format!("inches */{inches:.2}"))
280
    .into_response()
281
}
282
283
fn partial_inches(body: &str, offset: usize, start: f64, end: f64, total: f64) -> Response {
284
    let from = (millimetres(start) + offset).min(body.len() - 1);
285
    let to = (millimetres(end) + offset).clamp(from + 1, body.len());
286
    (
287
        StatusCode::PARTIAL_CONTENT,
288
        [
289
            (
290
                header::CONTENT_TYPE,
291
                "text/plain; charset=us-ascii".to_owned(),
292
            ),
293
            (header::ACCEPT_RANGES, "inches".to_owned()),
294
            (
295
                header::CONTENT_RANGE,
296
                format!("inches {start:.2}-{end:.2}/{total:.2}"),
297
            ),
298
        ],
299
        body[from..to].to_owned(),
300
    )
301
        .into_response()
302
}
303
304
fn get_length(run: &mut Run, ctx: &Ctx) -> Response {
305
    let inches = if run.items.ruler {
306
        run.current_length()
307
    } else {
308
        run.self_reported()
309
    };
310
    let body = shaft(millimetres(inches));
311
    let content_type = (
312
        header::CONTENT_TYPE,
313
        "text/plain; charset=us-ascii".to_owned(),
314
    );
315
    let accept_ranges = (header::ACCEPT_RANGES, "inches".to_owned());
316
317
    if let Some(range) = ctx
318
        .header(header::RANGE)
319
        .and_then(|range| parse_inch_range(range, inches))
320
    {
321
        match range {
322
            InchRange::Satisfiable(start, end) => {
323
                return partial_inches(&body, 0, start, end, inches);
324
            }
325
            InchRange::Unsatisfiable => return unsatisfied_range(inches),
326
        }
327
    }
328
329
    if run.items.ruler {
330
        return (StatusCode::OK, [content_type, accept_ranges], body).into_response();
331
    }
332
    let chunks: Vec<Result<Bytes, Infallible>> = body
333
        .into_bytes()
334
        .chunks(16)
335
        .map(|c| Ok(Bytes::copy_from_slice(c)))
336
        .collect();
337
    let body = Body::from_stream(futures_util::stream::iter(chunks));
338
    (StatusCode::OK, [content_type, accept_ranges], body).into_response()
339
}
340
341
fn get_foreskin(run: &mut Run, ctx: &Ctx) -> Response {
342
    let Some(inches) = run.foreskin else {
343
        return Problem::new(
344
            StatusCode::GONE,
345
            "foreskin-gone",
346
            "The foreskin is gone. It will not be returning.",
347
        )
348
        .into_response();
349
    };
350
    let body = format!("8({})D", "~".repeat(millimetres(inches)));
351
    if let Some(range) = ctx
352
        .header(header::RANGE)
353
        .and_then(|range| parse_inch_range(range, inches))
354
    {
355
        match range {
356
            InchRange::Satisfiable(start, end) => {
357
                return partial_inches(&body, 2, start, end, inches);
358
            }
359
            InchRange::Unsatisfiable => return unsatisfied_range(inches),
360
        }
361
    }
362
    (
363
        StatusCode::OK,
364
        [
365
            (header::ETAG, run.etag()),
366
            (
367
                header::CONTENT_TYPE,
368
                "text/plain; charset=us-ascii".to_owned(),
369
            ),
370
            (header::ACCEPT_RANGES, "inches".to_owned()),
371
        ],
372
        body,
373
    )
374
        .into_response()
375
}
376
377
fn delete_foreskin(run: &mut Run, ctx: &Ctx) -> Response {
378
    respond(run.delete_foreskin(ctx.header(header::IF_MATCH)))
379
}
380
381
fn get_inventory(run: &mut Run, _: &Ctx) -> Response {
382
    let items: Vec<Value> = run
383
        .items
384
        .owned()
385
        .into_iter()
386
        .map(|item| {
387
            json!({
388
                "name": item.slug(),
389
                "href": run.path(&format!("/inventory/{}", item.slug())),
390
            })
391
        })
392
        .collect();
393
    Json(json!({
394
        "items": items,
395
        "ice_packs": run.items.ice_packs,
396
        "supplements": run.items.supplements,
397
        "excuses": run.excuses(),
398
    }))
399
    .into_response()
400
}
401
402
fn owned_item(run: &Run, ctx: &Ctx) -> Result<Item, Problem> {
403
    Item::parse(ctx.param("item"))
404
        .filter(|&item| run.items.has(item))
405
        .ok_or_else(|| {
406
            Problem::new(
407
                StatusCode::NOT_FOUND,
408
                "no-such-item",
409
                "You do not have that.",
410
            )
411
        })
412
}
413
414
fn get_item(run: &mut Run, ctx: &Ctx) -> Response {
415
    match owned_item(run, ctx) {
416
        Ok(item) => {
417
            Json(json!({ "name": item.slug(), "description": item.description() })).into_response()
418
        }
419
        Err(problem) => problem.into_response(),
420
    }
421
}
422
423
fn delete_item(run: &mut Run, ctx: &Ctx) -> Response {
424
    match owned_item(run, ctx) {
425
        Ok(item) => respond(run.drop_item(item)),
426
        Err(problem) => problem.into_response(),
427
    }
428
}
429
430
fn get_techniques(run: &mut Run, _: &Ctx) -> Response {
431
    let listed: Vec<Value> = Technique::ALL
432
        .into_iter()
433
        .map(|t| t.describe(run.uli_taught))
434
        .collect();
435
    Json(json!({
436
        "usage": format!("JELQ {}?technique=<name>[,<name>]&intensity=<1-10>", run.path("")),
437
        "lubricant": "Declared with Content-Type.",
438
        "lubricants": LUBRICANTS,
439
        "eq_band": [EQ_BAND.start(), EQ_BAND.end()],
440
        "techniques": listed,
441
    }))
442
    .into_response()
443
}
444
445
fn search_drawer(run: &mut Run, _: &Ctx) -> Response {
446
    respond(run.search_drawer())
447
}
448
449
fn choose_branch(run: &mut Run, ctx: &Ctx) -> Response {
450
    respond(run.choose(ctx.param("choice")))
451
}
452
453
fn get_floor(run: &mut Run, _: &Ctx) -> Response {
454
    Json(run.floor_view()).into_response()
455
}
456
457
fn leave_floor(run: &mut Run, _: &Ctx) -> Response {
458
    respond(run.advance())
459
}
460
461
fn get_shop(run: &mut Run, _: &Ctx) -> Response {
462
    let view = run.shop_view();
463
    if view.is_ok() {
464
        run.here.shopping = true;
465
    }
466
    respond(view.map(Json))
467
}
468
469
fn buy(run: &mut Run, ctx: &Ctx) -> Response {
470
    respond(run.buy(ctx.param("item")))
471
}
472
473
fn raid_kitchen(run: &mut Run, _: &Ctx) -> Response {
474
    respond(run.raid_kitchen())
475
}
476
477
fn commit_melon(run: &mut Run, _: &Ctx) -> Response {
478
    respond(run.commit_melon())
479
}
480
481
fn re_read(run: &mut Run, _: &Ctx) -> Response {
482
    respond(run.read_thread())
483
}
484
485
fn get_portal(run: &mut Run, _: &Ctx) -> Response {
486
    Json(json!({
487
        "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.",
488
        "accept": { "href": run.path("/portal"), "method": "POST" },
489
    }))
490
    .into_response()
491
}
492
493
fn accept_portal(run: &mut Run, _: &Ctx) -> Response {
494
    respond(run.accept_terms())
495
}
496
497
fn get_elder(run: &mut Run, ctx: &Ctx) -> Response {
498
    respond(run.elder(
499
        ctx.header(header::PROXY_AUTHORIZATION),
500
        ctx.header(header::IF_MODIFIED_SINCE),
501
    ))
502
}
503
504
fn requested_grip(ctx: &Ctx) -> Option<Grip> {
505
    let connection = ctx.header(header::CONNECTION)?.to_ascii_lowercase();
506
    if !connection.split(',').any(|token| token.trim() == "upgrade") {
507
        return None;
508
    }
509
    ctx.header(header::UPGRADE)?
510
        .split(',')
511
        .find_map(|protocol| Grip::parse(protocol.trim()))
512
}
513
514
fn get_grip(run: &mut Run, ctx: &Ctx) -> Response {
515
    if let Some(grip) = requested_grip(ctx) {
516
        run.set_grip(grip);
517
        let mut response = (
518
            StatusCode::SWITCHING_PROTOCOLS,
519
            [
520
                (header::UPGRADE, grip.name()),
521
                (header::CONNECTION, "upgrade"),
522
            ],
523
        )
524
            .into_response();
525
        response.extensions_mut().insert(Greeting(format!(
526
            "You are now jelqing {}.\r\n",
527
            grip.name()
528
        )));
529
        return response;
530
    }
531
    let detail = match ctx.header(header::UPGRADE) {
532
        Some(protocol) => {
533
            format!("The server does not know the {protocol} grip. Grips are protocols.")
534
        }
535
        None => "Grips are protocols. Change grip by upgrading the connection.".to_owned(),
536
    };
537
    (
538
        StatusCode::OK,
539
        [(header::UPGRADE, "overhand, underhand")],
540
        Json(json!({ "grip": run.grip.name(), "detail": detail })),
541
    )
542
        .into_response()
543
}
544
545
fn get_diagnosis(run: &mut Run, ctx: &Ctx) -> Response {
546
    respond(run.diagnose(
547
        ctx.header(header::AUTHORIZATION),
548
        ctx.header(header::IF_NONE_MATCH),
549
    ))
550
}
551
552
fn get_footage(run: &mut Run, _: &Ctx) -> Response {
553
    let Some((filmed, age)) = run.footage() else {
554
        return Problem::new(
555
            StatusCode::NOT_FOUND,
556
            "no-footage",
557
            "There is no footage. Yet.",
558
        )
559
        .into_response();
560
    };
561
    (
562
        [
563
            (
564
                header::CACHE_CONTROL,
565
                "public, max-age=31536000, immutable".to_owned(),
566
            ),
567
            (header::AGE, age.to_string()),
568
            (header::LAST_MODIFIED, httpdate::fmt_http_date(filmed)),
569
        ],
570
        Json(json!({
571
            "detail": "A recording. It is grainy. It is unmistakably you. It has been shared.",
572
            "views": 1 + age * 37,
573
        })),
574
    )
575
        .into_response()
576
}