atagen

jelq

public

an http based roguelike rpg about jelqing

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