File: test_benchmarks_web_urldispatcher.py

package info (click to toggle)
python-aiohttp 3.11.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,156 kB
  • sloc: python: 51,898; ansic: 20,843; makefile: 395; javascript: 31; sh: 3
file content (575 lines) | stat: -rw-r--r-- 17,678 bytes parent folder | download
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""codspeed benchmarks for the URL dispatcher."""

import asyncio
import json
import pathlib
import random
import string
from pathlib import Path
from typing import NoReturn, Optional, cast
from unittest import mock

import pytest
from multidict import CIMultiDict, CIMultiDictProxy
from pytest_codspeed import BenchmarkFixture
from yarl import URL

import aiohttp
from aiohttp import web
from aiohttp.http import HttpVersion, RawRequestMessage


@pytest.fixture
def github_urls() -> list[str]:
    """GitHub api urls."""
    # The fixture provides OpenAPI generated info for github.
    # To update the local data file please run the following command:
    # $ curl https://raw.githubusercontent.com/github/rest-api-description/refs/heads/main/descriptions/api.github.com/api.github.com.json | jq ".paths | keys" > github-urls.json

    here = Path(__file__).parent
    with (here / "github-urls.json").open() as f:
        urls = json.load(f)

    return cast(list[str], urls)


def _mock_request(method: str, path: str) -> web.Request:
    message = RawRequestMessage(
        method,
        path,
        HttpVersion(1, 1),
        CIMultiDictProxy(CIMultiDict()),
        (),
        False,
        None,
        False,
        False,
        URL(path),
    )

    return web.Request(
        message, mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock()
    )


def test_resolve_root_route(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve top level PlainResources route 100 times."""
    resolve_count = 100

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    app.router.add_route("GET", "/", handler)
    app.freeze()
    router = app.router
    request = _mock_request(method="GET", path="/")

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for _ in range(resolve_count):
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["path"] == "/", ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_root_route_with_many_fixed_routes(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve top level PlainResources route 100 times."""
    resolve_count = 100

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    app.router.add_route("GET", "/", handler)
    for count in range(250):
        app.router.add_route("GET", f"/api/server/dispatch/{count}/update", handler)
        app.router.add_route("GET", f"/api/server/dispatch/{count}", handler)
    app.router.add_route("GET", "/api/server/dispatch", handler)
    app.router.add_route("GET", "/api/server", handler)
    app.router.add_route("GET", "/api", handler)
    app.freeze()
    router = app.router
    request = _mock_request(method="GET", path="/")

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for _ in range(resolve_count):
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["path"] == "/", ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_static_root_route(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve top level StaticResource route 100 times."""
    resolve_count = 100

    app = web.Application()
    here = pathlib.Path(aiohttp.__file__).parent
    app.router.add_static("/", here)
    app.freeze()
    router = app.router
    request = _mock_request(method="GET", path="/")

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for _ in range(resolve_count):
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["directory"] == here, ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_single_fixed_url_with_many_routes(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve PlainResources route 100 times."""
    resolve_count = 100

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for count in range(250):
        app.router.add_route("GET", f"/api/server/dispatch/{count}/update", handler)
    app.freeze()
    router = app.router
    request = _mock_request(method="GET", path="/api/server/dispatch/1/update")

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for _ in range(resolve_count):
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["path"] == "/api/server/dispatch/1/update", ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_multiple_fixed_url_with_many_routes(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve 250 different PlainResources routes."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for count in range(250):
        app.router.add_route("GET", f"/api/server/dispatch/{count}/update", handler)
    app.freeze()
    router = app.router

    requests = [
        _mock_request(method="GET", path=f"/api/server/dispatch/{count}/update")
        for count in range(250)
    ]

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)
        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["path"] == "/api/server/dispatch/249/update", ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_multiple_level_fixed_url_with_many_routes(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve 1024 different PlainResources routes."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    urls = [
        f"/api/{a}/{b}/{c}/{d}/{e}/update"
        for a in ("a", "b", "c", "d")
        for b in ("e", "f", "g", "h")
        for c in ("i", "j", "k", "l")
        for d in ("m", "n", "o", "p")
        for e in ("n", "o", "p", "q")
    ]
    for url in urls:
        app.router.add_route("GET", url, handler)
    app.freeze()
    router = app.router

    requests = [(_mock_request(method="GET", path=url), url) for url in urls]

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request, path in requests:
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["path"] == url, ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_dynamic_resource_url_with_many_static_routes(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve different a DynamicResource when there are 250 PlainResources registered."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for count in range(250):
        app.router.add_route("GET", f"/api/server/other/{count}/update", handler)
    app.router.add_route("GET", "/api/server/dispatch/{customer}/update", handler)
    app.freeze()
    router = app.router

    requests = [
        _mock_request(method="GET", path=f"/api/server/dispatch/{customer}/update")
        for customer in range(250)
    ]

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert (
        ret.get_info()["formatter"] == "/api/server/dispatch/{customer}/update"
    ), ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_dynamic_resource_url_with_many_dynamic_routes(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve different a DynamicResource when there are 250 DynamicResources registered."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for count in range(250):
        app.router.add_route(
            "GET", f"/api/server/other/{{customer}}/update{count}", handler
        )
    app.router.add_route("GET", "/api/server/dispatch/{customer}/update", handler)
    app.freeze()
    router = app.router

    requests = [
        _mock_request(method="GET", path=f"/api/server/dispatch/{customer}/update")
        for customer in range(250)
    ]

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert (
        ret.get_info()["formatter"] == "/api/server/dispatch/{customer}/update"
    ), ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_dynamic_resource_url_with_many_dynamic_routes_with_common_prefix(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve different a DynamicResource when there are 250 DynamicResources registered with the same common prefix."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for count in range(250):
        app.router.add_route("GET", f"/api/{{customer}}/show_{count}", handler)
    app.router.add_route("GET", "/api/{customer}/update", handler)
    app.freeze()
    router = app.router

    requests = [
        _mock_request(method="GET", path=f"/api/{customer}/update")
        for customer in range(250)
    ]

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)

        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["formatter"] == "/api/{customer}/update", ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_gitapi(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
    github_urls: list[str],
) -> None:
    """Resolve DynamicResource for simulated github API."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for url in github_urls:
        app.router.add_get(url, handler)
    app.freeze()
    router = app.router

    # PR reviews API was selected absolutely voluntary.
    # It is not any special but sits somewhere in the middle of the urls list.
    # If anybody has better idea please suggest.

    alnums = string.ascii_letters + string.digits

    requests = []
    for i in range(250):
        owner = "".join(random.sample(alnums, 10))
        repo = "".join(random.sample(alnums, 10))
        pull_number = random.randint(0, 250)
        requests.append(
            _mock_request(
                method="GET", path=f"/repos/{owner}/{repo}/pulls/{pull_number}/reviews"
            )
        )

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)
        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert (
        ret.get_info()["formatter"]
        == "/repos/{owner}/{repo}/pulls/{pull_number}/reviews"
    ), ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_gitapi_subapps(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
    github_urls: list[str],
) -> None:
    """Resolve DynamicResource for simulated github API, grouped in subapps."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    subapps = {
        "gists": web.Application(),
        "orgs": web.Application(),
        "projects": web.Application(),
        "repos": web.Application(),
        "teams": web.Application(),
        "user": web.Application(),
        "users": web.Application(),
    }

    app = web.Application()
    for url in github_urls:
        parts = url.split("/")
        subapp = subapps.get(parts[1])
        if subapp is not None:
            sub_url = "/".join([""] + parts[2:])
            if not sub_url:
                sub_url = "/"
            subapp.router.add_get(sub_url, handler)
        else:
            app.router.add_get(url, handler)
    for key, subapp in subapps.items():
        app.add_subapp("/" + key, subapp)
    app.freeze()
    router = app.router

    # PR reviews API was selected absolutely voluntary.
    # It is not any special but sits somewhere in the middle of the urls list.
    # If anybody has better idea please suggest.

    alnums = string.ascii_letters + string.digits

    requests = []
    for i in range(250):
        owner = "".join(random.sample(alnums, 10))
        repo = "".join(random.sample(alnums, 10))
        pull_number = random.randint(0, 250)
        requests.append(
            _mock_request(
                method="GET", path=f"/repos/{owner}/{repo}/pulls/{pull_number}/reviews"
            )
        )

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)
        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert (
        ret.get_info()["formatter"]
        == "/repos/{owner}/{repo}/pulls/{pull_number}/reviews"
    ), ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_gitapi_root(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
    github_urls: list[str],
) -> None:
    """Resolve the plain root for simulated github API."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for url in github_urls:
        app.router.add_get(url, handler)
    app.freeze()
    router = app.router

    request = _mock_request(method="GET", path="/")

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for i in range(250):
            ret = await router.resolve(request)
        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert ret.get_info()["path"] == "/", ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())


def test_resolve_prefix_resources_many_prefix_many_plain(
    loop: asyncio.AbstractEventLoop,
    benchmark: BenchmarkFixture,
) -> None:
    """Resolve prefix resource (sub_app) whene 250 PlainResources registered and there are 250 subapps that shares the same sub_app path prefix."""

    async def handler(request: web.Request) -> NoReturn:
        assert False

    app = web.Application()
    for count in range(250):
        app.router.add_get(f"/api/server/other/{count}/update", handler)
    for count in range(250):
        subapp = web.Application()
        # sub_apps exists for handling deep enough nested route trees
        subapp.router.add_get("/deep/enough/sub/path", handler)
        app.add_subapp(f"/api/path/to/plugin/{count}", subapp)
    app.freeze()
    router = app.router

    requests = [
        _mock_request(method="GET", path="/api/path/to/plugin/249/deep/enough/sub/path")
        for customer in range(250)
    ]

    async def run_url_dispatcher_benchmark() -> Optional[web.UrlMappingMatchInfo]:
        ret = None
        for request in requests:
            ret = await router.resolve(request)
        return ret

    ret = loop.run_until_complete(run_url_dispatcher_benchmark())
    assert ret is not None
    assert (
        ret.get_info()["path"] == "/api/path/to/plugin/249/deep/enough/sub/path"
    ), ret.get_info()

    @benchmark
    def _run() -> None:
        loop.run_until_complete(run_url_dispatcher_benchmark())