| 1 |
# mypy: allow-untyped-defs |
| 2 |
|
| 3 |
import abc |
| 4 |
import argparse |
| 5 |
import importlib |
| 6 |
import json |
| 7 |
import logging |
| 8 |
import multiprocessing |
| 9 |
import os |
| 10 |
import platform |
| 11 |
import subprocess |
| 12 |
import sys |
| 13 |
import threading |
| 14 |
import time |
| 15 |
import traceback |
| 16 |
import urllib |
| 17 |
import uuid |
| 18 |
from collections import defaultdict, OrderedDict |
| 19 |
from io import IOBase |
| 20 |
from itertools import chain, product |
| 21 |
from html5lib import html5parser |
| 22 |
from typing import ClassVar, List, Optional, Set, Tuple |
| 23 |
|
| 24 |
from localpaths import repo_root # type: ignore |
| 25 |
|
| 26 |
from manifest.sourcefile import read_script_metadata, js_meta_re, parse_variants # type: ignore |
| 27 |
from wptserve import server as wptserve, handlers |
| 28 |
from wptserve import stash |
| 29 |
from wptserve import config |
| 30 |
from wptserve.handlers import filesystem_path, wrap_pipeline |
| 31 |
from wptserve.response import ResponseHeaders |
| 32 |
from wptserve.utils import get_port, HTTPException, http2_compatible |
| 33 |
from pywebsocket3 import standalone as pywebsocket |
| 34 |
|
| 35 |
|
| 36 |
EDIT_HOSTS_HELP = ("Please ensure all the necessary WPT subdomains " |
| 37 |
"are mapped to a loopback device in /etc/hosts.\n" |
| 38 |
"See https://web-platform-tests.org/running-tests/from-local-system.html#system-setup " |
| 39 |
"for instructions.") |
| 40 |
|
| 41 |
|
| 42 |
def replace_end(s, old, new): |
| 43 |
""" |
| 44 |
Given a string `s` that ends with `old`, replace that occurrence of `old` |
| 45 |
with `new`. |
| 46 |
""" |
| 47 |
assert s.endswith(old) |
| 48 |
return s[:-len(old)] + new |
| 49 |
|
| 50 |
|
| 51 |
def domains_are_distinct(a, b): |
| 52 |
a_parts = a.split(".") |
| 53 |
b_parts = b.split(".") |
| 54 |
min_length = min(len(a_parts), len(b_parts)) |
| 55 |
slice_index = -1 * min_length |
| 56 |
|
| 57 |
return a_parts[slice_index:] != b_parts[slice_index:] |
| 58 |
|
| 59 |
|
| 60 |
def inject_script(html, script_tag): |
| 61 |
# Tokenize and find the position of the first content (e.g. after the |
| 62 |
# doctype, html, and head opening tags if present but before any other tags). |
| 63 |
token_types = html5parser.tokenTypes |
| 64 |
after_tags = {"html", "head"} |
| 65 |
before_tokens = {token_types["EndTag"], token_types["EmptyTag"], |
| 66 |
token_types["Characters"]} |
| 67 |
error_tokens = {token_types["ParseError"]} |
| 68 |
|
| 69 |
tokenizer = html5parser._tokenizer.HTMLTokenizer(html) |
| 70 |
stream = tokenizer.stream |
| 71 |
offset = 0 |
| 72 |
error = False |
| 73 |
for item in tokenizer: |
| 74 |
if item["type"] == token_types["StartTag"]: |
| 75 |
if not item["name"].lower() in after_tags: |
| 76 |
break |
| 77 |
elif item["type"] in before_tokens: |
| 78 |
break |
| 79 |
elif item["type"] in error_tokens: |
| 80 |
error = True |
| 81 |
break |
| 82 |
offset = stream.chunkOffset |
| 83 |
else: |
| 84 |
error = True |
| 85 |
|
| 86 |
if not error and stream.prevNumCols or stream.prevNumLines: |
| 87 |
# We're outside the first chunk, so we don't know what to do |
| 88 |
error = True |
| 89 |
|
| 90 |
if error: |
| 91 |
return html |
| 92 |
else: |
| 93 |
return html[:offset] + script_tag + html[offset:] |
| 94 |
|
| 95 |
|
| 96 |
class WrapperHandler(metaclass=abc.ABCMeta): |
| 97 |
|
| 98 |
headers: ClassVar[List[Tuple[str, str]]] = [] |
| 99 |
|
| 100 |
def __init__(self, base_path=None, url_base="/"): |
| 101 |
self.base_path = base_path |
| 102 |
self.url_base = url_base |
| 103 |
self.handler = handlers.handler(self.handle_request) |
| 104 |
|
| 105 |
def __call__(self, request, response): |
| 106 |
self.handler(request, response) |
| 107 |
|
| 108 |
def handle_request(self, request, response): |
| 109 |
headers = self.headers + handlers.load_headers( |
| 110 |
request, self._get_filesystem_path(request)) |
| 111 |
for header_name, header_value in headers: |
| 112 |
response.headers.set(header_name, header_value) |
| 113 |
|
| 114 |
self.check_exposure(request) |
| 115 |
|
| 116 |
path = self._get_path(request.url_parts.path, True) |
| 117 |
query = request.url_parts.query |
| 118 |
if query: |
| 119 |
query = "?" + query |
| 120 |
meta = "\n".join(self._get_meta(request)) |
| 121 |
script = "\n".join(self._get_script(request)) |
| 122 |
response.content = self.wrapper % {"meta": meta, "script": script, "path": path, "query": query} |
| 123 |
wrap_pipeline(path, request, response) |
| 124 |
|
| 125 |
def _get_path(self, path, resource_path): |
| 126 |
"""Convert the path from an incoming request into a path corresponding to an "unwrapped" |
| 127 |
resource e.g. the file on disk that will be loaded in the wrapper. |
| 128 |
|
| 129 |
:param path: Path from the HTTP request |
| 130 |
:param resource_path: Boolean used to control whether to get the path for the resource that |
| 131 |
this wrapper will load or the associated file on disk. |
| 132 |
Typically these are the same but may differ when there are multiple |
| 133 |
layers of wrapping e.g. for a .any.worker.html input the underlying disk file is |
| 134 |
.any.js but the top level html file loads a resource with a |
| 135 |
.any.worker.js extension, which itself loads the .any.js file. |
| 136 |
If True return the path to the resource that the wrapper will load, |
| 137 |
otherwise return the path to the underlying file on disk.""" |
| 138 |
for item in self.path_replace: |
| 139 |
if len(item) == 2: |
| 140 |
src, dest = item |
| 141 |
else: |
| 142 |
assert len(item) == 3 |
| 143 |
src = item[0] |
| 144 |
dest = item[2 if resource_path else 1] |
| 145 |
if path.endswith(src): |
| 146 |
path = replace_end(path, src, dest) |
| 147 |
return path |
| 148 |
|
| 149 |
def _get_filesystem_path(self, request): |
| 150 |
"""Get the path of the underlying resource file on disk.""" |
| 151 |
return self._get_path(filesystem_path(self.base_path, request, self.url_base), False) |
| 152 |
|
| 153 |
def _get_metadata(self, request): |
| 154 |
"""Get an iterator over script metadata based on // META comments in the |
| 155 |
associated js file. |
| 156 |
|
| 157 |
:param request: The Request being processed. |
| 158 |
""" |
| 159 |
path = self._get_filesystem_path(request) |
| 160 |
try: |
| 161 |
with open(path, "rb") as f: |
| 162 |
yield from read_script_metadata(f, js_meta_re) |
| 163 |
except OSError: |
| 164 |
raise HTTPException(404) |
| 165 |
|
| 166 |
def _get_meta(self, request): |
| 167 |
"""Get an iterator over strings to inject into the wrapper document |
| 168 |
based on // META comments in the associated js file. |
| 169 |
|
| 170 |
:param request: The Request being processed. |
| 171 |
""" |
| 172 |
for key, value in self._get_metadata(request): |
| 173 |
replacement = self._meta_replacement(key, value) |
| 174 |
if replacement: |
| 175 |
yield replacement |
| 176 |
|
| 177 |
def _get_script(self, request): |
| 178 |
"""Get an iterator over strings to inject into the wrapper document |
| 179 |
based on // META comments in the associated js file. |
| 180 |
|
| 181 |
:param request: The Request being processed. |
| 182 |
""" |
| 183 |
for key, value in self._get_metadata(request): |
| 184 |
replacement = self._script_replacement(key, value) |
| 185 |
if replacement: |
| 186 |
yield replacement |
| 187 |
|
| 188 |
@abc.abstractproperty |
| 189 |
def path_replace(self): |
| 190 |
# A list containing a mix of 2 item tuples with (input suffix, output suffix) |
| 191 |
# and 3-item tuples with (input suffix, filesystem suffix, resource suffix) |
| 192 |
# for the case where we want a different path in the generated resource to |
| 193 |
# the actual path on the filesystem (e.g. when there is another handler |
| 194 |
# that will wrap the file). |
| 195 |
return None |
| 196 |
|
| 197 |
@abc.abstractproperty |
| 198 |
def wrapper(self): |
| 199 |
# String template with variables path and meta for wrapper document |
| 200 |
return None |
| 201 |
|
| 202 |
@abc.abstractmethod |
| 203 |
def _meta_replacement(self, key, value): |
| 204 |
# Get the string to insert into the wrapper document, given |
| 205 |
# a specific metadata key: value pair. |
| 206 |
pass |
| 207 |
|
| 208 |
def check_exposure(self, request): |
| 209 |
# Raise an exception if this handler shouldn't be exposed after all. |
| 210 |
pass |
| 211 |
|
| 212 |
|
| 213 |
class HtmlWrapperHandler(WrapperHandler): |
| 214 |
global_type: ClassVar[Optional[str]] = None |
| 215 |
headers = [('Content-Type', 'text/html')] |
| 216 |
|
| 217 |
def check_exposure(self, request): |
| 218 |
if self.global_type is not None: |
| 219 |
global_variants = "" |
| 220 |
for (key, value) in self._get_metadata(request): |
| 221 |
if key == "global": |
| 222 |
global_variants = value |
| 223 |
break |
| 224 |
|
| 225 |
if self.global_type not in parse_variants(global_variants): |
| 226 |
raise HTTPException(404, "This test cannot be loaded in %s mode" % |
| 227 |
self.global_type) |
| 228 |
|
| 229 |
def _meta_replacement(self, key, value): |
| 230 |
if key == "timeout": |
| 231 |
if value == "long": |
| 232 |
return '<meta name="timeout" content="long">' |
| 233 |
if key == "title": |
| 234 |
value = value.replace("&", "&").replace("<", "<") |
| 235 |
return '<title>%s</title>' % value |
| 236 |
return None |
| 237 |
|
| 238 |
def _script_replacement(self, key, value): |
| 239 |
if key == "script": |
| 240 |
attribute = value.replace("&", "&").replace('"', """) |
| 241 |
return '<script src="%s"></script>' % attribute |
| 242 |
return None |
| 243 |
|
| 244 |
|
| 245 |
class HtmlScriptInjectorHandlerWrapper: |
| 246 |
def __init__(self, inject="", wrap=None): |
| 247 |
self.inject = inject |
| 248 |
self.wrap = wrap |
| 249 |
|
| 250 |
def __call__(self, request, response): |
| 251 |
self.wrap(request, response) |
| 252 |
# If the response content type isn't html, don't modify it. |
| 253 |
if not isinstance(response.headers, ResponseHeaders) or response.headers.get("Content-Type")[0] != b"text/html": |
| 254 |
return response |
| 255 |
|
| 256 |
# Skip injection on custom streaming responses. |
| 257 |
if not isinstance(response.content, (bytes, str, IOBase)) and not hasattr(response, "read"): |
| 258 |
return response |
| 259 |
|
| 260 |
response.content = inject_script( |
| 261 |
b"".join(response.iter_content(read_file=True)), |
| 262 |
b"<script>\n" + |
| 263 |
self.inject + b"\n" + |
| 264 |
(b"// Remove the injected script tag from the DOM.\n" |
| 265 |
b"document.currentScript.remove();\n" |
| 266 |
b"</script>\n")) |
| 267 |
return response |
| 268 |
|
| 269 |
|
| 270 |
class WorkersHandler(HtmlWrapperHandler): |
| 271 |
global_type = "dedicatedworker" |
| 272 |
path_replace = [(".any.worker.html", ".any.js", ".any.worker.js"), |
| 273 |
(".worker.html", ".worker.js")] |
| 274 |
wrapper = """<!doctype html> |
| 275 |
<meta charset=utf-8> |
| 276 |
%(meta)s |
| 277 |
<script src="/resources/testharness.js"></script> |
| 278 |
<script src="/resources/testharnessreport.js"></script> |
| 279 |
<div id=log></div> |
| 280 |
<script> |
| 281 |
fetch_tests_from_worker(new Worker("%(path)s%(query)s")); |
| 282 |
</script> |
| 283 |
""" |
| 284 |
|
| 285 |
|
| 286 |
class WorkerModulesHandler(HtmlWrapperHandler): |
| 287 |
global_type = "dedicatedworker-module" |
| 288 |
path_replace = [(".any.worker-module.html", ".any.js", ".any.worker-module.js"), |
| 289 |
(".worker.html", ".worker.js")] |
| 290 |
wrapper = """<!doctype html> |
| 291 |
<meta charset=utf-8> |
| 292 |
%(meta)s |
| 293 |
<script src="/resources/testharness.js"></script> |
| 294 |
<script src="/resources/testharnessreport.js"></script> |
| 295 |
<div id=log></div> |
| 296 |
<script> |
| 297 |
fetch_tests_from_worker(new Worker("%(path)s%(query)s", { type: "module" })); |
| 298 |
</script> |
| 299 |
""" |
| 300 |
|
| 301 |
|
| 302 |
class WindowHandler(HtmlWrapperHandler): |
| 303 |
path_replace = [(".window.html", ".window.js")] |
| 304 |
wrapper = """<!doctype html> |
| 305 |
<meta charset=utf-8> |
| 306 |
%(meta)s |
| 307 |
<script src="/resources/testharness.js"></script> |
| 308 |
<script src="/resources/testharnessreport.js"></script> |
| 309 |
%(script)s |
| 310 |
<div id=log></div> |
| 311 |
<script src="%(path)s"></script> |
| 312 |
""" |
| 313 |
|
| 314 |
|
| 315 |
class WindowModulesHandler(HtmlWrapperHandler): |
| 316 |
global_type = "window-module" |
| 317 |
path_replace = [(".any.window-module.html", ".any.js")] |
| 318 |
wrapper = """<!doctype html> |
| 319 |
<meta charset=utf-8> |
| 320 |
%(meta)s |
| 321 |
<script src="/resources/testharness.js"></script> |
| 322 |
<script src="/resources/testharnessreport.js"></script> |
| 323 |
%(script)s |
| 324 |
<div id=log></div> |
| 325 |
<script type=module src="%(path)s"></script> |
| 326 |
""" |
| 327 |
|
| 328 |
|
| 329 |
class AnyHtmlHandler(HtmlWrapperHandler): |
| 330 |
global_type = "window" |
| 331 |
path_replace = [(".any.html", ".any.js")] |
| 332 |
wrapper = """<!doctype html> |
| 333 |
<meta charset=utf-8> |
| 334 |
%(meta)s |
| 335 |
<script> |
| 336 |
self.GLOBAL = { |
| 337 |
isWindow: function() { return true; }, |
| 338 |
isWorker: function() { return false; }, |
| 339 |
isShadowRealm: function() { return false; }, |
| 340 |
}; |
| 341 |
</script> |
| 342 |
<script src="/resources/testharness.js"></script> |
| 343 |
<script src="/resources/testharnessreport.js"></script> |
| 344 |
%(script)s |
| 345 |
<div id=log></div> |
| 346 |
<script src="%(path)s"></script> |
| 347 |
""" |
| 348 |
|
| 349 |
|
| 350 |
class SharedWorkersHandler(HtmlWrapperHandler): |
| 351 |
global_type = "sharedworker" |
| 352 |
path_replace = [(".any.sharedworker.html", ".any.js", ".any.worker.js")] |
| 353 |
wrapper = """<!doctype html> |
| 354 |
<meta charset=utf-8> |
| 355 |
%(meta)s |
| 356 |
<script src="/resources/testharness.js"></script> |
| 357 |
<script src="/resources/testharnessreport.js"></script> |
| 358 |
<div id=log></div> |
| 359 |
<script> |
| 360 |
fetch_tests_from_worker(new SharedWorker("%(path)s%(query)s")); |
| 361 |
</script> |
| 362 |
""" |
| 363 |
|
| 364 |
|
| 365 |
class SharedWorkerModulesHandler(HtmlWrapperHandler): |
| 366 |
global_type = "sharedworker-module" |
| 367 |
path_replace = [(".any.sharedworker-module.html", ".any.js", ".any.worker-module.js")] |
| 368 |
wrapper = """<!doctype html> |
| 369 |
<meta charset=utf-8> |
| 370 |
%(meta)s |
| 371 |
<script src="/resources/testharness.js"></script> |
| 372 |
<script src="/resources/testharnessreport.js"></script> |
| 373 |
<div id=log></div> |
| 374 |
<script> |
| 375 |
fetch_tests_from_worker(new SharedWorker("%(path)s%(query)s", { type: "module" })); |
| 376 |
</script> |
| 377 |
""" |
| 378 |
|
| 379 |
|
| 380 |
class ServiceWorkersHandler(HtmlWrapperHandler): |
| 381 |
global_type = "serviceworker" |
| 382 |
path_replace = [(".any.serviceworker.html", ".any.js", ".any.worker.js")] |
| 383 |
wrapper = """<!doctype html> |
| 384 |
<meta charset=utf-8> |
| 385 |
%(meta)s |
| 386 |
<script src="/resources/testharness.js"></script> |
| 387 |
<script src="/resources/testharnessreport.js"></script> |
| 388 |
<div id=log></div> |
| 389 |
<script> |
| 390 |
(async function() { |
| 391 |
const scope = 'does/not/exist'; |
| 392 |
let reg = await navigator.serviceWorker.getRegistration(scope); |
| 393 |
if (reg) await reg.unregister(); |
| 394 |
reg = await navigator.serviceWorker.register("%(path)s%(query)s", {scope}); |
| 395 |
fetch_tests_from_worker(reg.installing); |
| 396 |
})(); |
| 397 |
</script> |
| 398 |
""" |
| 399 |
|
| 400 |
|
| 401 |
class ServiceWorkerModulesHandler(HtmlWrapperHandler): |
| 402 |
global_type = "serviceworker-module" |
| 403 |
path_replace = [(".any.serviceworker-module.html", |
| 404 |
".any.js", ".any.worker-module.js")] |
| 405 |
wrapper = """<!doctype html> |
| 406 |
<meta charset=utf-8> |
| 407 |
%(meta)s |
| 408 |
<script src="/resources/testharness.js"></script> |
| 409 |
<script src="/resources/testharnessreport.js"></script> |
| 410 |
<div id=log></div> |
| 411 |
<script> |
| 412 |
(async function() { |
| 413 |
const scope = 'does/not/exist'; |
| 414 |
let reg = await navigator.serviceWorker.getRegistration(scope); |
| 415 |
if (reg) await reg.unregister(); |
| 416 |
reg = await navigator.serviceWorker.register( |
| 417 |
"%(path)s%(query)s", |
| 418 |
{ scope, type: 'module' }, |
| 419 |
); |
| 420 |
fetch_tests_from_worker(reg.installing); |
| 421 |
})(); |
| 422 |
</script> |
| 423 |
""" |
| 424 |
|
| 425 |
|
| 426 |
class ShadowRealmInWindowHandler(HtmlWrapperHandler): |
| 427 |
global_type = "shadowrealm-in-window" |
| 428 |
path_replace = [(".any.shadowrealm-in-window.html", ".any.js")] |
| 429 |
|
| 430 |
wrapper = """<!doctype html> |
| 431 |
<meta charset=utf-8> |
| 432 |
%(meta)s |
| 433 |
<script src="/resources/testharness.js"></script> |
| 434 |
<script src="/resources/testharnessreport.js"></script> |
| 435 |
<script src="/resources/testharness-shadowrealm-outer.js"></script> |
| 436 |
<script> |
| 437 |
(async function() { |
| 438 |
const r = new ShadowRealm(); |
| 439 |
await shadowRealmEvalAsync(r, ` |
| 440 |
await import("/resources/testharness-shadowrealm-inner.js"); |
| 441 |
await import("/resources/testharness.js"); |
| 442 |
`); |
| 443 |
r.evaluate("setShadowRealmGlobalProperties")(location.search, fetchAdaptor); |
| 444 |
|
| 445 |
await shadowRealmEvalAsync(r, ` |
| 446 |
%(script)s |
| 447 |
await import("%(path)s"); |
| 448 |
`); |
| 449 |
|
| 450 |
await fetch_tests_from_shadow_realm(r); |
| 451 |
done(); |
| 452 |
})().catch(e => setup(() => { throw e; })); |
| 453 |
</script> |
| 454 |
""" |
| 455 |
|
| 456 |
def _script_replacement(self, key, value): |
| 457 |
if key == "script": |
| 458 |
return 'await import("%s");' % value |
| 459 |
return None |
| 460 |
|
| 461 |
|
| 462 |
class ShadowRealmInShadowRealmHandler(HtmlWrapperHandler): |
| 463 |
global_type = "shadowrealm-in-shadowrealm" |
| 464 |
path_replace = [(".any.shadowrealm-in-shadowrealm.html", ".any.js")] |
| 465 |
|
| 466 |
wrapper = """<!doctype html> |
| 467 |
<meta charset=utf-8> |
| 468 |
%(meta)s |
| 469 |
<script src="/resources/testharness.js"></script> |
| 470 |
<script src="/resources/testharnessreport.js"></script> |
| 471 |
<script src="/resources/testharness-shadowrealm-outer.js"></script> |
| 472 |
<script> |
| 473 |
(async function() { |
| 474 |
const outer = new ShadowRealm(); |
| 475 |
outer.evaluate(` |
| 476 |
var inner = new ShadowRealm(); |
| 477 |
`); |
| 478 |
await shadowRealmEvalAsync(outer, ` |
| 479 |
await import("/resources/testharness-shadowrealm-outer.js"); |
| 480 |
await shadowRealmEvalAsync(inner, \\` |
| 481 |
await import("/resources/testharness-shadowrealm-inner.js"); |
| 482 |
await import("/resources/testharness.js"); |
| 483 |
\\`); |
| 484 |
`); |
| 485 |
|
| 486 |
outer.evaluate(` |
| 487 |
inner.evaluate("setShadowRealmGlobalProperties") |
| 488 |
`)(location.search, fetchAdaptor); |
| 489 |
|
| 490 |
await shadowRealmEvalAsync(outer, ` |
| 491 |
await shadowRealmEvalAsync(inner, \\` |
| 492 |
%(script)s |
| 493 |
await import("%(path)s"); |
| 494 |
\\`); |
| 495 |
`); |
| 496 |
|
| 497 |
outer.evaluate(` |
| 498 |
function begin_shadow_realm_tests(windowCallback) { |
| 499 |
inner.evaluate("begin_shadow_realm_tests")(windowCallback); |
| 500 |
} |
| 501 |
`); |
| 502 |
await fetch_tests_from_shadow_realm(outer); |
| 503 |
done(); |
| 504 |
})().catch(e => setup(() => { throw e; })); |
| 505 |
</script> |
| 506 |
""" |
| 507 |
|
| 508 |
def _script_replacement(self, key, value): |
| 509 |
if key == "script": |
| 510 |
return 'await import("%s");' % value |
| 511 |
return None |
| 512 |
|
| 513 |
|
| 514 |
class ShadowRealmInDedicatedWorkerHandler(WorkersHandler): |
| 515 |
global_type = "shadowrealm-in-dedicatedworker" |
| 516 |
path_replace = [(".any.shadowrealm-in-dedicatedworker.html", |
| 517 |
".any.js", |
| 518 |
".any.worker-shadowrealm.js")] |
| 519 |
|
| 520 |
|
| 521 |
class ShadowRealmInSharedWorkerHandler(SharedWorkersHandler): |
| 522 |
global_type = "shadowrealm-in-sharedworker" |
| 523 |
path_replace = [(".any.shadowrealm-in-sharedworker.html", |
| 524 |
".any.js", |
| 525 |
".any.worker-shadowrealm.js")] |
| 526 |
|
| 527 |
|
| 528 |
class ShadowRealmInServiceWorkerHandler(ServiceWorkersHandler): |
| 529 |
global_type = "shadowrealm-in-serviceworker" |
| 530 |
path_replace = [(".https.any.shadowrealm-in-serviceworker.html", |
| 531 |
".any.js", |
| 532 |
".any.serviceworker-shadowrealm.js")] |
| 533 |
|
| 534 |
|
| 535 |
class ShadowRealmInAudioWorkletHandler(HtmlWrapperHandler): |
| 536 |
global_type = "shadowrealm-in-audioworklet" |
| 537 |
path_replace = [(".https.any.shadowrealm-in-audioworklet.html", ".any.js", |
| 538 |
".any.audioworklet-shadowrealm.js")] |
| 539 |
|
| 540 |
wrapper = """<!doctype html> |
| 541 |
<meta charset=utf-8> |
| 542 |
%(meta)s |
| 543 |
<script src="/resources/testharness.js"></script> |
| 544 |
<script src="/resources/testharnessreport.js"></script> |
| 545 |
<script src="/resources/testharness-shadowrealm-outer.js"></script> |
| 546 |
<script> |
| 547 |
(async function() { |
| 548 |
const context = new AudioContext(); |
| 549 |
await context.audioWorklet.addModule( |
| 550 |
"/resources/testharness-shadowrealm-outer.js"); |
| 551 |
await context.audioWorklet.addModule( |
| 552 |
"/resources/testharness-shadowrealm-audioworkletprocessor.js"); |
| 553 |
await context.audioWorklet.addModule("%(path)s%(query)s"); |
| 554 |
const node = new AudioWorkletNode(context, "test-runner"); |
| 555 |
setupFakeFetchOverMessagePort(node.port); |
| 556 |
fetch_tests_from_worker(node.port); |
| 557 |
})(); |
| 558 |
</script> |
| 559 |
""" |
| 560 |
|
| 561 |
|
| 562 |
class BaseWorkerHandler(WrapperHandler): |
| 563 |
headers = [('Content-Type', 'text/javascript')] |
| 564 |
|
| 565 |
def _meta_replacement(self, key, value): |
| 566 |
return None |
| 567 |
|
| 568 |
@abc.abstractmethod |
| 569 |
def _create_script_import(self, attribute): |
| 570 |
# Take attribute (a string URL to a JS script) and return JS source to import the script |
| 571 |
# into the worker. |
| 572 |
pass |
| 573 |
|
| 574 |
def _script_replacement(self, key, value): |
| 575 |
if key == "script": |
| 576 |
attribute = value.replace("\\", "\\\\").replace('"', '\\"') |
| 577 |
return self._create_script_import(attribute) |
| 578 |
if key == "title": |
| 579 |
value = value.replace("\\", "\\\\").replace('"', '\\"') |
| 580 |
return 'self.META_TITLE = "%s";' % value |
| 581 |
return None |
| 582 |
|
| 583 |
|
| 584 |
class ClassicWorkerHandler(BaseWorkerHandler): |
| 585 |
path_replace = [(".any.worker.js", ".any.js")] |
| 586 |
wrapper = """%(meta)s |
| 587 |
self.GLOBAL = { |
| 588 |
isWindow: function() { return false; }, |
| 589 |
isWorker: function() { return true; }, |
| 590 |
isShadowRealm: function() { return false; }, |
| 591 |
}; |
| 592 |
importScripts("/resources/testharness.js"); |
| 593 |
%(script)s |
| 594 |
importScripts("%(path)s"); |
| 595 |
done(); |
| 596 |
""" |
| 597 |
|
| 598 |
def _create_script_import(self, attribute): |
| 599 |
return 'importScripts("%s")' % attribute |
| 600 |
|
| 601 |
|
| 602 |
class ModuleWorkerHandler(BaseWorkerHandler): |
| 603 |
path_replace = [(".any.worker-module.js", ".any.js")] |
| 604 |
wrapper = """%(meta)s |
| 605 |
self.GLOBAL = { |
| 606 |
isWindow: function() { return false; }, |
| 607 |
isWorker: function() { return true; }, |
| 608 |
isShadowRealm: function() { return false; }, |
| 609 |
}; |
| 610 |
import "/resources/testharness.js"; |
| 611 |
%(script)s |
| 612 |
import "%(path)s"; |
| 613 |
done(); |
| 614 |
""" |
| 615 |
|
| 616 |
def _create_script_import(self, attribute): |
| 617 |
return 'import "%s";' % attribute |
| 618 |
|
| 619 |
|
| 620 |
class ShadowRealmWorkerWrapperHandler(BaseWorkerHandler): |
| 621 |
path_replace = [(".any.worker-shadowrealm.js", ".any.js")] |
| 622 |
wrapper = """%(meta)s |
| 623 |
importScripts("/resources/testharness-shadowrealm-outer.js"); |
| 624 |
(async function() { |
| 625 |
const postMessageFunc = await getPostMessageFunc(); |
| 626 |
try { |
| 627 |
const r = new ShadowRealm(); |
| 628 |
await shadowRealmEvalAsync(r, ` |
| 629 |
await import("/resources/testharness-shadowrealm-inner.js"); |
| 630 |
await import("/resources/testharness.js"); |
| 631 |
`); |
| 632 |
r.evaluate("setShadowRealmGlobalProperties")("%(query)s", fetchAdaptor); |
| 633 |
|
| 634 |
await shadowRealmEvalAsync(r, ` |
| 635 |
%(script)s |
| 636 |
await import("%(path)s"); |
| 637 |
`); |
| 638 |
|
| 639 |
function forwardMessage(msgJSON) { |
| 640 |
postMessageFunc(JSON.parse(msgJSON)); |
| 641 |
} |
| 642 |
r.evaluate('begin_shadow_realm_tests')(forwardMessage); |
| 643 |
} catch (e) { |
| 644 |
postMessageFunc(createSetupErrorResult(e)); |
| 645 |
} |
| 646 |
})(); |
| 647 |
""" |
| 648 |
|
| 649 |
def _create_script_import(self, attribute): |
| 650 |
return 'await import("%s");' % attribute |
| 651 |
|
| 652 |
|
| 653 |
class ShadowRealmServiceWorkerWrapperHandler(BaseWorkerHandler): |
| 654 |
path_replace = [(".any.serviceworker-shadowrealm.js", ".any.js")] |
| 655 |
wrapper = """%(meta)s |
| 656 |
importScripts("/resources/testharness-shadowrealm-outer.js"); |
| 657 |
|
| 658 |
(async function () { |
| 659 |
const postMessageFunc = await getPostMessageFunc(); |
| 660 |
try { |
| 661 |
const r = new ShadowRealm(); |
| 662 |
setupFakeDynamicImportInShadowRealm(r, fetchAdaptor); |
| 663 |
|
| 664 |
await shadowRealmEvalAsync(r, ` |
| 665 |
await fakeDynamicImport("/resources/testharness-shadowrealm-inner.js"); |
| 666 |
await fakeDynamicImport("/resources/testharness.js"); |
| 667 |
`); |
| 668 |
r.evaluate("setShadowRealmGlobalProperties")("%(query)s", fetchAdaptor); |
| 669 |
|
| 670 |
await shadowRealmEvalAsync(r, ` |
| 671 |
%(script)s |
| 672 |
await fakeDynamicImport("%(path)s"); |
| 673 |
`); |
| 674 |
|
| 675 |
function forwardMessage(msgJSON) { |
| 676 |
postMessageFunc(JSON.parse(msgJSON)); |
| 677 |
} |
| 678 |
r.evaluate("begin_shadow_realm_tests")(forwardMessage); |
| 679 |
} catch (e) { |
| 680 |
postMessageFunc(createSetupErrorResult(e)); |
| 681 |
} |
| 682 |
})(); |
| 683 |
""" |
| 684 |
|
| 685 |
def _create_script_import(self, attribute): |
| 686 |
return 'await fakeDynamicImport("%s");' % attribute |
| 687 |
|
| 688 |
|
| 689 |
class ShadowRealmAudioWorkletWrapperHandler(BaseWorkerHandler): |
| 690 |
path_replace = [(".any.audioworklet-shadowrealm.js", ".any.js")] |
| 691 |
wrapper = """%(meta)s |
| 692 |
TestRunner.prototype.createShadowRealmAndStartTests = async function() { |
| 693 |
try { |
| 694 |
const queryPart = import.meta.url.split('?')[1]; |
| 695 |
const locationSearch = queryPart ? '?' + queryPart : ''; |
| 696 |
|
| 697 |
const r = new ShadowRealm(); |
| 698 |
const adaptor = this.fetchOverPortExecutor.bind(this); |
| 699 |
setupFakeDynamicImportInShadowRealm(r, adaptor); |
| 700 |
|
| 701 |
await shadowRealmEvalAsync(r, ` |
| 702 |
await fakeDynamicImport("/resources/testharness-shadowrealm-inner.js"); |
| 703 |
await fakeDynamicImport("/resources/testharness.js"); |
| 704 |
`); |
| 705 |
r.evaluate("setShadowRealmGlobalProperties")(locationSearch, adaptor); |
| 706 |
|
| 707 |
await shadowRealmEvalAsync(r, ` |
| 708 |
%(script)s |
| 709 |
await fakeDynamicImport("%(path)s"); |
| 710 |
`); |
| 711 |
const forwardMessage = (msgJSON) => |
| 712 |
this.port.postMessage(JSON.parse(msgJSON)); |
| 713 |
r.evaluate("begin_shadow_realm_tests")(forwardMessage); |
| 714 |
} catch (e) { |
| 715 |
this.port.postMessage(createSetupErrorResult(e)); |
| 716 |
} |
| 717 |
} |
| 718 |
""" |
| 719 |
|
| 720 |
def _create_script_import(self, attribute): |
| 721 |
return 'await fakeDynamicImport("%s");' % attribute |
| 722 |
|
| 723 |
|
| 724 |
rewrites = [("GET", "/resources/WebIDLParser.js", "/resources/webidl2/lib/webidl2.js")] |
| 725 |
|
| 726 |
|
| 727 |
class RoutesBuilder: |
| 728 |
def __init__(self, inject_script = None): |
| 729 |
self.forbidden_override = [("GET", "/tools/runner/*", handlers.file_handler), |
| 730 |
("POST", "/tools/runner/update_manifest.py", |
| 731 |
handlers.python_script_handler)] |
| 732 |
|
| 733 |
self.forbidden = [("*", "/_certs/*", handlers.ErrorHandler(404)), |
| 734 |
("*", "/tools/*", handlers.ErrorHandler(404)), |
| 735 |
("*", "{spec}/tools/*", handlers.ErrorHandler(404)), |
| 736 |
("*", "/results/", handlers.ErrorHandler(404))] |
| 737 |
|
| 738 |
self.extra = [] |
| 739 |
self.inject_script_data = None |
| 740 |
if inject_script is not None: |
| 741 |
with open(inject_script, 'rb') as f: |
| 742 |
self.inject_script_data = f.read() |
| 743 |
|
| 744 |
self.mountpoint_routes = OrderedDict() |
| 745 |
|
| 746 |
self.add_mount_point("/", None) |
| 747 |
|
| 748 |
def get_routes(self): |
| 749 |
routes = self.forbidden_override + self.forbidden + self.extra |
| 750 |
# Using reversed here means that mount points that are added later |
| 751 |
# get higher priority. This makes sense since / is typically added |
| 752 |
# first. |
| 753 |
for item in reversed(self.mountpoint_routes.values()): |
| 754 |
routes.extend(item) |
| 755 |
return routes |
| 756 |
|
| 757 |
def add_handler(self, method, route, handler): |
| 758 |
self.extra.append((str(method), str(route), handler)) |
| 759 |
|
| 760 |
def add_static(self, path, format_args, content_type, route, headers=None): |
| 761 |
if headers is None: |
| 762 |
headers = {} |
| 763 |
handler = handlers.StaticHandler(path, format_args, content_type, **headers) |
| 764 |
self.add_handler("GET", str(route), handler) |
| 765 |
|
| 766 |
def add_mount_point(self, url_base, path): |
| 767 |
url_base = "/%s/" % url_base.strip("/") if url_base != "/" else "/" |
| 768 |
|
| 769 |
self.mountpoint_routes[url_base] = [] |
| 770 |
|
| 771 |
routes = [ |
| 772 |
("GET", "*.worker.html", WorkersHandler), |
| 773 |
("GET", "*.worker-module.html", WorkerModulesHandler), |
| 774 |
("GET", "*.window.html", WindowHandler), |
| 775 |
("GET", "*.any.html", AnyHtmlHandler), |
| 776 |
("GET", "*.any.sharedworker.html", SharedWorkersHandler), |
| 777 |
("GET", "*.any.sharedworker-module.html", SharedWorkerModulesHandler), |
| 778 |
("GET", "*.any.serviceworker.html", ServiceWorkersHandler), |
| 779 |
("GET", "*.any.serviceworker-module.html", ServiceWorkerModulesHandler), |
| 780 |
("GET", "*.any.shadowrealm-in-window.html", ShadowRealmInWindowHandler), |
| 781 |
("GET", "*.any.shadowrealm-in-shadowrealm.html", ShadowRealmInShadowRealmHandler), |
| 782 |
("GET", "*.any.shadowrealm-in-dedicatedworker.html", ShadowRealmInDedicatedWorkerHandler), |
| 783 |
("GET", "*.any.shadowrealm-in-sharedworker.html", ShadowRealmInSharedWorkerHandler), |
| 784 |
("GET", "*.any.shadowrealm-in-serviceworker.html", ShadowRealmInServiceWorkerHandler), |
| 785 |
("GET", "*.any.shadowrealm-in-audioworklet.html", ShadowRealmInAudioWorkletHandler), |
| 786 |
("GET", "*.any.window-module.html", WindowModulesHandler), |
| 787 |
("GET", "*.any.worker.js", ClassicWorkerHandler), |
| 788 |
("GET", "*.any.worker-module.js", ModuleWorkerHandler), |
| 789 |
("GET", "*.any.serviceworker-shadowrealm.js", ShadowRealmServiceWorkerWrapperHandler), |
| 790 |
("GET", "*.any.worker-shadowrealm.js", ShadowRealmWorkerWrapperHandler), |
| 791 |
("GET", "*.any.audioworklet-shadowrealm.js", ShadowRealmAudioWorkletWrapperHandler), |
| 792 |
("GET", "*.asis", handlers.AsIsHandler), |
| 793 |
("*", "/.well-known/attribution-reporting/report-event-attribution", handlers.PythonScriptHandler), |
| 794 |
("*", "/.well-known/attribution-reporting/debug/report-event-attribution", handlers.PythonScriptHandler), |
| 795 |
("*", "/.well-known/attribution-reporting/report-aggregate-attribution", handlers.PythonScriptHandler), |
| 796 |
("*", "/.well-known/attribution-reporting/debug/report-aggregate-attribution", handlers.PythonScriptHandler), |
| 797 |
("*", "/.well-known/attribution-reporting/debug/report-aggregate-debug", handlers.PythonScriptHandler), |
| 798 |
("*", "/.well-known/attribution-reporting/debug/verbose", handlers.PythonScriptHandler), |
| 799 |
("GET", "/.well-known/interest-group/permissions/", handlers.PythonScriptHandler), |
| 800 |
("*", "/.well-known/interest-group/real-time-report", handlers.PythonScriptHandler), |
| 801 |
("*", "/.well-known/private-aggregation/*", handlers.PythonScriptHandler), |
| 802 |
("GET", "/.well-known/shared-storage/trusted-origins", handlers.PythonScriptHandler), |
| 803 |
("*", "/.well-known/web-identity", handlers.PythonScriptHandler), |
| 804 |
("*", "*.py", handlers.PythonScriptHandler), |
| 805 |
("GET", "*", handlers.FileHandler) |
| 806 |
] |
| 807 |
|
| 808 |
for (method, suffix, handler_cls) in routes: |
| 809 |
handler = handler_cls(base_path=path, url_base=url_base) |
| 810 |
if self.inject_script_data is not None: |
| 811 |
handler = HtmlScriptInjectorHandlerWrapper(inject=self.inject_script_data, wrap=handler) |
| 812 |
|
| 813 |
self.mountpoint_routes[url_base].append( |
| 814 |
(method, |
| 815 |
"%s%s" % (url_base if url_base != "/" else "", suffix), |
| 816 |
handler)) |
| 817 |
|
| 818 |
def add_file_mount_point(self, file_url, base_path): |
| 819 |
assert file_url.startswith("/") |
| 820 |
url_base = file_url[0:file_url.rfind("/") + 1] |
| 821 |
self.mountpoint_routes[file_url] = [("GET", file_url, handlers.FileHandler(base_path=base_path, url_base=url_base))] |
| 822 |
|
| 823 |
|
| 824 |
def get_route_builder(logger, aliases, config): |
| 825 |
builder = RoutesBuilder(config.inject_script) |
| 826 |
for alias in aliases: |
| 827 |
url = alias["url-path"] |
| 828 |
directory = alias["local-dir"] |
| 829 |
if not url.startswith("/") or len(directory) == 0: |
| 830 |
logger.error("\"url-path\" value must start with '/'.") |
| 831 |
continue |
| 832 |
if url.endswith("/"): |
| 833 |
builder.add_mount_point(url, directory) |
| 834 |
else: |
| 835 |
builder.add_file_mount_point(url, directory) |
| 836 |
return builder |
| 837 |
|
| 838 |
|
| 839 |
class ServerProc: |
| 840 |
def __init__(self, mp_context, scheme=None): |
| 841 |
self.proc = None |
| 842 |
self.daemon = None |
| 843 |
self.mp_context = mp_context |
| 844 |
self.stop_flag = mp_context.Event() |
| 845 |
self.scheme = scheme |
| 846 |
|
| 847 |
def start(self, init_func, host, port, paths, routes, bind_address, config, log_handlers, **kwargs): |
| 848 |
self.proc = self.mp_context.Process(target=self.create_daemon, |
| 849 |
args=(init_func, host, port, paths, routes, bind_address, |
| 850 |
config, log_handlers, dict(**os.environ)), |
| 851 |
name='%s on port %s' % (self.scheme, port), |
| 852 |
kwargs=kwargs) |
| 853 |
self.proc.daemon = True |
| 854 |
self.proc.start() |
| 855 |
|
| 856 |
def create_daemon(self, init_func, host, port, paths, routes, bind_address, |
| 857 |
config, log_handlers, env, **kwargs): |
| 858 |
# Ensure that when we start this in a new process we have the global lock |
| 859 |
# in the logging module unlocked |
| 860 |
importlib.reload(logging) |
| 861 |
os.environ = env |
| 862 |
logger = get_logger(config.logging["level"], log_handlers) |
| 863 |
|
| 864 |
if sys.platform == "darwin": |
| 865 |
# on Darwin, NOFILE starts with a very low limit (256), so bump it up a little |
| 866 |
# by way of comparison, Debian starts with a limit of 1024, Windows 512 |
| 867 |
import resource # local, as it only exists on Unix-like systems |
| 868 |
maxfilesperproc = int(subprocess.check_output( |
| 869 |
["sysctl", "-n", "kern.maxfilesperproc"] |
| 870 |
).strip()) |
| 871 |
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) |
| 872 |
# 2048 is somewhat arbitrary, but gives us some headroom for wptrunner --parallel |
| 873 |
# note that it's expected that 2048 will be the min here |
| 874 |
new_soft = min(2048, maxfilesperproc, hard) |
| 875 |
if soft < new_soft: |
| 876 |
resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft, hard)) |
| 877 |
try: |
| 878 |
self.daemon = init_func(logger, host, port, paths, routes, bind_address, config, **kwargs) |
| 879 |
except OSError: |
| 880 |
logger.critical("Socket error on port %s" % port) |
| 881 |
raise |
| 882 |
except Exception: |
| 883 |
logger.critical(traceback.format_exc()) |
| 884 |
raise |
| 885 |
|
| 886 |
if self.daemon: |
| 887 |
try: |
| 888 |
self.daemon.start() |
| 889 |
try: |
| 890 |
self.stop_flag.wait() |
| 891 |
except KeyboardInterrupt: |
| 892 |
pass |
| 893 |
finally: |
| 894 |
self.daemon.stop() |
| 895 |
except Exception: |
| 896 |
logger.critical(traceback.format_exc()) |
| 897 |
raise |
| 898 |
|
| 899 |
def request_shutdown(self): |
| 900 |
if self.is_alive(): |
| 901 |
self.stop_flag.set() |
| 902 |
|
| 903 |
def wait(self, timeout=None): |
| 904 |
self.proc.join(timeout) |
| 905 |
|
| 906 |
def is_alive(self): |
| 907 |
return self.proc.is_alive() |
| 908 |
|
| 909 |
|
| 910 |
def check_subdomains(logger, config, routes, mp_context, log_handlers): |
| 911 |
paths = config.paths |
| 912 |
bind_address = config.bind_address |
| 913 |
|
| 914 |
host = config.server_host |
| 915 |
port = get_port() |
| 916 |
logger.debug("Going to use port %d to check subdomains" % port) |
| 917 |
|
| 918 |
wrapper = ServerProc(mp_context) |
| 919 |
wrapper.start(start_http_server, host, port, paths, routes, |
| 920 |
bind_address, config, log_handlers) |
| 921 |
|
| 922 |
url = f"http://{host}:{port}/" |
| 923 |
connected = False |
| 924 |
for i in range(10): |
| 925 |
try: |
| 926 |
urllib.request.urlopen(url) |
| 927 |
connected = True |
| 928 |
break |
| 929 |
except urllib.error.URLError: |
| 930 |
time.sleep(1) |
| 931 |
|
| 932 |
if not connected: |
| 933 |
logger.critical("Failed to connect to test server " |
| 934 |
"on {}. {}".format(url, EDIT_HOSTS_HELP)) |
| 935 |
sys.exit(1) |
| 936 |
|
| 937 |
for domain in config.domains_set: |
| 938 |
if domain == host: |
| 939 |
continue |
| 940 |
|
| 941 |
try: |
| 942 |
urllib.request.urlopen("http://%s:%d/" % (domain, port)) |
| 943 |
except Exception: |
| 944 |
logger.critical(f"Failed probing domain {domain}. {EDIT_HOSTS_HELP}") |
| 945 |
sys.exit(1) |
| 946 |
|
| 947 |
wrapper.request_shutdown() |
| 948 |
wrapper.wait() |
| 949 |
|
| 950 |
|
| 951 |
def make_hosts_file(config, host): |
| 952 |
rv = ["# Start web-platform-tests hosts"] |
| 953 |
|
| 954 |
for domain in sorted( |
| 955 |
config.domains_set, key=lambda x: tuple(reversed(x.split("."))) |
| 956 |
): |
| 957 |
rv.append("%s\t%s" % (host, domain)) |
| 958 |
|
| 959 |
# Windows interpets the IP address 0.0.0.0 as non-existent, making it an |
| 960 |
# appropriate alias for non-existent hosts. However, UNIX-like systems |
| 961 |
# interpret the same address to mean any IP address, which is inappropraite |
| 962 |
# for this context. These systems do not reserve any value for this |
| 963 |
# purpose, so the inavailability of the domains must be taken for granted. |
| 964 |
# |
| 965 |
# https://github.com/web-platform-tests/wpt/issues/10560 |
| 966 |
if platform.uname()[0] == "Windows": |
| 967 |
for not_domain in sorted( |
| 968 |
config.not_domains_set, key=lambda x: tuple(reversed(x.split("."))) |
| 969 |
): |
| 970 |
rv.append("0.0.0.0\t%s" % not_domain) |
| 971 |
|
| 972 |
rv.append("# End web-platform-tests hosts") |
| 973 |
rv.append("") |
| 974 |
|
| 975 |
return "\n".join(rv) |
| 976 |
|
| 977 |
|
| 978 |
def start_servers(logger, host, ports, paths, routes, bind_address, config, |
| 979 |
mp_context, log_handlers, **kwargs): |
| 980 |
servers = defaultdict(list) |
| 981 |
for scheme, ports in ports.items(): |
| 982 |
assert len(ports) == {"http": 2, "https": 2}.get(scheme, 1) |
| 983 |
|
| 984 |
# If trying to start HTTP/2.0 server, check compatibility |
| 985 |
if scheme == 'h2' and not http2_compatible(): |
| 986 |
logger.error('Cannot start HTTP/2.0 server as the environment is not compatible. ' + |
| 987 |
'Requires OpenSSL 1.0.2+') |
| 988 |
continue |
| 989 |
|
| 990 |
# Skip WebTransport over HTTP/3 server unless if is enabled explicitly. |
| 991 |
if scheme == 'webtransport-h3' and not kwargs.get("webtransport_h3"): |
| 992 |
continue |
| 993 |
|
| 994 |
for port in ports: |
| 995 |
if port is None: |
| 996 |
continue |
| 997 |
|
| 998 |
init_func = { |
| 999 |
"http": start_http_server, |
| 1000 |
"http-private": start_http_server, |
| 1001 |
"http-public": start_http_server, |
| 1002 |
"https": start_https_server, |
| 1003 |
"https-private": start_https_server, |
| 1004 |
"https-public": start_https_server, |
| 1005 |
"h2": start_http2_server, |
| 1006 |
"ws": start_ws_server, |
| 1007 |
"wss": start_wss_server, |
| 1008 |
"webtransport-h3": start_webtransport_h3_server, |
| 1009 |
}[scheme] |
| 1010 |
|
| 1011 |
server_proc = ServerProc(mp_context, scheme=scheme) |
| 1012 |
server_proc.start(init_func, host, port, paths, routes, bind_address, |
| 1013 |
config, log_handlers, **kwargs) |
| 1014 |
servers[scheme].append((port, server_proc)) |
| 1015 |
|
| 1016 |
return servers |
| 1017 |
|
| 1018 |
|
| 1019 |
def startup_failed(logger): |
| 1020 |
logger.critical(EDIT_HOSTS_HELP) |
| 1021 |
sys.exit(1) |
| 1022 |
|
| 1023 |
|
| 1024 |
def start_http_server(logger, host, port, paths, routes, bind_address, config, **kwargs): |
| 1025 |
try: |
| 1026 |
return wptserve.WebTestHttpd(host=host, |
| 1027 |
port=port, |
| 1028 |
doc_root=paths["doc_root"], |
| 1029 |
routes=routes, |
| 1030 |
rewrites=rewrites, |
| 1031 |
bind_address=bind_address, |
| 1032 |
config=config, |
| 1033 |
use_ssl=False, |
| 1034 |
key_file=None, |
| 1035 |
certificate=None, |
| 1036 |
latency=kwargs.get("latency")) |
| 1037 |
except Exception as error: |
| 1038 |
logger.critical(f"start_http_server: Caught exception from wptserve.WebTestHttpd: {error}") |
| 1039 |
startup_failed(logger) |
| 1040 |
|
| 1041 |
|
| 1042 |
def start_https_server(logger, host, port, paths, routes, bind_address, config, **kwargs): |
| 1043 |
try: |
| 1044 |
return wptserve.WebTestHttpd(host=host, |
| 1045 |
port=port, |
| 1046 |
doc_root=paths["doc_root"], |
| 1047 |
routes=routes, |
| 1048 |
rewrites=rewrites, |
| 1049 |
bind_address=bind_address, |
| 1050 |
config=config, |
| 1051 |
use_ssl=True, |
| 1052 |
key_file=config.ssl_config["key_path"], |
| 1053 |
certificate=config.ssl_config["cert_path"], |
| 1054 |
encrypt_after_connect=config.ssl_config["encrypt_after_connect"], |
| 1055 |
latency=kwargs.get("latency")) |
| 1056 |
except Exception as error: |
| 1057 |
logger.critical(f"start_https_server: Caught exception from wptserve.WebTestHttpd: {error}") |
| 1058 |
startup_failed(logger) |
| 1059 |
|
| 1060 |
|
| 1061 |
def start_http2_server(logger, host, port, paths, routes, bind_address, config, **kwargs): |
| 1062 |
try: |
| 1063 |
return wptserve.WebTestHttpd(host=host, |
| 1064 |
port=port, |
| 1065 |
handler_cls=wptserve.Http2WebTestRequestHandler, |
| 1066 |
doc_root=paths["doc_root"], |
| 1067 |
ws_doc_root=paths["ws_doc_root"], |
| 1068 |
routes=routes, |
| 1069 |
rewrites=rewrites, |
| 1070 |
bind_address=bind_address, |
| 1071 |
config=config, |
| 1072 |
use_ssl=True, |
| 1073 |
key_file=config.ssl_config["key_path"], |
| 1074 |
certificate=config.ssl_config["cert_path"], |
| 1075 |
encrypt_after_connect=config.ssl_config["encrypt_after_connect"], |
| 1076 |
latency=kwargs.get("latency"), |
| 1077 |
http2=True) |
| 1078 |
except Exception as error: |
| 1079 |
logger.critical(f"start_http2_server: Caught exception from wptserve.WebTestHttpd: {error}") |
| 1080 |
startup_failed(logger) |
| 1081 |
|
| 1082 |
|
| 1083 |
class WebSocketDaemon: |
| 1084 |
def __init__(self, host, port, doc_root, handlers_root, bind_address, ssl_config, |
| 1085 |
extra_handler_paths=None): |
| 1086 |
logger = logging.getLogger() |
| 1087 |
self.host = host |
| 1088 |
cmd_args = ["-p", port, |
| 1089 |
"-d", doc_root, |
| 1090 |
"-w", handlers_root] |
| 1091 |
|
| 1092 |
if ssl_config is not None: |
| 1093 |
cmd_args += ["--tls", |
| 1094 |
"--private-key", ssl_config["key_path"], |
| 1095 |
"--certificate", ssl_config["cert_path"]] |
| 1096 |
|
| 1097 |
if (bind_address): |
| 1098 |
cmd_args = ["-H", host] + cmd_args |
| 1099 |
opts, args = pywebsocket._parse_args_and_config(cmd_args) |
| 1100 |
opts.cgi_directories = [] |
| 1101 |
opts.is_executable_method = None |
| 1102 |
self.server = pywebsocket.WebSocketServer(opts) |
| 1103 |
if extra_handler_paths: |
| 1104 |
for path in extra_handler_paths: |
| 1105 |
self.server.websocket_server_options.dispatcher._source_handler_files_in_dir(path, path, False, None) |
| 1106 |
ports = [item[0].getsockname()[1] for item in self.server._sockets] |
| 1107 |
if not ports: |
| 1108 |
# TODO: Fix the logging configuration in WebSockets processes |
| 1109 |
# see https://github.com/web-platform-tests/wpt/issues/22719 |
| 1110 |
logger.critical("Failed to start websocket server on port %s, " |
| 1111 |
"is something already using that port?" % port) |
| 1112 |
raise OSError() |
| 1113 |
assert all(item == ports[0] for item in ports) |
| 1114 |
self.port = ports[0] |
| 1115 |
self.started = False |
| 1116 |
self.server_thread = None |
| 1117 |
|
| 1118 |
def start(self): |
| 1119 |
self.started = True |
| 1120 |
self.server_thread = threading.Thread(target=self.server.serve_forever) |
| 1121 |
self.server_thread.setDaemon(True) # don't hang on exit |
| 1122 |
self.server_thread.start() |
| 1123 |
|
| 1124 |
def stop(self): |
| 1125 |
""" |
| 1126 |
Stops the server. |
| 1127 |
|
| 1128 |
If the server is not running, this method has no effect. |
| 1129 |
""" |
| 1130 |
if self.started: |
| 1131 |
try: |
| 1132 |
self.server.shutdown() |
| 1133 |
self.server.server_close() |
| 1134 |
self.server_thread.join() |
| 1135 |
self.server_thread = None |
| 1136 |
except AttributeError: |
| 1137 |
pass |
| 1138 |
self.started = False |
| 1139 |
self.server = None |
| 1140 |
|
| 1141 |
|
| 1142 |
def start_ws_server(logger, host, port, paths, routes, bind_address, config, **kwargs): |
| 1143 |
try: |
| 1144 |
return WebSocketDaemon(host, |
| 1145 |
str(port), |
| 1146 |
repo_root, |
| 1147 |
config.paths["ws_doc_root"], |
| 1148 |
bind_address, |
| 1149 |
ssl_config=None, |
| 1150 |
extra_handler_paths=config.paths["ws_extra"]) |
| 1151 |
except Exception as error: |
| 1152 |
logger.critical(f"start_ws_server: Caught exception from WebSocketDomain: {error}") |
| 1153 |
startup_failed(logger) |
| 1154 |
|
| 1155 |
|
| 1156 |
def start_wss_server(logger, host, port, paths, routes, bind_address, config, **kwargs): |
| 1157 |
try: |
| 1158 |
return WebSocketDaemon(host, |
| 1159 |
str(port), |
| 1160 |
repo_root, |
| 1161 |
config.paths["ws_doc_root"], |
| 1162 |
bind_address, |
| 1163 |
config.ssl_config, |
| 1164 |
extra_handler_paths=config.paths["ws_extra"]) |
| 1165 |
except Exception as error: |
| 1166 |
logger.critical(f"start_wss_server: Caught exception from WebSocketDomain: {error}") |
| 1167 |
startup_failed(logger) |
| 1168 |
|
| 1169 |
|
| 1170 |
def start_webtransport_h3_server(logger, host, port, paths, routes, bind_address, config, **kwargs): |
| 1171 |
try: |
| 1172 |
# TODO(bashi): Move the following import to the beginning of this file |
| 1173 |
# once WebTransportH3Server is enabled by default. |
| 1174 |
from webtransport.h3.webtransport_h3_server import WebTransportH3Server # type: ignore |
| 1175 |
return WebTransportH3Server(host=host, |
| 1176 |
port=port, |
| 1177 |
doc_root=paths["doc_root"], |
| 1178 |
cert_path=config.ssl_config["cert_path"], |
| 1179 |
key_path=config.ssl_config["key_path"], |
| 1180 |
logger=logger) |
| 1181 |
except Exception as error: |
| 1182 |
logger.critical( |
| 1183 |
f"Failed to start WebTransport over HTTP/3 server: {error}") |
| 1184 |
sys.exit(0) |
| 1185 |
|
| 1186 |
|
| 1187 |
def start(logger, config, routes, mp_context, log_handlers, **kwargs): |
| 1188 |
host = config["server_host"] |
| 1189 |
ports = config.ports |
| 1190 |
paths = config.paths |
| 1191 |
bind_address = config["bind_address"] |
| 1192 |
|
| 1193 |
logger.debug("Using ports: %r" % ports) |
| 1194 |
|
| 1195 |
servers = start_servers(logger, host, ports, paths, routes, bind_address, config, mp_context, |
| 1196 |
log_handlers, **kwargs) |
| 1197 |
|
| 1198 |
return servers |
| 1199 |
|
| 1200 |
|
| 1201 |
def iter_servers(servers): |
| 1202 |
for servers in servers.values(): |
| 1203 |
for port, server in servers: |
| 1204 |
yield server |
| 1205 |
|
| 1206 |
|
| 1207 |
def _make_subdomains_product(s: Set[str], depth: int = 2) -> Set[str]: |
| 1208 |
return {".".join(x) for x in chain(*(product(s, repeat=i) for i in range(1, depth+1)))} |
| 1209 |
|
| 1210 |
|
| 1211 |
_subdomains = {"www", |
| 1212 |
"www1", |
| 1213 |
"www2", |
| 1214 |
"天気の良い日", |
| 1215 |
"élève"} |
| 1216 |
|
| 1217 |
_not_subdomains = {"nonexistent"} |
| 1218 |
|
| 1219 |
_subdomains = _make_subdomains_product(_subdomains) |
| 1220 |
|
| 1221 |
_not_subdomains = _make_subdomains_product(_not_subdomains) |
| 1222 |
|
| 1223 |
|
| 1224 |
class ConfigBuilder(config.ConfigBuilder): |
| 1225 |
"""serve config |
| 1226 |
|
| 1227 |
This subclasses wptserve.config.ConfigBuilder to add serve config options. |
| 1228 |
""" |
| 1229 |
|
| 1230 |
_default = { |
| 1231 |
"browser_host": "web-platform.test", |
| 1232 |
"alternate_hosts": { |
| 1233 |
"alt": "not-web-platform.test" |
| 1234 |
}, |
| 1235 |
"doc_root": repo_root, |
| 1236 |
"ws_doc_root": os.path.join(repo_root, "websockets", "handlers"), |
| 1237 |
"ws_extra": None, |
| 1238 |
"server_host": None, |
| 1239 |
"ports": { |
| 1240 |
"http": [8000, "auto"], |
| 1241 |
"http-private": ["auto"], |
| 1242 |
"http-public": ["auto"], |
| 1243 |
"https": [8443, 8444], |
| 1244 |
"https-private": ["auto"], |
| 1245 |
"https-public": ["auto"], |
| 1246 |
"ws": ["auto"], |
| 1247 |
"wss": ["auto"], |
| 1248 |
"webtransport-h3": ["auto"], |
| 1249 |
}, |
| 1250 |
"check_subdomains": True, |
| 1251 |
"bind_address": True, |
| 1252 |
"ssl": { |
| 1253 |
"type": "pregenerated", |
| 1254 |
"encrypt_after_connect": False, |
| 1255 |
"openssl": { |
| 1256 |
"openssl_binary": "openssl", |
| 1257 |
"base_path": "_certs", |
| 1258 |
"password": "web-platform-tests", |
| 1259 |
"force_regenerate": False, |
| 1260 |
"duration": 30, |
| 1261 |
"base_conf_path": None |
| 1262 |
}, |
| 1263 |
"pregenerated": { |
| 1264 |
"host_key_path": os.path.join(repo_root, "tools", "certs", "web-platform.test.key"), |
| 1265 |
"host_cert_path": os.path.join(repo_root, "tools", "certs", "web-platform.test.pem") |
| 1266 |
}, |
| 1267 |
"none": {} |
| 1268 |
}, |
| 1269 |
"aliases": [], |
| 1270 |
"logging": { |
| 1271 |
"level": "info", |
| 1272 |
"suppress_handler_traceback": False |
| 1273 |
} |
| 1274 |
} |
| 1275 |
|
| 1276 |
computed_properties = ["ws_doc_root"] + config.ConfigBuilder.computed_properties |
| 1277 |
|
| 1278 |
def __init__(self, logger, *args, **kwargs): |
| 1279 |
if "subdomains" not in kwargs: |
| 1280 |
kwargs["subdomains"] = _subdomains |
| 1281 |
if "not_subdomains" not in kwargs: |
| 1282 |
kwargs["not_subdomains"] = _not_subdomains |
| 1283 |
super().__init__( |
| 1284 |
logger, |
| 1285 |
*args, |
| 1286 |
**kwargs |
| 1287 |
) |
| 1288 |
with self as c: |
| 1289 |
browser_host = c.get("browser_host") |
| 1290 |
alternate_host = c.get("alternate_hosts", {}).get("alt") |
| 1291 |
|
| 1292 |
if not domains_are_distinct(browser_host, alternate_host): |
| 1293 |
raise ValueError( |
| 1294 |
"Alternate host must be distinct from browser host" |
| 1295 |
) |
| 1296 |
|
| 1297 |
def _get_ws_doc_root(self, data): |
| 1298 |
if data["ws_doc_root"] is not None: |
| 1299 |
return data["ws_doc_root"] |
| 1300 |
else: |
| 1301 |
return os.path.join(data["doc_root"], "websockets", "handlers") |
| 1302 |
|
| 1303 |
def _get_paths(self, data): |
| 1304 |
rv = super()._get_paths(data) |
| 1305 |
rv["ws_doc_root"] = data["ws_doc_root"] |
| 1306 |
rv["ws_extra"] = data["ws_extra"] |
| 1307 |
return rv |
| 1308 |
|
| 1309 |
|
| 1310 |
def build_config(logger, override_path=None, config_cls=ConfigBuilder, **kwargs): |
| 1311 |
rv = config_cls(logger) |
| 1312 |
|
| 1313 |
enable_http2 = kwargs.get("h2") |
| 1314 |
if enable_http2 is None: |
| 1315 |
enable_http2 = True |
| 1316 |
if enable_http2: |
| 1317 |
rv._default["ports"]["h2"] = [9000] |
| 1318 |
|
| 1319 |
if override_path and os.path.exists(override_path): |
| 1320 |
with open(override_path) as f: |
| 1321 |
override_obj = json.load(f) |
| 1322 |
rv.update(override_obj) |
| 1323 |
|
| 1324 |
if kwargs.get("config_path"): |
| 1325 |
other_path = os.path.abspath(os.path.expanduser(kwargs.get("config_path"))) |
| 1326 |
if os.path.exists(other_path): |
| 1327 |
with open(other_path) as f: |
| 1328 |
override_obj = json.load(f) |
| 1329 |
rv.update(override_obj) |
| 1330 |
else: |
| 1331 |
raise ValueError("Config path %s does not exist" % other_path) |
| 1332 |
|
| 1333 |
if kwargs.get("verbose"): |
| 1334 |
rv.logging["level"] = "DEBUG" |
| 1335 |
|
| 1336 |
setattr(rv, "inject_script", kwargs.get("inject_script")) |
| 1337 |
|
| 1338 |
overriding_path_args = [("doc_root", "Document root"), |
| 1339 |
("ws_doc_root", "WebSockets document root")] |
| 1340 |
for key, title in overriding_path_args: |
| 1341 |
value = kwargs.get(key) |
| 1342 |
if value is None: |
| 1343 |
continue |
| 1344 |
value = os.path.abspath(os.path.expanduser(value)) |
| 1345 |
if not os.path.exists(value): |
| 1346 |
raise ValueError("%s path %s does not exist" % (title, value)) |
| 1347 |
setattr(rv, key, value) |
| 1348 |
|
| 1349 |
return rv |
| 1350 |
|
| 1351 |
|
| 1352 |
def get_parser(): |
| 1353 |
parser = argparse.ArgumentParser() |
| 1354 |
parser.add_argument("--latency", type=int, |
| 1355 |
help="Artificial latency to add before sending http responses, in ms") |
| 1356 |
parser.add_argument("--config", dest="config_path", |
| 1357 |
help="Path to external config file") |
| 1358 |
parser.add_argument("--doc_root", help="Path to document root. Overrides config.") |
| 1359 |
parser.add_argument("--ws_doc_root", |
| 1360 |
help="Path to WebSockets document root. Overrides config.") |
| 1361 |
parser.add_argument("--ws_extra", action="append", default=[], |
| 1362 |
help="Path to extra directory containing ws handlers. Overrides config.") |
| 1363 |
parser.add_argument("--inject-script", |
| 1364 |
help="Path to script file to inject, useful for testing polyfills.") |
| 1365 |
parser.add_argument("--alias_file", |
| 1366 |
help="File with entries for aliases/multiple doc roots. In form of `/ALIAS_NAME/, DOC_ROOT\\n`") |
| 1367 |
parser.add_argument("--h2", action="store_true", default=None, |
| 1368 |
help=argparse.SUPPRESS) |
| 1369 |
parser.add_argument("--no-h2", action="store_false", dest="h2", default=None, |
| 1370 |
help="Disable the HTTP/2.0 server") |
| 1371 |
parser.add_argument("--webtransport-h3", action="store_true", |
| 1372 |
help="Enable WebTransport over HTTP/3 server") |
| 1373 |
parser.add_argument("--exit-after-start", action="store_true", |
| 1374 |
help="Exit after starting servers") |
| 1375 |
parser.add_argument("--verbose", action="store_true", help="Enable verbose logging") |
| 1376 |
parser.set_defaults(report=False) |
| 1377 |
parser.set_defaults(is_wave=False) |
| 1378 |
return parser |
| 1379 |
|
| 1380 |
|
| 1381 |
class MpContext: |
| 1382 |
def __getattr__(self, name): |
| 1383 |
return getattr(multiprocessing, name) |
| 1384 |
|
| 1385 |
|
| 1386 |
def get_logger(log_level, log_handlers): |
| 1387 |
"""Get a logger configured to log at level log_level |
| 1388 |
|
| 1389 |
If the logger has existing handlers the log_handlers argument is ignored. |
| 1390 |
Otherwise the handlers in log_handlers are added to the logger. If there are |
| 1391 |
no log_handlers passed and no configured handlers, a stream handler is added |
| 1392 |
to the logger. |
| 1393 |
|
| 1394 |
Typically this is called once per process to set up logging in that process. |
| 1395 |
|
| 1396 |
:param log_level: - A string representing a log level e.g. "info" |
| 1397 |
:param log_handlers: - Optional list of Handler objects. |
| 1398 |
""" |
| 1399 |
logger = logging.getLogger() |
| 1400 |
logger.setLevel(getattr(logging, log_level.upper())) |
| 1401 |
if not logger.hasHandlers(): |
| 1402 |
if log_handlers is not None: |
| 1403 |
for handler in log_handlers: |
| 1404 |
logger.addHandler(handler) |
| 1405 |
else: |
| 1406 |
handler = logging.StreamHandler(sys.stdout) |
| 1407 |
formatter = logging.Formatter("[%(asctime)s %(processName)s] %(levelname)s - %(message)s") |
| 1408 |
handler.setFormatter(formatter) |
| 1409 |
logger.addHandler(handler) |
| 1410 |
return logger |
| 1411 |
|
| 1412 |
|
| 1413 |
def run(config_cls=ConfigBuilder, route_builder=None, mp_context=None, log_handlers=None, |
| 1414 |
**kwargs): |
| 1415 |
logger = get_logger("INFO", log_handlers) |
| 1416 |
|
| 1417 |
if mp_context is None: |
| 1418 |
mp_context = multiprocessing.get_context("spawn") |
| 1419 |
|
| 1420 |
with build_config(logger, |
| 1421 |
os.path.join(repo_root, "config.json"), |
| 1422 |
config_cls=config_cls, |
| 1423 |
**kwargs) as config: |
| 1424 |
# This sets the right log level |
| 1425 |
logger = get_logger(config.logging["level"], log_handlers) |
| 1426 |
|
| 1427 |
bind_address = config["bind_address"] |
| 1428 |
|
| 1429 |
if kwargs.get("alias_file"): |
| 1430 |
with open(kwargs["alias_file"]) as alias_file: |
| 1431 |
for line in alias_file: |
| 1432 |
alias, doc_root = (x.strip() for x in line.split(',')) |
| 1433 |
config["aliases"].append({ |
| 1434 |
'url-path': alias, |
| 1435 |
'local-dir': doc_root, |
| 1436 |
}) |
| 1437 |
|
| 1438 |
if route_builder is None: |
| 1439 |
route_builder = get_route_builder |
| 1440 |
routes = route_builder(logger, config.aliases, config).get_routes() |
| 1441 |
|
| 1442 |
if config["check_subdomains"]: |
| 1443 |
check_subdomains(logger, config, routes, mp_context, log_handlers) |
| 1444 |
|
| 1445 |
stash_address = None |
| 1446 |
if bind_address: |
| 1447 |
stash_address = (config.server_host, get_port("")) |
| 1448 |
logger.debug("Going to use port %d for stash" % stash_address[1]) |
| 1449 |
|
| 1450 |
with stash.StashServer(stash_address, authkey=str(uuid.uuid4())): |
| 1451 |
servers = start(logger, config, routes, mp_context, log_handlers, **kwargs) |
| 1452 |
|
| 1453 |
if not kwargs.get("exit_after_start"): |
| 1454 |
try: |
| 1455 |
# Periodically check if all the servers are alive |
| 1456 |
server_process_exited = False |
| 1457 |
while not server_process_exited: |
| 1458 |
for server in iter_servers(servers): |
| 1459 |
server.proc.join(1) |
| 1460 |
if not server.proc.is_alive(): |
| 1461 |
server_process_exited = True |
| 1462 |
break |
| 1463 |
except KeyboardInterrupt: |
| 1464 |
pass |
| 1465 |
|
| 1466 |
failed_subproc = 0 |
| 1467 |
for server in iter_servers(servers): |
| 1468 |
logger.info('Status of subprocess "%s": running', server.proc.name) |
| 1469 |
server.request_shutdown() |
| 1470 |
|
| 1471 |
for server in iter_servers(servers): |
| 1472 |
server.wait(timeout=1) |
| 1473 |
if server.proc.exitcode == 0: |
| 1474 |
logger.info('Status of subprocess "%s": exited correctly', server.proc.name) |
| 1475 |
elif server.proc.exitcode is None: |
| 1476 |
logger.warning( |
| 1477 |
'Status of subprocess "%s": shutdown timed out', |
| 1478 |
server.proc.name) |
| 1479 |
failed_subproc += 1 |
| 1480 |
else: |
| 1481 |
subproc = server.proc |
| 1482 |
logger.warning('Status of subprocess "%s": failed. Exit with non-zero status: %d', |
| 1483 |
subproc.name, subproc.exitcode) |
| 1484 |
failed_subproc += 1 |
| 1485 |
return failed_subproc |
| 1486 |
|
| 1487 |
|
| 1488 |
def main(): |
| 1489 |
kwargs = vars(get_parser().parse_args()) |
| 1490 |
return run(**kwargs) |