-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi.py
More file actions
2515 lines (2303 loc) · 88.5 KB
/
api.py
File metadata and controls
2515 lines (2303 loc) · 88.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
FastAPI service for exposing vmcrawl Mastodon instance data.
This API provides read-only access to collected Mastodon instance statistics,
version information, and domain data.
"""
import getpass
import json
import logging
import os
import socket
import threading
import time
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import Any
import httpx
import paramiko
import toml
from dotenv import load_dotenv
from fastapi import (
Depends,
FastAPI,
HTTPException,
Path,
Query,
Response,
Security,
status,
)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response as StarletteResponse
from fastapi.security import APIKeyHeader
from fastapi.staticfiles import StaticFiles
from psycopg import sql
from psycopg_pool import ConnectionPool
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from slowapi.util import get_remote_address
# Mastodon-compatible software names shared with crawler logic.
MASTODON_COMPATIBLE_SOFTWARE = ("mastodon", "hometown", "kmyblue")
# Load environment variables
_ = load_dotenv()
# Load application metadata
toml_file_path = os.path.join(os.path.dirname(__file__), "pyproject.toml")
try:
project_info = toml.load(toml_file_path)
appname: str = project_info["project"]["name"]
appversion: str = project_info["project"]["version"]
except (FileNotFoundError, toml.TomlDecodeError, KeyError):
appname = "vmcrawl-api"
appversion = "0.1.0"
# Optional SSH tunnel for remote database access
_ssh_transport: paramiko.Transport | None = None
_ssh_tunnel_port: int | None = None
_ssh_host = os.getenv("VMCRAWL_SSH_HOST")
if _ssh_host:
import sys
_db_host = os.getenv("VMCRAWL_POSTGRES_HOST", "localhost")
_db_port = int(os.getenv("VMCRAWL_POSTGRES_PORT", "5432"))
_ssh_port = int(os.getenv("VMCRAWL_SSH_PORT", "22"))
_ssh_user = os.getenv("VMCRAWL_SSH_USER") or getpass.getuser()
_ssh_key_path = os.path.expanduser(os.getenv("VMCRAWL_SSH_KEY", "~/.ssh/id_rsa"))
_ssh_key_pass = os.getenv("VMCRAWL_SSH_KEY_PASS")
# Load the SSH key once at startup
_ssh_pkey: paramiko.PKey | None = None
for _key_class in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
try:
_ssh_pkey = _key_class.from_private_key_file(
_ssh_key_path, password=_ssh_key_pass
)
break
except (paramiko.SSHException, ValueError):
continue
if _ssh_pkey is None:
print(f"Error establishing SSH tunnel: Unable to load SSH key: {_ssh_key_path}")
sys.exit(1)
_ssh_host_str: str = _ssh_host # narrowed: we're inside `if _ssh_host:`
def _connect_ssh_transport() -> paramiko.Transport:
"""Open and authenticate a new SSH transport."""
transport = paramiko.Transport((_ssh_host_str, _ssh_port))
transport.connect(username=_ssh_user, pkey=_ssh_pkey)
return transport
try:
_ssh_transport = _connect_ssh_transport()
# Bind a local listening socket for the tunnel (port stays fixed for lifetime)
_tunnel_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_tunnel_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_tunnel_sock.bind(("127.0.0.1", 0))
_ssh_tunnel_port = _tunnel_sock.getsockname()[1]
_tunnel_sock.listen(15)
def _ssh_tunnel_accept_loop() -> None:
"""Accept local connections and forward them through the SSH tunnel.
Reconnects automatically if the SSH transport drops.
"""
global _ssh_transport
_reconnect_delay = 5 # seconds between reconnect attempts
while True:
# Reconnect if the transport has gone away
if _ssh_transport is None or not _ssh_transport.is_active():
print("SSH tunnel lost, attempting to reconnect…")
try:
_ssh_transport = _connect_ssh_transport()
print(
f"SSH tunnel reconnected: 127.0.0.1:{_ssh_tunnel_port}"
f" -> {_db_host}:{_db_port} via {_ssh_host}"
)
except Exception as exc:
print(
f"SSH reconnect failed: {exc}, retrying in {_reconnect_delay}s"
)
time.sleep(_reconnect_delay)
continue
try:
_tunnel_sock.settimeout(1.0)
client_sock, _ = _tunnel_sock.accept()
except socket.timeout:
continue
except OSError:
break
try:
channel = _ssh_transport.open_channel(
"direct-tcpip",
(_db_host, _db_port),
client_sock.getpeername(),
)
except Exception:
client_sock.close()
continue
def _forward(src: Any, dst: Any) -> None:
try:
while True:
data = src.recv(65536)
if not data:
break
dst.sendall(data)
except Exception:
pass
finally:
try:
src.close()
except Exception:
pass
try:
dst.close()
except Exception:
pass
threading.Thread(
target=_forward, args=(client_sock, channel), daemon=True
).start()
threading.Thread(
target=_forward, args=(channel, client_sock), daemon=True
).start()
_tunnel_thread = threading.Thread(target=_ssh_tunnel_accept_loop, daemon=True)
_tunnel_thread.start()
print(
f"SSH tunnel established: 127.0.0.1:{_ssh_tunnel_port}"
f" -> {_db_host}:{_db_port} via {_ssh_host}"
)
except Exception as exception:
print(f"Error establishing SSH tunnel: {exception}")
sys.exit(1)
_db_connect_host = (
"127.0.0.1" if _ssh_tunnel_port else os.getenv("VMCRAWL_POSTGRES_HOST", "localhost")
)
_db_connect_port = (
str(_ssh_tunnel_port)
if _ssh_tunnel_port
else os.getenv("VMCRAWL_POSTGRES_PORT", "5432")
)
# Database connection
conn_string = (
f"postgresql://{os.getenv('VMCRAWL_POSTGRES_USER')}:"
f"{os.getenv('VMCRAWL_POSTGRES_PASS')}@"
f"{_db_connect_host}:"
f"{_db_connect_port}/"
f"{os.getenv('VMCRAWL_POSTGRES_DATA')}"
f"?sslmode={os.getenv('VMCRAWL_POSTGRES_SSLMODE', 'require')}"
)
# Create connection pool
db_pool = ConnectionPool(
conn_string,
min_size=2,
max_size=10,
timeout=30,
)
# Lifespan context manager for cleanup
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Handle application lifespan events."""
yield
# Cleanup on shutdown
try:
db_pool.close()
except Exception:
pass
if _ssh_transport is not None:
try:
_ssh_transport.close()
except Exception:
pass
# Initialize FastAPI app
app = FastAPI(
title=f"{appname} API",
version=appversion,
description="API for accessing Mastodon instance statistics and version data",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan,
)
logger = logging.getLogger("vmcrawl.api")
def _db_error(status_code: int = 500) -> HTTPException:
"""Log the active exception and return a sanitized HTTPException."""
logger.exception("Database error")
return HTTPException(status_code=status_code, detail="Internal server error")
def _chart_error(status_code: int = 502) -> HTTPException:
"""Log the active exception and return a sanitized HTTPException."""
logger.exception("Chart rendering error")
return HTTPException(status_code=status_code, detail="Chart rendering failed")
# Rate limiting (per client IP). Requires uvicorn --proxy-headers so
# get_remote_address reads the real client IP from X-Forwarded-For.
limiter = Limiter(key_func=get_remote_address, default_limits=["120/minute"])
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)
# Strict CSP for the dashboard. Chart.js is loaded from jsdelivr with SRI.
# Inline style attributes on a couple of table headers require
# 'unsafe-inline' for style-src; script-src stays strict.
_DASHBOARD_CSP = (
"default-src 'self'; "
"script-src 'self' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"font-src 'self'; "
"connect-src 'self'; "
"object-src 'none'; "
"base-uri 'self'; "
"frame-ancestors 'none'; "
"form-action 'self'"
)
# Swagger UI and ReDoc pull assets from a CDN and use inline bootstrap
# scripts, so they need a relaxed CSP to function.
_DOCS_CSP = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
"img-src 'self' data: https://fastapi.tiangolo.com; "
"font-src 'self' data:; "
"connect-src 'self'; "
"object-src 'none'; "
"base-uri 'self'; "
"frame-ancestors 'none'"
)
_DOCS_PATHS = ("/docs", "/redoc", "/docs/oauth2-redirect")
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next) -> StarletteResponse:
response = await call_next(request)
path = request.url.path
if path in _DOCS_PATHS:
response.headers.setdefault("Content-Security-Policy", _DOCS_CSP)
else:
response.headers.setdefault("Content-Security-Policy", _DASHBOARD_CSP)
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "no-referrer")
response.headers.setdefault(
"Permissions-Policy",
"geolocation=(), microphone=(), camera=(), payment=(), usb=()",
)
response.headers.setdefault("Cross-Origin-Opener-Policy", "same-origin")
response.headers.setdefault("Cross-Origin-Resource-Policy", "same-origin")
return response
app.add_middleware(SecurityHeadersMiddleware)
# CORS is only needed if the dashboard is served from a different origin
# than the API. The default deployment mounts web/ on this same app, so
# cross-origin requests are unnecessary and disabled by default. Set
# VMCRAWL_CORS_ORIGINS to a comma-separated list (or "*") to opt in.
_cors_origins_env = os.getenv("VMCRAWL_CORS_ORIGINS", "").strip()
if _cors_origins_env:
_cors_origins = [o.strip() for o in _cors_origins_env.split(",") if o.strip()]
app.add_middleware(
CORSMiddleware,
allow_origins=_cors_origins,
allow_methods=["GET"],
allow_headers=["X-API-Key"],
)
# =============================================================================
# AUTHENTICATION
# =============================================================================
# API Key Authentication
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def get_api_key(api_key: str | None = Security(api_key_header)):
"""Validate API key from X-API-Key header.
If VMCRAWL_API_KEY is not set in environment, authentication is disabled.
"""
valid_key = os.getenv("VMCRAWL_API_KEY")
# If no key is configured, allow access (authentication disabled)
if not valid_key:
return None
# Key is configured, so require it
if api_key is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Missing API Key. Include X-API-Key header.",
headers={"WWW-Authenticate": "ApiKey"},
)
if api_key != valid_key:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid API Key",
)
return api_key
# =============================================================================
# HEALTH CHECK
# =============================================================================
@app.get("/api", tags=["Health"])
async def root():
"""API information endpoint."""
return {
"name": f"{appname} API",
"version": appversion,
"status": "operational",
"docs": "/docs",
}
@app.get("/health", tags=["Health"])
async def health_check():
"""Unauthenticated liveness probe.
Returns 200 {"status": "healthy"} when the database is reachable,
503 {"status": "unhealthy"} otherwise. The detailed failure reason
is logged server-side and never included in the response body.
"""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
_ = cur.execute("SELECT 1")
_ = cur.fetchone()
return {"status": "healthy"}
except Exception:
logger.exception("Health check failed")
return JSONResponse(status_code=503, content={"status": "unhealthy"})
# =============================================================================
# STATISTICS ENDPOINTS
# =============================================================================
@app.get("/stats/summary", tags=["Statistics"])
async def get_summary_stats(_api_key: str | None = Depends(get_api_key)):
"""Get summary statistics for all known Mastodon instances."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
# Total instances
_ = cur.execute("SELECT COUNT(*) FROM mastodon_domains")
result = cur.fetchone()
total_instances = result[0] if result else 0
# Total MAU
_ = cur.execute("SELECT SUM(active_users_monthly) FROM mastodon_domains")
result = cur.fetchone()
total_mau = result[0] if result and result[0] else 0
# Unique versions
_ = cur.execute(
"SELECT COUNT(DISTINCT software_version) FROM mastodon_domains"
)
result = cur.fetchone()
unique_versions = result[0] if result else 0
# Latest timestamp
_ = cur.execute("SELECT MAX(timestamp) FROM mastodon_domains")
result = cur.fetchone()
last_updated = result[0] if result else None
return {
"total_instances": total_instances,
"monthly_active_users": total_mau,
"unique_versions": unique_versions,
"last_updated": last_updated.isoformat() if last_updated else None,
}
except Exception as e:
raise _db_error() from None
@app.get("/stats/versions", tags=["Statistics"])
async def get_version_stats(_api_key: str | None = Depends(get_api_key)):
"""Get instance count and user count by Mastodon version."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
_ = cur.execute(
"""
SELECT
software_version,
COUNT(*) as instance_count,
SUM(active_users_monthly) as total_mau
FROM mastodon_domains
GROUP BY software_version
ORDER BY instance_count DESC
"""
)
results = cur.fetchall()
return {
"versions": [
{
"version": row[0],
"instances": row[1],
"monthly_active_users": row[2] or 0,
}
for row in results
]
}
except Exception as e:
raise _db_error() from None
@app.get("/stats/branches", tags=["Statistics"])
async def get_branch_stats(_api_key: str | None = Depends(get_api_key)):
"""Get statistics organized by Mastodon release branches."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
# Main branch
_ = cur.execute(
"""
SELECT
COUNT(*) as instances,
SUM(active_users_monthly) as mau
FROM mastodon_domains
WHERE software_version LIKE (
SELECT branch || '.%' FROM release_versions WHERE n_level = -1
)
"""
)
main_result = cur.fetchone()
# Latest release branch
_ = cur.execute(
"""
SELECT
COUNT(*) as instances,
SUM(active_users_monthly) as mau
FROM mastodon_domains
WHERE software_version LIKE (
SELECT branch || '.%' FROM release_versions WHERE n_level = 0
)
"""
)
latest_result = cur.fetchone()
# Previous release branch
_ = cur.execute(
"""
SELECT
COUNT(*) as instances,
SUM(active_users_monthly) as mau
FROM mastodon_domains
WHERE software_version LIKE (
SELECT branch || '.%' FROM release_versions WHERE n_level = 1
)
"""
)
previous_result = cur.fetchone()
# Deprecated branches
_ = cur.execute(
"""
SELECT
COUNT(*) as instances,
SUM(active_users_monthly) as mau
FROM mastodon_domains
WHERE EXISTS (
SELECT 1
FROM release_versions
WHERE status = 'release'
AND n_level >= 2
AND mastodon_domains.software_version LIKE release_versions.branch || '.%'
)
"""
)
deprecated_result = cur.fetchone()
# EOL versions
_ = cur.execute(
"""
SELECT
COUNT(*) as instances,
SUM(active_users_monthly) as mau
FROM mastodon_domains
WHERE EXISTS (
SELECT 1
FROM release_versions
WHERE status = 'eol'
AND mastodon_domains.software_version LIKE release_versions.branch || '.%'
)
"""
)
eol_result = cur.fetchone()
return {
"main": {
"instances": main_result[0] if main_result else 0,
"monthly_active_users": (main_result[1] or 0) if main_result else 0,
},
"latest": {
"instances": latest_result[0] if latest_result else 0,
"monthly_active_users": (latest_result[1] or 0) if latest_result else 0,
},
"previous": {
"instances": previous_result[0] if previous_result else 0,
"monthly_active_users": (previous_result[1] or 0)
if previous_result
else 0,
},
"deprecated": {
"instances": deprecated_result[0] if deprecated_result else 0,
"monthly_active_users": (deprecated_result[1] or 0)
if deprecated_result
else 0,
},
"eol": {
"instances": eol_result[0] if eol_result else 0,
"monthly_active_users": (eol_result[1] or 0) if eol_result else 0,
},
}
except Exception as e:
raise _db_error() from None
@app.get("/stats/patch-adoption", tags=["Statistics"])
async def get_patch_adoption(_api_key: str | None = Depends(get_api_key)):
"""Get patch adoption statistics (percentage of instances and MAU that are patched)."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
# Calculate patched instances percentage
_ = cur.execute(
"""
WITH version_cases AS (
SELECT latest AS software_version
FROM release_versions
),
eol_check AS (
SELECT DISTINCT md.software_version
FROM mastodon_domains md
WHERE EXISTS (
SELECT 1
FROM release_versions rv
WHERE rv.status = 'eol'
AND md.software_version LIKE rv.branch || '.%'
)
),
unpatched_or_eol AS (
SELECT COUNT(*) AS cnt
FROM mastodon_domains md
WHERE md.software_version IN (SELECT software_version FROM eol_check)
OR md.software_version NOT IN (SELECT software_version FROM version_cases)
),
totals AS (
SELECT COUNT(DISTINCT domain) AS total_domains
FROM mastodon_domains
)
SELECT
(
(t.total_domains - COALESCE(u.cnt, 0)) * 100.0
/ NULLIF(t.total_domains, 0)
) AS patched_percent
FROM totals t
CROSS JOIN unpatched_or_eol u
"""
)
instances_result = cur.fetchone()
patched_instances_percent = (
round(instances_result[0], 2)
if instances_result and instances_result[0] is not None
else 0
)
# Calculate patched MAU percentage
_ = cur.execute(
"""
WITH version_cases AS (
SELECT latest AS software_version
FROM release_versions
),
eol_check AS (
SELECT DISTINCT md.software_version
FROM mastodon_domains md
WHERE EXISTS (
SELECT 1
FROM release_versions rv
WHERE rv.status = 'eol'
AND md.software_version LIKE rv.branch || '.%'
)
),
totals AS (
SELECT SUM(active_users_monthly) AS total_users
FROM mastodon_domains
),
unpatched_or_eol AS (
SELECT SUM(active_users_monthly) AS cnt
FROM mastodon_domains md
WHERE md.software_version IN (SELECT software_version FROM eol_check)
OR md.software_version NOT IN (SELECT software_version FROM version_cases)
)
SELECT
(
(COALESCE(t.total_users, 0) - COALESCE(u.cnt, 0)) * 100.0
/ NULLIF(COALESCE(t.total_users, 0), 0)
) AS patched_users_percent
FROM totals t
CROSS JOIN unpatched_or_eol u
"""
)
mau_result = cur.fetchone()
patched_mau_percent = (
round(mau_result[0], 2)
if mau_result and mau_result[0] is not None
else 0
)
return {
"instances_patched_percent": patched_instances_percent,
"mau_patched_percent": patched_mau_percent,
}
except Exception as e:
raise _db_error() from None
@app.get("/stats/crawler-health", tags=["Statistics"])
async def get_crawler_health(_api_key: str | None = Depends(get_api_key)):
"""Get crawler health statistics (error counts by type)."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
compatible_software = list(MASTODON_COMPATIBLE_SOFTWARE)
# TCP Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT rd.domain) AS unique_domain_count
FROM raw_domains rd
WHERE LOWER(rd.nodeinfo) = ANY(%s::text[])
AND rd.reason LIKE 'TCP%%'
AND (rd.alias IS NULL OR rd.alias = FALSE)
AND EXISTS (
SELECT 1
FROM mastodon_domains md
WHERE md.domain = rd.domain
)
""",
(compatible_software,),
)
result = cur.fetchone()
tcp_issues = result[0] if result else 0
# SSL Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT rd.domain) AS unique_domain_count
FROM raw_domains rd
WHERE LOWER(rd.nodeinfo) = ANY(%s::text[])
AND rd.reason LIKE 'SSL%%'
AND (rd.alias IS NULL OR rd.alias = FALSE)
AND EXISTS (
SELECT 1
FROM mastodon_domains md
WHERE md.domain = rd.domain
)
""",
(compatible_software,),
)
result = cur.fetchone()
ssl_issues = result[0] if result else 0
# DNS Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT rd.domain) AS unique_domain_count
FROM raw_domains rd
WHERE LOWER(rd.nodeinfo) = ANY(%s::text[])
AND rd.reason LIKE 'DNS%%'
AND (rd.alias IS NULL OR rd.alias = FALSE)
AND EXISTS (
SELECT 1
FROM mastodon_domains md
WHERE md.domain = rd.domain
)
""",
(compatible_software,),
)
result = cur.fetchone()
dns_issues = result[0] if result else 0
# 5xx Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT rd.domain) AS unique_domain_count
FROM raw_domains rd
WHERE LOWER(rd.nodeinfo) = ANY(%s::text[])
AND rd.reason ~ '^5[0-9]{2}'
AND (rd.alias IS NULL OR rd.alias = FALSE)
AND EXISTS (
SELECT 1
FROM mastodon_domains md
WHERE md.domain = rd.domain
)
""",
(compatible_software,),
)
result = cur.fetchone()
http_5xx_issues = result[0] if result else 0
# 4xx Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT rd.domain) AS unique_domain_count
FROM raw_domains rd
WHERE LOWER(rd.nodeinfo) = ANY(%s::text[])
AND rd.reason ~ '^4[0-9]{2}'
AND (rd.alias IS NULL OR rd.alias = FALSE)
AND EXISTS (
SELECT 1
FROM mastodon_domains md
WHERE md.domain = rd.domain
)
""",
(compatible_software,),
)
result = cur.fetchone()
http_4xx_issues = result[0] if result else 0
# File Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT rd.domain) AS unique_domain_count
FROM raw_domains rd
WHERE LOWER(rd.nodeinfo) = ANY(%s::text[])
AND (rd.reason LIKE 'FILE%%' or rd.reason LIKE 'TYPE%%' or rd.reason LIKE 'JSON%%')
AND (rd.alias IS NULL OR rd.alias = FALSE)
AND EXISTS (
SELECT 1
FROM mastodon_domains md
WHERE md.domain = rd.domain
)
""",
(compatible_software,),
)
result = cur.fetchone()
file_issues = result[0] if result else 0
# MAU Issues
_ = cur.execute(
"""
SELECT COUNT(DISTINCT domain) AS unique_domain_count
FROM raw_domains
WHERE LOWER(nodeinfo) = ANY(%s::text[])
AND reason LIKE 'MAU%%'
AND (alias IS NULL OR alias = FALSE)
""",
(compatible_software,),
)
result = cur.fetchone()
mau_issues = result[0] if result else 0
return {
"tcp_issues": tcp_issues,
"ssl_issues": ssl_issues,
"dns_issues": dns_issues,
"http_5xx_issues": http_5xx_issues,
"http_4xx_issues": http_4xx_issues,
"file_issues": file_issues,
"mau_issues": mau_issues,
}
except Exception as e:
raise _db_error() from None
@app.get("/stats/domains", tags=["Statistics"])
async def get_domain_stats(_api_key: str | None = Depends(get_api_key)):
"""Get domain statistics (known, dead, blocked, non-Mastodon)."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
# Known Domains
_ = cur.execute(
"""
SELECT COUNT(DISTINCT domain) AS unique_domain_count
FROM raw_domains
"""
)
result = cur.fetchone()
known_domains = result[0] if result else 0
# Dead Domains
_ = cur.execute(
"""
SELECT COUNT(DISTINCT domain) AS unique_domain_count
FROM raw_domains
WHERE (bad_dns IS NOT NULL OR bad_ssl IS NOT NULL
OR bad_tcp IS NOT NULL OR bad_type IS NOT NULL
OR bad_file IS NOT NULL OR bad_api IS NOT NULL
OR bad_json IS NOT NULL OR bad_http2xx IS NOT NULL
OR bad_http3xx IS NOT NULL OR bad_http4xx IS NOT NULL
OR bad_http5xx IS NOT NULL
OR bad_hard IS NOT NULL OR bad_robot IS NOT NULL)
"""
)
result = cur.fetchone()
dead_domains = result[0] if result else 0
# Non-Mastodon Instances
_ = cur.execute(
"""
SELECT COUNT(DISTINCT domain) AS unique_domain_count
FROM raw_domains
WHERE nodeinfo IS NOT NULL
AND LOWER(nodeinfo) != ALL(%s::text[])
""",
(list(MASTODON_COMPATIBLE_SOFTWARE),),
)
result = cur.fetchone()
non_mastodon_instances = result[0] if result else 0
return {
"known_domains": known_domains,
"dead_domains": dead_domains,
"non_mastodon_instances": non_mastodon_instances,
}
except Exception as e:
raise _db_error() from None
@app.get("/stats/raw-versions", tags=["Statistics"])
async def get_raw_versions(_api_key: str | None = Depends(get_api_key)):
"""Get count of unique raw versions (before normalization/cleaning)."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
_ = cur.execute(
"""
SELECT COUNT(DISTINCT full_version) AS unique_software_versions
FROM mastodon_domains
"""
)
result = cur.fetchone()
raw_versions = result[0] if result else 0
return {"raw_versions": raw_versions}
except Exception as e:
raise _db_error() from None
@app.get("/stats/most-deployed", tags=["Statistics"])
async def get_most_deployed(_api_key: str | None = Depends(get_api_key)):
"""Get the most deployed Mastodon version by instance count and by MAU."""
try:
with db_pool.connection() as conn, conn.cursor() as cur:
# Most deployed by instance count
_ = cur.execute(
"""
SELECT
software_version,
COUNT(*) as instance_count,
SUM(active_users_monthly) as total_mau
FROM mastodon_domains
GROUP BY software_version
ORDER BY instance_count DESC
LIMIT 1
"""
)
instance_result = cur.fetchone()
# Most deployed by MAU
_ = cur.execute(
"""
SELECT
software_version,
COUNT(*) as instance_count,
SUM(active_users_monthly) as total_mau
FROM mastodon_domains
GROUP BY software_version
ORDER BY total_mau DESC NULLS LAST
LIMIT 1
"""
)
mau_result = cur.fetchone()
return {
"by_instance_count": {
"version": instance_result[0] if instance_result else None,
"instance_count": instance_result[1] if instance_result else 0,
"total_mau": instance_result[2] if instance_result else 0,
},
"by_mau": {
"version": mau_result[0] if mau_result else None,
"instance_count": mau_result[1] if mau_result else 0,
"total_mau": mau_result[2] if mau_result else 0,
},
}
except Exception as e:
raise _db_error() from None
# =============================================================================
# INSTANCE ENDPOINTS
# =============================================================================
@app.get("/instances", tags=["Instances"])
async def get_instances(
_api_key: str | None = Depends(get_api_key),
limit: int = Query(100, ge=1, le=1000, description="Number of results to return"),
offset: int = Query(0, ge=0, description="Number of results to skip"),
sort_by: str = Query("mau", description="Sort field: mau, domain, version"),
order: str = Query("desc", description="Sort order: asc or desc"),
):
"""Get a list of Mastodon instances with pagination."""
# Validate sort_by
valid_sort_fields = {
"mau": "active_users_monthly",
"domain": "domain",
"version": "software_version",
}
if sort_by not in valid_sort_fields:
raise HTTPException(
status_code=400,
detail=f"Invalid sort_by field. Must be one of: {', '.join(valid_sort_fields.keys())}",
)
# Validate order
order = order.lower()
if order not in ["asc", "desc"]:
raise HTTPException(status_code=400, detail="Order must be 'asc' or 'desc'")
try:
with db_pool.connection() as conn, conn.cursor() as cur:
# Use the validated order value directly as a SQL keyword
sort_order_sql = (
sql.SQL("ASC") if order.lower() == "asc" else sql.SQL("DESC")