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
use dashmap::{DashMap, DashSet};

use crate::*;

#[derive(Clone)]
pub struct ViewCount {
    articles: Arc<DashMap<String, (bool, u64)>>,
    ips: Arc<DashMap<String, DashSet<IpAddr>>>,
}

async fn parse(s: &str) -> Option<ViewCount> {
    let s = tokio::fs::read_to_string(s).await.ok()?;

    let articles = DashMap::new();
    for l in s.lines().skip(1) {
        // rsplit so the commas in article don't skrew with us
        let (article, count) = l.rsplit_once(',')?;
        let article = if article.contains("\\,")
            || article.contains("\\\\")
            || article.contains("\\\n")
            || article.contains("\\\r")
        {
            article
                .replace("\\\\", "\\")
                .replace("\\,", ",")
                .replace("\\n", "\n")
                .replace("\\r", "\r")
        } else {
            article.to_owned()
        };
        let count = count.parse().ok()?;
        articles.insert(article, (false, count));
    }
    Some(ViewCount {
        articles: Arc::new(articles),
        ips: Arc::new(DashMap::new()),
    })
}

pub async fn mount(
    extensions: &mut Extensions,
    predicate: impl Fn(&FatRequest) -> bool + Send + Sync + 'static,
    log_file_name: impl Into<String>,
    commit_interval: Duration,
    accept_same_ip_interval: Duration,
) -> ViewCount {
    let predicate = Box::new(predicate);
    let path = log_file_name.into();
    let total_path = format!("{path}-totals.csv");
    let changes_path = format!("{path}-history.csv");

    let view_count = match parse(&total_path).await {
        Some(x) => x,
        None => {
            #[cfg(feature = "uring")]
            let path_exists = tokio_uring::fs::statx(&total_path).await.is_ok();
            #[cfg(not(feature = "uring"))]
            let path_exists = tokio::fs::metadata(&total_path).await.is_ok();

            if path_exists {
                warn!("Overriding view count total at '{total_path}'");
            }
            ViewCount {
                articles: Arc::new(DashMap::new()),
                ips: Arc::new(DashMap::new()),
            }
        }
    };

    {
        let c = view_count.clone();
        let _task = spawn(async move {
            loop {
                tokio::time::sleep(commit_interval).await;

                let mut any_changed = false;
                for v in c.articles.iter() {
                    if v.0 {
                        any_changed = true;
                    }
                }
                if any_changed {
                    #[allow(unused_mut)] // uring doesn't mutate
                    let mut file = match fs::OpenOptions::new()
                        .create(true)
                        .write(true)
                        .append(true)
                        .open(&changes_path)
                        .await
                    {
                        Err(err) => {
                            error!(
                            "Failed to open file to log view count history ('{changes_path}'): {err:?}"
                        );
                            break;
                        }
                        Ok(f) => f,
                    };
                    #[cfg(feature = "uring")]
                    let size = tokio_uring::fs::statx(&changes_path)
                        .await
                        .expect("Failed to get stat for view counter changes file").stx_size;
                    #[cfg(not(feature = "uring"))]
                    let size = tokio::fs::metadata(&changes_path)
                        .await
                        .expect("Failed to get stat for view counter changes file").len();


                    let mut data = String::new();

                    if size == 0 {
                        data.push_str("article path,view count,Rfc3339 date\n");
                    }
                    let now = chrono::OffsetDateTime::now_utc()
                        .replace_nanosecond(0)
                        .unwrap();
                    let date = now
                        .format(&chrono::time::format_description::well_known::Rfc3339)
                        .unwrap();
                    for mut v in c.articles.iter_mut() {
                        let (article, (changed, count)) = v.pair_mut();

                        if *changed {
                            *changed = false;
                            let count = *count;
                            let line = if article.contains(',')
                                || article.contains('\\')
                                || article.contains('\n')
                                || article.contains('\r')
                            {
                                let article = article.replace('\\', "\\\\");
                                let article = article.replace(',', "\\,");
                                let article = article.replace('\n', "\\n");
                                let article = article.replace('\r', "\\r");

                                format!("{article},{count},{date}\n")
                            } else {
                                format!("{article},{count},{date}\n")
                            };
                            debug!("Add to history: {:?}", line.trim_end());
                            data.push_str(&line);
                        }
                    }

                    #[cfg(feature = "uring")]
                    file.write_all_at(data.into_bytes(), 0).await.0.unwrap();
                    #[cfg(not(feature = "uring"))]
                    file.write_all(data.as_bytes()).await.unwrap();

                    drop(file);
                    debug!("Updating total");
                    #[allow(unused_mut)] // uring doesn't mutate
                    let mut file = match fs::File::create(&total_path).await {
                        Err(err) => {
                            error!(
                            "Failed to open file to log view count history ('{changes_path}'): {err:?}"
                        );
                            break;
                        }
                        Ok(f) => f,
                    };
                    let mut data = b"article path,view count\n".to_vec();
                    for v in c.articles.iter() {
                        let count = v.1;
                        let article = v.key();
                        let line = if article.contains(',')
                            || article.contains('\\')
                            || article.contains('\n')
                            || article.contains('\r')
                        {
                            let article = article.replace('\\', "\\\\");
                            let article = article.replace(',', "\\,");
                            let article = article.replace('\n', "\\n");
                            let article = article.replace('\r', "\\r");

                            format!("{article},{count}\n")
                        } else {
                            format!("{article},{count}\n")
                        };
                        data.append(&mut line.into_bytes());
                    }
                    #[cfg(feature = "uring")]
                    file.write_all_at(data, 0).await.0.unwrap();
                    #[cfg(not(feature = "uring"))]
                    file.write_all(&data).await.unwrap();
                    drop(file);
                }
            }
        }).await;
    }
    {
        let c = view_count.clone();
        threading::spawn(async move {
            loop {
                tokio::time::sleep(accept_same_ip_interval).await;
                c.ips.clear();
            }
        });
    }

    let c = view_count.clone();
    extensions.add_post(
        post!(
            request,
            _host,
            _response_pipe,
            _identity_body,
            addr,
            move |c: ViewCount,
                  predicate: Box<dyn Fn(&FatRequest) -> bool + Send + Sync + 'static>| {
                let c: &ViewCount = c;
                if !predicate(request)
                    || c.ips
                        .get(request.uri().path())
                        .map_or(false, |ips| ips.contains(&addr.ip()))
                {
                    return;
                }
                let mut ips = None;
                while ips.is_none() {
                    ips = c.ips.get(request.uri().path());
                    if ips.is_none() {
                        c.ips
                            .insert(request.uri().path().to_owned(), DashSet::new());
                    }
                }
                let ips = ips.unwrap();
                ips.insert(addr.ip());
                let mut count = c
                    .articles
                    .entry(request.uri().path().to_string())
                    .or_insert((false, 0));
                count.0 = true;
                count.1 += 1;
            }
        ),
        Id::new(-1024, "View counter").no_override(),
    );
    let c = view_count.clone();
    extensions.add_present_internal(
        "view-counter",
        present!(args, move |c: ViewCount| {
            let needle = b"${view-count}";
            let mut pos = 0;
            let mut view_count = None;
            while let Some(idx) = memchr::memmem::find(&args.response.body()[pos..], needle) {
                let idx = pos + idx;
                pos = idx;
                let view_count = match &view_count {
                    Some(v) => v,
                    None => {
                        let article = args.request.uri().path();
                        let n = c.articles.get(article).map_or(1, |v| v.1);
                        view_count.insert(n.to_string())
                    }
                };
                args.response
                    .body_mut()
                    .replace(idx..idx + needle.len(), view_count.as_bytes());
            }
        }),
    );
    view_count
}
pub fn starts_with_predicate(
    starts_with: impl Into<String>,
) -> impl Fn(&FatRequest) -> bool + Send + Sync + 'static {
    let path = starts_with.into();
    move |request| {
        request.uri().path().ends_with(".html") && request.uri().path().starts_with(&path)
    }
}