-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.rs
264 lines (237 loc) · 7.38 KB
/
main.rs
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
use core::path::{GenericPath};
use io::WriterUtil;
use path::{Path};
//use mustache::*;
use std::getopts::*;
use std::map::HashMap;
use server = rwebserve;
use rwebserve::{Config, Request, Response, ResponseHandler, Route, linear_map_from_vector};
type Options = {root: Path, admin: bool};
// str constants aren't supported yet.
// TODO: get this (somehow) from the link attribute in the rc file (going the other way
// doesn't work because vers in the link attribute has to be a literal)
fn get_version() -> ~str
{
~"0.1"
}
fn print_usage()
{
io::println(fmt!("server %s - sample rwebserve server", get_version()));
io::println(~"");
io::println(~"./server [options] --root=<dir>");
io::println(~"--admin allows web clients to shut the server down");
io::println(~"-h, --help prints this message and exits");
io::println(~"--root=DIR path to the directory containing html files");
io::println(~"--version prints the server version number and exits");
}
fn parse_command_line(args: &[~str]) -> Options
{
let opts = ~[
optflag(~"admin"),
reqopt(~"root"),
optflag(~"h"),
optflag(~"help"),
optflag(~"version")
];
let mut t = ~[];
for vec::eachi(args) // TODO: tail should work eventually (see https://github.com/mozilla/rust/issues/2770)
|i, a|
{
if i > 0
{
vec::push(&mut t, a.to_owned());
}
}
//let t = vec::tail(args);
let matched = match getopts(t, opts)
{
result::Ok(m) => copy(m),
result::Err(f) => {io::stderr().write_line(fail_str(f)); libc::exit(1_i32)}
};
if opt_present(&matched, ~"h") || opt_present(&matched, ~"help")
{
print_usage();
libc::exit(0_i32);
}
else if opt_present(&matched, ~"version")
{
io::println(fmt!("server %s", get_version()));
libc::exit(0_i32);
}
else if vec::is_not_empty(matched.free)
{
io::stderr().write_line("Positional arguments are not allowed.");
libc::exit(1_i32);
}
{root: GenericPath::from_str(opt_str(&matched, ~"root")), admin: opt_present(&matched, ~"admin")}
}
fn validate_options(options: &Options)
{
if !os::path_is_dir(&options.root)
{
io::stderr().write_line(fmt!("'%s' does not point to a directory.", options.root.to_str()));
libc::exit(1_i32);
}
}
fn process_command_line(args: ~[~str]) -> ~str
{
if vec::len(args) != 2u || !str::starts_with(args[1], "--root=")
{
io::stderr().write_line("Expected a --root-path argument pointing to the html pages.");
libc::exit(1_i32);
}
str::slice(args[1], str::len("--root="), str::len(args[1]))
}
fn home_view(_config: &Config, options: &Options, _request: &Request, response: Response) -> Response
{
response.context.insert(@~"admin", mustache::Bool(options.admin));
Response {template: ~"home.html", ..response}
}
fn greeting_view(_config: &Config, request: &Request, response: Response) -> Response
{
response.context.insert(@~"user-name", mustache::Str(@request.matches.get(@~"name")));
Response {template: ~"hello.html", ..response}
}
enum StateMesg
{
AddListener(~str, oldcomm::Chan<int>), // str is used to identify the listener
RemoveListener(~str),
Shutdown,
}
type StateChan = oldcomm::Chan<StateMesg>;
// Like spawn_listener except that it supports custom modes. This allows code that blocks
// within a foreign function to avoid blocking other tasks which may be on its thread.
fn spawn_moded_listener<A: Owned>(mode: task::SchedMode, +f: fn~(oldcomm::Port<A>)) -> oldcomm::Chan<A>
{
let setup_po = oldcomm::Port();
let setup_ch = oldcomm::Chan(&setup_po);
do task::spawn_sched(mode)
{
let po = oldcomm::Port();
let ch = oldcomm::Chan(&po);
oldcomm::send(setup_ch, ch);
f(po);
}
oldcomm::recv(setup_po)
}
// This is a single task that manages the state for our sample server. Normally this will
// do something like get notified of database changes and send messages to connection
// specific listeners. The listeners could then use server-sent events (sse) to push new
// data to the client.
//
// In this case our state is just an int and we notify listeners when we change it.
fn manage_state() -> StateChan
{
do spawn_moded_listener(task::ManualThreads(1))
|state_port: oldcomm::Port<StateMesg>|
{
let mut time = 0;
let listeners = std::map::HashMap();
loop
{
time += 1;
libc::funcs::posix88::unistd::sleep(1);
for listeners.each_value |ch| {oldcomm::send(ch, copy(time))};
if state_port.peek()
{
match state_port.recv()
{
AddListener(key, ch) =>
{
let added = listeners.insert(key, ch);
assert added;
}
RemoveListener(key) =>
{
listeners.remove(key);
}
Shutdown =>
{
break;
}
}
}
}
}
}
// Each client connection that hits /uptime will cause an instance of this task to run. When
// manage_state tells us that the world has changed we push the new world (an int in
// this case) out to the client.
fn uptime_sse(registrar: StateChan, request: &Request, push: server::PushChan) -> server::ControlChan
{
let seconds = request.params.get(&~"units") == ~"s";
do spawn_moded_listener(task::ThreadPerCore) |control_port: server::ControlPort|
{
info!("starting uptime sse stream");
let notify_port = oldcomm::Port();
let notify_chan = oldcomm::Chan(¬ify_port);
let key = fmt!("uptime %?", ptr::addr_of(¬ify_port));
oldcomm::send(registrar, AddListener(copy key, notify_chan));
loop
{
let mut time = 0;
match oldcomm::select2(notify_port, control_port)
{
either::Left(new_time) =>
{
// To help test the request code we can push uptimes as
// seconds or minutes based on a query string.
if seconds
{
time = new_time;
}
else
{
time = new_time/60;
}
oldcomm::send(push, fmt!("retry: 5000\ndata: %?\n\n", time));
}
either::Right(server::RefreshEvent) =>
{
oldcomm::send(push, fmt!("retry: 5000\ndata: %?\n\n", time));
}
either::Right(server::CloseEvent) =>
{
info!("shutting down uptime sse stream");
oldcomm::send(registrar, RemoveListener(key));
break;
}
}
}
}
}
fn main()
{
let options = parse_command_line(os::args());
validate_options(&options);
let registrar = manage_state();
// This is an example of how additional information can be communicated to
// a view handler (in this case we're only communicating options.admin so
// using settings would be simpler).
let up: server::OpenSse = |_config: &Config, request: &Request, push| {uptime_sse(registrar, request, push)};
let greeting_v: ResponseHandler = greeting_view;
let home_v: ResponseHandler = |config, request, response, copy options| {home_view(config, &options, request, response)};
let shutdown_v: ResponseHandler = |_config, _request, _response| {info!("received shutdown request"); libc::exit(0)};
let config = server::Config
{
hosts: ~[~"localhost", ~"10.6.210.132"],
port: 8088_u16,
server_info: ~"sample rrest server " + get_version(),
resources_root: copy options.root,
routes: ~[
Route(~"home", ~"GET", ~"/"),
Route(~"shutdown", ~"GET", ~"/shutdown"), // TODO: enable this via debug cfg (or maybe via a command line option)
Route(~"greeting", ~"GET", ~"/hello/{name}"),
],
views: linear_map_from_vector(~[
(~"greeting", greeting_v),
(~"home", home_v),
(~"shutdown", shutdown_v),
]),
sse: linear_map_from_vector(~[(~"/uptime", up)]),
settings: linear_map_from_vector(~[(~"debug", ~"true")]),
..server::initialize_config()
};
server::start(&config);
info!("exiting sample server"); // usually don't land here
}