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
//! Convert a [`rocket::Request`] to a
//! [Rack environment](https://www.rubydoc.info/github/rack/rack/file/SPEC#label-The+Environment).
//!
//! Based on
//! [`Rack::Handler::Webrick`](https://github.com/rack/rack/blob/2.0.7/lib/rack/handler/webrick.rb).

use mruby::convert::FromMrb;
use mruby::value::Value;
use mruby::Mrb;

use crate::Error;

pub trait Request {
    fn origin(&self) -> String;

    fn http_version(&self) -> Option<String>;

    fn request_method(&self) -> String;

    fn script_name(&self) -> String;

    fn path_info(&self) -> String;

    fn query_string(&self) -> String;

    fn server_name(&self) -> String;

    fn server_port(&self) -> u16;

    fn url_scheme(&self) -> String;

    /// Convert a `Request` into a Rack Environment.
    ///
    /// The
    /// [Rack specification](https://www.rubydoc.info/github/rack/rack/file/SPEC#label-The+Environment)
    /// enumerates the required keys. This implementation is based on
    /// [`Rack::Handler::Webrick`](https://github.com/rack/rack/blob/2.0.7/lib/rack/handler/webrick.rb).
    fn to_env(&self, interp: &Mrb) -> Result<Value, Error> {
        let mut env = vec![];
        env.push(("rack.version", Value::from_mrb(interp, vec![1_i64, 3_i64])));
        if let Some(version) = self.http_version() {
            env.push(("HTTP_VERSION", Value::from_mrb(interp, version)));
        }
        env.push((
            "REQUEST_METHOD",
            Value::from_mrb(interp, self.request_method()),
        ));
        env.push(("SCRIPT_NAME", Value::from_mrb(interp, self.script_name())));
        env.push(("PATH_INFO", Value::from_mrb(interp, self.path_info())));
        env.push(("QUERY_STRING", Value::from_mrb(interp, self.query_string())));
        env.push(("SERVER_NAME", Value::from_mrb(interp, self.server_name())));
        env.push((
            "SERVER_PORT",
            Value::from_mrb(interp, self.server_port().to_string()),
        ));
        env.push((
            "rack.url_scheme",
            Value::from_mrb(interp, self.url_scheme()),
        ));

        // TODO: implement Rack IO, see GH-9.
        env.push(("rack.input", Value::from_mrb(interp, None::<Value>)));
        env.push(("rack.errors", Value::from_mrb(interp, None::<Value>)));

        env.push(("rack.multithread", Value::from_mrb(interp, false)));
        env.push(("rack.multiprocess", Value::from_mrb(interp, false)));
        env.push(("rack.run_once", Value::from_mrb(interp, false)));

        Ok(Value::from_mrb(interp, env))
    }
}

#[cfg(test)]
mod tests {
    use mruby::convert::FromMrb;
    use mruby::eval::MrbEval;
    use mruby::value::{Value, ValueLike};
    use mruby_gems::rubygems::rack;

    // This module hard codes Rack constant names to avoid retrieving them via
    // the mruby VM. This test ensures that the inlined constants map to the
    // real ones in Ruby source.
    #[test]
    fn rack_constants_match() {
        let interp = mruby::interpreter().expect("mrb init");
        rack::init(&interp).unwrap();
        let rack = interp.eval("require 'rack'; Rack").unwrap();
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "RACK_VERSION")]),
            Ok("rack.version".to_owned())
        );
        assert_eq!(
            rack.funcall::<Vec<i64>, _, _>("const_get", &[Value::from_mrb(&interp, "VERSION")]),
            Ok(vec![1, 3])
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "HTTP_VERSION")]),
            Ok("HTTP_VERSION".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>(
                "const_get",
                &[Value::from_mrb(&interp, "REQUEST_METHOD")]
            ),
            Ok("REQUEST_METHOD".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "SCRIPT_NAME")]),
            Ok("SCRIPT_NAME".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "PATH_INFO")]),
            Ok("PATH_INFO".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "QUERY_STRING")]),
            Ok("QUERY_STRING".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "SERVER_NAME")]),
            Ok("SERVER_NAME".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "SERVER_PORT")]),
            Ok("SERVER_PORT".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>(
                "const_get",
                &[Value::from_mrb(&interp, "RACK_URL_SCHEME")]
            ),
            Ok("rack.url_scheme".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "RACK_INPUT")]),
            Ok("rack.input".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "RACK_ERRORS")]),
            Ok("rack.errors".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>(
                "const_get",
                &[Value::from_mrb(&interp, "RACK_MULTITHREAD")]
            ),
            Ok("rack.multithread".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>(
                "const_get",
                &[Value::from_mrb(&interp, "RACK_MULTIPROCESS")]
            ),
            Ok("rack.multiprocess".to_owned())
        );
        assert_eq!(
            rack.funcall::<String, _, _>("const_get", &[Value::from_mrb(&interp, "RACK_RUNONCE")]),
            Ok("rack.run_once".to_owned())
        );
    }
}