vibe.http.router 0/329(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
/** Pattern based URL router for HTTP request. See `URLRouter` for more details. Copyright: © 2012-2015 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.http.router; public import vibe.http.server; import vibe.core.log; import std.functional; /** Routes HTTP requests based on the request method and URL. Routes are matched using a special URL match string that supports two forms of placeholders. See the sections below for more details. Registered routes are matched according to the same sequence as initially specified using `match`, `get`, `post` etc. Matching ends as soon as a route handler writes a response using `res.writeBody()` or similar means. If no route matches or if no route handler writes a response, the router will simply not handle the request and the HTTP server will automatically generate a 404 error. Match_patterns: Match patterns are character sequences that can optionally contain placeholders or raw wildcards ("*"). Raw wild cards match any character sequence, while placeholders match only sequences containing no slash ("/") characters. Placeholders are started using a colon (":") and are directly followed by their name. The first "/" character (or the end of the match string) denotes the end of the placeholder name. The part of the string that matches a placeholder will be stored in the `HTTPServerRequest.params` map using the placeholder name as the key. Match strings are subject to the following rules: $(UL $(LI A raw wildcard ("*") may only occur at the end of the match string) $(LI At least one character must be placed between any two placeholders or wildcards) $(LI The maximum allowed number of placeholders in a single match string is 64) ) Match_String_Examples: $(UL $(LI `"/foo/bar"` matches only `"/foo/bar"` itself) $(LI `"/foo/*"` matches `"/foo/"`, `"/foo/bar"`, `"/foo/bar/baz"` or _any other string beginning with `"/foo/"`) $(LI `"/:x/"` matches `"/foo/"`, `"/bar/"` and similar strings (and stores `"foo"`/`"bar"` in `req.params["x"]`), but not `"/foo/bar/"`) $(LI Matching partial path entries with wildcards is possible: `"/foo:x"` matches `"/foo"`, `"/foobar"`, but not `"/foo/bar"`) $(LI Multiple placeholders and raw wildcards can be combined: `"/:x/:y/*"`) ) */ final class URLRouter : HTTPServerRequestHandler { @safe: private { MatchTree!Route m_routes; string m_prefix; bool m_computeBasePath; } this(string prefix = null) { m_prefix = prefix; } /** Sets a common prefix for all registered routes. All routes will implicitly have this prefix prepended before being matched against incoming requests. */ @property string prefix() const { return m_prefix; } /** Controls the computation of the "routerRootDir" parameter. This parameter is available as `req.params["routerRootDir"]` and contains the relative path to the base path of the router. The base path is determined by the `prefix` property. Note that this feature currently is requires dynamic memory allocations and is opt-in for this reason. */ @property void enableRootDir(bool enable) { m_computeBasePath = enable; } /// Returns a single route handle to conveniently register multiple methods. URLRoute route(string path) in { assert(path.length, "Cannot register null or empty path!"); } body { return URLRoute(this, path); } /// unittest { void getFoo(scope HTTPServerRequest req, scope HTTPServerResponse res) { /* ... */ } void postFoo(scope HTTPServerRequest req, scope HTTPServerResponse res) { /* ... */ } void deleteFoo(scope HTTPServerRequest req, scope HTTPServerResponse res) { /* ... */ } auto r = new URLRouter; // using 'with' statement with (r.route("/foo")) { get(&getFoo); post(&postFoo); delete_(&deleteFoo); } // using method chaining r.route("/foo") .get(&getFoo) .post(&postFoo) .delete_(&deleteFoo); // without using route() r.get("/foo", &getFoo); r.post("/foo", &postFoo); r.delete_("/foo", &deleteFoo); } /// Adds a new route for requests matching the specified HTTP method and pattern. URLRouter match(Handler)(HTTPMethod method, string path, Handler handler) if (isValidHandler!Handler) { import std.algorithm; assert(path.length, "Cannot register null or empty path!"); assert(count(path, ':') <= maxRouteParameters, "Too many route parameters"); logDebug("add route %s %s", method, path); m_routes.addTerminal(path, Route(method, path, handlerDelegate(handler))); return this; } /// ditto URLRouter match(HTTPMethod method, string path, HTTPServerRequestDelegate handler) { return match!HTTPServerRequestDelegate(method, path, handler); } /// Adds a new route for GET requests matching the specified pattern. URLRouter get(Handler)(string url_match, Handler handler) if (isValidHandler!Handler) { return match(HTTPMethod.GET, url_match, handler); } /// ditto URLRouter get(string url_match, HTTPServerRequestDelegate handler) { return match(HTTPMethod.GET, url_match, handler); } /// Adds a new route for POST requests matching the specified pattern. URLRouter post(Handler)(string url_match, Handler handler) if (isValidHandler!Handler) { return match(HTTPMethod.POST, url_match, handler); } /// ditto URLRouter post(string url_match, HTTPServerRequestDelegate handler) { return match(HTTPMethod.POST, url_match, handler); } /// Adds a new route for PUT requests matching the specified pattern. URLRouter put(Handler)(string url_match, Handler handler) if (isValidHandler!Handler) { return match(HTTPMethod.PUT, url_match, handler); } /// ditto URLRouter put(string url_match, HTTPServerRequestDelegate handler) { return match(HTTPMethod.PUT, url_match, handler); } /// Adds a new route for DELETE requests matching the specified pattern. URLRouter delete_(Handler)(string url_match, Handler handler) if (isValidHandler!Handler) { return match(HTTPMethod.DELETE, url_match, handler); } /// ditto URLRouter delete_(string url_match, HTTPServerRequestDelegate handler) { return match(HTTPMethod.DELETE, url_match, handler); } /// Adds a new route for PATCH requests matching the specified pattern. URLRouter patch(Handler)(string url_match, Handler handler) if (isValidHandler!Handler) { return match(HTTPMethod.PATCH, url_match, handler); } /// ditto URLRouter patch(string url_match, HTTPServerRequestDelegate handler) { return match(HTTPMethod.PATCH, url_match, handler); } /// Adds a new route for requests matching the specified pattern, regardless of their HTTP verb. URLRouter any(Handler)(string url_match, Handler handler) { import std.traits; static HTTPMethod[] all_methods = [EnumMembers!HTTPMethod]; foreach(immutable method; all_methods) match(method, url_match, handler); return this; } /// ditto URLRouter any(string url_match, HTTPServerRequestDelegate handler) { return any!HTTPServerRequestDelegate(url_match, handler); } /** Rebuilds the internal matching structures to account for newly added routes. This should be used after a lot of routes have been added to the router, to force eager computation of the match structures. The alternative is to let the router lazily compute the structures when the first request happens, which can delay this request. */ void rebuild() { m_routes.rebuildGraph(); } /// Handles a HTTP request by dispatching it to the registered route handlers. void handleRequest(HTTPServerRequest req, HTTPServerResponse res) { auto method = req.method; string calcBasePath() @safe { import vibe.inet.path; auto p = InetPath(prefix.length ? prefix : "/"); p.endsWithSlash = true; return p.relativeToWeb(InetPath(req.path)).toString(); } auto path = req.path; if (path.length < m_prefix.length || path[0 .. m_prefix.length] != m_prefix) return; path = path[m_prefix.length .. $]; while (true) { bool done = m_routes.match(path, (ridx, scope values) @safe { auto r = () @trusted { return &m_routes.getTerminalData(ridx); } (); if (r.method != method) return false; logDebugV("route match: %s -> %s %s %s", req.path, r.method, r.pattern, values); foreach (i, v; values) req.params[m_routes.getTerminalVarNames(ridx)[i]] = v; if (m_computeBasePath) req.params["routerRootDir"] = calcBasePath(); r.cb(req, res); return res.headerWritten; }); if (done) return; if (method == HTTPMethod.HEAD) method = HTTPMethod.GET; else break; } logDebug("no route match: %s %s", req.method, req.requestURL); } /// Returns all registered routes as const AA const(Route)[] getAllRoutes() { auto routes = new Route[m_routes.terminalCount]; foreach (i, ref r; routes) r = m_routes.getTerminalData(i); return routes; } template isValidHandler(Handler) { @system { alias USDel = void delegate(HTTPServerRequest, HTTPServerResponse) @system; alias USFun = void function(HTTPServerRequest, HTTPServerResponse) @system; alias USDelS = void delegate(scope HTTPServerRequest, scope HTTPServerResponse) @system; alias USFunS = void function(scope HTTPServerRequest, scope HTTPServerResponse) @system; } static if ( is(Handler : HTTPServerRequestDelegate) || is(Handler : HTTPServerRequestFunction) || is(Handler : HTTPServerRequestHandler) || is(Handler : HTTPServerRequestDelegateS) || is(Handler : HTTPServerRequestFunctionS) || is(Handler : HTTPServerRequestHandlerS) ) { enum isValidHandler = true; } else static if ( is(Handler : USDel) || is(Handler : USFun) || is(Handler : USDelS) || is(Handler : USFunS) ) { enum isValidHandler = true; } else { enum isValidHandler = false; } } static void delegate(HTTPServerRequest, HTTPServerResponse) @safe handlerDelegate(Handler)(Handler handler) { import std.traits : isFunctionPointer; static if (isFunctionPointer!Handler) return handlerDelegate(() @trusted { return toDelegate(handler); } ()); else static if (is(Handler == class) || is(Handler == interface)) return &handler.handleRequest; else static if (__traits(compiles, () @safe { handler(HTTPServerRequest.init, HTTPServerResponse.init); } ())) return handler; else return (req, res) @trusted { handler(req, res); }; } unittest { static assert(isValidHandler!HTTPServerRequestFunction); static assert(isValidHandler!HTTPServerRequestDelegate); static assert(isValidHandler!HTTPServerRequestHandler); static assert(isValidHandler!HTTPServerRequestFunctionS); static assert(isValidHandler!HTTPServerRequestDelegateS); static assert(isValidHandler!HTTPServerRequestHandlerS); static assert(isValidHandler!(void delegate(HTTPServerRequest req, HTTPServerResponse res) @system)); static assert(isValidHandler!(void function(HTTPServerRequest req, HTTPServerResponse res) @system)); static assert(isValidHandler!(void delegate(scope HTTPServerRequest req, scope HTTPServerResponse res) @system)); static assert(isValidHandler!(void function(scope HTTPServerRequest req, scope HTTPServerResponse res) @system)); static assert(!isValidHandler!(int delegate(HTTPServerRequest req, HTTPServerResponse res) @system)); static assert(!isValidHandler!(int delegate(HTTPServerRequest req, HTTPServerResponse res) @safe)); void test(H)(H h) { static assert(isValidHandler!H); } test((HTTPServerRequest req, HTTPServerResponse res) {}); } } /// @safe unittest { import vibe.http.fileserver; void addGroup(HTTPServerRequest req, HTTPServerResponse res) { // Route variables are accessible via the params map logInfo("Getting group %s for user %s.", req.params["groupname"], req.params["username"]); } void deleteUser(HTTPServerRequest req, HTTPServerResponse res) { // ... } void auth(HTTPServerRequest req, HTTPServerResponse res) { // TODO: check req.session to see if a user is logged in and // write an error page or throw an exception instead. } void setup() { auto router = new URLRouter; // Matches all GET requests for /users/*/groups/* and places // the place holders in req.params as 'username' and 'groupname'. router.get("/users/:username/groups/:groupname", &addGroup); // Matches all requests. This can be useful for authorization and // similar tasks. The auth method will only write a response if the // user is _not_ authorized. Otherwise, the router will fall through // and continue with the following routes. router.any("*", &auth); // Matches a POST request router.post("/users/:username/delete", &deleteUser); // Matches all GET requests in /static/ such as /static/img.png or // /static/styles/sty.css router.get("/static/*", serveStaticFiles("public/")); // Setup a HTTP server... auto settings = new HTTPServerSettings; // ... // The router can be directly passed to the listenHTTP function as // the main request handler. listenHTTP(settings, router); } } /** Using nested routers to map components to different sub paths. A component could for example be an embedded blog engine. */ @safe unittest { // some embedded component: void showComponentHome(HTTPServerRequest req, HTTPServerResponse res) { // ... } void showComponentUser(HTTPServerRequest req, HTTPServerResponse res) { // ... } void registerComponent(URLRouter router) { router.get("/", &showComponentHome); router.get("/users/:user", &showComponentUser); } // main application: void showHome(HTTPServerRequest req, HTTPServerResponse res) { // ... } void setup() { auto c1router = new URLRouter("/component1"); registerComponent(c1router); auto mainrouter = new URLRouter; mainrouter.get("/", &showHome); // forward all unprocessed requests to the component router mainrouter.any("*", c1router); // now the following routes will be matched: // / -> showHome // /component1/ -> showComponentHome // /component1/users/:user -> showComponentUser // Start the HTTP server auto settings = new HTTPServerSettings; // ... listenHTTP(settings, mainrouter); } } @safe unittest { // issue #1668 auto r = new URLRouter; r.get("/", (req, res) { if ("foo" in req.headers) res.writeBody("bar"); }); r.get("/", (scope req, scope res) { if ("foo" in req.headers) res.writeBody("bar"); }); r.get("/", (req, res) {}); r.post("/", (req, res) {}); r.put("/", (req, res) {}); r.delete_("/", (req, res) {}); r.patch("/", (req, res) {}); r.any("/", (req, res) {}); } @safe unittest { // issue #1866 auto r = new URLRouter; r.match(HTTPMethod.HEAD, "/foo", (scope req, scope res) { res.writeVoidBody; }); r.match(HTTPMethod.HEAD, "/foo", (req, res) { res.writeVoidBody; }); r.match(HTTPMethod.HEAD, "/foo", (scope HTTPServerRequest req, scope HTTPServerResponse res) { res.writeVoidBody; }); r.match(HTTPMethod.HEAD, "/foo", (HTTPServerRequest req, HTTPServerResponse res) { res.writeVoidBody; }); auto r2 = new URLRouter; r.match(HTTPMethod.HEAD, "/foo", r2); } @safe unittest { import vibe.inet.url; auto router = new URLRouter; string result; void a(HTTPServerRequest req, HTTPServerResponse) { result ~= "A"; } void b(HTTPServerRequest req, HTTPServerResponse) { result ~= "B"; } void c(HTTPServerRequest req, HTTPServerResponse) { assert(req.params["test"] == "x", "Wrong variable contents: "~req.params["test"]); result ~= "C"; } void d(HTTPServerRequest req, HTTPServerResponse) { assert(req.params["test"] == "y", "Wrong variable contents: "~req.params["test"]); result ~= "D"; } router.get("/test", &a); router.post("/test", &b); router.get("/a/:test", &c); router.get("/a/:test/", &d); auto res = createTestHTTPServerResponse(); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/")), res); assert(result == "", "Matched for non-existent / path"); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/test")), res); assert(result == "A", "Didn't match a simple GET request"); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/test"), HTTPMethod.POST), res); assert(result == "AB", "Didn't match a simple POST request"); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/a/"), HTTPMethod.GET), res); assert(result == "AB", "Matched empty variable. "~result); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/a/x"), HTTPMethod.GET), res); assert(result == "ABC", "Didn't match a trailing 1-character var."); // currently fails due to Path not accepting "//" //router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/a//"), HTTPMethod.GET), res); //assert(result == "ABC", "Matched empty string or slash as var. "~result); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/a/y/"), HTTPMethod.GET), res); assert(result == "ABCD", "Didn't match 1-character infix variable."); } @safe unittest { import vibe.inet.url; auto router = new URLRouter("/test"); string result; void a(HTTPServerRequest req, HTTPServerResponse) { result ~= "A"; } void b(HTTPServerRequest req, HTTPServerResponse) { result ~= "B"; } router.get("/x", &a); router.get("/y", &b); auto res = createTestHTTPServerResponse(); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/test")), res); assert(result == ""); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/test/x")), res); assert(result == "A"); router.handleRequest(createTestHTTPServerRequest(URL("http://localhost/test/y")), res); assert(result == "AB"); } @safe unittest { string ensureMatch(string pattern, string local_uri, string[string] expected_params = null) { import vibe.inet.url : URL; string ret = local_uri ~ " did not match " ~ pattern; auto r = new URLRouter; r.get(pattern, (req, res) { ret = null; foreach (k, v; expected_params) { if (k !in req.params) { ret = "Parameter "~k~" was not matched."; return; } if (req.params[k] != v) { ret = "Parameter "~k~" is '"~req.params[k]~"' instead of '"~v~"'."; return; } } }); auto req = createTestHTTPServerRequest(URL("http://localhost"~local_uri)); auto res = createTestHTTPServerResponse(); r.handleRequest(req, res); return ret; } assert(ensureMatch("/foo bar/", "/foo%20bar/") is null); // normalized pattern: "/foo%20bar/" //assert(ensureMatch("/foo%20bar/", "/foo%20bar/") is null); // normalized pattern: "/foo%20bar/" assert(ensureMatch("/foo/bar/", "/foo/bar/") is null); // normalized pattern: "/foo/bar/" //assert(ensureMatch("/foo/bar/", "/foo%2fbar/") !is null); //assert(ensureMatch("/foo%2fbar/", "/foo%2fbar/") is null); // normalized pattern: "/foo%2Fbar/" //assert(ensureMatch("/foo%2Fbar/", "/foo%2fbar/") is null); // normalized pattern: "/foo%2Fbar/" //assert(ensureMatch("/foo%2fbar/", "/foo%2Fbar/") is null); //assert(ensureMatch("/foo%2fbar/", "/foo/bar/") !is null); //assert(ensureMatch("/:foo/", "/foo%2Fbar/", ["foo": "foo/bar"]) is null); assert(ensureMatch("/:foo/", "/foo/bar/") !is null); } /** Convenience abstraction for a single `URLRouter` route. See `URLRouter.route` for a usage example. */ struct URLRoute { @safe: URLRouter router; string path; ref URLRoute get(Handler)(Handler h) { router.get(path, h); return this; } ref URLRoute post(Handler)(Handler h) { router.post(path, h); return this; } ref URLRoute put(Handler)(Handler h) { router.put(path, h); return this; } ref URLRoute delete_(Handler)(Handler h) { router.delete_(path, h); return this; } ref URLRoute patch(Handler)(Handler h) { router.patch(path, h); return this; } ref URLRoute any(Handler)(Handler h) { router.any(path, h); return this; } ref URLRoute match(Handler)(HTTPMethod method, Handler h) { router.match(method, path, h); return this; } } private enum maxRouteParameters = 64; private struct Route { HTTPMethod method; string pattern; HTTPServerRequestDelegate cb; } private string skipPathNode(string str, ref size_t idx) @safe { size_t start = idx; while( idx < str.length && str[idx] != '/' ) idx++; return str[start .. idx]; } private string skipPathNode(ref string str) @safe { size_t idx = 0; auto ret = skipPathNode(str, idx); str = str[idx .. $]; return ret; } private struct MatchTree(T) { @safe: import std.algorithm : countUntil; import std.array : array; private { alias NodeIndex = uint; alias TerminalTagIndex = uint; alias TerminalIndex = ushort; alias VarIndex = ushort; struct Node { TerminalTagIndex terminalsStart; // slice into m_terminalTags TerminalTagIndex terminalsEnd; NodeIndex[ubyte.max+1] edges = NodeIndex.max; // character -> index into m_nodes } struct TerminalTag { TerminalIndex index; // index into m_terminals array VarIndex var = VarIndex.max; // index into Terminal.varNames/varValues or VarIndex.max } struct Terminal { string pattern; T data; string[] varNames; VarIndex[NodeIndex] varMap; } Node[] m_nodes; // all nodes as a single array TerminalTag[] m_terminalTags; Terminal[] m_terminals; enum TerminalChar = 0; bool m_upToDate = false; } @property size_t terminalCount() const { return m_terminals.length; } void addTerminal(string pattern, T data) { assert(m_terminals.length < TerminalIndex.max, "Attempt to register too many routes."); m_terminals ~= Terminal(pattern, data, null, null); m_upToDate = false; } bool match(string text, scope bool delegate(size_t terminal, scope string[] vars) @safe del) { // lazily update the match graph if (!m_upToDate) rebuildGraph(); return doMatch(text, del); } const(string)[] getTerminalVarNames(size_t terminal) const { return m_terminals[terminal].varNames; } ref inout(T) getTerminalData(size_t terminal) inout { return m_terminals[terminal].data; } void print() const { import std.algorithm : map; import std.array : join; import std.conv : to; import std.range : iota; import std.string : format; logInfo("Nodes:"); foreach (i, n; m_nodes) { logInfo(" %s %s", i, m_terminalTags[n.terminalsStart .. n.terminalsEnd] .map!(t => format("T%s%s", t.index, t.var != VarIndex.max ? "("~m_terminals[t.index].varNames[t.var]~")" : "")).join(" ")); //logInfo(" %s %s-%s", i, n.terminalsStart, n.terminalsEnd); static string mapChar(ubyte ch) { if (ch == TerminalChar) return "$"; if (ch >= '0' && ch <= '9') return to!string(cast(dchar)ch); if (ch >= 'a' && ch <= 'z') return to!string(cast(dchar)ch); if (ch >= 'A' && ch <= 'Z') return to!string(cast(dchar)ch); if (ch == '/') return "/"; if (ch == '^') return "^"; return ch.to!string; } void printRange(uint node, ubyte from, ubyte to) { if (to - from <= 10) logInfo(" %s -> %s", iota(from, cast(uint)to+1).map!(ch => mapChar(cast(ubyte)ch)).join("|"), node); else logInfo(" %s-%s -> %s", mapChar(from), mapChar(to), node); } auto last_to = NodeIndex.max; ubyte last_ch = 0; foreach (ch, e; n.edges) if (e != last_to) { if (last_to != NodeIndex.max) printRange(last_to, last_ch, cast(ubyte)(ch-1)); last_ch = cast(ubyte)ch; last_to = e; } if (last_to != NodeIndex.max) printRange(last_to, last_ch, ubyte.max); } } private bool doMatch(string text, scope bool delegate(size_t terminal, scope string[] vars) @safe del) const { string[maxRouteParameters] vars_buf;// = void; import std.algorithm : canFind; // first, determine the end node, if any auto n = matchTerminals(text); if (!n) return false; // then, go through the terminals and match their variables foreach (ref t; m_terminalTags[n.terminalsStart .. n.terminalsEnd]) { auto term = &m_terminals[t.index]; auto vars = vars_buf[0 .. term.varNames.length]; matchVars(vars, term, text); if (vars.canFind!(v => v.length == 0)) continue; // all variables must be non-empty to match if (del(t.index, vars)) return true; } return false; } private inout(Node)* matchTerminals(string text) inout { if (!m_nodes.length) return null; auto n = &m_nodes[0]; // follow the path through the match graph foreach (i, char ch; text) { auto nidx = n.edges[cast(size_t)ch]; if (nidx == NodeIndex.max) return null; n = &m_nodes[nidx]; } // finally, find a matching terminal node auto nidx = n.edges[TerminalChar]; if (nidx == NodeIndex.max) return null; n = &m_nodes[nidx]; return n; } private void matchVars(string[] dst, in Terminal* term, string text) const { NodeIndex nidx = 0; VarIndex activevar = VarIndex.max; size_t activevarstart; dst[] = null; // folow the path throgh the match graph foreach (i, char ch; text) { auto var = term.varMap.get(nidx, VarIndex.max); // detect end of variable if (var != activevar && activevar != VarIndex.max) { dst[activevar] = text[activevarstart .. i-1]; activevar = VarIndex.max; } // detect beginning of variable if (var != VarIndex.max && activevar == VarIndex.max) { activevar = var; activevarstart = i; } nidx = m_nodes[nidx].edges[cast(ubyte)ch]; assert(nidx != NodeIndex.max); } // terminate any active varible with the end of the input string or with the last character auto var = term.varMap.get(nidx, VarIndex.max); if (activevar != VarIndex.max) dst[activevar] = text[activevarstart .. (var == activevar ? $ : $-1)]; } private void rebuildGraph() @trusted { import std.array : appender; import std.conv : to; if (m_upToDate) return; m_upToDate = true; m_nodes = null; m_terminalTags = null; if (!m_terminals.length) return; MatchGraphBuilder builder; foreach (i, ref t; m_terminals) { t.varNames = builder.insert(t.pattern, i.to!TerminalIndex); assert(t.varNames.length <= VarIndex.max, "Too many variables in route."); } //builder.print(); builder.disambiguate(); auto nodemap = new NodeIndex[builder.m_nodes.length]; nodemap[] = NodeIndex.max; auto nodes = appender!(Node[]); nodes.reserve(1024); auto termtags = appender!(TerminalTag[]); termtags.reserve(1024); NodeIndex process(NodeIndex n) { import std.algorithm : canFind; if (nodemap[n] != NodeIndex.max) return nodemap[n]; auto nmidx = cast(NodeIndex)nodes.data.length; nodemap[n] = nmidx; nodes.put(Node.init); Node nn; nn.terminalsStart = termtags.data.length.to!TerminalTagIndex; foreach (t; builder.m_nodes[n].terminals) { auto var = cast(VarIndex)t.var; assert(!termtags.data[nn.terminalsStart .. $].canFind!(u => u.index == t.index && u.var == var)); termtags ~= TerminalTag(cast(TerminalIndex)t.index, var); if (var != VarIndex.max) m_terminals[t.index].varMap[nmidx] = var; } nn.terminalsEnd = termtags.data.length.to!TerminalTagIndex; foreach (ch, targets; builder.m_nodes[n].edges) foreach (to; builder.m_edgeEntries.getItems(targets)) nn.edges[ch] = process(to); nodes.data[nmidx] = nn; return nmidx; } assert(builder.m_edgeEntries.hasLength(builder.m_nodes[0].edges['^'], 1), "Graph must be disambiguated before purging."); process(builder.m_edgeEntries.getItems(builder.m_nodes[0].edges['^']).front); m_nodes = nodes.data; m_terminalTags = termtags.data; logDebug("Match tree has %s (of %s in the builder) nodes, %s terminals", m_nodes.length, builder.m_nodes.length, m_terminals.length); } } unittest { import std.string : format; MatchTree!int m; void testMatch(string str, size_t[] terms, string[] vars) { size_t[] mterms; string[] mvars; m.match(str, (t, scope vals) { mterms ~= t; mvars ~= vals; return false; }); assert(mterms == terms, format("Mismatched terminals: %s (expected %s)", mterms, terms)); assert(mvars == vars, format("Mismatched variables; %s (expected %s)", mvars, vars)); } m.addTerminal("a", 0); m.addTerminal("b", 0); m.addTerminal("ab", 0); m.rebuildGraph(); assert(m.getTerminalVarNames(0) == []); assert(m.getTerminalVarNames(1) == []); assert(m.getTerminalVarNames(2) == []); testMatch("a", [0], []); testMatch("ab", [2], []); testMatch("abc", [], []); testMatch("b", [1], []); m = MatchTree!int.init; m.addTerminal("ab", 0); m.addTerminal("a*", 0); m.rebuildGraph(); assert(m.getTerminalVarNames(0) == []); assert(m.getTerminalVarNames(1) == []); testMatch("a", [1], []); testMatch("ab", [0, 1], []); testMatch("abc", [1], []); m = MatchTree!int.init; m.addTerminal("ab", 0); m.addTerminal("a:var", 0); m.rebuildGraph(); assert(m.getTerminalVarNames(0) == []); assert(m.getTerminalVarNames(1) == ["var"], format("%s", m.getTerminalVarNames(1))); testMatch("a", [], []); // vars may not be empty testMatch("ab", [0, 1], ["b"]); testMatch("abc", [1], ["bc"]); m = MatchTree!int.init; m.addTerminal(":var1/:var2", 0); m.addTerminal("a/:var3", 0); m.addTerminal(":var4/b", 0); m.rebuildGraph(); assert(m.getTerminalVarNames(0) == ["var1", "var2"]); assert(m.getTerminalVarNames(1) == ["var3"]); assert(m.getTerminalVarNames(2) == ["var4"]); testMatch("a", [], []); testMatch("a/a", [0, 1], ["a", "a", "a"]); testMatch("a/b", [0, 1, 2], ["a", "b", "b", "a"]); testMatch("a/bc", [0, 1], ["a", "bc", "bc"]); testMatch("ab/b", [0, 2], ["ab", "b", "ab"]); testMatch("ab/bc", [0], ["ab", "bc"]); m = MatchTree!int.init; m.addTerminal(":var1/", 0); m.rebuildGraph(); assert(m.getTerminalVarNames(0) == ["var1"]); testMatch("ab/", [0], ["ab"]); testMatch("ab", [], []); testMatch("/ab", [], []); testMatch("a/b", [], []); testMatch("ab//", [], []); } private struct MatchGraphBuilder { @safe: import std.container.array : Array; import std.array : array; import std.algorithm : filter; import std.string : format; alias NodeIndex = uint; alias TerminalIndex = ushort; alias VarIndex = ushort; alias NodeSet = LinkedSetBacking!NodeIndex.Handle; private { enum TerminalChar = 0; struct TerminalTag { TerminalIndex index; VarIndex var = VarIndex.max; } struct Node { Array!TerminalTag terminals; NodeSet[ubyte.max+1] edges; } Array!Node m_nodes; LinkedSetBacking!NodeIndex m_edgeEntries; } @disable this(this); string[] insert(string pattern, TerminalIndex terminal) { import std.algorithm : canFind; auto full_pattern = pattern; string[] vars; if (!m_nodes.length) addNode(); // create start node and connect to zero node auto nidx = addNode(); addEdge(0, nidx, '^', terminal); while (pattern.length) { auto ch = pattern[0]; if (ch == '*') { assert(pattern.length == 1, "Asterisk is only allowed at the end of a pattern: "~full_pattern); pattern = null; foreach (v; ubyte.min .. ubyte.max+1) { if (v == TerminalChar) continue; addEdge(nidx, nidx, cast(ubyte)v, terminal); } } else if (ch == ':') { pattern = pattern[1 .. $]; auto name = skipPathNode(pattern); assert(name.length > 0, "Missing placeholder name: "~full_pattern); assert(!vars.canFind(name), "Duplicate placeholder name ':"~name~"': '"~full_pattern~"'"); auto varidx = cast(VarIndex)vars.length; vars ~= name; assert(!pattern.length || (pattern[0] != '*' && pattern[0] != ':'), "Cannot have two placeholders directly follow each other."); foreach (v; ubyte.min .. ubyte.max+1) { if (v == TerminalChar || v == '/') continue; addEdge(nidx, nidx, cast(ubyte)v, terminal, varidx); } } else { nidx = addEdge(nidx, ch, terminal); pattern = pattern[1 .. $]; } } addEdge(nidx, TerminalChar, terminal); return vars; } void disambiguate() @trusted { import std.algorithm : map, sum; import std.array : appender, join; //logInfo("Disambiguate with %s initial nodes", m_nodes.length); if (!m_nodes.length) return; import vibe.utils.hashmap; HashMap!(size_t, NodeIndex) combined_nodes; Array!bool visited; visited.length = m_nodes.length * 2; Stack!NodeIndex node_stack; node_stack.reserve(m_nodes.length); node_stack.push(0); while (!node_stack.empty) { auto n = node_stack.pop(); while (n >= visited.length) visited.length = visited.length * 2; if (visited[n]) continue; //logInfo("Disambiguate %s (stack=%s)", n, node_stack.fill); visited[n] = true; foreach (ch; ubyte.min .. ubyte.max+1) { auto chnodes = m_nodes[n].edges[ch]; size_t chhash = m_edgeEntries.getHash(chnodes); // handle trivial cases if (m_edgeEntries.hasMaxLength(chnodes, 1)) continue; // generate combined state for ambiguous edges if (auto pn = () @trusted { return chhash in combined_nodes; } ()) { m_nodes[n].edges[ch] = m_edgeEntries.create(*pn); assert(m_edgeEntries.hasLength(m_nodes[n].edges[ch], 1)); continue; } // for new combinations, create a new node NodeIndex ncomb = addNode(); combined_nodes[chhash] = ncomb; // write all edges size_t idx = 0; foreach (to_ch; ubyte.min .. ubyte.max+1) { auto e = &m_nodes[ncomb].edges[to_ch]; foreach (chn; m_edgeEntries.getItems(chnodes)) m_edgeEntries.insert(e, m_edgeEntries.getItems(m_nodes[chn].edges[to_ch])); } // add terminal indices foreach (chn; m_edgeEntries.getItems(chnodes)) foreach (t; m_nodes[chn].terminals) addTerminal(ncomb, t.index, t.var); foreach (i; 1 .. m_nodes[ncomb].terminals.length) assert(m_nodes[ncomb].terminals[0] != m_nodes[ncomb].terminals[i]); m_nodes[n].edges[ch] = m_edgeEntries.create(ncomb); assert(m_edgeEntries.hasLength(m_nodes[n].edges[ch], 1)); } // process nodes recursively foreach (ch; ubyte.min .. ubyte.max+1) { // should only have single out-edges now assert(m_edgeEntries.hasMaxLength(m_nodes[n].edges[ch], 1)); foreach (e; m_edgeEntries.getItems(m_nodes[n].edges[ch])) node_stack.push(e); } } import std.algorithm.sorting : sort; foreach (ref n; m_nodes) n.terminals[].sort!((a, b) => a.index < b.index)(); debug logDebug("Disambiguate done: %s nodes, %s max stack size", m_nodes.length, node_stack.maxSize); } void print() const @trusted { import std.algorithm : map; import std.array : join; import std.conv : to; import std.string : format; logInfo("Nodes:"); size_t i = 0; foreach (n; m_nodes) { string mapChar(ubyte ch) { if (ch == TerminalChar) return "$"; if (ch >= '0' && ch <= '9') return to!string(cast(dchar)ch); if (ch >= 'a' && ch <= 'z') return to!string(cast(dchar)ch); if (ch >= 'A' && ch <= 'Z') return to!string(cast(dchar)ch); if (ch == '^') return "^"; if (ch == '/') return "/"; return format("$%s", ch); } logInfo(" %s: %s", i, n.terminals[].map!(t => t.var != VarIndex.max ? format("T%s(%s)", t.index, t.var) : format("T%s", t.index)).join(" ")); ubyte first_char; size_t list_hash; NodeSet list; void printEdges(ubyte last_char) { if (!list.empty) { string targets; foreach (tn; m_edgeEntries.getItems(list)) targets ~= format(" %s", tn); if (targets.length > 0) logInfo(" [%s ... %s] -> %s", mapChar(first_char), mapChar(last_char), targets); } } foreach (ch, tnodes; n.edges) { auto h = m_edgeEntries.getHash(tnodes); if (h != list_hash) { printEdges(cast(ubyte)(ch-1)); list_hash = h; list = tnodes; first_char = cast(ubyte)ch; } } printEdges(ubyte.max); i++; } } private void addEdge(NodeIndex from, NodeIndex to, ubyte ch, TerminalIndex terminal, VarIndex var = VarIndex.max) @trusted { m_edgeEntries.insert(&m_nodes[from].edges[ch], to); addTerminal(to, terminal, var); } private NodeIndex addEdge(NodeIndex from, ubyte ch, TerminalIndex terminal, VarIndex var = VarIndex.max) @trusted { import std.algorithm : canFind; import std.string : format; if (!m_nodes[from].edges[ch].empty) assert(false, format("%s is in %s", ch, m_nodes[from].edges[])); auto nidx = addNode(); addEdge(from, nidx, ch, terminal, var); return nidx; } private void addTerminal(NodeIndex node, TerminalIndex terminal, VarIndex var) @trusted { foreach (ref t; m_nodes[node].terminals) { if (t.index == terminal) { if (t.var != VarIndex.max && t.var != var) assert(false, format("Ambiguous route var match!? %s vs %s", t.var, var)); t.var = var; return; } } m_nodes[node].terminals ~= TerminalTag(terminal, var); } private NodeIndex addNode() @trusted { assert(m_nodes.length <= 1_000_000_000, "More than 1B nodes in tree!?"); auto idx = cast(NodeIndex)m_nodes.length; m_nodes ~= Node.init; return idx; } } struct LinkedSetBacking(T) { import std.container.array : Array; import std.range : isInputRange; static struct Handle { uint index = uint.max; @property bool empty() const { return index == uint.max; } } private { static struct Entry { uint next; T value; } Array!Entry m_storage; static struct Range { private { Array!Entry* backing; uint index; } @property bool empty() const { return index == uint.max; } @property ref const(T) front() const { return (*backing)[index].value; } void popFront() { index = (*backing)[index].next; } } } @property Handle emptySet() { return Handle.init; } Handle create(scope T[] items...) { Handle ret; foreach (i; items) ret.index = createNode(i, ret.index); return ret; } void insert(Handle* h, T value) { /*foreach (c; getItems(*h)) if (value == c) return;*/ h.index = createNode(value, h.index); } void insert(R)(Handle* h, R items) if (isInputRange!R) { foreach (itm; items) insert(h, itm); } size_t getHash(Handle sh) const { // NOTE: the returned hash is order independent, to avoid bogus // mismatches when comparing lists of different order size_t ret = 0x72d2da6c; while (sh != Handle.init) { ret ^= (hashOf(m_storage[sh.index].value) ^ 0xb1bdfb8d) * 0x5dbf04a4; sh.index = m_storage[sh.index].next; } return ret; } auto getItems(Handle sh) { return Range(&m_storage, sh.index); } auto getItems(Handle sh) const { return Range(&(cast()this).m_storage, sh.index); } bool hasMaxLength(Handle sh, size_t l) const { uint idx = sh.index; do { if (idx == uint.max) return true; idx = m_storage[idx].next; } while (l-- > 0); return false; } bool hasLength(Handle sh, size_t l) const { uint idx = sh.index; while (l-- > 0) { if (idx == uint.max) return false; idx = m_storage[idx].next; } return idx == uint.max; } private uint createNode(ref T val, uint next) { auto id = cast(uint)m_storage.length; m_storage ~= Entry(next, val); return id; } } unittest { import std.algorithm.comparison : equal; LinkedSetBacking!int b; auto s = b.emptySet; assert(s.empty); assert(b.getItems(s).empty); s = b.create(3, 5, 7); assert(b.getItems(s).equal([7, 5, 3])); assert(!b.hasLength(s, 2)); assert(b.hasLength(s, 3)); assert(!b.hasLength(s, 4)); assert(!b.hasMaxLength(s, 2)); assert(b.hasMaxLength(s, 3)); assert(b.hasMaxLength(s, 4)); auto h = b.getHash(s); assert(h != b.getHash(b.emptySet)); s = b.create(5, 3, 7); assert(b.getHash(s) == h); b.insert(&s, 11); assert(b.hasLength(s, 4)); assert(b.getHash(s) != h); } private struct Stack(E) { import std.range : isInputRange; private { E[] m_storage; size_t m_fill; debug size_t m_maxFill; } @property bool empty() const { return m_fill == 0; } @property size_t fill() const { return m_fill; } debug @property size_t maxSize() const { return m_maxFill; } void reserve(size_t amt) { auto minsz = m_fill + amt; if (m_storage.length < minsz) { auto newlength = 64; while (newlength < minsz) newlength *= 2; m_storage.length = newlength; } } void push(E el) { reserve(1); m_storage[m_fill++] = el; debug if (m_fill > m_maxFill) m_maxFill = m_fill; } void push(R)(R els) if (isInputRange!R) { reserve(els.length); foreach (el; els) m_storage[m_fill++] = el; debug if (m_fill > m_maxFill) m_maxFill = m_fill; } E pop() { assert(!empty, "Stack underflow."); return m_storage[--m_fill]; } }