forked from webmachine/webmachine
-
Notifications
You must be signed in to change notification settings - Fork 27
/
webmachine_router.erl
305 lines (261 loc) · 9.81 KB
/
webmachine_router.erl
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
%% @author Kevin A. Smith <ksmith@basho.com>
%% @copyright 2007-2010 Basho Technologies
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%% @doc Module to add and remove dynamic routes to webmachine's routing
%% table. Dynamic routes are not persistent between executions of
%% a webmachine application. They will need to be added to the
%% the table each time webmachine restarts.
-module(webmachine_router).
-behaviour(gen_server).
%% API
-export([start_link/0,
add_route/1,
add_route/2,
remove_route/1,
remove_route/2,
remove_resource/1,
remove_resource/2,
get_routes/0,
get_routes/1,
init_routes/1,
init_routes/2
]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
%% @type hostmatchterm() = {hostmatch(), [pathmatchterm()]}.
% The dispatch configuration contains a list of these terms, and the
% first one whose host and one pathmatchterm match is used.
%% @type pathmatchterm() = {[pathterm()], matchmod(), matchopts()}.
% The dispatch configuration contains a list of these terms, and the
% first one whose list of pathterms matches the input path is used.
%% @type pathterm() = '*' | string() | atom().
% A list of pathterms is matched against a '/'-separated input path.
% The '*' pathterm matches all remaining tokens.
% A string pathterm will match a token of exactly the same string.
% Any atom pathterm other than '*' will match any token and will
% create a binding in the result if a complete match occurs.
%% @type matchmod() = atom().
% This atom, if present in a successful matchterm, will appear in
% the resulting dispterm. In Webmachine this is used to name the
% resource module that will handle the matching request.
%% @type matchopts() = [term()].
% This term, if present in a successful matchterm, will appear in
% the resulting dispterm. In Webmachine this is used to provide
% arguments to the resource module handling the matching request.
-define(SERVER, ?MODULE).
%% @spec add_route(hostmatchterm() | pathmatchterm()) -> ok
%% @doc Adds a route to webmachine's route table. The route should
%% be the format documented here:
%% http://bitbucket.org/justin/webmachine/wiki/DispatchConfiguration
add_route(Route) ->
add_route(default, Route).
add_route(Name, Route) ->
gen_server:call(?SERVER, {add_route, Name, Route}, infinity).
%% @spec remove_route(hostmatchterm() | pathmatchterm()) -> ok
%% @doc Removes a route from webamchine's route table. The route
%% route must be properly formatted
%% @see add_route/2
remove_route(Route) ->
remove_route(default, Route).
remove_route(Name, Route) ->
gen_server:call(?SERVER, {remove_route, Name, Route}, infinity).
%% @spec remove_resource(atom()) -> ok
%% @doc Removes all routes for a specific resource module.
remove_resource(Resource) when is_atom(Resource) ->
remove_resource(default, Resource).
remove_resource(Name, Resource) when is_atom(Resource) ->
gen_server:call(?SERVER, {remove_resource, Name, Resource}, infinity).
%% @spec get_routes() -> [{[], res, []}]
%% @doc Retrieve a list of routes and resources set in webmachine's
%% route table.
get_routes() ->
get_routes(default).
get_routes(Name) ->
get_dispatch_list(Name).
%% @spec init_routes([hostmatchterm() | pathmatchterm()]) -> ok
%% @doc Set the default routes, unless the routing table isn't empty.
init_routes(DefaultRoutes) ->
init_routes(default, DefaultRoutes).
init_routes(Name, DefaultRoutes) ->
gen_server:call(?SERVER, {init_routes, Name, DefaultRoutes}, infinity).
%% @spec start_link() -> {ok, pid()} | {error, any()}
%% @doc Starts the webmachine_router gen_server.
start_link() ->
%% We expect to only be called from webmachine_sup
%%
%% Set up the ETS configuration table.
try ets:new(?MODULE, [named_table, public, set, {keypos, 1},
{read_concurrency, true}]) of
_Result ->
ok
catch
error:badarg ->
%% The table already exists, which is fine. The webmachine_router
%% probably crashed and this is a restart.
ok
end,
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
%% @private
init([]) ->
{ok, undefined}.
%% @private
handle_call({remove_resource, Name, Resource}, _From, State) ->
DL = filter_by_resource(Resource, get_dispatch_list(Name)),
{reply, set_dispatch_list(Name, DL), State};
handle_call({remove_route, Name, Route}, _From, State) ->
DL = [D || D <- get_dispatch_list(Name),
D /= Route],
{reply, set_dispatch_list(Name, DL), State};
handle_call({add_route, Name, Route}, _From, State) ->
DL = [Route|[D || D <- get_dispatch_list(Name),
D /= Route]],
{reply, set_dispatch_list(Name, DL), State};
handle_call({init_routes, Name, DefaultRoutes}, _From, State) ->
%% if the table lacks a dispatch_list row, set it
ets:insert_new(?MODULE, {Name, DefaultRoutes}),
{reply, ok, State};
handle_call(_Request, _From, State) ->
{reply, ignore, State}.
%% @private
handle_cast(_Msg, State) ->
{noreply, State}.
%% @private
handle_info(_Info, State) ->
{noreply, State}.
%% @private
terminate(_Reason, _State) ->
ok.
%% @private
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% Internal functions
%% @doc Remove any dispatch rule that directs requests to `Resource'
filter_by_resource(Resource, Dispatch) ->
lists:foldr(filter_by_resource(Resource), [], Dispatch).
filter_by_resource(Resource) ->
fun({_, R, _}, Acc) when R == Resource -> % basic dispatch
Acc;
({_, _, R, _}, Acc) when R == Resource -> % guarded dispatch
Acc;
({Host, Disp}, Acc) -> % host-based dispatch
[{Host, filter_by_resource(Resource, Disp)}|Acc];
(Other, Acc) -> % dispatch not mentioning this resource
[Other|Acc]
end.
get_dispatch_list(Name) ->
case ets:lookup(?MODULE, Name) of
[{Name, Dispatch}] ->
Dispatch;
[] ->
[]
end.
set_dispatch_list(Name, DispatchList) ->
true = ets:insert(?MODULE, {Name, DispatchList}),
ok.
%%
%% Tests
%%
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
webmachine_router_test_() ->
{setup,
fun() ->
{ok, Pid} = webmachine_router:start_link(),
unlink(Pid),
{Pid}
end,
fun({Pid}) ->
exit(Pid, kill),
wait_for_termination(webmachine_router),
%% the test process owns the table, so we clear it between tests
ets:delete(?MODULE)
end,
[{"add_remove_route", fun add_remove_route/0},
{"add_remove_resource", fun add_remove_resource/0},
{"no_dupe_path", fun no_dupe_path/0}
]}.
%% Wait until the given registered name cannot be found, to ensure that
%% another test can safely start it again via start_link
wait_for_termination(RegName) ->
IdOrUndefined = whereis(RegName),
case IdOrUndefined of
undefined ->
ok;
_ ->
timer:sleep(100),
wait_for_termination(RegName)
end.
add_remove_route() ->
PathSpec = {["foo"], foo, []},
webmachine_router:add_route(PathSpec),
?assertEqual([PathSpec], get_routes()),
webmachine_router:remove_route(PathSpec),
?assertEqual([], get_routes()),
ok.
add_remove_resource() ->
PathSpec1 = {["foo"], foo, []},
PathSpec2 = {["bar"], foo, []},
PathSpec3 = {["baz"], bar, []},
PathSpec4 = {["foo"], fun(_) -> true end, foo, []},
PathSpec5 = {["foo"], {webmachine_router, test_guard}, foo, []},
webmachine_router:add_route(PathSpec1),
webmachine_router:add_route(PathSpec2),
webmachine_router:add_route(PathSpec3),
webmachine_router:remove_resource(foo),
?assertEqual([PathSpec3], get_routes()),
webmachine_router:add_route(PathSpec4),
webmachine_router:remove_resource(foo),
?assertEqual([PathSpec3], get_routes()),
webmachine_router:add_route(PathSpec5),
webmachine_router:remove_resource(foo),
?assertEqual([PathSpec3], get_routes()),
webmachine_router:remove_route(PathSpec3),
[begin
PathSpec = {"localhost", [HostPath]},
webmachine_router:add_route(PathSpec),
webmachine_router:remove_resource(foo),
?assertEqual([{"localhost", []}], get_routes()),
webmachine_router:remove_route({"localhost", []})
end || HostPath <- [PathSpec1, PathSpec4, PathSpec5]],
ok.
no_dupe_path() ->
PathSpec = {["foo"], foo, []},
webmachine_router:add_route(PathSpec),
webmachine_router:add_route(PathSpec),
?assertEqual([PathSpec], get_routes()),
ok.
supervisor_restart_keeps_routes_test() ->
{ok, Pid} = webmachine_router:start_link(),
unlink(Pid),
PathSpec = {["foo"], foo, []},
webmachine_router:add_route(PathSpec),
?assertEqual([PathSpec], get_routes()),
OldRouter = whereis(webmachine_router),
?assertEqual(Pid, OldRouter),
exit(whereis(webmachine_router), kill),
timer:sleep(100),
%% Note: This test is currently broken and wasn't actually testing what it
%% was supposed to
NewRouter = undefined,
?assert(OldRouter /= NewRouter),
?assertEqual([PathSpec], get_routes()),
exit(Pid, kill),
ets:delete(?MODULE),
ok.
-endif.