atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
058650ec79d6eb6841ce768ab49335ed74ae8b97
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/http/run.rsRust285 lines10.2 KB
1
//! Plumbing shared by every resource under `/runs/{id}`.
2
3
use axum::{
4
    http::{HeaderName, HeaderValue, StatusCode, header},
5
    response::{IntoResponse, Response},
6
};
7
use hyper_util::rt::TokioIo;
8
use tokio::io::AsyncWriteExt;
9
10
use super::{AppState, ctx::Ctx, meta, middleware::Compress, resource::Resource, runs};
11
use crate::{
12
    game::{
13
        Elder, FORUM_THREAD, Floor, Run, SHOP, Story,
14
        balance::{FRICTION_MAX, KITCHEN_TELLINGS, SUSPICION_LIMIT},
15
    },
16
    headers::{
17
        X_CASH, X_EQ, X_FLOOR, X_FORESKIN, X_FRICTION, X_GIRTH, X_LENGTH, X_OBSERVED_BY,
18
        X_SELF_REPORTED_LENGTH, X_SHAME, X_STAMINA, X_SUSPICION,
19
    },
20
    locale::Locale,
21
    problem::{PROBLEM_BASE, Problem},
22
    secret::Secret,
23
};
24
25
pub const REL_BASE: &str = "https://jelq.dev/rels/";
26
const COOKIE_ATTRIBUTES: &str = "Max-Age=31536000; Path=/; HttpOnly; SameSite=Strict";
27
/// Which household hazards stand between a request and the run.
28
#[derive(Clone, Copy, PartialEq, Eq)]
29
pub enum Scope {
30
    Home,
31
    Pockets,
32
}
33
34
pub struct RunResource {
35
    pub scope: Scope,
36
    pub resource: Resource<Run>,
37
}
38
39
/// What the server writes over the connection after a `101`.
40
#[derive(Clone)]
41
pub struct Greeting(pub String);
42
43
pub fn serve(state: &AppState, mut ctx: Ctx, target: &RunResource) -> Response {
44
    let mut runs = state.runs();
45
    let Some(run) = runs.get_mut(ctx.param("id")) else {
46
        return Problem::new(
47
            StatusCode::NOT_FOUND,
48
            "no-such-run",
49
            "There is no such run. There may never have been.",
50
        )
51
        .into_response();
52
    };
53
    if let Some(ending) = &run.ended {
54
        return Problem::new(StatusCode::GONE, "run-ended", "This run has ended.")
55
            .with("cause", format!("{PROBLEM_BASE}{}", ending.cause.slug()))
56
            .with("turn", ending.turn)
57
            .with("graveyard", "/graveyard")
58
            .into_response();
59
    }
60
    run.last_seen = 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) -> String {
97
    let thread_reachable = run.thread_reachable();
98
    let linked: [(&str, &RunResource, bool); 15] = [
99
        ("", &runs::RUN, true),
100
        ("floor", &runs::FLOOR, true),
101
        ("length", &runs::LENGTH, true),
102
        ("foreskin", &runs::FORESKIN, run.foreskin.is_some()),
103
        ("inventory", &runs::INVENTORY, true),
104
        ("techniques", &runs::TECHNIQUES, true),
105
        ("drawer", &runs::DRAWER, run.drawer_worth_searching()),
106
        ("kitchen", &runs::KITCHEN, {
107
            run.floor.has_kitchen() && run.kitchen_tellings < KITCHEN_TELLINGS
108
        }),
109
        ("re-read", &runs::REREAD, thread_reachable),
110
        ("grip", &runs::GRIP, true),
111
        ("shop", &runs::SHOP, run.floor.shop_open()),
112
        (
113
            "portal",
114
            &runs::PORTAL,
115
            run.floor == Floor::Hotel && !run.here.wifi_accepted,
116
        ),
117
        (
118
            "elder",
119
            &runs::ELDER,
120
            run.floor == Floor::Forum && run.elder != Elder::Beaten,
121
        ),
122
        ("footage", &runs::FOOTAGE, run.filmed_at.is_some()),
123
        ("diagnosis", &runs::DIAGNOSIS, run.floor == Floor::Clinic),
124
    ];
125
    linked
126
        .into_iter()
127
        .filter(|(_, _, relevant)| *relevant)
128
        .map(|(rel, target, _)| {
129
            let (path, name) = if rel.is_empty() {
130
                (run.path(""), "run")
131
            } else {
132
                (run.path(&format!("/{rel}")), rel)
133
            };
134
            let allow = target.resource.allow(run);
135
            format!("<{path}>; rel=\"{REL_BASE}{name}\"; allow=\"{allow}\"")
136
        })
137
        .chain(thread_reachable.then(|| {
138
            format!(
139
                "<{FORUM_THREAD}>; rel=\"{REL_BASE}thread\"; allow=\"{}\"",
140
                meta::THREAD.allow_any()
141
            )
142
        }),)
143
        .chain((run.story == Story::Pending).then(|| {
144
            let choice = |slug: &str, title: &str| {
145
                format!(
146
                    "<{}>; rel=\"{REL_BASE}branch\"; title=\"{title}\"; allow=\"POST\"",
147
                    run.path(&format!("/branches/{slug}"))
148
                )
149
            };
150
            [choice("forum", "Read the forum"), choice("close-tab", "Close the tab")].join(", ")
151
        }))
152
        .chain(run.techniques_now().into_iter().map(|technique| {
153
            let name = technique.name();
154
            let lubricant = technique
155
                .lubricant()
156
                .map_or(String::new(), |rule| format!("; lubricant=\"{rule}\""));
157
            format!(
158
                "<{}?technique={name}>; rel=\"{REL_BASE}technique\"; title=\"{name}\"; allow=\"JELQ\"{lubricant}",
159
                run.path("")
160
            )
161
        }))
162
        .chain(run.here.shopping.then(|| {
163
            SHOP.iter()
164
                .filter_map(|item| {
165
                    let price = item.price()?;
166
                    Some(format!(
167
                        "<{}>; rel=\"{REL_BASE}shop-item\"; title=\"{} for {price}\"; allow=\"POST\"",
168
                        run.path(&format!("/shop/{}", item.slug())),
169
                        item.slug()
170
                    ))
171
                })
172
                .collect::<Vec<_>>()
173
                .join(", ")
174
        }))
175
        .collect::<Vec<_>>()
176
        .join(", ")
177
}
178
179
/// Shame lives in a signed cookie so it follows the player across runs. Each response adds this
180
/// run's new shame to whatever total the client presents, so two runs at once both count.
181
fn settle_shame(run: &mut Run, ctx: &Ctx, secret: &Secret) -> u32 {
182
    let presented = ctx
183
        .cookie("shame")
184
        .and_then(|signed| secret.verify("shame", signed))
185
        .and_then(|total| total.parse::<u32>().ok());
186
    let total = presented.unwrap_or(run.shame_total) + (run.shame - run.shame_reported);
187
    run.shame_reported = run.shame;
188
    run.shame_total = total;
189
    total
190
}
191
192
pub fn finish(run: &mut Run, ctx: &Ctx, secret: &Secret, mut response: Response) -> Response {
193
    let status = response.status();
194
    if status == StatusCode::NOT_MODIFIED {
195
        return response;
196
    }
197
    let shame = settle_shame(run, ctx, secret);
198
    let mut stats: Vec<(HeaderName, String)> = vec![
199
        if run.items.ruler {
200
            (X_LENGTH, format!("{:.2}", run.current_length()))
201
        } else {
202
            (
203
                X_SELF_REPORTED_LENGTH,
204
                format!("{:.2}", run.self_reported()),
205
            )
206
        },
207
        (X_GIRTH, format!("{:.2}", run.girth)),
208
        (
209
            X_FORESKIN,
210
            run.foreskin.map_or("gone".into(), |f| format!("{f:.2}")),
211
        ),
212
        (X_FRICTION, format!("{}/{}", run.friction, FRICTION_MAX)),
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)),
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
    if run.conditions.friction_burn {
233
        stats.push((header::WARNING, "199 - \"friction burn\"".into()));
234
    }
235
    for notice in run.notices.drain(..) {
236
        stats.push((header::WARNING, format!("199 - \"{notice}\"")));
237
    }
238
    if run.eq > 70 && run.ended.is_none() {
239
        stats.push((header::WARNING, "199 - \"it is turning purple\"".into()));
240
    }
241
    stats.push((
242
        header::SET_COOKIE,
243
        format!(
244
            "shame={}; {COOKIE_ATTRIBUTES}",
245
            secret.sign("shame", &shame.to_string())
246
        ),
247
    ));
248
    if run.items.ruler {
249
        stats.push((
250
            header::SET_COOKIE,
251
            format!("ruler={}; {COOKIE_ATTRIBUTES}", secret.sign("ruler", "1")),
252
        ));
253
    }
254
    let headers = response.headers_mut();
255
    for (name, value) in stats {
256
        if let Ok(value) = HeaderValue::from_str(&value) {
257
            headers.append(name, value);
258
        }
259
    }
260
    let bodiless = status.is_informational() || status == StatusCode::NO_CONTENT;
261
    if run.items.ring && !bodiless {
262
        response.extensions_mut().insert(Compress);
263
    }
264
    response
265
}
266
267
fn greet(response: Response, ctx: &mut Ctx) -> Response {
268
    if response.status() != StatusCode::SWITCHING_PROTOCOLS {
269
        return response;
270
    }
271
    let (Some(Greeting(text)), Some(upgrade)) = (
272
        response.extensions().get::<Greeting>().cloned(),
273
        ctx.upgrade.take(),
274
    ) else {
275
        return response;
276
    };
277
    tokio::spawn(async move {
278
        if let Ok(upgraded) = upgrade.await {
279
            let mut io = TokioIo::new(upgraded);
280
            let _ = io.write_all(text.as_bytes()).await;
281
            let _ = io.shutdown().await;
282
        }
283
    });
284
    response
285
}