about summary refs log tree commit diff
path: root/corp/rih/backend/src/main.rs
blob: 28e4e8dfde00b8d84dfc5466e51a2b38c4cfbb4d (plain) (blame)
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
use anyhow::{bail, Context, Result};
use rouille::{Request, Response};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::env;
use std::net::SocketAddr;
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;

/// Represents a single record as filled in by a user. This is the
/// primary data structure we want to populate and persist somewhere.
#[derive(Debug, Deserialize, Serialize)]
struct Record {
    // Record-specific metadata
    uuid: Uuid,

    // Personal information
    name: String,
    email: String,
    citizenship: String, // TODO
    personal_details: String,

    // Job information
    position: String,
    technologies: BTreeSet<String>,
    job_details: String,
    work_background: String,
}

impl Record {
    fn validate(&self) -> bool {
        true
    }
}

fn persist_record(ip: &SocketAddr, record: &Record) -> Result<()> {
    let bucket_name = "rih-backend-data";
    let credentials = s3::creds::Credentials::from_env()?;
    let yandex_region: s3::Region = s3::Region::Custom {
        region: "ru-central1".to_string(),
        endpoint: "storage.yandexcloud.net".to_string(),
    };

    let bucket = s3::Bucket::new(bucket_name, yandex_region, credentials)?;

    let path_uuid = Uuid::new_v4();
    let epoch = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
    let path = format!("/records/{}-{}.json", epoch, path_uuid);

    let data = serde_json::json!({
        "ip": ip.to_string(),
        "record": record,
    });

    let _response = bucket.put_object(path, data.to_string().as_bytes());
    Ok(())
}

fn handle_submit(req: &Request) -> Result<Response> {
    let record: Record = rouille::input::json::json_input(req)?;

    if !record.validate() {
        bail!("invalid record: {:?}", record);
    }

    persist_record(req.remote_addr(), &record)?;

    Ok(Response::text("success"))
}

fn main() -> Result<()> {
    let port = env::var("PORT").unwrap_or_else(|_| /* rihb = */ "7442".to_string());
    let listen = format!("0.0.0.0:{port}");
    rouille::start_server(&listen, move |request| {
        if request.url() == "/submit" {
            match handle_submit(request) {
                Ok(response) => response,
                Err(_err) => Response::empty_400(), // TODO
            }
        } else {
            Response::empty_404()
        }
    });
}