aboutsummaryrefslogtreecommitdiffstats
path: root/cms-backd/src/comm.rs
blob: ab9f28a615be92085c19258f5a4f766c7b5733ba (plain)
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
// -*- coding: utf-8 -*-
//
// Simple CMS
//
// Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use anyhow::{self as ah, format_err as err, Context as _};
use chrono::prelude::*;
use cms_ident::{CheckedIdent, CheckedIdentElem, Tail};
use cms_socket::{CmsSocketConn, MsgSerde as _};
use cms_socket_db::{Msg as MsgDb, SOCK_FILE as SOCK_FILE_DB};
use cms_socket_post::{Msg as MsgPost, SOCK_FILE as SOCK_FILE_POST};
use lru::LruCache;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};

const DEBUG: bool = false;
const MACRO_CACHE_SIZE: usize = 512;

fn epoch_stamp(seconds: u64) -> DateTime<Utc> {
    DateTime::from_timestamp(seconds.try_into().unwrap_or_default(), 0).unwrap_or_default()
}

#[derive(Clone, Debug, Default)]
pub struct CommGetPage {
    pub path: CheckedIdent,
    pub get_title: bool,
    pub get_data: bool,
    pub get_stamp: bool,
    pub get_redirect: bool,
}

#[derive(Clone, Debug, Default)]
pub struct CommPage {
    pub title: Option<String>,
    pub data: Option<String>,
    pub stamp: Option<DateTime<Utc>>,
    pub redirect: Option<String>,
}

#[derive(Clone, Debug, Default)]
pub struct CommSubPages {
    pub names: Vec<String>,
    pub nav_labels: Vec<String>,
    pub nav_stops: Vec<bool>,
    pub stamps: Vec<DateTime<Utc>>,
    pub prios: Vec<u64>,
}

#[derive(Clone, Debug, Default)]
pub struct CommRunPostHandler {
    pub path: CheckedIdent,
    pub query: HashMap<String, Vec<u8>>,
    pub form_fields: HashMap<String, Vec<u8>>,
}

#[derive(Clone, Debug, Default)]
pub struct CommPostHandlerResult {
    pub error: String,
    pub body: Vec<u8>,
    pub mime: String,
}

/// Communication with database and post handler.
pub struct CmsComm {
    sock_path_db: PathBuf,
    sock_path_post: PathBuf,
    sock_db: Option<CmsSocketConn>,
    sock_post: Option<CmsSocketConn>,
    macro_cache: LruCache<String, String>,
}

impl CmsComm {
    pub fn new(rundir: &Path) -> Self {
        let sock_path_db = rundir.join(SOCK_FILE_DB);
        let sock_path_post = rundir.join(SOCK_FILE_POST);
        Self {
            sock_path_db,
            sock_path_post,
            sock_db: None,
            sock_post: None,
            macro_cache: LruCache::new(MACRO_CACHE_SIZE.try_into().unwrap()),
        }
    }

    async fn sock_db(&mut self) -> ah::Result<&mut CmsSocketConn> {
        if self.sock_db.is_none() {
            self.sock_db = Some(CmsSocketConn::connect(&self.sock_path_db).await?);
        }
        Ok(self.sock_db.as_mut().unwrap())
    }

    async fn sock_post(&mut self) -> ah::Result<&mut CmsSocketConn> {
        if self.sock_post.is_none() {
            self.sock_post = Some(CmsSocketConn::connect(&self.sock_path_post).await?);
        }
        Ok(self.sock_post.as_mut().unwrap())
    }

    async fn comm_db(&mut self, request: &MsgDb) -> ah::Result<MsgDb> {
        if DEBUG {
            println!("DB comm: {request:?}");
        }
        let sock = self.sock_db().await?;
        sock.send_msg(request).await?;
        if let Some(reply) = sock.recv_msg(MsgDb::try_msg_deserialize).await? {
            Ok(reply)
        } else {
            Err(err!("cms-fsd disconnected"))
        }
    }

    async fn comm_post(&mut self, request: &MsgPost) -> ah::Result<MsgPost> {
        if DEBUG {
            println!("Post comm: {request:?}");
        }
        let sock = self.sock_post().await?;
        sock.send_msg(request).await?;
        if let Some(reply) = sock.recv_msg(MsgPost::try_msg_deserialize).await? {
            Ok(reply)
        } else {
            Err(err!("cms-postd disconnected"))
        }
    }

    pub async fn get_db_page(&mut self, get: CommGetPage) -> ah::Result<CommPage> {
        let reply = self
            .comm_db(&MsgDb::GetPage {
                path: get.path.downgrade_clone(),
                get_title: get.get_title,
                get_data: get.get_data,
                get_stamp: get.get_stamp,
                get_redirect: get.get_redirect,
            })
            .await;
        if let Ok(MsgDb::Page {
            title,
            data,
            stamp,
            redirect,
        }) = reply
        {
            Ok(CommPage {
                title: title.and_then(|x| String::from_utf8(x).ok()),
                data: data.and_then(|x| String::from_utf8(x).ok()),
                stamp: stamp.map(epoch_stamp),
                redirect: redirect.and_then(|x| String::from_utf8(x).ok()),
            })
        } else {
            Err(err!("Page: Invalid db reply."))
        }
    }

    pub async fn get_db_sub_pages(&mut self, path: &CheckedIdent) -> ah::Result<CommSubPages> {
        let reply = self
            .comm_db(&MsgDb::GetSubPages {
                path: path.downgrade_clone(),
                get_nav_labels: true,
                get_nav_stops: true,
                get_stamps: true,
                get_prios: true,
            })
            .await;
        if let Ok(MsgDb::SubPages {
            names,
            nav_labels,
            nav_stops,
            stamps,
            prios,
        }) = reply
        {
            let count = names.len();
            if nav_labels.len() == count
                && nav_stops.len() == count
                && stamps.len() == count
                && prios.len() == count
            {
                Ok(CommSubPages {
                    names: names
                        .into_iter()
                        .map(|x| String::from_utf8(x).unwrap_or_default())
                        .collect(),
                    nav_labels: nav_labels
                        .into_iter()
                        .map(|x| String::from_utf8(x).unwrap_or_default())
                        .collect(),
                    nav_stops,
                    stamps: stamps.into_iter().map(epoch_stamp).collect(),
                    prios,
                })
            } else {
                Err(err!("GetSubPages: Invalid db reply (length)."))
            }
        } else {
            Err(err!("GetSubPages: Invalid db reply."))
        }
    }

    pub async fn get_db_headers(&mut self, path: &CheckedIdent) -> ah::Result<String> {
        let reply = self
            .comm_db(&MsgDb::GetHeaders {
                path: path.downgrade_clone(),
            })
            .await;
        if let Ok(MsgDb::Headers { data }) = reply {
            Ok(String::from_utf8(data).context("Headers: Data is not valid UTF-8")?)
        } else {
            Err(err!("Headers: Invalid db reply."))
        }
    }

    pub async fn get_db_string(&mut self, name: &str) -> ah::Result<String> {
        let reply = self
            .comm_db(&MsgDb::GetString {
                name: name.parse().context("Invalid DB string name")?,
            })
            .await;
        if let Ok(MsgDb::String { data }) = reply {
            Ok(String::from_utf8(data).context("String: Data is not valid UTF-8")?)
        } else {
            Err(err!("String: Invalid db reply."))
        }
    }

    pub async fn get_db_macro(
        &mut self,
        parent: Option<&CheckedIdent>,
        name: &CheckedIdentElem,
    ) -> ah::Result<String> {
        let cache_name = if let Some(parent) = parent {
            parent.to_fs_path(Path::new(""), &Tail::One(name.clone()))
        } else {
            name.to_fs_path(Path::new(""), &Tail::None)
        };
        let cache_name = cache_name.into_os_string().into_string().unwrap();

        // Try to get it from the cache.
        if let Some(data) = self.macro_cache.get(&cache_name) {
            return Ok(data.clone());
        }

        let reply = self
            .comm_db(&MsgDb::GetMacro {
                parent: parent.unwrap_or(&CheckedIdent::ROOT).downgrade_clone(),
                name: name.downgrade_clone(),
            })
            .await;
        if let Ok(MsgDb::Macro { data }) = reply {
            let data = String::from_utf8(data).context("Macro: Data is not valid UTF-8")?;

            // Put it into the cache.
            self.macro_cache.push(cache_name, data.clone());
            Ok(data)
        } else {
            Err(err!("Macro: Invalid db reply."))
        }
    }

    pub async fn get_db_image(&mut self, name: &CheckedIdentElem) -> ah::Result<Vec<u8>> {
        let reply = self
            .comm_db(&MsgDb::GetImage {
                name: name.downgrade_clone(),
            })
            .await;
        if let Ok(MsgDb::Image { data }) = reply {
            Ok(data)
        } else {
            Err(err!("Image: Invalid db reply."))
        }
    }

    pub async fn run_post_handler(
        &mut self,
        run: CommRunPostHandler,
    ) -> ah::Result<CommPostHandlerResult> {
        let reply = self
            .comm_post(&MsgPost::RunPostHandler {
                path: run.path.downgrade_clone(),
                query: run.query,
                form_fields: run.form_fields,
            })
            .await;
        if let Ok(MsgPost::PostHandlerResult { error, body, mime }) = reply {
            Ok(CommPostHandlerResult { error, body, mime })
        } else {
            Err(err!("RunPostHandler: Invalid postd reply."))
        }
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface