atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
f39b10e20a0b672c83264ded097f223a248730bd
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git

Blame: src/http/run.rs

782069860236atagen2026-10-10 12:44 UTC1
//! Plumbing shared by every resource under `/runs/{id}`.
782069860236atagen2026-10-10 12:44 UTC2
58e1fb3943e6atagen2026-10-10 13:30 UTC3
use std::time::Instant;
58e1fb3943e6atagen2026-10-10 13:30 UTC4
782069860236atagen2026-10-10 12:44 UTC5
use axum::{
782069860236atagen2026-10-10 12:44 UTC6
    http::{HeaderName, HeaderValue, StatusCode, header},
782069860236atagen2026-10-10 12:44 UTC7
    response::{IntoResponse, Response},
782069860236atagen2026-10-10 12:44 UTC8
};
782069860236atagen2026-10-10 12:44 UTC9
use hyper_util::rt::TokioIo;
782069860236atagen2026-10-10 12:44 UTC10
use tokio::io::AsyncWriteExt;
782069860236atagen2026-10-10 12:44 UTC11
d604371299fbatagen2026-10-10 13:54 UTC12
use super::{AppState, ctx::Ctx, meta, middleware::Compress, resource::Resource, runs};
782069860236atagen2026-10-10 12:44 UTC13
use crate::{
d604371299fbatagen2026-10-10 13:54 UTC14
    game::{Elder, FORUM_THREAD, Floor, Run, balance::SUSPICION_LIMIT},
782069860236atagen2026-10-10 12:44 UTC15
    headers::{
f39b10e20a0batagen2026-10-10 14:33 UTC16
        X_CASH, X_EQ, X_FLOOR, X_FORESKIN, X_GIRTH, X_LENGTH, X_OBSERVED_BY,
f39b10e20a0batagen2026-10-10 14:33 UTC17
        X_SELF_REPORTED_LENGTH, X_SHAME, X_STAMINA, X_SUSPICION,
782069860236atagen2026-10-10 12:44 UTC18
    },
ef7d6dee5976atagen2026-10-10 13:23 UTC19
    locale::Locale,
782069860236atagen2026-10-10 12:44 UTC20
    problem::{PROBLEM_BASE, Problem},
782069860236atagen2026-10-10 12:44 UTC21
    secret::Secret,
782069860236atagen2026-10-10 12:44 UTC22
};
782069860236atagen2026-10-10 12:44 UTC23
782069860236atagen2026-10-10 12:44 UTC24
pub const REL_BASE: &str = "https://jelq.dev/rels/";
782069860236atagen2026-10-10 12:44 UTC25
const COOKIE_ATTRIBUTES: &str = "Max-Age=31536000; Path=/; HttpOnly; SameSite=Strict";
782069860236atagen2026-10-10 12:44 UTC26
/// Which household hazards stand between a request and the run.
782069860236atagen2026-10-10 12:44 UTC27
#[derive(Clone, Copy, PartialEq, Eq)]
782069860236atagen2026-10-10 12:44 UTC28
pub enum Scope {
782069860236atagen2026-10-10 12:44 UTC29
    Home,
782069860236atagen2026-10-10 12:44 UTC30
    Pockets,
782069860236atagen2026-10-10 12:44 UTC31
}
782069860236atagen2026-10-10 12:44 UTC32
782069860236atagen2026-10-10 12:44 UTC33
pub struct RunResource {
782069860236atagen2026-10-10 12:44 UTC34
    pub scope: Scope,
782069860236atagen2026-10-10 12:44 UTC35
    pub resource: Resource<Run>,
782069860236atagen2026-10-10 12:44 UTC36
}
782069860236atagen2026-10-10 12:44 UTC37
782069860236atagen2026-10-10 12:44 UTC38
/// What the server writes over the connection after a `101`.
782069860236atagen2026-10-10 12:44 UTC39
#[derive(Clone)]
782069860236atagen2026-10-10 12:44 UTC40
pub struct Greeting(pub String);
782069860236atagen2026-10-10 12:44 UTC41
782069860236atagen2026-10-10 12:44 UTC42
pub fn serve(state: &AppState, mut ctx: Ctx, target: &RunResource) -> Response {
782069860236atagen2026-10-10 12:44 UTC43
    let mut runs = state.runs();
782069860236atagen2026-10-10 12:44 UTC44
    let Some(run) = runs.get_mut(ctx.param("id")) else {
782069860236atagen2026-10-10 12:44 UTC45
        return Problem::new(
782069860236atagen2026-10-10 12:44 UTC46
            StatusCode::NOT_FOUND,
782069860236atagen2026-10-10 12:44 UTC47
            "no-such-run",
782069860236atagen2026-10-10 12:44 UTC48
            "There is no such run. There may never have been.",
782069860236atagen2026-10-10 12:44 UTC49
        )
782069860236atagen2026-10-10 12:44 UTC50
        .into_response();
782069860236atagen2026-10-10 12:44 UTC51
    };
782069860236atagen2026-10-10 12:44 UTC52
    if let Some(ending) = &run.ended {
782069860236atagen2026-10-10 12:44 UTC53
        return Problem::new(StatusCode::GONE, "run-ended", "This run has ended.")
782069860236atagen2026-10-10 12:44 UTC54
            .with("cause", format!("{PROBLEM_BASE}{}", ending.cause.slug()))
782069860236atagen2026-10-10 12:44 UTC55
            .with("turn", ending.turn)
782069860236atagen2026-10-10 12:44 UTC56
            .with("graveyard", "/graveyard")
782069860236atagen2026-10-10 12:44 UTC57
            .into_response();
782069860236atagen2026-10-10 12:44 UTC58
    }
782069860236atagen2026-10-10 12:44 UTC59
    run.last_seen = ctx.now;
e76ab808e7adatagen2026-10-10 13:46 UTC60
    run.recover(ctx.now);
782069860236atagen2026-10-10 12:44 UTC61
    run.observed = None;
782069860236atagen2026-10-10 12:44 UTC62
    let response =
782069860236atagen2026-10-10 12:44 UTC63
        gate(run, &ctx, target.scope).unwrap_or_else(|| target.resource.dispatch(run, &ctx));
782069860236atagen2026-10-10 12:44 UTC64
    let response = finish(run, &ctx, &state.config.secret, response);
782069860236atagen2026-10-10 12:44 UTC65
    drop(runs);
782069860236atagen2026-10-10 12:44 UTC66
    greet(response, &mut ctx)
782069860236atagen2026-10-10 12:44 UTC67
}
782069860236atagen2026-10-10 12:44 UTC68
782069860236atagen2026-10-10 12:44 UTC69
fn gate(run: &mut Run, ctx: &Ctx, scope: Scope) -> Option<Response> {
782069860236atagen2026-10-10 12:44 UTC70
    if scope == Scope::Pockets {
782069860236atagen2026-10-10 12:44 UTC71
        return None;
782069860236atagen2026-10-10 12:44 UTC72
    }
782069860236atagen2026-10-10 12:44 UTC73
    if run.floor == Floor::Hotel && !run.here.wifi_accepted {
782069860236atagen2026-10-10 12:44 UTC74
        let portal = run.path("/portal");
782069860236atagen2026-10-10 12:44 UTC75
        return Some(
782069860236atagen2026-10-10 12:44 UTC76
            Problem::new(
782069860236atagen2026-10-10 12:44 UTC77
                StatusCode::NETWORK_AUTHENTICATION_REQUIRED,
782069860236atagen2026-10-10 12:44 UTC78
                "captive-portal",
782069860236atagen2026-10-10 12:44 UTC79
                "The network requires authentication. The hotel would like you to agree to some terms.",
782069860236atagen2026-10-10 12:44 UTC80
            )
782069860236atagen2026-10-10 12:44 UTC81
            .with("portal", portal.as_str())
782069860236atagen2026-10-10 12:44 UTC82
            .header(header::LINK, format!("<{portal}>; rel=\"{REL_BASE}portal\""))
782069860236atagen2026-10-10 12:44 UTC83
            .into_response(),
782069860236atagen2026-10-10 12:44 UTC84
        );
782069860236atagen2026-10-10 12:44 UTC85
    }
ef7d6dee5976atagen2026-10-10 13:23 UTC86
    let authorization = ctx
ef7d6dee5976atagen2026-10-10 13:23 UTC87
        .header(header::AUTHORIZATION)
ef7d6dee5976atagen2026-10-10 13:23 UTC88
        .map(|text| Locale::negotiate(ctx.header(header::ACCEPT_LANGUAGE)).canonicalise(text));
ef7d6dee5976atagen2026-10-10 13:23 UTC89
    run.answer_door(authorization.as_deref())
782069860236atagen2026-10-10 12:44 UTC90
        .err()
782069860236atagen2026-10-10 12:44 UTC91
        .map(IntoResponse::into_response)
782069860236atagen2026-10-10 12:44 UTC92
}
782069860236atagen2026-10-10 12:44 UTC93
58e1fb3943e6atagen2026-10-10 13:30 UTC94
/// Every resource the run can reach right now, then every technique a JELQ could use. The `allow`
58e1fb3943e6atagen2026-10-10 13:30 UTC95
/// and `lubricant` extension attributes (RFC 8288 §3) say what each accepts, so a client never guesses.
58e1fb3943e6atagen2026-10-10 13:30 UTC96
fn links(run: &Run, now: Instant) -> String {
185851447cebatagen2026-10-10 12:58 UTC97
    let linked: [(&str, &RunResource, bool); 13] = [
185851447cebatagen2026-10-10 12:58 UTC98
        ("", &runs::RUN, true),
185851447cebatagen2026-10-10 12:58 UTC99
        ("floor", &runs::FLOOR, true),
185851447cebatagen2026-10-10 12:58 UTC100
        ("length", &runs::LENGTH, true),
185851447cebatagen2026-10-10 12:58 UTC101
        ("foreskin", &runs::FORESKIN, run.foreskin.is_some()),
185851447cebatagen2026-10-10 12:58 UTC102
        ("inventory", &runs::INVENTORY, true),
185851447cebatagen2026-10-10 12:58 UTC103
        ("techniques", &runs::TECHNIQUES, true),
d604371299fbatagen2026-10-10 13:54 UTC104
        ("drawer", &runs::DRAWER, run.drawer_worth_searching()),
185851447cebatagen2026-10-10 12:58 UTC105
        ("grip", &runs::GRIP, true),
185851447cebatagen2026-10-10 12:58 UTC106
        ("shop", &runs::SHOP, run.floor.shop_open()),
d604371299fbatagen2026-10-10 13:54 UTC107
        (
d604371299fbatagen2026-10-10 13:54 UTC108
            "portal",
d604371299fbatagen2026-10-10 13:54 UTC109
            &runs::PORTAL,
d604371299fbatagen2026-10-10 13:54 UTC110
            run.floor == Floor::Hotel && !run.here.wifi_accepted,
d604371299fbatagen2026-10-10 13:54 UTC111
        ),
d604371299fbatagen2026-10-10 13:54 UTC112
        (
d604371299fbatagen2026-10-10 13:54 UTC113
            "elder",
d604371299fbatagen2026-10-10 13:54 UTC114
            &runs::ELDER,
d604371299fbatagen2026-10-10 13:54 UTC115
            run.floor == Floor::Forum && run.elder != Elder::Beaten,
d604371299fbatagen2026-10-10 13:54 UTC116
        ),
185851447cebatagen2026-10-10 12:58 UTC117
        ("footage", &runs::FOOTAGE, run.filmed_at.is_some()),
d604371299fbatagen2026-10-10 13:54 UTC118
        ("diagnosis", &runs::DIAGNOSIS, run.floor == Floor::Clinic),
185851447cebatagen2026-10-10 12:58 UTC119
    ];
185851447cebatagen2026-10-10 12:58 UTC120
    linked
185851447cebatagen2026-10-10 12:58 UTC121
        .into_iter()
185851447cebatagen2026-10-10 12:58 UTC122
        .filter(|(_, _, relevant)| *relevant)
185851447cebatagen2026-10-10 12:58 UTC123
        .map(|(rel, target, _)| {
185851447cebatagen2026-10-10 12:58 UTC124
            let (path, name) = if rel.is_empty() {
185851447cebatagen2026-10-10 12:58 UTC125
                (run.path(""), "run")
185851447cebatagen2026-10-10 12:58 UTC126
            } else {
185851447cebatagen2026-10-10 12:58 UTC127
                (run.path(&format!("/{rel}")), rel)
185851447cebatagen2026-10-10 12:58 UTC128
            };
185851447cebatagen2026-10-10 12:58 UTC129
            let allow = target.resource.allow(run);
185851447cebatagen2026-10-10 12:58 UTC130
            format!("<{path}>; rel=\"{REL_BASE}{name}\"; allow=\"{allow}\"")
185851447cebatagen2026-10-10 12:58 UTC131
        })
d604371299fbatagen2026-10-10 13:54 UTC132
        .chain(
d604371299fbatagen2026-10-10 13:54 UTC133
            (run.forum_read() || run.floor.number() >= Floor::Forum.number()).then(|| {
d604371299fbatagen2026-10-10 13:54 UTC134
                format!(
d604371299fbatagen2026-10-10 13:54 UTC135
                    "<{FORUM_THREAD}>; rel=\"{REL_BASE}thread\"; allow=\"{}\"",
d604371299fbatagen2026-10-10 13:54 UTC136
                    meta::THREAD.allow_any()
d604371299fbatagen2026-10-10 13:54 UTC137
                )
d604371299fbatagen2026-10-10 13:54 UTC138
            }),
d604371299fbatagen2026-10-10 13:54 UTC139
        )
58e1fb3943e6atagen2026-10-10 13:30 UTC140
        .chain(run.techniques_now(now).into_iter().map(|technique| {
58e1fb3943e6atagen2026-10-10 13:30 UTC141
            let name = technique.name();
58e1fb3943e6atagen2026-10-10 13:30 UTC142
            let lubricant = technique
58e1fb3943e6atagen2026-10-10 13:30 UTC143
                .lubricant()
58e1fb3943e6atagen2026-10-10 13:30 UTC144
                .map_or(String::new(), |rule| format!("; lubricant=\"{rule}\""));
58e1fb3943e6atagen2026-10-10 13:30 UTC145
            format!(
58e1fb3943e6atagen2026-10-10 13:30 UTC146
                "<{}?technique={name}>; rel=\"{REL_BASE}technique\"; title=\"{name}\"; allow=\"JELQ\"{lubricant}",
58e1fb3943e6atagen2026-10-10 13:30 UTC147
                run.path("")
58e1fb3943e6atagen2026-10-10 13:30 UTC148
            )
58e1fb3943e6atagen2026-10-10 13:30 UTC149
        }))
185851447cebatagen2026-10-10 12:58 UTC150
        .collect::<Vec<_>>()
185851447cebatagen2026-10-10 12:58 UTC151
        .join(", ")
782069860236atagen2026-10-10 12:44 UTC152
}
782069860236atagen2026-10-10 12:44 UTC153
782069860236atagen2026-10-10 12:44 UTC154
/// Shame lives in a signed cookie so it follows the player across runs. Each response adds this
782069860236atagen2026-10-10 12:44 UTC155
/// run's new shame to whatever total the client presents, so two runs at once both count.
782069860236atagen2026-10-10 12:44 UTC156
fn settle_shame(run: &mut Run, ctx: &Ctx, secret: &Secret) -> u32 {
782069860236atagen2026-10-10 12:44 UTC157
    let presented = ctx
782069860236atagen2026-10-10 12:44 UTC158
        .cookie("shame")
782069860236atagen2026-10-10 12:44 UTC159
        .and_then(|signed| secret.verify("shame", signed))
782069860236atagen2026-10-10 12:44 UTC160
        .and_then(|total| total.parse::<u32>().ok());
782069860236atagen2026-10-10 12:44 UTC161
    let total = presented.unwrap_or(run.shame_total) + (run.shame - run.shame_reported);
782069860236atagen2026-10-10 12:44 UTC162
    run.shame_reported = run.shame;
782069860236atagen2026-10-10 12:44 UTC163
    run.shame_total = total;
782069860236atagen2026-10-10 12:44 UTC164
    total
782069860236atagen2026-10-10 12:44 UTC165
}
782069860236atagen2026-10-10 12:44 UTC166
782069860236atagen2026-10-10 12:44 UTC167
pub fn finish(run: &mut Run, ctx: &Ctx, secret: &Secret, mut response: Response) -> Response {
782069860236atagen2026-10-10 12:44 UTC168
    let status = response.status();
782069860236atagen2026-10-10 12:44 UTC169
    if status == StatusCode::NOT_MODIFIED {
782069860236atagen2026-10-10 12:44 UTC170
        return response;
782069860236atagen2026-10-10 12:44 UTC171
    }
782069860236atagen2026-10-10 12:44 UTC172
    let shame = settle_shame(run, ctx, secret);
782069860236atagen2026-10-10 12:44 UTC173
    let mut stats: Vec<(HeaderName, String)> = vec![
f39b10e20a0batagen2026-10-10 14:33 UTC174
        if run.items.ruler {
f39b10e20a0batagen2026-10-10 14:33 UTC175
            (X_LENGTH, format!("{:.2}", run.length))
f39b10e20a0batagen2026-10-10 14:33 UTC176
        } else {
f39b10e20a0batagen2026-10-10 14:33 UTC177
            (
f39b10e20a0batagen2026-10-10 14:33 UTC178
                X_SELF_REPORTED_LENGTH,
f39b10e20a0batagen2026-10-10 14:33 UTC179
                format!("{:.2}", run.self_reported()),
f39b10e20a0batagen2026-10-10 14:33 UTC180
            )
f39b10e20a0batagen2026-10-10 14:33 UTC181
        },
782069860236atagen2026-10-10 12:44 UTC182
        (X_GIRTH, format!("{:.2}", run.girth)),
782069860236atagen2026-10-10 12:44 UTC183
        (
782069860236atagen2026-10-10 12:44 UTC184
            X_FORESKIN,
782069860236atagen2026-10-10 12:44 UTC185
            run.foreskin.map_or("gone".into(), |f| format!("{f:.2}")),
782069860236atagen2026-10-10 12:44 UTC186
        ),
782069860236atagen2026-10-10 12:44 UTC187
        (X_EQ, run.eq.to_string()),
782069860236atagen2026-10-10 12:44 UTC188
        (X_STAMINA, format!("{}/{}", run.stamina, run.max_stamina())),
782069860236atagen2026-10-10 12:44 UTC189
        (X_SUSPICION, format!("{}/{SUSPICION_LIMIT}", run.suspicion)),
782069860236atagen2026-10-10 12:44 UTC190
        (X_SHAME, shame.to_string()),
782069860236atagen2026-10-10 12:44 UTC191
        (X_CASH, run.cash.to_string()),
782069860236atagen2026-10-10 12:44 UTC192
        (X_FLOOR, run.floor.number().to_string()),
58e1fb3943e6atagen2026-10-10 13:30 UTC193
        (header::LINK, links(run, ctx.now)),
782069860236atagen2026-10-10 12:44 UTC194
    ];
782069860236atagen2026-10-10 12:44 UTC195
    if let Some(observer) = run.observed {
782069860236atagen2026-10-10 12:44 UTC196
        stats.push((X_OBSERVED_BY, observer.name().into()));
782069860236atagen2026-10-10 12:44 UTC197
    }
9683736a2c5eatagen2026-10-10 13:15 UTC198
    if run.mum.is_some() {
9683736a2c5eatagen2026-10-10 13:15 UTC199
        stats.push((header::VIA, "1.1 mum".into()));
9683736a2c5eatagen2026-10-10 13:15 UTC200
        stats.push((header::VARY, "Mum".into()));
782069860236atagen2026-10-10 12:44 UTC201
    }
782069860236atagen2026-10-10 12:44 UTC202
    // RFC 9111 obsoleted Warning, which is why nobody heeds it.
782069860236atagen2026-10-10 12:44 UTC203
    if run.conditions.pulled_muscle {
782069860236atagen2026-10-10 12:44 UTC204
        stats.push((header::WARNING, "199 - \"a muscle has been pulled\"".into()));
782069860236atagen2026-10-10 12:44 UTC205
    }
782069860236atagen2026-10-10 12:44 UTC206
    if run.eq > 70 && run.ended.is_none() {
782069860236atagen2026-10-10 12:44 UTC207
        stats.push((header::WARNING, "199 - \"it is turning purple\"".into()));
782069860236atagen2026-10-10 12:44 UTC208
    }
782069860236atagen2026-10-10 12:44 UTC209
    stats.push((
782069860236atagen2026-10-10 12:44 UTC210
        header::SET_COOKIE,
782069860236atagen2026-10-10 12:44 UTC211
        format!(
782069860236atagen2026-10-10 12:44 UTC212
            "shame={}; {COOKIE_ATTRIBUTES}",
782069860236atagen2026-10-10 12:44 UTC213
            secret.sign("shame", &shame.to_string())
782069860236atagen2026-10-10 12:44 UTC214
        ),
782069860236atagen2026-10-10 12:44 UTC215
    ));
782069860236atagen2026-10-10 12:44 UTC216
    if run.items.ruler {
782069860236atagen2026-10-10 12:44 UTC217
        stats.push((
782069860236atagen2026-10-10 12:44 UTC218
            header::SET_COOKIE,
782069860236atagen2026-10-10 12:44 UTC219
            format!("ruler={}; {COOKIE_ATTRIBUTES}", secret.sign("ruler", "1")),
782069860236atagen2026-10-10 12:44 UTC220
        ));
782069860236atagen2026-10-10 12:44 UTC221
    }
782069860236atagen2026-10-10 12:44 UTC222
    let headers = response.headers_mut();
782069860236atagen2026-10-10 12:44 UTC223
    for (name, value) in stats {
782069860236atagen2026-10-10 12:44 UTC224
        if let Ok(value) = HeaderValue::from_str(&value) {
782069860236atagen2026-10-10 12:44 UTC225
            headers.append(name, value);
782069860236atagen2026-10-10 12:44 UTC226
        }
782069860236atagen2026-10-10 12:44 UTC227
    }
782069860236atagen2026-10-10 12:44 UTC228
    let bodiless = status.is_informational() || status == StatusCode::NO_CONTENT;
782069860236atagen2026-10-10 12:44 UTC229
    if run.items.ring && !bodiless {
782069860236atagen2026-10-10 12:44 UTC230
        response.extensions_mut().insert(Compress);
782069860236atagen2026-10-10 12:44 UTC231
    }
782069860236atagen2026-10-10 12:44 UTC232
    response
782069860236atagen2026-10-10 12:44 UTC233
}
782069860236atagen2026-10-10 12:44 UTC234
782069860236atagen2026-10-10 12:44 UTC235
fn greet(response: Response, ctx: &mut Ctx) -> Response {
782069860236atagen2026-10-10 12:44 UTC236
    if response.status() != StatusCode::SWITCHING_PROTOCOLS {
782069860236atagen2026-10-10 12:44 UTC237
        return response;
782069860236atagen2026-10-10 12:44 UTC238
    }
782069860236atagen2026-10-10 12:44 UTC239
    let (Some(Greeting(text)), Some(upgrade)) = (
782069860236atagen2026-10-10 12:44 UTC240
        response.extensions().get::<Greeting>().cloned(),
782069860236atagen2026-10-10 12:44 UTC241
        ctx.upgrade.take(),
782069860236atagen2026-10-10 12:44 UTC242
    ) else {
782069860236atagen2026-10-10 12:44 UTC243
        return response;
782069860236atagen2026-10-10 12:44 UTC244
    };
782069860236atagen2026-10-10 12:44 UTC245
    tokio::spawn(async move {
782069860236atagen2026-10-10 12:44 UTC246
        if let Ok(upgraded) = upgrade.await {
782069860236atagen2026-10-10 12:44 UTC247
            let mut io = TokioIo::new(upgraded);
782069860236atagen2026-10-10 12:44 UTC248
            let _ = io.write_all(text.as_bytes()).await;
782069860236atagen2026-10-10 12:44 UTC249
            let _ = io.shutdown().await;
782069860236atagen2026-10-10 12:44 UTC250
        }
782069860236atagen2026-10-10 12:44 UTC251
    });
782069860236atagen2026-10-10 12:44 UTC252
    response
782069860236atagen2026-10-10 12:44 UTC253
}