atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
e76ab808e7ad49d0b6fccd17728da137daacdb8c
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/run.rsRust233 lines8.2 KB
1
//! Plumbing shared by every resource under `/runs/{id}`.
2
3
use std::time::Instant;
4
5
use axum::{
6
    http::{HeaderName, HeaderValue, StatusCode, header},
7
    response::{IntoResponse, Response},
8
};
9
use hyper_util::rt::TokioIo;
10
use tokio::io::AsyncWriteExt;
11
12
use super::{AppState, ctx::Ctx, middleware::Compress, resource::Resource, runs};
13
use crate::{
14
    game::{Floor, Run, balance::SUSPICION_LIMIT},
15
    headers::{
16
        X_CASH, X_EQ, X_FLOOR, X_FORESKIN, X_GIRTH, X_OBSERVED_BY, X_SELF_REPORTED_LENGTH, X_SHAME,
17
        X_STAMINA, X_SUSPICION,
18
    },
19
    locale::Locale,
20
    problem::{PROBLEM_BASE, Problem},
21
    secret::Secret,
22
};
23
24
pub const REL_BASE: &str = "https://jelq.dev/rels/";
25
const COOKIE_ATTRIBUTES: &str = "Max-Age=31536000; Path=/; HttpOnly; SameSite=Strict";
26
/// Which household hazards stand between a request and the run.
27
#[derive(Clone, Copy, PartialEq, Eq)]
28
pub enum Scope {
29
    Home,
30
    Pockets,
31
}
32
33
pub struct RunResource {
34
    pub scope: Scope,
35
    pub resource: Resource<Run>,
36
}
37
38
/// What the server writes over the connection after a `101`.
39
#[derive(Clone)]
40
pub struct Greeting(pub String);
41
42
pub fn serve(state: &AppState, mut ctx: Ctx, target: &RunResource) -> Response {
43
    let mut runs = state.runs();
44
    let Some(run) = runs.get_mut(ctx.param("id")) else {
45
        return Problem::new(
46
            StatusCode::NOT_FOUND,
47
            "no-such-run",
48
            "There is no such run. There may never have been.",
49
        )
50
        .into_response();
51
    };
52
    if let Some(ending) = &run.ended {
53
        return Problem::new(StatusCode::GONE, "run-ended", "This run has ended.")
54
            .with("cause", format!("{PROBLEM_BASE}{}", ending.cause.slug()))
55
            .with("turn", ending.turn)
56
            .with("graveyard", "/graveyard")
57
            .into_response();
58
    }
59
    run.last_seen = ctx.now;
60
    run.recover(ctx.now);
61
    run.observed = None;
62
    let response =
63
        gate(run, &ctx, target.scope).unwrap_or_else(|| target.resource.dispatch(run, &ctx));
64
    let response = finish(run, &ctx, &state.config.secret, response);
65
    drop(runs);
66
    greet(response, &mut ctx)
67
}
68
69
fn gate(run: &mut Run, ctx: &Ctx, scope: Scope) -> Option<Response> {
70
    if scope == Scope::Pockets {
71
        return None;
72
    }
73
    if run.floor == Floor::Hotel && !run.here.wifi_accepted {
74
        let portal = run.path("/portal");
75
        return Some(
76
            Problem::new(
77
                StatusCode::NETWORK_AUTHENTICATION_REQUIRED,
78
                "captive-portal",
79
                "The network requires authentication. The hotel would like you to agree to some terms.",
80
            )
81
            .with("portal", portal.as_str())
82
            .header(header::LINK, format!("<{portal}>; rel=\"{REL_BASE}portal\""))
83
            .into_response(),
84
        );
85
    }
86
    let authorization = ctx
87
        .header(header::AUTHORIZATION)
88
        .map(|text| Locale::negotiate(ctx.header(header::ACCEPT_LANGUAGE)).canonicalise(text));
89
    run.answer_door(authorization.as_deref())
90
        .err()
91
        .map(IntoResponse::into_response)
92
}
93
94
/// Every resource the run can reach right now, then every technique a JELQ could use. The `allow`
95
/// and `lubricant` extension attributes (RFC 8288 §3) say what each accepts, so a client never guesses.
96
fn links(run: &Run, now: Instant) -> String {
97
    let linked: [(&str, &RunResource, bool); 13] = [
98
        ("", &runs::RUN, true),
99
        ("floor", &runs::FLOOR, true),
100
        ("length", &runs::LENGTH, true),
101
        ("foreskin", &runs::FORESKIN, run.foreskin.is_some()),
102
        ("inventory", &runs::INVENTORY, true),
103
        ("techniques", &runs::TECHNIQUES, true),
104
        ("drawer", &runs::DRAWER, true),
105
        ("grip", &runs::GRIP, true),
106
        ("shop", &runs::SHOP, run.floor.shop_open()),
107
        ("portal", &runs::PORTAL, run.floor == Floor::Hotel),
108
        ("elder", &runs::ELDER, run.floor == Floor::Forum),
109
        ("footage", &runs::FOOTAGE, run.filmed_at.is_some()),
110
        ("diagnosis", &runs::DIAGNOSIS, true),
111
    ];
112
    linked
113
        .into_iter()
114
        .filter(|(_, _, relevant)| *relevant)
115
        .map(|(rel, target, _)| {
116
            let (path, name) = if rel.is_empty() {
117
                (run.path(""), "run")
118
            } else {
119
                (run.path(&format!("/{rel}")), rel)
120
            };
121
            let allow = target.resource.allow(run);
122
            format!("<{path}>; rel=\"{REL_BASE}{name}\"; allow=\"{allow}\"")
123
        })
124
        .chain(run.techniques_now(now).into_iter().map(|technique| {
125
            let name = technique.name();
126
            let lubricant = technique
127
                .lubricant()
128
                .map_or(String::new(), |rule| format!("; lubricant=\"{rule}\""));
129
            format!(
130
                "<{}?technique={name}>; rel=\"{REL_BASE}technique\"; title=\"{name}\"; allow=\"JELQ\"{lubricant}",
131
                run.path("")
132
            )
133
        }))
134
        .collect::<Vec<_>>()
135
        .join(", ")
136
}
137
138
/// Shame lives in a signed cookie so it follows the player across runs. Each response adds this
139
/// run's new shame to whatever total the client presents, so two runs at once both count.
140
fn settle_shame(run: &mut Run, ctx: &Ctx, secret: &Secret) -> u32 {
141
    let presented = ctx
142
        .cookie("shame")
143
        .and_then(|signed| secret.verify("shame", signed))
144
        .and_then(|total| total.parse::<u32>().ok());
145
    let total = presented.unwrap_or(run.shame_total) + (run.shame - run.shame_reported);
146
    run.shame_reported = run.shame;
147
    run.shame_total = total;
148
    total
149
}
150
151
pub fn finish(run: &mut Run, ctx: &Ctx, secret: &Secret, mut response: Response) -> Response {
152
    let status = response.status();
153
    if status == StatusCode::NOT_MODIFIED {
154
        return response;
155
    }
156
    let shame = settle_shame(run, ctx, secret);
157
    let mut stats: Vec<(HeaderName, String)> = vec![
158
        (
159
            X_SELF_REPORTED_LENGTH,
160
            format!("{:.2}", run.self_reported()),
161
        ),
162
        (X_GIRTH, format!("{:.2}", run.girth)),
163
        (
164
            X_FORESKIN,
165
            run.foreskin.map_or("gone".into(), |f| format!("{f:.2}")),
166
        ),
167
        (X_EQ, run.eq.to_string()),
168
        (X_STAMINA, format!("{}/{}", run.stamina, run.max_stamina())),
169
        (X_SUSPICION, format!("{}/{SUSPICION_LIMIT}", run.suspicion)),
170
        (X_SHAME, shame.to_string()),
171
        (X_CASH, run.cash.to_string()),
172
        (X_FLOOR, run.floor.number().to_string()),
173
        (header::LINK, links(run, ctx.now)),
174
    ];
175
    if let Some(observer) = run.observed {
176
        stats.push((X_OBSERVED_BY, observer.name().into()));
177
    }
178
    if run.mum.is_some() {
179
        stats.push((header::VIA, "1.1 mum".into()));
180
        stats.push((header::VARY, "Mum".into()));
181
    }
182
    // RFC 9111 obsoleted Warning, which is why nobody heeds it.
183
    if run.conditions.pulled_muscle {
184
        stats.push((header::WARNING, "199 - \"a muscle has been pulled\"".into()));
185
    }
186
    if run.eq > 70 && run.ended.is_none() {
187
        stats.push((header::WARNING, "199 - \"it is turning purple\"".into()));
188
    }
189
    stats.push((
190
        header::SET_COOKIE,
191
        format!(
192
            "shame={}; {COOKIE_ATTRIBUTES}",
193
            secret.sign("shame", &shame.to_string())
194
        ),
195
    ));
196
    if run.items.ruler {
197
        stats.push((
198
            header::SET_COOKIE,
199
            format!("ruler={}; {COOKIE_ATTRIBUTES}", secret.sign("ruler", "1")),
200
        ));
201
    }
202
    let headers = response.headers_mut();
203
    for (name, value) in stats {
204
        if let Ok(value) = HeaderValue::from_str(&value) {
205
            headers.append(name, value);
206
        }
207
    }
208
    let bodiless = status.is_informational() || status == StatusCode::NO_CONTENT;
209
    if run.items.ring && !bodiless {
210
        response.extensions_mut().insert(Compress);
211
    }
212
    response
213
}
214
215
fn greet(response: Response, ctx: &mut Ctx) -> Response {
216
    if response.status() != StatusCode::SWITCHING_PROTOCOLS {
217
        return response;
218
    }
219
    let (Some(Greeting(text)), Some(upgrade)) = (
220
        response.extensions().get::<Greeting>().cloned(),
221
        ctx.upgrade.take(),
222
    ) else {
223
        return response;
224
    };
225
    tokio::spawn(async move {
226
        if let Ok(upgraded) = upgrade.await {
227
            let mut io = TokioIo::new(upgraded);
228
            let _ = io.write_all(text.as_bytes()).await;
229
            let _ = io.shutdown().await;
230
        }
231
    });
232
    response
233
}