about summary refs log tree commit diff
path: root/web/atward/src/main.rs
blob: 94e9fff9bc71cb9d9dd34c86922a70ffb01f24ef (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
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
//! Atward implements TVL's redirection service, living at
//! atward.tvl.fyi
//!
//! This service is designed to be added as a search engine to web
//! browsers and attempts to send users to useful locations based on
//! their search query (falling back to another search engine).
use regex::Regex;
use rouille::input::cookies;
use rouille::{Request, Response};

/// A query handler supported by atward. It consists of a pattern on
/// which to match and trigger the query, and a function to execute
/// that returns the target URL.
struct Handler {
    /// Regular expression on which to match the query string.
    pattern: Regex,

    /// Function to construct the target URL. If the pattern matches,
    /// this is invoked with the captured matches and the entire URI.
    ///
    /// Returning `None` causes atward to fall through to the next
    /// query (and eventually to the default search engine).
    target: for<'s> fn(&Query, regex::Captures<'s>) -> Option<String>,
}

/// An Atward query supplied by a user.
#[derive(Debug, PartialEq)]
struct Query {
    /// Query string itself.
    query: String,

    /// Should Sourcegraph be used instead of cgit?
    cs: bool,
}

/// Helper function for setting a parameter based on a query
/// parameter.
fn query_setting(req: &Request, config: &mut bool, param: &str) {
    match req.get_param(param) {
        Some(s) if s == "true" => *config = true,
        Some(s) if s == "false" => *config = false,
        _ => {}
    }
}

impl Query {
    fn from_request(req: &Request) -> Option<Query> {
        // First extract the actual search query ...
        let mut query = match req.get_param("q") {
            Some(query) => Query { query, cs: false },
            None => return None,
        };

        // ... then apply settings to it. Settings in query parameters
        // take precedence over cookies.
        for cookie in cookies(req) {
            match cookie {
                ("cs", "true") => {
                    query.cs = true;
                }
                _ => {}
            }
        }

        query_setting(req, &mut query.cs, "cs");

        Some(query)
    }
}

#[cfg(test)]
impl From<&str> for Query {
    fn from(query: &str) -> Query {
        Query {
            query: query.to_string(),
            cs: false,
        }
    }
}

/// Create a URL to a file (and, optionally, specific line) in cgit.
fn cgit_url(path: &str) -> String {
    if path.ends_with(".md") {
        format!("https://code.tvl.fyi/about/{}", path)
    } else {
        format!("https://code.tvl.fyi/tree/{}", path)
    }
}

/// Create a URL to a path in Sourcegraph.
fn sourcegraph_path_url(path: &str) -> String {
    format!("https://cs.tvl.fyi/depot/-/tree/{}", path)
}

/// Definition of all supported query handlers in atward.
fn handlers() -> Vec<Handler> {
    vec![
        // Bug IDs (e.g. b/123)
        Handler {
            pattern: Regex::new("^b/(?P<bug>\\d+)$").unwrap(),
            target: |_, captures| Some(format!("https://b.tvl.fyi/{}", &captures["bug"])),
        },
        // Changelists (e.g. cl/42)
        Handler {
            pattern: Regex::new("^cl/(?P<cl>\\d+)$").unwrap(),
            target: |_, captures| Some(format!("https://cl.tvl.fyi/{}", &captures["cl"])),
        },
        // Non-parameterised short hostnames should redirect to $host.tvl.fyi
        Handler {
            pattern: Regex::new("^(?P<host>b|cl|cs|code|at|todo)$").unwrap(),
            target: |_, captures| Some(format!("https://{}.tvl.fyi/", &captures["host"])),
        },
        // Depot paths (e.g. //web/atward or //ops/nixos/whitby/default.nix)
        // TODO(tazjin): Add support for specifying lines in a query parameter
        Handler {
            pattern: Regex::new("^//(?P<path>[a-zA-Z].*)?$").unwrap(),
            target: |query, captures| {
                // Pass an empty string if the path is missing, to
                // redirect to the depot root.
                let path = captures.name("path")
                    .map(|m| m.as_str())
                    .unwrap_or("");

                if query.cs {
                    Some(sourcegraph_path_url(path))
                } else {
                    Some(cgit_url(path))
                }
            },
        },
    ]
}

/// Attempt to match against all known query types, and return the
/// destination URL if one is found.
fn dispatch(handlers: &[Handler], query: &Query) -> Option<String> {
    for handler in handlers {
        if let Some(captures) = handler.pattern.captures(&query.query) {
            if let Some(destination) = (handler.target)(query, captures) {
                return Some(destination);
            }
        }
    }

    None
}

/// Return the opensearch.xml file which is required for adding atward
/// as a search engine in Firefox.
fn opensearch() -> Response {
    Response::text(include_str!("opensearch.xml"))
        .with_unique_header("Content-Type", "application/opensearchdescription+xml")
}

/// Render the atward index page which gives users some information
/// about how to use the service.
fn index() -> Response {
    Response::html(include_str!(env!("ATWARD_INDEX_HTML")))
}

/// Render the fallback page which informs users that their query is
/// unsupported.
fn fallback() -> Response {
    Response::text("error for emphasis that i am angery and the query whimchst i angery atward")
        .with_status_code(404)
}

fn main() {
    let queries = handlers();
    let address = std::env::var("ATWARD_LISTEN_ADDRESS")
        .expect("ATWARD_LISTEN_ADDRESS environment variable must be set");

    rouille::start_server(&address, move |request| {
        rouille::log(&request, std::io::stderr(), || {
            if request.url() == "/opensearch.xml" {
                return opensearch();
            }

            let query = match Query::from_request(&request) {
                Some(q) => q,
                None => return index(),
            };

            match dispatch(&queries, &query) {
                None => fallback(),
                Some(destination) => Response::redirect_303(destination),
            }
        })
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bug_query() {
        assert_eq!(
            dispatch(&handlers(), &"b/42".into()),
            Some("https://b.tvl.fyi/42".to_string())
        );

        assert_eq!(
            dispatch(&handlers(), &"something only mentioning b/42".into()),
            None,
        );
        assert_eq!(dispatch(&handlers(), &"b/invalid".into()), None,);
    }

    #[test]
    fn cl_query() {
        assert_eq!(
            dispatch(&handlers(), &"cl/42".into()),
            Some("https://cl.tvl.fyi/42".to_string())
        );

        assert_eq!(
            dispatch(&handlers(), &"something only mentioning cl/42".into()),
            None,
        );
        assert_eq!(dispatch(&handlers(), &"cl/invalid".into()), None,);
    }

    #[test]
    fn depot_path_cgit_query() {
        assert_eq!(
            dispatch(&handlers(), &"//web/atward/default.nix".into()),
            Some("https://code.tvl.fyi/tree/web/atward/default.nix".to_string()),
        );

        assert_eq!(
            dispatch(&handlers(), &"//nix/readTree/README.md".into()),
            Some("https://code.tvl.fyi/about/nix/readTree/README.md".to_string()),
        );

        assert_eq!(dispatch(&handlers(), &"/not/a/depot/path".into()), None);
    }

    #[test]
    fn depot_path_sourcegraph_query() {
        assert_eq!(
            dispatch(
                &handlers(),
                &Query {
                    query: "//web/atward/default.nix".to_string(),
                    cs: true,
                }
            ),
            Some("https://cs.tvl.fyi/depot/-/tree/web/atward/default.nix".to_string()),
        );

        assert_eq!(
            dispatch(
                &handlers(),
                &Query {
                    query: "/not/a/depot/path".to_string(),
                    cs: true,
                }
            ),
            None
        );
    }

    #[test]
    fn depot_root_cgit_query() {
        assert_eq!(
            dispatch(
                &handlers(),
                &Query {
                    query: "//".to_string(),
                    cs: false,
                }
            ),
            Some("https://code.tvl.fyi/tree/".to_string()),
        );
    }

    #[test]
    fn plain_host_queries() {
        assert_eq!(
            dispatch(&handlers(), &"cs".into()),
            Some("https://cs.tvl.fyi/".to_string()),
        );

        assert_eq!(
            dispatch(&handlers(), &"cl".into()),
            Some("https://cl.tvl.fyi/".to_string()),
        );

        assert_eq!(
            dispatch(&handlers(), &"b".into()),
            Some("https://b.tvl.fyi/".to_string()),
        );

        assert_eq!(
            dispatch(&handlers(), &"todo".into()),
            Some("https://todo.tvl.fyi/".to_string()),
        );
    }

    #[test]
    fn request_to_query() {
        assert_eq!(
            Query::from_request(&Request::fake_http("GET", "/?q=b%2F42", vec![], vec![]))
                .expect("request should parse to a query"),
            Query {
                query: "b/42".to_string(),
                cs: false,
            },
        );

        assert_eq!(
            Query::from_request(&Request::fake_http("GET", "/", vec![], vec![])),
            None
        );
    }

    #[test]
    fn settings_from_cookie() {
        assert_eq!(
            Query::from_request(&Request::fake_http(
                "GET",
                "/?q=b%2F42",
                vec![("Cookie".to_string(), "cs=true;".to_string())],
                vec![]
            ))
            .expect("request should parse to a query"),
            Query {
                query: "b/42".to_string(),
                cs: true,
            },
        );
    }

    #[test]
    fn settings_from_query_parameter() {
        assert_eq!(
            Query::from_request(&Request::fake_http(
                "GET",
                "/?q=b%2F42&cs=true",
                vec![],
                vec![]
            ))
            .expect("request should parse to a query"),
            Query {
                query: "b/42".to_string(),
                cs: true,
            },
        );

        // Query parameter should override cookie
        assert_eq!(
            Query::from_request(&Request::fake_http(
                "GET",
                "/?q=b%2F42&cs=false",
                vec![("Cookie".to_string(), "cs=true;".to_string())],
                vec![]
            ))
            .expect("request should parse to a query"),
            Query {
                query: "b/42".to_string(),
                cs: false,
            },
        );
    }
}