atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
7288fc269bb68466e68614d7f97cb55fc4ae1358
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/run.rsRust232 lines8.1 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.observed = None;
61
    let response =
62
        gate(run, &ctx, target.scope).unwrap_or_else(|| target.resource.dispatch(run, &ctx));
63
    let response = finish(run, &ctx, &state.config.secret, response);
64
    drop(runs);
65
    greet(response, &mut ctx)
66
}
67
68
fn gate(run: &mut Run, ctx: &Ctx, scope: Scope) -> Option<Response> {
69
    if scope == Scope::Pockets {
70
        return None;
71
    }
72
    if run.floor == Floor::Hotel && !run.here.wifi_accepted {
73
        let portal = run.path("/portal");
74
        return Some(
75
            Problem::new(
76
                StatusCode::NETWORK_AUTHENTICATION_REQUIRED,
77
                "captive-portal",
78
                "The network requires authentication. The hotel would like you to agree to some terms.",
79
            )
80
            .with("portal", portal.as_str())
81
            .header(header::LINK, format!("<{portal}>; rel=\"{REL_BASE}portal\""))
82
            .into_response(),
83
        );
84
    }
85
    let authorization = ctx
86
        .header(header::AUTHORIZATION)
87
        .map(|text| Locale::negotiate(ctx.header(header::ACCEPT_LANGUAGE)).canonicalise(text));
88
    run.answer_door(authorization.as_deref())
89
        .err()
90
        .map(IntoResponse::into_response)
91
}
92
93
/// Every resource the run can reach right now, then every technique a JELQ could use. The `allow`
94
/// and `lubricant` extension attributes (RFC 8288 §3) say what each accepts, so a client never guesses.
95
fn links(run: &Run, now: Instant) -> String {
96
    let linked: [(&str, &RunResource, bool); 13] = [
97
        ("", &runs::RUN, true),
98
        ("floor", &runs::FLOOR, true),
99
        ("length", &runs::LENGTH, true),
100
        ("foreskin", &runs::FORESKIN, run.foreskin.is_some()),
101
        ("inventory", &runs::INVENTORY, true),
102
        ("techniques", &runs::TECHNIQUES, true),
103
        ("drawer", &runs::DRAWER, true),
104
        ("grip", &runs::GRIP, true),
105
        ("shop", &runs::SHOP, run.floor.shop_open()),
106
        ("portal", &runs::PORTAL, run.floor == Floor::Hotel),
107
        ("elder", &runs::ELDER, run.floor == Floor::Forum),
108
        ("footage", &runs::FOOTAGE, run.filmed_at.is_some()),
109
        ("diagnosis", &runs::DIAGNOSIS, true),
110
    ];
111
    linked
112
        .into_iter()
113
        .filter(|(_, _, relevant)| *relevant)
114
        .map(|(rel, target, _)| {
115
            let (path, name) = if rel.is_empty() {
116
                (run.path(""), "run")
117
            } else {
118
                (run.path(&format!("/{rel}")), rel)
119
            };
120
            let allow = target.resource.allow(run);
121
            format!("<{path}>; rel=\"{REL_BASE}{name}\"; allow=\"{allow}\"")
122
        })
123
        .chain(run.techniques_now(now).into_iter().map(|technique| {
124
            let name = technique.name();
125
            let lubricant = technique
126
                .lubricant()
127
                .map_or(String::new(), |rule| format!("; lubricant=\"{rule}\""));
128
            format!(
129
                "<{}?technique={name}>; rel=\"{REL_BASE}technique\"; title=\"{name}\"; allow=\"JELQ\"{lubricant}",
130
                run.path("")
131
            )
132
        }))
133
        .collect::<Vec<_>>()
134
        .join(", ")
135
}
136
137
/// Shame lives in a signed cookie so it follows the player across runs. Each response adds this
138
/// run's new shame to whatever total the client presents, so two runs at once both count.
139
fn settle_shame(run: &mut Run, ctx: &Ctx, secret: &Secret) -> u32 {
140
    let presented = ctx
141
        .cookie("shame")
142
        .and_then(|signed| secret.verify("shame", signed))
143
        .and_then(|total| total.parse::<u32>().ok());
144
    let total = presented.unwrap_or(run.shame_total) + (run.shame - run.shame_reported);
145
    run.shame_reported = run.shame;
146
    run.shame_total = total;
147
    total
148
}
149
150
pub fn finish(run: &mut Run, ctx: &Ctx, secret: &Secret, mut response: Response) -> Response {
151
    let status = response.status();
152
    if status == StatusCode::NOT_MODIFIED {
153
        return response;
154
    }
155
    let shame = settle_shame(run, ctx, secret);
156
    let mut stats: Vec<(HeaderName, String)> = vec![
157
        (
158
            X_SELF_REPORTED_LENGTH,
159
            format!("{:.2}", run.self_reported()),
160
        ),
161
        (X_GIRTH, format!("{:.2}", run.girth)),
162
        (
163
            X_FORESKIN,
164
            run.foreskin.map_or("gone".into(), |f| format!("{f:.2}")),
165
        ),
166
        (X_EQ, run.eq.to_string()),
167
        (X_STAMINA, format!("{}/{}", run.stamina, run.max_stamina())),
168
        (X_SUSPICION, format!("{}/{SUSPICION_LIMIT}", run.suspicion)),
169
        (X_SHAME, shame.to_string()),
170
        (X_CASH, run.cash.to_string()),
171
        (X_FLOOR, run.floor.number().to_string()),
172
        (header::LINK, links(run, ctx.now)),
173
    ];
174
    if let Some(observer) = run.observed {
175
        stats.push((X_OBSERVED_BY, observer.name().into()));
176
    }
177
    if run.mum.is_some() {
178
        stats.push((header::VIA, "1.1 mum".into()));
179
        stats.push((header::VARY, "Mum".into()));
180
    }
181
    // RFC 9111 obsoleted Warning, which is why nobody heeds it.
182
    if run.conditions.pulled_muscle {
183
        stats.push((header::WARNING, "199 - \"a muscle has been pulled\"".into()));
184
    }
185
    if run.eq > 70 && run.ended.is_none() {
186
        stats.push((header::WARNING, "199 - \"it is turning purple\"".into()));
187
    }
188
    stats.push((
189
        header::SET_COOKIE,
190
        format!(
191
            "shame={}; {COOKIE_ATTRIBUTES}",
192
            secret.sign("shame", &shame.to_string())
193
        ),
194
    ));
195
    if run.items.ruler {
196
        stats.push((
197
            header::SET_COOKIE,
198
            format!("ruler={}; {COOKIE_ATTRIBUTES}", secret.sign("ruler", "1")),
199
        ));
200
    }
201
    let headers = response.headers_mut();
202
    for (name, value) in stats {
203
        if let Ok(value) = HeaderValue::from_str(&value) {
204
            headers.append(name, value);
205
        }
206
    }
207
    let bodiless = status.is_informational() || status == StatusCode::NO_CONTENT;
208
    if run.items.ring && !bodiless {
209
        response.extensions_mut().insert(Compress);
210
    }
211
    response
212
}
213
214
fn greet(response: Response, ctx: &mut Ctx) -> Response {
215
    if response.status() != StatusCode::SWITCHING_PROTOCOLS {
216
        return response;
217
    }
218
    let (Some(Greeting(text)), Some(upgrade)) = (
219
        response.extensions().get::<Greeting>().cloned(),
220
        ctx.upgrade.take(),
221
    ) else {
222
        return response;
223
    };
224
    tokio::spawn(async move {
225
        if let Ok(upgraded) = upgrade.await {
226
            let mut io = TokioIo::new(upgraded);
227
            let _ = io.write_all(text.as_bytes()).await;
228
            let _ = io.shutdown().await;
229
        }
230
    });
231
    response
232
}