split_url_events: switch to a WHATWG parser (ada-url) when the Python floor reaches 3.10

Open
#174 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 10 days

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Refactor
Clarity
Mostly clear
Activity status
Active
Tech stack
python
Domain
backend, testing

Research direction

Start with aw_transform.split_url_events and the urlcompare.py comparison harness, which checks results against aw-server-rust's split_url_event. Review the Python-version requirements and release bundle constraint before making the dependency change. Done means using ada-url once aw-core supports Python 3.10 and preserving the 218/218 comparison results.

Written by the indexing model from the issue text.

Description

split_url_events (ActivityWatch/aw-core#173) has to produce exactly the same fields as aw-server-rust's split_url_event, which parses URLs with the url crate (the WHATWG URL Standard). #173 does this with a hand-written Python implementation of the relevant parts of the URL Standard, because no WHATWG parser supports aw-core's Python floor (^3.8).

Proposal: once aw-core's Python floor reaches 3.10, replace the hand-written parsing with ada-url. It binds ada, the WHATWG parser Node.js uses, which passes the same URL tests as the url crate. That removes the whole class of parser divergences instead of fixing them one by one. ada-url needs Python ≥3.10 (1.19–1.27 needed ≥3.9, and no release supports 3.8).

aw-research (>=3.12,<4) and quantifiedme (^3.12) already require Python 3.12, so bumping aw-core's floor would unblock this. The ActivityWatch release bundle currently builds with Python 3.9.

Current state (#173)

The hand-written parsing matches aw-server-rust on 218/218 URLs in the comparison harness below, on Python 3.8 and 3.11. These edge-case categories were found and fixed in #173's review rounds 1 to 5:

  • special schemes: any number of slashes or backslashes before the authority (http:example.com, http:///x), and backslashes as path separators;
  • ports: non-numeric, non-ASCII (², full-width digits) or above 65535 leave the event unchanged, and an odd URL can no longer abort the transform;
  • hosts: forbidden and percent-encoded forbidden characters; IPv4 in all URL-Standard forms (127.1, 0x7f.1, 2130706433); compressed IPv6; lowercase;
  • UTS 46 (non-transitional) via the idna package: deviation characters kept (faß.de), soft hyphens removed, invalid A-labels rejected, leading combining marks, RFC 5892 CONTEXTJ joiners (including Persian ZWNJ), and RFC 5893 bidi rules on the Unicode form of every label;
  • paths and queries: dot segments (including %2e), percent-encoding with the path and query sets;
  • file: URLs: localhost is no host, and Windows drive letters stay in the path (and C| becomes C: like the url crate);
  • non-special schemes (mailto:, chrome://, foo://): opaque hosts and paths percent-encoded, ports validated, IPv6 without the port, and credentials or a port with an empty host rejected.

Known remaining risk: exotic or malformed URLs that browsers don't send (aw-watcher-web reports already-serialized WHATWG URLs), where some untested corner of the URL Standard still differs. Each such difference only affects how those rare events are grouped.

Comparison harness

This runs a list of URLs through aw-server-rust's aw_transform::split_url_event and aw-core's split_url_events and prints every difference. Put urlharness/ next to an aw-server-rust checkout, then:

cd urlharness && cargo build --release && cd ..
URLHARNESS=urlharness/target/release/urlharness python3 urlcompare.py path/to/aw-core
urlharness/Cargo.toml
[package]
name = "urlharness"
version = "0.1.0"
edition = "2021"

[dependencies]
aw-transform = { path = "../aw-server-rust/aw-transform" }
aw-models = { path = "../aw-server-rust/aw-models" }
serde_json = "1"
chrono = "0.4"

[workspace]
urlharness/src/main.rs
use std::io::BufRead;
use aw_models::Event;
use serde_json::{json, Value};

fn main() {
    // One JSON string (the url) per stdin line; prints the event data after split_url_event.
    for line in std::io::stdin().lock().lines() {
        let url: Value = serde_json::from_str(&line.unwrap()).unwrap();
        let mut data = serde_json::Map::new();
        data.insert("url".into(), url);
        let mut event = Event { id: None, timestamp: chrono::Utc::now(), duration: chrono::Duration::zero(), data };
        aw_transform::split_url_event(&mut event);
        println!("{}", json!(event.data));
    }
}
urlcompare.py (the 218 URLs)
"""Compare aw-core split_url_events with aw-server-rust's split_url_event on many URLs."""
import json
import os
import subprocess
import sys
from datetime import datetime, timezone

sys.path.insert(0, sys.argv[1])  # aw-core checkout
from aw_core.models import Event  # noqa: E402
from aw_transform import split_url_events  # noqa: E402

URLS = [
    # review cases
    "http:example.com", "https:example.com/a", "http:/example.com", "http:\\\\example.com\\a",
    "https://example.com:not-a-port/a", "https://example.com:99999/a", "https://example.com:/a",
    "https://example.com:0/a", "https://example.com:65535/a", "https://example.com:65536/a",
    # ordinary
    "https://x.org:8080/a;p?b=c#d", "http://asd.com/test/?a=1", "https://www.www.x.org/", "https://WWW.Example.COM",
    "https://x.org", "https://x.org?q=1", "https://x.org#frag", "https://user:[email protected]:81/p",
    "http://[::1]:5600/api", "http://[::1]", "http://127.0.0.1:5600/", "file:///home/x.txt", "file://host/x",
    "about:blank", "about:newtab", "mailto:[email protected]", "chrome://settings/", "chrome-extension://abc/p.html",
    "moz-extension://uuid/popup.html", "data:text/plain,hi", "javascript:void(0)", "view-source:https://x.org",
    "ws://x.org:80/s", "wss://x.org/s", "ftp://ftp.x.org/pub",
    # invalid / odd
    "not a url", "/relative/path", "http://", "https://", "http:///x", "localhost:8080", "x.org/path",
    "https://x.org/a b", "https://x.org/ä", "https://bücher.de/", "HTTP://X.ORG/A", "https://x.org/%7e",
    " https://x.org/ ", "https://x.org/a\\b", "https://-x.org/", "https://x..org/", "https://x_y.org/",
    "https://x.org:8080", "https://x.org.:443/", "", "http://a b.com/",
    # dot segments, encoding, whitespace
    "https://x.org/a/../b", "https://x.org/a/./b/", "https://x.org/a/%2e%2E/b", "https://x.org/..",
    "https://x.org/a?q=a b&r=ä#f g", "https://x.org/a?q='x'", "https://x.org/%41%zz", "https://x.org/<>\"`{}",
    "http://x.org/\ta\nb", "https://X.org:080/", "https://x.org:443/", "http://x.org:80/",
    "https://[email protected]/", "https://@x.org/", "https://x.org%2Fevil/", "https://x.org/?", "https://x.org/#",
    "HTTPS:X.ORG", "https:\\\\x.org", "https://[2001:db8::1]:443/p", "https://[::ffff:1.2.3.4]/",
    "https://xn--bcher-kva.de/", "https://ÉCOLE.fr/", "https://x.org/a%20b", "https://x.org/a+b",
    "chrome://extensions/?id=abc", "about:blank#top", "file:///C:/x/y.txt", "file:///home/a%20b",
    "http://0x7f.1/", "http://127.1/", "http://2130706433/", "http://1.2.3.4.5/", "http://999.1.1.1/",
    "https://%78.org/", "https://x.org/%7E%7e", "https://a:b:[email protected]/", "https://x.org:/", "https://x.org/?a",
    "https://x.org/a?", "https://x.org/a#b?c", "https://x.org/;a;b", "https://x.org//a//b", "https://x.org/./",
    "http:x.org:8080/a", "https:////x.org/", "ftp:x.org", "ws:x", "HTTPS://WWW.X.ORG:443/A/../B?Q=1",
    "http://1..2/", "http://x.1/", "http://1.x/", "http://1.2.3./", "http://.1/", "http://0x/", "http://09/",
    "http://0x1g/", "http://1.2.3.256/", "http://4294967295/", "http://4294967296/", "http://x.0x10/",
    # round 2: ports, IDNA, file, authority terminators
    "https://example.com:²/a", "https://example.org:12/a", "https://faß.de/", "https://ΣΊΣΥΦΟΣ.gr/",
    "https://日本.jp/", "https://EXAMPLE.com/", "https://Ⅷ.example/", "https://İstanbul.tr/", "https://a\u200db.com/",
    "https://xn--fa-hia.de/", "https://☃.net/", "https://x.org。y/", "https://-.org/",
    "file://localhost/etc", "file:c:/foo", "file:///C:/../a", "file:C:/Users/a", "file:///c|/x", "file://C:/x",
    "file://host.example/share/x", "file:/home/x", "file:home/x", "file:\\\\server\\share", "FILE:///X",
    "file://LOCALHOST/x", "file:///C:/a/../../b", "file:///home/../..", "file:///a%20b/c d",
    "http://example.com?x/y", "http://example.com#x/y", "http://example.com?a#b/c",
    "file://c|/x", "file:c|/x", "file:/c|/x", "file:///C|", "file://C:/x", "file:///c|/../x", "file://c|/../x",
    # round 3: UTS 46 validity, non-special schemes
    "https://\u0301.com/", "https://foo\u00adbar.com/", "https://xn--zz.com/", "https://xn--fa-hia.de/",
    "https://xn--ab.com/", "https://a.xn--.com/", "https://\u00e9cole.fr/", "https://e\u0301cole.fr/",
    "foo://host:not-a-port/a", "foo://host:99999/a", "foo://[::1]:80/a", "foo://host:80/a",
    "mailto:[email protected]?subject=hello world", "foo://host/a b", "foo://host/a\\b", "foo:/a/../b",
    "foo://h/a/../b", "foo://Host/X", "foo://ho st/", "foo://h%20st/", "data:text/plain,a b",
    "javascript:alert(1) x", "sms:+1?body=a b", "foo://user:pw@h:1/p?q#f", "foo://h?x/y", "foo://",
    "foo:///x", "foo:ä", "foo://ä/x", "foo://h/ä?ä", "chrome://settings/?search=a b", "about:blank?a b",
    "foo://h/a%2e%2e/b", "foo://[::1", "foo://h:/x", "view-source:http://x.org/a b",
    # round 4
    "https://\u05d0\u05d1x.com/", "https://\u200d\u094d.com/", "foo://:80/a", "foo://@/a", "foo://u@h/a",
    "foo://:@h/a", "mailto:[email protected] ?subject=x", "mailto:a #f", "https://\u05d0\u05d1.com/",
    "https://\u05d0\u05d11.com/", "https://1\u05d0.com/", "https://\u05d0\u05d1.x.com/", "https://x.\u0627\u0628/",
    "https://a.b.\u0661\u0662/", "https://\u0627\u0661/", "foo://:/a", "foo://h@/a",
    # round 5
    "https://xn--x-zhcd.com/", "https://x.org/a^b", "foo://h/a^b", "https://\u0646\u0627\u0645\u0647\u200c\u0627\u06cc.com/",
    "https://xn--4dbc.com/", "https://xn--4dbc.x.com/", "https://x.xn--4dbc/", "https://\u200c.com/",
    "https://a\u200cb.com/", "https://\u0915\u094d\u200d\u0937.in/",
]


def rust(urls):
    out = subprocess.run(
        [os.environ.get("URLHARNESS", "urlharness/target/release/urlharness")],
        input="\n".join(json.dumps(u) for u in urls) + "\n",
        capture_output=True, text=True, check=True,
    ).stdout.splitlines()
    return [json.loads(line) for line in out]


def python(urls):
    now = datetime.now(timezone.utc)
    events = [Event(timestamp=now, duration=0, data={"url": u}) for u in urls]
    return [dict(e.data) for e in split_url_events(events)]


mismatch = 0
for url, r, p in zip(URLS, rust(URLS), python(URLS)):
    if r != p:
        mismatch += 1
        print(f"MISMATCH {url!r}\n  rust:   {r}\n  python: {p}")
print(f"{len(URLS) - mismatch}/{len(URLS)} match")
Dominant language
Python
Stars
65
Forks
74
Avg merge
7d 7h
Merged PRs (30d)
11

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ActivityWatch/aw-core

All issues in ActivityWatch/aw-core

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.