Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.1.280.1 KB2026-09-140.1.167.6 KB2026-09-140.1.064.9 KB2026-09-14
Version
0.1.2
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-09-14
Size
80.1 KB
Downloads
1
Checksum
65387e928cd11d6abf76cfb0f7a839dd3b2b7bb9cdbe78e7b058d3213d9fbcc2
Dependencies
None

session.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
//! セッション。クッキーには id だけを入れ、中身は置き場に保存する。
//!
//! 置き場は SESSION_STORE で選ぶ(none / memory / file / sqlite)。
//! 表の名前も置き場のディレクトリもクッキー名も、決め打ちにせず使う側が選べる。
//! id は 256 bit の乱数で、判定は置き場にあるかどうかなので署名はしない。
//!
//! 置き場には id そのものではなく、id の SHA-256 を鍵として入れる。
//! 表やファイルが漏れても、そこからクッキーの値はわからない。
//!
//! 発行は遅らせる。読むだけなら何も作らず、Set-Cookie も出さない。
//! 書いたときに初めて id を作り、保存し、クッキーを出す。
//! こうしないと、初めて来た相手 1 人につき 1 件、クローラの分まで溜まっていく。

use anyhow::{Context, bail};
use axum::Router;
use axum::extract::{FromRequestParts, Request, State};
use axum::http::request::Parts;
use axum::http::{HeaderValue, StatusCode, header};
use axum::middleware::Next;
use axum::response::Response;
use axum::routing::get;
use chrono::{DateTime, Utc};
use crate::conf::Conf;
use crate::error::{self, AppError};
use crate::extract::Json;
use crate::state::AppState;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use sqlx::SqlitePool;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use tokio::sync::RwLock;


/// 期限切れを掃除する間隔
const SWEEP_INTERVAL: Duration = Duration::from_secs(60 * 60);

/// id のバイト数
const ID_BYTES: usize = 32;

/// id の長さ(16 進で書いた 32 バイト)。置き場の鍵(SHA-256 を 16 進で書いたもの)も同じ長さになる
const ID_LENGTH: usize = ID_BYTES * 2;

/// 書きかけのファイルの名前に入れる乱数のバイト数
const TEMPORARY_BYTES: usize = 8;

/// POST /api/session で受け取る言語タグの長さの上限。BCP 47 が推奨する 35 字に合わせる
const LANGUAGE_LENGTH: usize = 35;


/// セッションに入れておくもの。項目はここに足す。
/// JSON で保存するので、足しても置き場の側は変わらない。
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionData {
    /// 利用者が選んだ言語
    pub language: Option<String>,
}

/// 置き場に入っている 1 件
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
    /// 入れておいたもの
    pub data: SessionData,
    /// 最後に保存した時刻。期限はここから測る
    pub updated_at: DateTime<Utc>,
}

/// 置き場。増やすときはここに 1 つ足すと、扱っていない場所をコンパイラが指す
#[derive(Clone)]
pub enum Store {
    /// セッションを使わない
    None,
    /// プロセスの中。再起動で消える。2 つ目の値は件数の上限(SESSION_MEMORY_LIMIT)
    Memory(Arc<RwLock<HashMap<String, Record>>>, usize),
    /// ディレクトリの中に `<鍵>.json` として置く
    File(PathBuf),
    /// SQLite の表に置く。表の名前も使う側が決める
    Sqlite(SqlitePool, String),
}

/// ハンドラが受け取るセッション。中身は共有なので Clone は安価である
#[derive(Clone)]
pub struct Session {
    inner: Arc<Mutex<Inner>>,
}

struct Inner {
    data: SessionData,
    changed: bool,
    destroyed: bool,
    renewed: bool,
    /// write() の戻り値がまだ手放されていないか
    writing: bool,
}

/// ハンドラが終わったあとに、handle が取り出すもの
struct Outcome {
    data: SessionData,
    changed: bool,
    destroyed: bool,
    renewed: bool,
}

/// POST /api/session の本文
#[derive(Debug, Deserialize)]
pub struct WriteSession {
    /// 入れ直す言語
    pub language: Option<String>,
}

/// GET と POST /api/session が返すもの。
/// SessionData をそのまま返すと、あとから足した項目まで相手に見えるので、返す項目はここで決める
#[derive(Debug, Serialize)]
struct SessionView {
    language: Option<String>,
}


/// セッションの表を用意する。sqlite を選んだときだけ効く。
/// 使う側のマイグレーションに混ざらないよう、この表はライブラリが自分で作る。
/// id の列には、id そのものではなく鍵(id の SHA-256)を入れる。
pub async fn prepare(store: &Store) -> anyhow::Result<()> {
    let Store::Sqlite(database, table) = store else {
        return Ok(());
    };

    sqlx::query(&format!(
        "create table if not exists {table} (\
         id text primary key not null, data text not null, updated_at text not null)"
    ))
    .execute(database)
    .await
    .with_context(|| format!("{table} の表を作れません"))?;

    sqlx::query(&format!(
        "create index if not exists {table}_updated_at on {table} (updated_at)"
    ))
    .execute(database)
    .await
    .with_context(|| format!("{table} の索引を作れません"))?;

    Ok(())
}


/// 設定から置き場を組み立てる
pub fn store(conf: &Conf, database: &SqlitePool) -> Store {
    match conf.session_store.as_str() {
        "memory" => Store::Memory(Arc::new(RwLock::new(HashMap::new())), conf.session_memory_limit),
        "file" => Store::File(PathBuf::from(&conf.session_directory)),
        "sqlite" => Store::Sqlite(database.clone(), conf.session_table.clone()),
        _ => Store::None,
    }
}


/// 1 件を読む。期限が切れていたら消して None を返す。
/// mon が出した形の id でなければ、置き場を見ずに None を返す
pub async fn load(store: &Store, id: &str, max_age: Duration) -> Option<Record> {
    if !is_id(id) {
        return None;
    }

    let key = key_of(id);
    let record = match store {
        Store::None => None,
        Store::Memory(map, _) => map.read().await.get(&key).cloned(),
        Store::File(directory) => read_file(directory, &key).await,
        Store::Sqlite(database, table) => read_row(database, table, &key).await,
    }?;

    if expired(&record, max_age) {
        if let Err(error) = remove(store, &key).await {
            tracing::warn!(error = ?error, "期限の切れたセッションを消せません");
        }

        return None;
    }

    Some(record)
}


/// 1 件を保存する。保存した時刻から期限を測り直す。
/// mon が出した形の id でなければ保存しない
pub async fn save(store: &Store, id: &str, data: &SessionData) -> anyhow::Result<()> {
    if !is_id(id) {
        bail!("セッションの id の形が違います");
    }

    let key = key_of(id);
    let record = Record {data: data.clone(), updated_at: Utc::now()};

    match store {
        Store::None => {}

        Store::Memory(map, limit) => {
            let mut map = map.write().await;

            // 新しい鍵を足すときだけ上限を見る。すでにあるものの書き換えは通す
            if !map.contains_key(&key) && map.len() >= *limit {
                bail!("memory の置き場が上限の {limit} 件に達しています");
            }

            map.insert(key, record);
        }

        Store::File(directory) => {
            write_file(directory, &key, serde_json::to_string(&record)?).await?;
        }

        Store::Sqlite(database, table) => {
            sqlx::query(&format!(
                "insert into {table} (id, data, updated_at) values (?, ?, ?) \
                 on conflict(id) do update set \
                 data = excluded.data, updated_at = excluded.updated_at"
            ))
            .bind(&key)
            .bind(serde_json::to_string(&record.data)?)
            .bind(record.updated_at)
            .execute(database)
            .await?;
        }
    }

    Ok(())
}


/// 1 件を消す。mon が出した形の id でなければ何もしない
pub async fn forget(store: &Store, id: &str) -> anyhow::Result<()> {
    if !is_id(id) {
        return Ok(());
    }

    remove(store, &key_of(id)).await
}


/// 鍵で 1 件を消す。もうなければ何もしない
async fn remove(store: &Store, key: &str) -> anyhow::Result<()> {
    match store {
        Store::None => {}

        Store::Memory(map, _) => {
            map.write().await.remove(key);
        }

        Store::File(directory) => {
            let result = tokio::fs::remove_file(file_path(directory, key)).await;
            if let Err(error) = result
                && error.kind() != std::io::ErrorKind::NotFound
            {
                return Err(error.into());
            }
        }

        Store::Sqlite(database, table) => {
            sqlx::query(&format!("delete from {table} where id = ?"))
                .bind(key)
                .execute(database)
                .await?;
        }
    }

    Ok(())
}


/// 期限切れを掃除する。
///
/// file の置き場では、mon が書いた形の名前のファイルだけを見る。
/// 同じディレクトリにあるほかのファイルやディレクトリには触らない。1 件消せなくても、残りの掃除は続ける。
pub async fn sweep(store: &Store, max_age: Duration) -> anyhow::Result<()> {
    match store {
        Store::None => {}

        Store::Memory(map, _) => {
            map.write().await.retain(|_, record| !expired(record, max_age));
        }

        Store::File(directory) => {
            let Ok(mut entries) = tokio::fs::read_dir(directory).await else {
                return Ok(());
            };

            while let Some(entry) = entries.next_entry().await? {
                if !entry.file_name().to_str().is_some_and(is_session_file) {
                    continue;
                }

                let Ok(detail) = entry.metadata().await else {
                    continue;
                };

                let stale = detail.is_file()
                    && detail
                        .modified()
                        .ok()
                        .and_then(|at| at.elapsed().ok())
                        .is_some_and(|age| age > max_age);

                if stale && let Err(error) = tokio::fs::remove_file(entry.path()).await {
                    tracing::warn!(error = ?error, "期限の切れたセッションを消せません");
                }
            }
        }

        Store::Sqlite(database, table) => {
            sqlx::query(&format!("delete from {table} where updated_at < ?"))
                .bind(limit_time(max_age))
                .execute(database)
                .await?;
        }
    }

    Ok(())
}


/// 起動してすぐ 1 回、そのあとは 1 時間ごとに掃除する
pub fn start_sweep(store: Store, max_age: Duration) {
    tokio::spawn(async move {
        let mut ticker = tokio::time::interval(SWEEP_INTERVAL);

        loop {
            ticker.tick().await;

            if let Err(error) = sweep(&store, max_age).await {
                tracing::warn!(error = ?error, "セッションを掃除できません");
            }
        }
    });
}


/// クッキーを読み、あれば中身を載せてハンドラへ渡す。
/// 書かれていたら保存し、Set-Cookie を付けて返す。
pub async fn handle(State(state): State<AppState>, mut request: Request, next: Next) -> Response {
    let conf = state.conf.clone();

    // 置き場がないなら、読み込みも発行もしない。空のセッションを渡してハンドラを通す
    if matches!(state.session, Store::None) {
        request.extensions_mut().insert(Session::new(SessionData::default()));
        return next.run(request).await;
    }

    let sent = cookie_value(request.headers(), &conf.session_cookie).filter(|value| is_id(value));

    // 覚えのない id は採らない。相手が決めた id をそのまま使うと、あとから乗っ取られる
    let found = match sent {
        Some(id) => load(&state.session, &id, conf.session_max_age)
            .await
            .map(|record| (id, record)),
        None => None,
    };

    let data = found
        .as_ref()
        .map(|(_, record)| record.data.clone())
        .unwrap_or_default();
    let session = Session::new(data);
    request.extensions_mut().insert(session.clone());

    let mut response = next.run(request).await;
    let outcome = session.outcome();

    if outcome.destroyed {
        // 消せないまま成功と返すと、相手はログアウトできたと思い込み、古い id も使えるまま残る
        if let Some((id, _)) = &found
            && let Err(error) = forget(&state.session, id).await
        {
            tracing::error!(error = ?error, "セッションを消せません");
            response = error::json(StatusCode::INTERNAL_SERVER_ERROR, "internal server error");
        }

        put_cookie(&mut response, &conf, "", Duration::ZERO);
        return response;
    }

    // 期限の半分を過ぎていたら、書き換えがなくても保存し直して先へ延ばす
    let halfway = found
        .as_ref()
        .is_some_and(|(_, record)| expired(record, max_age_half(conf.session_max_age)));

    // 保存しないなら、クッキーも出さない。読むだけの相手には何も出さず、
    // 変わっていないセッションにも付けない。毎回付けると共有キャッシュに載らなくなる
    if !outcome.changed && !halfway {
        return response;
    }

    // 作り直すなら、古いほうを先に捨てる
    if outcome.renewed
        && let Some((id, _)) = &found
        && let Err(error) = forget(&state.session, id).await
    {
        tracing::warn!(error = ?error, "作り直す前のセッションを消せません");
    }

    let id = match &found {
        Some((id, _)) if !outcome.renewed => id.clone(),
        _ => new_id(),
    };

    if let Err(error) = save(&state.session, &id, &outcome.data).await {
        tracing::error!(error = ?error, "セッションを保存できません");

        // ハンドラが書いたのに保存できなかったなら、成功とは返さない。返すと、相手は保存できたと思い込む。
        // 期限を延ばすための保存だけなら、ハンドラの応答はそのまま返す
        if outcome.changed {
            return error::json(StatusCode::INTERNAL_SERVER_ERROR, "internal server error");
        }

        return response;
    }

    put_cookie(&mut response, &conf, &id, conf.session_max_age);
    response
}


/// セッションを読む・書く・捨てるルート
pub fn router() -> Router<AppState> {
    Router::new().route("/", get(read).post(write).delete(destroy))
}


/// GET /api/session
async fn read(session: Session) -> Json<SessionView> {
    let data = session.read().await;
    Json(view(&data))
}


/// POST /api/session  `{"language": "ja"}`
async fn write(session: Session, Json(body): Json<WriteSession>) -> Result<Json<SessionView>, AppError> {
    // 長さを見ないと、1 件に BODY_LIMIT まで入り、置き場を埋められる
    if let Some(language) = &body.language
        && !is_language(language)
    {
        return Err(AppError::Validation(format!(
            "language は英数字と - で {LANGUAGE_LENGTH} 字以内にしてください"
        )));
    }

    let mut data = session.write().await;
    data.language = body.language;
    Ok(Json(view(&data)))
}


/// DELETE /api/session
async fn destroy(session: Session) -> StatusCode {
    session.destroy().await;
    StatusCode::NO_CONTENT
}


/// 相手に返す項目だけを取り出す
fn view(data: &SessionData) -> SessionView {
    SessionView {language: data.language.clone()}
}


impl Session {
    fn new(data: SessionData) -> Session {
        Session {
            inner: Arc::new(Mutex::new(Inner {
                data,
                changed: false,
                destroyed: false,
                renewed: false,
                writing: false,
            })),
        }
    }

    /// 中で panic しても中身が壊れる操作はないので、poison は気にせず使う
    fn lock(&self) -> MutexGuard<'_, Inner> {
        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn outcome(&self) -> Outcome {
        let inner = self.lock();

        Outcome {
            data: inner.data.clone(),
            changed: inner.changed,
            destroyed: inner.destroyed,
            renewed: inner.renewed,
        }
    }

    /// 中身の写しを見る。見るだけでは保存しない。
    /// write() の戻り値を持っている間に呼んでも待たないが、見えるのは書き戻す前の中身である
    pub async fn read(&self) -> SessionRead<'_> {
        SessionRead {data: self.lock().data.clone(), _session: PhantomData}
    }

    /// 中身を書き換える。呼んだ時点で保存する印が立ち、戻り値を手放したときに書き戻す。
    ///
    /// 戻り値を持ったまま read()、renew()、destroy() を呼んでも止まらない。
    /// 戻り値を 2 つ同時に持つと、先に手放したほうの書き換えが消えるので、そのときは panic する。
    pub async fn write(&self) -> SessionWrite<'_> {
        let mut inner = self.lock();

        if inner.writing {
            drop(inner);
            panic!("session.write() の戻り値を持ったまま、もう一度 write() を呼んでいます");
        }

        inner.writing = true;
        inner.changed = true;
        let data = inner.data.clone();
        drop(inner);

        SessionWrite {session: self, data}
    }

    /// 中身は残したまま、id だけ作り直す。
    ///
    /// ログインのように相手の立場が変わったところで呼ぶ。呼ばないと、
    /// 攻撃者が自分で取った id を相手のブラウザに置き、そのまま認証を通せる。
    /// mon は覚えのない id を採らないので id の捏造は防げるが、
    /// 正規に取った id を置かれる場合は、こちらで id を替えないと防げない。
    pub async fn renew(&self) {
        let mut inner = self.lock();
        inner.changed = true;
        inner.renewed = true;
    }

    /// 置き場から消し、クッキーも消す
    pub async fn destroy(&self) {
        let mut inner = self.lock();
        inner.data = SessionData::default();
        inner.destroyed = true;
    }
}


impl<S: Send + Sync> FromRequestParts<S> for Session {
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<Session>()
            .cloned()
            .ok_or_else(|| AppError::Internal(anyhow::anyhow!("セッションの層が掛かっていません")))
    }
}


/// read() が返す、中身の写し。[`SessionData`] としてそのまま扱える
pub struct SessionRead<'a> {
    data: SessionData,
    _session: PhantomData<&'a Session>,
}

/// write() が返す、書き換えるための写し。手放したときにセッションへ書き戻す
pub struct SessionWrite<'a> {
    session: &'a Session,
    data: SessionData,
}


impl Deref for SessionRead<'_> {
    type Target = SessionData;

    fn deref(&self) -> &SessionData {
        &self.data
    }
}


impl Deref for SessionWrite<'_> {
    type Target = SessionData;

    fn deref(&self) -> &SessionData {
        &self.data
    }
}


impl DerefMut for SessionWrite<'_> {
    fn deref_mut(&mut self) -> &mut SessionData {
        &mut self.data
    }
}


impl Drop for SessionWrite<'_> {
    fn drop(&mut self) {
        let mut inner = self.session.lock();
        inner.data = std::mem::take(&mut self.data);
        inner.writing = false;
    }
}


/// 32 バイトの乱数を 16 進で書いたもの
fn new_id() -> String {
    random_hex(ID_BYTES)
}


/// 自分が出した形の id かどうか。置き場の鍵も同じ形である
fn is_id(value: &str) -> bool {
    value.len() == ID_LENGTH && value.bytes().all(|byte| byte.is_ascii_hexdigit())
}


/// 置き場に入れるときの鍵。id の SHA-256 を 16 進で書いたもの。
/// 16 進の 64 字にしかならないので、ファイル名に使っても置き場の外を指すことはない
fn key_of(id: &str) -> String {
    hex(&Sha256::digest(id.as_bytes()))
}


/// mon が file の置き場に書く名前か。`<鍵>.json` と、書きかけの `<鍵>.<乱数>.tmp` の 2 つである
fn is_session_file(name: &str) -> bool {
    if let Some(stem) = name.strip_suffix(".json") {
        return is_id(stem);
    }

    let Some((stem, random)) = name.strip_suffix(".tmp").and_then(|rest| rest.split_once('.')) else {
        return false;
    };

    is_id(stem)
        && random.len() == TEMPORARY_BYTES * 2
        && random.bytes().all(|byte| byte.is_ascii_hexdigit())
}


/// 言語タグとして受け取れるか。英数字と `-` だけで、長さは LANGUAGE_LENGTH まで
fn is_language(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= LANGUAGE_LENGTH
        && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}


fn random_hex(length: usize) -> String {
    let mut seed = vec![0u8; length];
    getrandom::fill(&mut seed).expect("乱数を取れません");
    hex(&seed)
}


fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}


fn file_path(directory: &Path, key: &str) -> PathBuf {
    directory.join(format!("{key}.json"))
}


async fn read_file(directory: &Path, key: &str) -> Option<Record> {
    let text = tokio::fs::read_to_string(file_path(directory, key)).await.ok()?;
    serde_json::from_str(&text).ok()
}


/// 一時ファイルに書いてから、名前を変えて置き換える。
///
/// 直接上書きすると、書いている途中に読んだ側が空か途中までの JSON を読み、セッションがないものとして扱う。
/// ディレクトリは 0700、ファイルは 0600 で作り、同じマシンの別のユーザーから読めないようにする。
async fn write_file(directory: &Path, key: &str, text: String) -> anyhow::Result<()> {
    let directory = directory.to_owned();
    let key = key.to_owned();

    tokio::task::spawn_blocking(move || write_file_now(&directory, &key, &text))
        .await
        .context("セッションを書く処理が途中で止まりました")?
}


fn write_file_now(directory: &Path, key: &str, text: &str) -> anyhow::Result<()> {
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
    builder
        .create(directory)
        .with_context(|| format!("{} を作れません", directory.display()))?;

    let temporary = directory.join(format!("{key}.{}.tmp", random_hex(TEMPORARY_BYTES)));
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);

    let written = options
        .open(&temporary)
        .and_then(|mut file| std::io::Write::write_all(&mut file, text.as_bytes()))
        .and_then(|()| std::fs::rename(&temporary, file_path(directory, key)));

    if let Err(error) = written {
        // 書きかけを残さない。消せなくても、期限が切れれば掃除が消す
        let _ = std::fs::remove_file(&temporary);
        return Err(error).with_context(|| format!("{key}.json を書けません"));
    }

    Ok(())
}


async fn read_row(database: &SqlitePool, table: &str, key: &str) -> Option<Record> {
    let row: Option<(String, DateTime<Utc>)> =
        sqlx::query_as(&format!("select data, updated_at from {table} where id = ?"))
            .bind(key)
            .fetch_optional(database)
            .await
            .ok()?;

    let (data, updated_at) = row?;
    Some(Record {data: serde_json::from_str(&data).ok()?, updated_at})
}


fn expired(record: &Record, max_age: Duration) -> bool {
    (Utc::now() - record.updated_at)
        .to_std()
        .is_ok_and(|age| age > max_age)
}


fn max_age_half(max_age: Duration) -> Duration {
    max_age / 2
}


fn limit_time(max_age: Duration) -> DateTime<Utc> {
    Utc::now() - chrono::Duration::from_std(max_age).unwrap_or(chrono::Duration::zero())
}


fn cookie_value(headers: &axum::http::HeaderMap, name: &str) -> Option<String> {
    let header = headers.get(header::COOKIE)?.to_str().ok()?;
    let prefix = format!("{name}=");

    for part in header.split(';') {
        let trimmed = part.trim();

        if let Some(value) = trimmed.strip_prefix(&prefix) {
            return Some(value.to_owned());
        }
    }

    None
}


fn put_cookie(response: &mut Response, conf: &Conf, id: &str, max_age: Duration) {
    let mut line = format!(
        "{}={}; Path=/; HttpOnly; SameSite={}; Max-Age={}",
        conf.session_cookie,
        id,
        same_site(&conf.session_same_site),
        max_age.as_secs()
    );

    if conf.session_secure {
        line.push_str("; Secure");
    }

    if let Ok(value) = HeaderValue::from_str(&line) {
        response.headers_mut().append(header::SET_COOKIE, value);
        keep_private(response);
    }
}


/// Set-Cookie を付けた応答を、共有キャッシュに保存させない。
///
/// Set-Cookie があっても、共有キャッシュは応答を保存してよいことになっている(RFC 9111)。
/// 保存されると、ある人の sid が別の人に返る。静的ファイルの応答にも、期限を延ばすときは Set-Cookie が付く。
/// private はブラウザ自身のキャッシュには保存させるので、本人が読み直すときはそのまま速い。
fn keep_private(response: &mut Response) {
    let current = response
        .headers()
        .get(header::CACHE_CONTROL)
        .and_then(|value| value.to_str().ok())
        .unwrap_or("")
        .to_owned();

    // public と s-maxage は共有キャッシュに向けた指定なので外す
    let mut directive: Vec<&str> = current
        .split(',')
        .map(str::trim)
        .filter(|one| !one.is_empty() && !is_shared_directive(one))
        .collect();

    let private = directive
        .iter()
        .any(|one| one.eq_ignore_ascii_case("private") || one.eq_ignore_ascii_case("no-store"));
    if !private {
        directive.insert(0, "private");
    }

    if let Ok(value) = HeaderValue::from_str(&directive.join(", ")) {
        response.headers_mut().insert(header::CACHE_CONTROL, value);
    }
}


/// 共有キャッシュだけに向けた指定か
fn is_shared_directive(directive: &str) -> bool {
    let name = directive.split('=').next().unwrap_or("").trim();
    name.eq_ignore_ascii_case("public") || name.eq_ignore_ascii_case("s-maxage")
}


fn same_site(value: &str) -> &'static str {
    match value {
        "strict" => "Strict",
        "none" => "None",
        _ => "Lax",
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use std::time::SystemTime;

    #[test]
    fn the_key_is_not_the_id() {
        let id = new_id();
        let key = key_of(&id);

        assert!(is_id(&key));
        assert_ne!(key, id);
    }

    #[test]
    fn only_session_file_names_are_recognized() {
        let key = key_of(&new_id());

        assert!(is_session_file(&format!("{key}.json")));
        assert!(is_session_file(&format!("{key}.0123456789abcdef.tmp")));
        assert!(!is_session_file("notes.txt"));
        assert!(!is_session_file("Cargo.toml"));
        assert!(!is_session_file(&format!("{key}.txt")));
        assert!(!is_session_file(&format!("{key}.xyz.tmp")));
    }

    #[test]
    fn a_language_tag_is_short_and_plain() {
        assert!(is_language("ja"));
        assert!(is_language("zh-Hant-TW"));
        assert!(!is_language(""));
        assert!(!is_language(&"a".repeat(LANGUAGE_LENGTH + 1)));
        assert!(!is_language("ja;"));
    }

    /// 掃除は、mon が書いた形の名前のものしか消さない
    #[tokio::test]
    async fn the_sweep_leaves_other_files() {
        let directory = PathBuf::from("target/test-sweep");
        std::fs::create_dir_all(&directory).unwrap();

        let foreign = directory.join("notes.txt");
        let session = directory.join(format!("{}.json", key_of(&new_id())));
        std::fs::write(&foreign, "keep").unwrap();
        std::fs::write(&session, "{}").unwrap();

        let old = SystemTime::now() - Duration::from_secs(60 * 60 * 48);
        for path in [&foreign, &session] {
            let file = std::fs::File::options().write(true).open(path).unwrap();
            file.set_modified(old).unwrap();
        }

        sweep(&Store::File(directory), Duration::from_secs(60 * 60 * 24)).await.unwrap();

        assert!(foreign.exists());
        assert!(!session.exists());
    }

    /// file の置き場は、同じマシンの別のユーザーから読めない権限で書く
    #[cfg(unix)]
    #[tokio::test]
    async fn a_session_file_is_private() {
        use std::os::unix::fs::PermissionsExt;

        let directory = PathBuf::from("target/test-session-mode");
        let id = new_id();
        save(&Store::File(directory.clone()), &id, &SessionData::default()).await.unwrap();

        let file = std::fs::metadata(directory.join(format!("{}.json", key_of(&id)))).unwrap();
        assert_eq!(file.permissions().mode() & 0o777, 0o600);

        let folder = std::fs::metadata(&directory).unwrap();
        assert_eq!(folder.permissions().mode() & 0o777, 0o700);
    }

    /// id の形でないものは、置き場に書かない。ディレクトリの外を指すこともできない
    #[tokio::test]
    async fn a_malformed_id_is_not_saved() {
        let store = Store::File(PathBuf::from("target/test-session-malformed"));

        assert!(save(&store, "../escape", &SessionData::default()).await.is_err());
        assert!(load(&store, "../escape", Duration::from_secs(60)).await.is_none());
    }

    /// write() の戻り値を持ったままでも、read() と renew() は待たない
    #[tokio::test]
    async fn writing_does_not_block_reading_or_renewing() {
        let session = Session::new(SessionData::default());
        let mut data = session.write().await;
        data.language = Some("ja".to_owned());

        assert_eq!(session.read().await.language, None);
        session.renew().await;
        drop(data);

        let outcome = session.outcome();
        assert_eq!(outcome.data.language.as_deref(), Some("ja"));
        assert!(outcome.changed && outcome.renewed);
    }

    /// 書き換えの写しを 2 つ同時に持つと、片方の書き換えが消えるので止める
    #[tokio::test]
    #[should_panic(expected = "もう一度 write()")]
    async fn writing_twice_at_once_panics() {
        let session = Session::new(SessionData::default());
        let _first = session.write().await;
        let _second = session.write().await;
    }

    /// Set-Cookie を付けた応答は private にし、共有キャッシュ向けの指定を外す
    #[test]
    fn a_cookie_answer_becomes_private() {
        let mut response = Response::new(Body::empty());
        response.headers_mut().insert(
            header::CACHE_CONTROL,
            HeaderValue::from_static("public, max-age=31536000, immutable"),
        );
        keep_private(&mut response);
        assert_eq!(response.headers()[header::CACHE_CONTROL], "private, max-age=31536000, immutable");

        let mut response = Response::new(Body::empty());
        keep_private(&mut response);
        assert_eq!(response.headers()[header::CACHE_CONTROL], "private");

        let mut response = Response::new(Body::empty());
        response.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
        keep_private(&mut response);
        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
    }
}