django-hostmap 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,31 @@
1
+ """``manage.py hostmap``: print the resolved map (04-interfaces.md section 4)."""
2
+
3
+ from django.core.management.base import BaseCommand
4
+
5
+ from hostmap.conf import hostmap_settings
6
+ from hostmap.map import resolved_entries
7
+
8
+
9
+ class Command(BaseCommand):
10
+ help = "Print the resolved hostmap: each entry's effective host, URLconf, and redirect target."
11
+
12
+ def handle(self, *args, **options):
13
+ entries = resolved_entries()
14
+ if not entries:
15
+ self.stdout.write("HOSTMAP is empty; hostmap is disabled.")
16
+ return
17
+
18
+ default = hostmap_settings.DEFAULT
19
+ self.stdout.write(f"Parent domain: {hostmap_settings.PARENT_DOMAIN or '(none)'}")
20
+ self.stdout.write(f"Default entry: {default or '(unset)'}")
21
+ self.stdout.write(f"Scheme: {hostmap_settings.SCHEME} Port: {hostmap_settings.PORT or '(none)'}")
22
+ self.stdout.write("")
23
+
24
+ for label, entry in entries.items():
25
+ marker = " *default*" if label == default else ""
26
+ self.stdout.write(f"{label}{marker}")
27
+ self.stdout.write(f" host: {entry.host}{' (wildcard)' if entry.wildcard else ''}")
28
+ if entry.is_redirect:
29
+ self.stdout.write(f" redirect: -> {entry.redirect_to}")
30
+ else:
31
+ self.stdout.write(f" urlconf: {entry.urlconf}")
hostmap/map.py ADDED
@@ -0,0 +1,194 @@
1
+ """Host map parsing, resolved entries, and host matching.
2
+
3
+ The map is a settings dict (01-data-model.md); parsing it yields one
4
+ immutable ``ResolvedEntry`` per label. Parsing and per-entry resolver
5
+ acquisition are cached so matching and cross-host fallback are cheap
6
+ (BR-HOSTMAP-005). The cache is keyed on the map's identity plus the
7
+ domain/default settings, so a test that swaps ``settings.HOSTMAP`` rebuilds
8
+ transparently.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+ from functools import cache
15
+
16
+ from hostmap.conf import hostmap_settings
17
+
18
+ # Keys a valid entry may carry. Any other key is a malformed entry (E001).
19
+ _KNOWN_KEYS = frozenset({"host", "subdomain", "urlconf", "redirect_to"})
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class ResolvedEntry:
24
+ """One parsed host map entry.
25
+
26
+ ``host`` is the effective host (subdomain joined to the parent domain, or
27
+ the literal ``host`` value). ``wildcard`` is true for ``subdomain: "*"``
28
+ entries. ``redirect_to`` holds the target label for redirect entries and
29
+ is ``None`` otherwise; a redirect entry has no ``urlconf``.
30
+ """
31
+
32
+ label: str
33
+ host: str
34
+ urlconf: str | None
35
+ redirect_to: str | None
36
+ wildcard: bool
37
+
38
+ @property
39
+ def is_redirect(self) -> bool:
40
+ return self.redirect_to is not None
41
+
42
+
43
+ def effective_host(entry: dict, parent_domain: str) -> str:
44
+ """Return the effective host for a raw entry dict.
45
+
46
+ A ``host`` entry uses its literal value. A ``subdomain`` entry joins the
47
+ label to ``parent_domain``; ``""`` means the parent domain itself and
48
+ ``"*"`` yields the wildcard sentinel ``"*.<parent_domain>"``.
49
+ """
50
+ if "host" in entry:
51
+ return str(entry["host"]).lower()
52
+ subdomain = str(entry.get("subdomain", ""))
53
+ if subdomain == "":
54
+ return parent_domain.lower()
55
+ return f"{subdomain}.{parent_domain}".lower()
56
+
57
+
58
+ def _parse(hostmap: dict, parent_domain: str) -> dict[str, ResolvedEntry]:
59
+ """Parse the raw map into an ordered dict of resolved entries.
60
+
61
+ Declaration order is preserved (dict insertion order), which
62
+ BR-HOSTMAP-005 relies on for cross-host resolution order. This does not
63
+ validate; system checks (checks.py) own validation. It tolerates a
64
+ malformed entry by skipping it so a misconfiguration surfaces as a check
65
+ error rather than an import-time crash.
66
+ """
67
+ resolved: dict[str, ResolvedEntry] = {}
68
+ for label, entry in hostmap.items():
69
+ if not isinstance(entry, dict):
70
+ continue
71
+ subdomain = entry.get("subdomain")
72
+ resolved[label] = ResolvedEntry(
73
+ label=label,
74
+ host=effective_host(entry, parent_domain),
75
+ urlconf=entry.get("urlconf"),
76
+ redirect_to=entry.get("redirect_to"),
77
+ wildcard=subdomain == "*",
78
+ )
79
+ return resolved
80
+
81
+
82
+ @cache
83
+ def _parse_cached(items: tuple, parent_domain: str) -> dict[str, ResolvedEntry]:
84
+ # Rebuild the raw map from the frozen key: each label maps to either its
85
+ # sorted item tuples (a dict entry) or the raw value (a malformed entry).
86
+ raw = {label: (dict(value) if isinstance(value, tuple) else value) for label, value in items}
87
+ return _parse(raw, parent_domain)
88
+
89
+
90
+ def _map_key(hostmap: dict) -> tuple:
91
+ """A hashable snapshot of the raw map for caching.
92
+
93
+ Entries are dicts (unhashable), so freeze each into sorted item tuples.
94
+ A non-dict (malformed) entry is carried through verbatim so ``_parse``
95
+ still sees and skips it.
96
+ """
97
+ return tuple(
98
+ (label, tuple(sorted(entry.items())) if isinstance(entry, dict) else entry) for label, entry in hostmap.items()
99
+ )
100
+
101
+
102
+ def resolved_entries() -> dict[str, ResolvedEntry]:
103
+ """Return the resolved entries for the current settings, cached.
104
+
105
+ Falls back to an uncached parse if the map contains an unhashable
106
+ malformed value (a list, say); such a map fails a system check anyway.
107
+ """
108
+ hostmap = hostmap_settings.MAP
109
+ parent_domain = hostmap_settings.PARENT_DOMAIN
110
+ try:
111
+ return _parse_cached(_map_key(hostmap), parent_domain)
112
+ except TypeError:
113
+ return _parse(hostmap, parent_domain)
114
+
115
+
116
+ def default_entry() -> ResolvedEntry | None:
117
+ """Return the ``HOSTMAP_DEFAULT`` resolved entry, or ``None`` if unset."""
118
+ entries = resolved_entries()
119
+ return entries.get(hostmap_settings.DEFAULT)
120
+
121
+
122
+ def redirect_target(entry: ResolvedEntry) -> ResolvedEntry | None:
123
+ """Resolve a redirect entry to its (non-redirect) target entry."""
124
+ if entry.redirect_to is None:
125
+ return None
126
+ return resolved_entries().get(entry.redirect_to)
127
+
128
+
129
+ def _strip_port(host: str) -> str:
130
+ """Return ``host`` lowercased with any ``:port`` removed (BR-HOSTMAP-002).
131
+
132
+ IPv6 literals are bracketed (``[::1]:8000``); split on the last colon only
133
+ when it falls outside a bracket.
134
+ """
135
+ host = host.lower()
136
+ if host.startswith("["):
137
+ # [ipv6]:port — the port, if any, follows the closing bracket.
138
+ end = host.find("]")
139
+ if end != -1:
140
+ return host[: end + 1]
141
+ return host
142
+ if ":" in host:
143
+ return host.rsplit(":", 1)[0]
144
+ return host
145
+
146
+
147
+ def match(host: str) -> ResolvedEntry | None:
148
+ """Match a request host against the map (BR-HOSTMAP-001, 002).
149
+
150
+ Case-insensitive and port-blind. Exact hosts are tried first, then
151
+ wildcard entries (in declaration order). Returns the matched
152
+ ``ResolvedEntry``, or ``None`` when nothing matches (the caller applies
153
+ ``HOSTMAP_UNMATCHED``).
154
+ """
155
+ normalised = _strip_port(host)
156
+ entries = resolved_entries()
157
+
158
+ # Exact matches beat wildcards.
159
+ for entry in entries.values():
160
+ if not entry.wildcard and entry.host == normalised:
161
+ return entry
162
+
163
+ # Wildcard entries: match a single subdomain level under the parent.
164
+ for entry in entries.values():
165
+ if entry.wildcard and _wildcard_matches(entry, normalised):
166
+ return entry
167
+
168
+ return None
169
+
170
+
171
+ def _wildcard_matches(entry: ResolvedEntry, host: str) -> bool:
172
+ """True when ``host`` is a single-level subdomain under the wildcard's parent."""
173
+ # entry.host is "*.<parent_domain>"; the suffix is ".<parent_domain>".
174
+ suffix = entry.host[1:] # drop the leading "*"
175
+ if not host.endswith(suffix):
176
+ return False
177
+ label = host[: -len(suffix)]
178
+ # Exactly one level: a non-empty label with no further dots.
179
+ return bool(label) and "." not in label
180
+
181
+
182
+ def captured_subdomain(entry: ResolvedEntry, host: str) -> str | None:
183
+ """Return the wildcard label captured from ``host``, or ``None``.
184
+
185
+ Only wildcard entries capture a subdomain; for exact entries this is
186
+ always ``None`` (01-data-model.md, ``request.hostmap.subdomain``).
187
+ """
188
+ if not entry.wildcard:
189
+ return None
190
+ normalised = _strip_port(host)
191
+ suffix = entry.host[1:]
192
+ if normalised.endswith(suffix):
193
+ return normalised[: -len(suffix)] or None
194
+ return None
hostmap/middleware.py ADDED
@@ -0,0 +1,79 @@
1
+ """HostmapMiddleware: per-host URLconf, active-host context, request.hostmap.
2
+
3
+ Implements BR-HOSTMAP-001, 002 (routing) and BR-HOSTMAP-008 (redirect
4
+ entries). Must sit before ``CommonMiddleware``, whose ``APPEND_SLASH``
5
+ resolves against the request's URLconf (03-services.md section 1).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ from django.http import Http404, HttpResponsePermanentRedirect, HttpResponseRedirect
13
+
14
+ from hostmap import context
15
+ from hostmap import map as hostmap_map
16
+ from hostmap.conf import hostmap_settings
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class HostmapInfo:
21
+ """The namespaced ``request.hostmap`` object (01-data-model.md).
22
+
23
+ Kept deliberately at two attributes; no bare ``request.subdomain`` is set,
24
+ which django-subdomains and other middleware historically claimed
25
+ (BR-HOSTMAP-009).
26
+ """
27
+
28
+ label: str
29
+ subdomain: str | None = None
30
+
31
+
32
+ class HostmapMiddleware:
33
+ """Route each request by host and record the active entry."""
34
+
35
+ def __init__(self, get_response):
36
+ self.get_response = get_response
37
+
38
+ def __call__(self, request):
39
+ entry = self._resolve_entry(request)
40
+
41
+ if entry is None:
42
+ # No match and HOSTMAP_UNMATCHED == "reject".
43
+ raise Http404("Host does not match any hostmap entry.")
44
+
45
+ if entry.is_redirect:
46
+ return self._redirect(request, entry)
47
+
48
+ request.urlconf = entry.urlconf
49
+ request.hostmap = HostmapInfo(
50
+ label=entry.label,
51
+ subdomain=hostmap_map.captured_subdomain(entry, request.get_host()),
52
+ )
53
+
54
+ token = context.set_active(entry)
55
+ try:
56
+ return self.get_response(request)
57
+ finally:
58
+ context.reset_active(token)
59
+
60
+ def _resolve_entry(self, request):
61
+ """Match the host, applying ``HOSTMAP_UNMATCHED`` on no match."""
62
+ entry = hostmap_map.match(request.get_host())
63
+ if entry is not None:
64
+ return entry
65
+ if hostmap_settings.UNMATCHED == "reject":
66
+ return None
67
+ return hostmap_map.default_entry()
68
+
69
+ def _redirect(self, request, entry):
70
+ """Redirect to the same path and query on the target host (BR-HOSTMAP-008)."""
71
+ from hostmap.urls import build_absolute_uri
72
+
73
+ target = hostmap_map.redirect_target(entry)
74
+ # Preserve the full path including the query string. ``host`` accepts a
75
+ # label; the target is always a non-redirect entry (E004 forbids chains).
76
+ location = build_absolute_uri(request.get_full_path(), host=target.label if target else None)
77
+ if hostmap_settings.REDIRECT_PERMANENT:
78
+ return HttpResponsePermanentRedirect(location)
79
+ return HttpResponseRedirect(location)
hostmap/resolvers.py ADDED
@@ -0,0 +1,159 @@
1
+ """The resolver seam: host-aware cross-host fallback under stock ``reverse()``.
2
+
3
+ Why patching ``reverse`` alone cannot work (03-services.md section 2):
4
+ third-party apps bind ``from django.urls import reverse`` at their own import
5
+ time, before any ``AppConfig.ready()`` runs, so rebinding
6
+ ``django.urls.reverse`` afterwards does not affect those references. The
7
+ integration must sit at a seam every call passes through dynamically.
8
+
9
+ The chosen seam is resolver acquisition. ``django.urls.base.reverse`` calls
10
+ ``get_resolver(urlconf)`` on every call and then
11
+ ``resolver._reverse_with_prefix(...)``. We wrap ``get_resolver`` so that, for
12
+ the active host's URLconf, it returns a :class:`HostAwareResolver`, a
13
+ ``URLResolver`` subclass whose ``_reverse_with_prefix`` retries the other
14
+ hosts' resolvers on ``NoReverseMatch`` and returns an absolute URL for a
15
+ cross-host match. Non-active URLconfs get the ordinary stock resolver, so the
16
+ fallback targets never wrap and the search cannot recurse. Same-host
17
+ reversing is untouched and stays byte-identical (BR-HOSTMAP-003).
18
+
19
+ Installed and removed at ``AppConfig.ready()`` and gated by
20
+ ``HOSTMAP_PATCH_REVERSE`` (BR-HOSTMAP-007).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from functools import cache
26
+
27
+ from django.urls import NoReverseMatch
28
+ from django.urls import resolvers as django_resolvers
29
+ from django.urls.resolvers import RegexPattern, URLResolver
30
+
31
+ # The stock resolver factory we wrap, captured at install time so uninstall
32
+ # restores exactly what was there. ``None`` means "not installed".
33
+ _original_get_resolver = None
34
+
35
+
36
+ class HostAwareResolver(URLResolver):
37
+ """A ``URLResolver`` that falls back to other hosts on ``NoReverseMatch``.
38
+
39
+ Only the active host's URLconf is ever wrapped in this class; the per-host
40
+ resolvers it retries during fallback are plain stock resolvers, so there is
41
+ no recursion.
42
+ """
43
+
44
+ def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs):
45
+ try:
46
+ return super()._reverse_with_prefix(lookup_view, _prefix, *args, **kwargs)
47
+ except NoReverseMatch:
48
+ return self._cross_host_reverse(lookup_view, _prefix, args, kwargs)
49
+
50
+ def _cross_host_reverse(self, lookup_view, _prefix, args, kwargs):
51
+ # BR-HOSTMAP-005 ordering comes from the one canonical source in
52
+ # urls.entry_order(); the seam only supplies the low-level reverse
53
+ # primitive (watch flag 2, one code path). entry_order()[0] is the
54
+ # active host, whose miss brought us here, so we skip it.
55
+ from hostmap.urls import _absolute_url, entry_order, logger
56
+
57
+ order = entry_order()
58
+ for entry in order[1:]:
59
+ resolver = _stock_resolver(entry.urlconf)
60
+ try:
61
+ path = resolver._reverse_with_prefix(lookup_view, _prefix, *args, **kwargs)
62
+ except NoReverseMatch:
63
+ continue
64
+ logger.debug("hostmap cross-host reverse: %r -> host %s (%s)", lookup_view, entry.host, entry.label)
65
+ return _absolute_url(entry, path)
66
+
67
+ searched = ", ".join(e.host for e in order) or "(no hostmap entries)"
68
+ raise NoReverseMatch(f"Reverse for '{lookup_view}' not found on any hostmap host. Searched: {searched}.")
69
+
70
+
71
+ def _stock_resolver(urlconf):
72
+ """A plain (unwrapped) stock ``URLResolver`` for ``urlconf``.
73
+
74
+ Uses the original ``get_resolver`` so the fallback resolvers are ordinary
75
+ resolvers, never ``HostAwareResolver`` (which would recurse). Django caches
76
+ these, so this is a single cheap dict lookup after the first call
77
+ (BR-HOSTMAP-005).
78
+ """
79
+ factory = _original_get_resolver or django_resolvers.get_resolver
80
+ return factory(urlconf)
81
+
82
+
83
+ @cache
84
+ def _host_aware_resolver(urlconf) -> HostAwareResolver:
85
+ """Build (once per URLconf) a ``HostAwareResolver`` for the active host.
86
+
87
+ A distinct object from Django's cached stock resolver, so the stock cache
88
+ is never mutated and fallback resolvers stay plain. Cached here so the
89
+ active resolver is built once, not per ``reverse()`` call.
90
+ """
91
+ return HostAwareResolver(RegexPattern(r"^/"), urlconf)
92
+
93
+
94
+ def install():
95
+ """Wrap ``get_resolver`` so the active URLconf acquires a ``HostAwareResolver``.
96
+
97
+ Idempotent. The wrapper returns the host-aware resolver only for the active
98
+ host's URLconf (or the default entry's, out of request); every other
99
+ URLconf, including the fallback targets, gets the ordinary stock resolver.
100
+ """
101
+ global _original_get_resolver
102
+ if _original_get_resolver is not None:
103
+ return # already installed
104
+
105
+ _original_get_resolver = django_resolvers.get_resolver
106
+
107
+ def hostmap_get_resolver(urlconf=None):
108
+ target = urlconf if urlconf is not None else _root_urlconf()
109
+ if _is_active_urlconf(target):
110
+ return _host_aware_resolver(target)
111
+ return _original_get_resolver(urlconf)
112
+
113
+ django_resolvers.get_resolver = hostmap_get_resolver
114
+ _patch_base_reference(hostmap_get_resolver)
115
+
116
+
117
+ def uninstall():
118
+ """Restore the original ``get_resolver``; routing keeps working (BR-HOSTMAP-007)."""
119
+ global _original_get_resolver
120
+ if _original_get_resolver is None:
121
+ return
122
+ django_resolvers.get_resolver = _original_get_resolver
123
+ _patch_base_reference(_original_get_resolver)
124
+ _original_get_resolver = None
125
+ _host_aware_resolver.cache_clear()
126
+
127
+
128
+ def is_installed() -> bool:
129
+ return _original_get_resolver is not None
130
+
131
+
132
+ def _is_active_urlconf(urlconf) -> bool:
133
+ """True when ``urlconf`` is the active entry's URLconf.
134
+
135
+ Out of request the active entry is the ``HOSTMAP_DEFAULT`` entry, so
136
+ import-time and out-of-request reversing (against ROOT_URLCONF) is
137
+ host-aware too (BR-HOSTMAP-006).
138
+ """
139
+ from hostmap import context
140
+
141
+ active = context.get_active()
142
+ return active is not None and not active.is_redirect and urlconf == active.urlconf
143
+
144
+
145
+ def _root_urlconf():
146
+ from django.conf import settings
147
+
148
+ return settings.ROOT_URLCONF
149
+
150
+
151
+ def _patch_base_reference(factory):
152
+ """Point ``django.urls.base``'s ``get_resolver`` at ``factory``.
153
+
154
+ ``django.urls.base.reverse`` imports ``get_resolver`` into its own module
155
+ namespace, so replacing only ``resolvers.get_resolver`` is not enough.
156
+ """
157
+ from django.urls import base
158
+
159
+ base.get_resolver = factory
@@ -0,0 +1,10 @@
1
+ """Testing helpers for consuming projects (04-interfaces.md section 6).
2
+
3
+ Scope is fixed at exactly ``host_client()``, a ``use_host`` re-export, and
4
+ pytest fixtures; no request-factory or assertion-helper sprawl (watch flag 3).
5
+ """
6
+
7
+ from hostmap.testing.helpers import host_client
8
+ from hostmap.urls import use_host
9
+
10
+ __all__ = ["host_client", "use_host"]
@@ -0,0 +1,18 @@
1
+ """pytest fixtures for hostmap (04-interfaces.md section 6).
2
+
3
+ Import into a project's ``conftest.py`` with::
4
+
5
+ from hostmap.testing.fixtures import * # noqa: F401,F403
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import pytest
11
+
12
+ from hostmap.testing.helpers import host_client as _host_client
13
+
14
+
15
+ @pytest.fixture
16
+ def host_client():
17
+ """Factory fixture: ``host_client("api")`` returns a host-bound test client."""
18
+ return _host_client
@@ -0,0 +1,33 @@
1
+ """``host_client(label)``: a Django test client wired to a hostmap host."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from django.test import Client
6
+
7
+ from hostmap.map import resolved_entries
8
+
9
+
10
+ def host_client(label: str, **kwargs) -> Client:
11
+ """Return a Django test :class:`~django.test.Client` bound to an entry's host.
12
+
13
+ Sets ``SERVER_NAME`` to the entry's effective host so every request the
14
+ client makes routes to that host through ``HostmapMiddleware``. Extra
15
+ keyword arguments pass through to ``Client``.
16
+
17
+ Usage::
18
+
19
+ client = host_client("api")
20
+ response = client.get("/users/7/")
21
+ """
22
+ entries = resolved_entries()
23
+ if label not in entries:
24
+ raise KeyError(f"host_client: '{label}' is not a HOSTMAP label. Known labels: {sorted(entries)}.")
25
+ entry = entries[label]
26
+ # A wildcard entry has no single concrete host; require an explicit host.
27
+ if entry.wildcard:
28
+ raise ValueError(
29
+ f"host_client: '{label}' is a wildcard entry with no single host; "
30
+ "pass SERVER_NAME to a plain Client for the concrete host you want."
31
+ )
32
+ kwargs.setdefault("SERVER_NAME", entry.host)
33
+ return Client(**kwargs)