atagen

jelq

public

an http based roguelike rpg about jelqing

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