-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
369 lines (321 loc) · 16.5 KB
/
Copy pathrun.py
File metadata and controls
369 lines (321 loc) · 16.5 KB
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
"""
dash-leaflet2 documentation site — Leaflet 2 on Dash 4, markdown-driven.
Shell is the dash-documentation-boilerplate's AppShell (DMC header + navbar +
markdown-loaded docs). Each `docs/<slug>/<slug>.md` registers as a Dash page;
the body is rendered by markdown2dash and its `.. exec::docs.<slug>.example`
directive imports the corresponding `example.py` to embed the live demo.
The showcase pages live in `docs/<slug>/example.py` with their
`dash.register_page(...)` stripped — the markdown loader is the single source
of routing. The hooks-driven Leaflet 2 CDN delivery lives here at the app level
so the JS showcase pages and the compiled `dl2.*` pages both work.
This is the PUBLIC mirror of the dash-leaflet2 project, deployed at
https://leaflet.2plot.dev as a 2plot network satellite:
* ads — lib/ad_client.py → 2plot.dev/api/ad-network/serve
* traffic — lib/analytics_tracker.py (per-request ledger) +
lib/traffic_rollup.py (the hub's own daily definitions) +
lib/satellite_reporter.py → 2plot.ai/api/satellite/traffic
* auth — lib/auth.py → Clerk satellite of the 2plot.ai primary
* control — pages/control_board.py → /admin/control-board
Every one of those is dormant without its env keys, so a plain `python run.py`
gives you the same local docs site it always did.
Run:
python run.py # FastAPI backend (default)
DASH_BACKEND=flask python run.py # Flask fallback
# open http://127.0.0.1:8050
"""
import os
from dotenv import load_dotenv
# .env loads MUI_PRO_API_KEY (TreeViewPro on the /tile-layers-pro page), the
# CLERK_* satellite keys, CROSS_APP_WEBHOOK_SECRET and anything else env-driven
# before Dash imports run.
load_dotenv()
import dash
from dash import Dash, _dash_renderer, hooks
# AI/LLM Integration & SEO via dash-improve-my-llms.
from dash_improve_my_llms import (
LLMSConfig,
RobotsConfig,
add_llms_routes,
mark_hidden,
register_page_metadata,
)
from lib import auth, bulletin, network_directory
from lib.analytics_tracker import tracker
from lib.backend import get_backend_info, resolve_backend
from lib.constants import (
APP_VERSION,
BASE_URL,
LEAFLET_VERSION,
SITE_BRAND,
SITE_DESCRIPTION,
require_owned_base_url,
)
# ----------------------------------------------------------------------------
# Pluggable backend (Dash 4.1+). FastAPI default so WebSocket / background
# callbacks remain available for the sim pages.
# ----------------------------------------------------------------------------
BACKEND = resolve_backend()
BACKEND_INFO = get_backend_info(BACKEND)
# DMC 2.x targets React 18.2; Dash 4 ships 18.3.1 — pin to keep DMC happy.
_dash_renderer._set_react_version("18.2.0")
print(f"[dash-leaflet2] v{APP_VERSION} on Dash {dash.__version__} · backend='{BACKEND}'")
# ----------------------------------------------------------------------------
# Clerk satellite auth. MUST run BEFORE Dash(...) — register_clerk_auth installs
# @dash.hooks callbacks that fire during app construction, so calling it later
# silently does nothing. Fully dormant without the CLERK_* keys.
# ----------------------------------------------------------------------------
CLERK_ENABLED = auth.register()
if not CLERK_ENABLED:
print("[auth] Clerk dormant — every visibility tier falls open to public.")
# ----------------------------------------------------------------------------
# Leaflet 2 alpha delivery via dash.hooks — the same no-build-step contract
# the showcase pages rely on. The compiled `dl2.*` components bundle their
# own Leaflet 2 in UMD scope, so these hooks don't conflict with them.
#
# Note: the version string MUST be "2.0.0-alpha.1" WITH the dot — the
# dotless form 404s on unpkg. window.leaflet (NOT window.L) is the global.
# ----------------------------------------------------------------------------
hooks.stylesheet([
{
"external_url": f"https://unpkg.com/leaflet@{LEAFLET_VERSION}/dist/leaflet.css",
"external_only": True,
}
])
hooks.script([
{
"external_url": f"https://unpkg.com/leaflet@{LEAFLET_VERSION}/dist/leaflet-global.js",
"external_only": True,
}
])
# Iconify web component for the Emoji/Iconify markers page.
hooks.script([
{
"external_url": "https://unpkg.com/iconify-icon@3.0.2/dist/iconify-icon.min.js",
"external_only": True,
}
])
# ----------------------------------------------------------------------------
# Dash app
# ----------------------------------------------------------------------------
_dash_kwargs = dict(
use_pages=True,
suppress_callback_exceptions=True,
prevent_initial_callbacks=True,
update_title=None,
title=SITE_BRAND,
index_string=open("templates/index.html").read(),
)
# `backend=` is Dash 4.2+, NOT 4.1 as its own release notes imply — verified
# against two separate 4.1.0 installs, where `Dash()` has no such parameter and
# raises TypeError. The dash_leaflet2 PACKAGE never touches it (it needs only
# `dash>=4.1`), so this fallback is what lets the documentation site keep
# running on the package's own support floor instead of quietly raising it.
try:
app = Dash(__name__, backend=BACKEND, **_dash_kwargs)
except TypeError:
print(
f"[dash-leaflet2] Dash {dash.__version__} has no `backend=` parameter "
"(added in 4.2) — falling back to the bundled Flask backend. The async "
"backends need Dash 4.2 or newer."
)
BACKEND = "flask"
BACKEND_INFO = get_backend_info(BACKEND)
app = Dash(__name__, **_dash_kwargs)
app._backend_info = BACKEND_INFO
# Post-construction Clerk wiring (sessions, /api/auth/*, request identity).
auth.configure_app(app)
# ----------------------------------------------------------------------------
# AI/LLM & SEO configuration
# ----------------------------------------------------------------------------
app._base_url = BASE_URL
app._robots_config = RobotsConfig(
# DELIBERATE open posture, reviewed against dash-improve-my-llms 2.3.3.
#
# 2.3.3 makes `True` safe — it blocks the real training crawlers (GPTBot,
# ClaudeBot, CCBot) while still allowing Claude-User, Claude-SearchBot and
# ChatGPT-User, so the old reason to run `False` (blocking broke claude.ai
# fetches through the legacy aliases) is gone. We stay `False` anyway,
# because for MIT-licensed component documentation being in the training
# corpus is the point: it is how a model recommends this library to someone
# who never visits the site. Flip to `True` if that calculus changes.
#
# Note this diverges from the fleet fingerprint in
# handoff/existing_subdomains.md, whose verification expects
# `ClaudeBot -> Disallow`. The divergence is intentional, not drift.
block_ai_training=False,
allow_ai_search=True,
allow_traditional=True,
crawl_delay=10,
# The admin control board is not documentation — keep it out of the index.
disallowed_paths=["/admin/"],
)
# The home page's registered `name` is this site's published identity, not a
# nav label: dash-improve-my-llms 2.3.4 resolves it through `resolve_site_title`
# into the /llms.txt H1, og:title and the llms viewer's brand chip. It must be
# SITE_BRAND and nothing else — docs/home/home.md registers the page as "Home",
# which `resolve_site_title` SKIPS as generic, so without this call the site
# would fall through to `app.title` and, on a pre-2.3.4 artifact, to a bare
# "Dash". `register_page_metadata` MERGES (2.2.0+), so this refines the entry
# the markdown loader created without touching the prose it registered.
register_page_metadata(
path="/",
name=SITE_BRAND,
description=SITE_DESCRIPTION,
)
# ----------------------------------------------------------------------------
# Pages: pages/markdown.py walks docs/**/*.md and calls dash.register_page
# on each. Dash's use_pages=True auto-imports anything under pages/ during
# Dash(...) construction, so we DON'T re-import it here — doing so caused
# every page to register twice (visible as DMC Select "Duplicate options
# are not supported" errors when the search dropdown re-rendered).
# ----------------------------------------------------------------------------
# Cross-host network directory. A sitemap is scoped to its own origin by
# design, so nothing in this site's markup would otherwise say the other 2plot
# hosts exist — an agent landing here sees one library and no ecosystem. This
# emits <link rel="related"> tags, a "## Network" section in /llms.txt, and
# followed links in the prerendered body. Must run BEFORE add_llms_routes.
#
# The peer list is kept in one place (copied verbatim from the boilerplate) and
# self-excludes by URL, so there is nothing app-specific to edit here — editing
# it per repo is how twelve copies drift apart.
network_directory.apply(BASE_URL)
# /admin/control-board is an admin surface, not documentation. It is the one
# registered page with no llms.txt prose, so it must be marked hidden BEFORE
# add_llms_routes — otherwise it is the sole reason the missing-prose warning
# below can never reach zero. mark_hidden also keeps it out of the sitemap and
# out of /llms.txt, which matches the robots `disallowed_paths` above.
mark_hidden("/admin/control-board")
# /healthz for the hub's hourly health sweep and render.yaml's
# healthCheckPath. Registered BEFORE add_llms_routes so the package's
# catch-all routing can never shadow it on the ASGI backends; served with or
# without a webhook secret, which is what makes it a valid liveness probe.
from lib.health import register_health_route # noqa: E402
register_health_route(app, BACKEND)
# ============================================================================
# Analytics tracking (Flask / Quart) — MUST be registered BEFORE
# add_llms_routes. (Mirrors the boilerplate's run.py.)
#
# `before_request` hooks run in registration order, and the package's
# `_bot_middleware` short-circuits AI-search crawlers (ClaudeBot, ChatGPT-User,
# PerplexityBot, ...) with its own response. Registered after it, this hook
# never runs for exactly the bot traffic a docs site most wants counted, and
# the `bot_hits` we report to 2plot.ai would be quietly too low — the
# structural `bot_hits: 0` this satellite once shipped.
#
# FastAPI is the mirror image and is wired further down: Starlette runs the
# LAST-added middleware outermost, so ours goes on after add_llms_routes.
# ============================================================================
if BACKEND == "flask":
from flask import request as _flask_request
@app.server.before_request
def track_visitor():
"""Track visitor analytics before each request."""
try:
# Headers are passed so the tracker can read the REAL client IP
# and country from the proxy/CDN (behind Render or Cloudflare,
# remote_addr is the proxy — every visitor would look like one).
tracker.track_visit(
_flask_request.path,
_flask_request.headers.get('User-Agent', ''),
_flask_request.remote_addr,
headers=dict(_flask_request.headers),
)
except Exception:
pass
elif BACKEND == "quart":
from quart import request as _quart_request
@app.server.before_request
async def track_visitor():
"""Track visitor analytics before each request (Quart)."""
try:
tracker.track_visit(
_quart_request.path,
_quart_request.headers.get('User-Agent', ''),
_quart_request.remote_addr,
headers=dict(_quart_request.headers),
)
except Exception:
pass
# Tiered corpus documents (dash-improve-my-llms >= 2.4.0). Pseudo-paths:
# they never enter dash.page_registry, so they cannot leak into listings —
# registering them here lets this satellite tier its compact briefing and
# full corpus via env (LLMS_SMALL_TIER / LLMS_FULL_TIER; unset = the
# default tier, i.e. public), and the hub can tighten either network-wide
# through its page-tier ceilings with no redeploy here. Inert on older
# package versions. (The boilerplate pairs this with lib/access.py
# enforcement, which has no counterpart in this repo yet — the registrations
# are the contract the hub reads either way.)
from lib import page_tiers as _page_tiers # noqa: E402
_page_tiers.register("/llms-small.txt", os.environ.get("LLMS_SMALL_TIER"))
_page_tiers.register("/llms-full.txt", os.environ.get("LLMS_FULL_TIER"))
# Wire up /llms.txt, /<page>/llms.txt, /robots.txt, /sitemap.xml + bot
# middleware. dash-improve-my-llms auto-detects the active backend
# (flask / fastapi / quart) and dispatches to the matching adapter, so we
# no longer have to gate this on the backend. Per-page prose is registered
# through lib.page_visibility.register_llms_doc (see pages/markdown.py) so the
# control board's llms.txt switch can swap a page's body for a stub.
#
# warn_missing_llms_doc is deliberately TRUE. It was silenced while the home
# page still lost its prose to the assign-semantics bug in 2.0; 2.2.0 made
# register_page_metadata MERGE, so every page now keeps the llms_doc the
# markdown loader gave it and the warning should stay at zero. If it starts
# firing, a page has genuinely lost its prose — which is worth hearing about.
add_llms_routes(app, LLMSConfig(warn_missing_llms_doc=True))
# The hub's announcement feed, rendered in the header of this site's llms.txt
# viewer. Opt-in: with NETWORK_BULLETIN_URL unset the feature is simply off and
# the viewer still renders, so the failure mode is an announcement that never
# appears — which nobody notices.
#
# Hence a function that RETURNS whether it wired, and a boot line that says so.
# The boilerplate shipped four commented-out lines here for weeks, against a
# hub endpoint that was already serving, and the only symptom was silence. An
# unwired host still renders both banner panels; the tell is one generic tip
# where the hub publishes two.
print(
"[dash-leaflet2] network bulletin: "
+ (f"wired -> {bulletin.url()}" if bulletin.configure()
else "off (NETWORK_BULLETIN_URL unset)")
)
# A hosted deploy advertising the wrong origin is invisible from inside the
# container — the site renders perfectly and every published URL is dead or
# points at another host. The old check here only WARNED, one line into a wall
# of boot output; the fleet standard is the boilerplate's hard guard, which
# refuses to boot on Render without an owned APP_BASE_URL. See lib.constants.
require_owned_base_url()
print(f"[dash-leaflet2] base url: {BASE_URL}")
# ----------------------------------------------------------------------------
# Layout
# ----------------------------------------------------------------------------
from components.appshell import create_appshell # noqa: E402 (needs the registry)
app.layout = create_appshell(dash.page_registry.values())
server = app.server
# ============================================================================
# Analytics tracking (FastAPI) — added LAST on purpose.
# Starlette runs the most recently added middleware outermost, so registering
# here (after add_llms_routes) puts the tracker in front of the package's bot
# middleware and every request gets counted — including the crawler traffic
# `_bot_middleware` answers itself, which is exactly the traffic a docs site
# most wants counted (the structural `bot_hits: 0` this satellite once
# reported). The Flask/Quart hooks are the mirror image and live above,
# BEFORE add_llms_routes.
# ============================================================================
if BACKEND == "fastapi":
from lib.asgi_middleware import register_asgi_middleware # noqa: E402
register_asgi_middleware(app)
# ============================================================================
# Network analytics — hourly signed rollup POSTed to 2plot.ai so the hub's
# owner-only /traffic dashboard can chart this app alongside the network.
# Contract: 2plotai/docs/network/satellite-analytics.md.
# No-op unless CROSS_APP_WEBHOOK_SECRET is set — and it SAYS so at boot,
# which is the line the fleet's acceptance check reads.
# ============================================================================
from lib.satellite_reporter import start_reporter # noqa: E402
start_reporter()
if __name__ == "__main__":
# Host/port are env-driven so the compat-matrix harness can run several
# Dash versions side by side without editing this file.
app.run(
debug=os.getenv("DASH_DEBUG", "true").lower() not in ("0", "false", "no"),
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", "8050")),
)