Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4c351ce73 | ||
|
|
adc2c70c21 |
No files matched your search
+14
-2
@@ -18,12 +18,24 @@ SERVICEMAP_DOCKER_HOST=unix:///var/run/docker.sock
|
||||
SERVICEMAP_DOCKER_PROVIDER=socket
|
||||
SERVICEMAP_DOCKER_BROKER_URL=
|
||||
SERVICEMAP_DOCKER_BROKER_TOKEN_FILE=
|
||||
# Used only by docker-compose.broker.yml. The host token file must already
|
||||
# exist with restrictive permissions; Compose will not create it.
|
||||
SERVICEMAP_DOCKER_BROKER_TOKEN_HOST_FILE=
|
||||
# Existing external Docker network shared with the registered read broker.
|
||||
SERVICEMAP_DOCKER_BROKER_NETWORK=
|
||||
SERVICEMAP_APPOPS_URL=
|
||||
# Leave empty unless this host address is reachable from the ServiceMap container.
|
||||
SERVICEMAP_PROBE_HOST=
|
||||
# Optional OIDC API authorization. Keep disabled until a dedicated ServiceMap
|
||||
# API authorization. "token": reads stay open, changes need the admin token
|
||||
# generated in /data/admin-token on first start (read it with
|
||||
# docker exec servicemap cat /data/admin-token). "disabled" removes all
|
||||
# checks except the cross-site Origin guard. OIDC: keep it off until a dedicated ServiceMap
|
||||
# client, issuer, audience and role groups have been provisioned.
|
||||
SERVICEMAP_AUTH_MODE=disabled
|
||||
SERVICEMAP_AUTH_MODE=token
|
||||
# Optional: a different token file (at least 24 characters).
|
||||
SERVICEMAP_ADMIN_TOKEN_FILE=
|
||||
# Optional DNS-rebinding guard, comma-separated host names. Empty accepts any Host.
|
||||
SERVICEMAP_ALLOWED_HOSTS=
|
||||
SERVICEMAP_OIDC_ISSUER=
|
||||
SERVICEMAP_OIDC_AUDIENCE=
|
||||
SERVICEMAP_OIDC_ROLE_CLAIMS=groups,roles
|
||||
|
||||
+2
-2
@@ -11,12 +11,12 @@ FROM python:3.12-slim
|
||||
|
||||
LABEL org.opencontainers.image.title="ServiceMap" \
|
||||
org.opencontainers.image.description="Production infrastructure intelligence" \
|
||||
org.opencontainers.image.version="1.6.2" \
|
||||
org.opencontainers.image.licenses="MIT"
|
||||
org.opencontainers.image.version="1.6.3"
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MALLOC_ARENA_MAX=2 \
|
||||
SERVICEMAP_DB=/data/servicemap.db \
|
||||
SERVICEMAP_STATIC_DIR=/app/static
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
# Public source export
|
||||
|
||||
This source snapshot was generated from the private canonical repository at revision `203eba8143a0d195e80eb0abfd88b7388ca93e0c`. It contains no private Git history or operational evidence. Changes are published from the canonical repository.
|
||||
This source snapshot was generated from the private canonical repository at revision `af46f684e468dffd3a5190e28d3b572d4c26bfd7`. It contains no private Git history or operational evidence. Changes are published from the canonical repository.
|
||||
+277
-107
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceRevision": "203eba8143a0d195e80eb0abfd88b7388ca93e0c",
|
||||
"sourceRevision": "af46f684e468dffd3a5190e28d3b572d4c26bfd7",
|
||||
"files": [
|
||||
{
|
||||
"path": ".dockerignore",
|
||||
@@ -9,8 +9,8 @@
|
||||
},
|
||||
{
|
||||
"path": ".env.example",
|
||||
"sha256": "d330c4ef60e843b1c7afab674d19ffeb8dbae7afe7be401494c50738f88ef0c6",
|
||||
"bytes": 1321
|
||||
"sha256": "3671bd15b95a235ba96ef607a94bd1c6054b8086640bdab78a0761b9d0dd2891",
|
||||
"bytes": 2034
|
||||
},
|
||||
{
|
||||
"path": ".gitignore",
|
||||
@@ -19,53 +19,63 @@
|
||||
},
|
||||
{
|
||||
"path": "Dockerfile.unraid",
|
||||
"sha256": "ee62d905b84f8246e1d4634ea0acdd385be371805ff4ff24efe8987b49d3b326",
|
||||
"bytes": 904
|
||||
"sha256": "17f22770bafe4ca9ed6389e9040fd25ff9691a4d25ba134a509b25357c076204",
|
||||
"bytes": 881
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"sha256": "9092c2af29ae9b85339695743e5b66967fee7572f2b235461b6eb9af82db79a4",
|
||||
"bytes": 5345
|
||||
"sha256": "e5b878912e376d3301e7e83d532551a07af03d954deb1f917dd4911bd51f2004",
|
||||
"bytes": 5508
|
||||
},
|
||||
{
|
||||
"path": "backend/Dockerfile",
|
||||
"sha256": "feb54353dd7dc2790d5d0b9acd9064845082e540fd3d0150bd25d7d711859b55",
|
||||
"bytes": 359
|
||||
"sha256": "4812bed1f2b84b2e61c8a1e4f261e0a0ec71e436866ae18d8f25825cd73567ca",
|
||||
"bytes": 384
|
||||
},
|
||||
{
|
||||
"path": "backend/app/__init__.py",
|
||||
"sha256": "a92a1d83b9c8b121eb7f0ae90305b8f08c61bc81c997441c050755e56dd440ed",
|
||||
"bytes": 34
|
||||
},
|
||||
{
|
||||
"path": "backend/app/alerts.py",
|
||||
"sha256": "8ecb57d224480b31b75f493ed2bd8bc99cb255d94ee9912d20248f468d63aeab",
|
||||
"bytes": 10339
|
||||
},
|
||||
{
|
||||
"path": "backend/app/auth.py",
|
||||
"sha256": "72df1122912bf79c664386e48a5f251322b3dd7ea310df56418e02aed7930edd",
|
||||
"bytes": 6700
|
||||
"sha256": "8bf2c98d9ab7672d79859c412fb931a4a52d3ac2d0f4f9c399e019efc65f7c47",
|
||||
"bytes": 12660
|
||||
},
|
||||
{
|
||||
"path": "backend/app/backups.py",
|
||||
"sha256": "c02eff2912dcdd36492d408b76d24f39faf79b05154b2a9a3a7c2c0bca6323d3",
|
||||
"bytes": 5466
|
||||
},
|
||||
{
|
||||
"path": "backend/app/config_io.py",
|
||||
"sha256": "801323f5749570b48dc15fb5df7a71c557c8629cb1830542493ed117600f6cb9",
|
||||
"bytes": 7082
|
||||
"sha256": "ad09b0b83fd0d37b15ca0a1f5cfbefe82480a572f6e34531323eb663772b91a0",
|
||||
"bytes": 6207
|
||||
},
|
||||
{
|
||||
"path": "backend/app/demo.py",
|
||||
"sha256": "582a38df568726386f122458d5186e3b78e47caf9943aa73b20ab47cf37b5f38",
|
||||
"bytes": 6098
|
||||
"sha256": "8a442c3ef25fad5b3827cac17e14d9b275c4e8f09c916709173e6180b8157691",
|
||||
"bytes": 6119
|
||||
},
|
||||
{
|
||||
"path": "backend/app/discovery.py",
|
||||
"sha256": "50f1829a80037208a8645bf7b617e21daec2500dc25f3806c23b2937a464ad3a",
|
||||
"bytes": 52188
|
||||
"sha256": "179ab428d3524a8e4b9d1eed2d3ea106e2938a160f864fb00a61e773e36c9949",
|
||||
"bytes": 52308
|
||||
},
|
||||
{
|
||||
"path": "backend/app/discovery_store.py",
|
||||
"sha256": "cabc2ce75950e7b3b950d75dc6ee620b5f470ef0799d13c37af5877cf26140ce",
|
||||
"bytes": 47138
|
||||
"sha256": "f5b3e01f73b1875d3a6d69032b3926fc5e30b920f3238919bd535236ff339522",
|
||||
"bytes": 51154
|
||||
},
|
||||
{
|
||||
"path": "backend/app/docker_discovery.py",
|
||||
"sha256": "0d25862558aa735334b1fd3ac1897fe297f384e8fe93df95ec371ffb2f2f0ce4",
|
||||
"bytes": 31442
|
||||
"sha256": "192753d685fb709263a90fc0d1b5f4fca3d59b2a3468911ba6d2cbaa6d59baee",
|
||||
"bytes": 34489
|
||||
},
|
||||
{
|
||||
"path": "backend/app/docker_provider.py",
|
||||
@@ -74,62 +84,72 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/app/events.py",
|
||||
"sha256": "038d4536f55bb2ad9918a6e5450b0b46e11067b3a2773efe040f071a31cf2c52",
|
||||
"bytes": 2091
|
||||
"sha256": "a65aae536b3bcba99e15014729634f66f421842c960ccb97e78a57771752f5f6",
|
||||
"bytes": 3444
|
||||
},
|
||||
{
|
||||
"path": "backend/app/evidence.py",
|
||||
"sha256": "b0ec499cbc1ddb23b30a37bf3a5f2c8804a0a9b904448e4e967834818cd4c08b",
|
||||
"bytes": 4709
|
||||
"sha256": "90869b50809fb5eadf4e986d308af17b26f56536d4cb5c0b2ce2648867b70812",
|
||||
"bytes": 4724
|
||||
},
|
||||
{
|
||||
"path": "backend/app/health.py",
|
||||
"sha256": "591ae93438e98359d397c2c765ec57e7a0e2e2b1dd93f18835d8a48c256de10f",
|
||||
"bytes": 5964
|
||||
"sha256": "30de59e37d4cc48d26bb7d715d8b368e6663c6c570c8eb775a0c6b245cd7fa55",
|
||||
"bytes": 5763
|
||||
},
|
||||
{
|
||||
"path": "backend/app/incidents.py",
|
||||
"sha256": "a061a60377ad46606f9be6bff096fb48b65e93ae6302fdc6a5d741ec651a0693",
|
||||
"bytes": 7147
|
||||
"sha256": "dd4f4cf37813426e4aaaa7707cb1fa564d3510ca41ac742c43c7eedfcee10d60",
|
||||
"bytes": 7726
|
||||
},
|
||||
{
|
||||
"path": "backend/app/loops.py",
|
||||
"sha256": "08a101f36fe5b35bba80b808c8b28aea5dc5bc9c481203a0aa7a8068481795f9",
|
||||
"bytes": 5206
|
||||
},
|
||||
{
|
||||
"path": "backend/app/main.py",
|
||||
"sha256": "7ce4163b281c8f987a492c1cf227188aafefbd6720691431b0aee6909e6aa45c",
|
||||
"bytes": 30512
|
||||
"sha256": "91f8f01aa81a364e9c2968c3cd28339d3884d696191ea547851fbee433175fc9",
|
||||
"bytes": 43917
|
||||
},
|
||||
{
|
||||
"path": "backend/app/models.py",
|
||||
"sha256": "ed6a764feea6fe44bf6733fa056d924360775673acb7d6c664f5af821483b5d1",
|
||||
"bytes": 27523
|
||||
"sha256": "b701ce2f76efaf0f9d9935b3de95ad4c119d0f940bc680f65d5d90bd5c88e50a",
|
||||
"bytes": 28140
|
||||
},
|
||||
{
|
||||
"path": "backend/app/observation.py",
|
||||
"sha256": "2ffc1158f521e7db57c9b8346b851671725392a4e573e89594f4f0ce18df77f6",
|
||||
"bytes": 8872
|
||||
"sha256": "d33f3e2c790f72d3f10653942d36afe3a9683c6301da7459160d5b506576ad0e",
|
||||
"bytes": 8900
|
||||
},
|
||||
{
|
||||
"path": "backend/app/probes.py",
|
||||
"sha256": "bffd02553a09a94fd0598da8e439a0c284d3389611aab9247b4f9fae1b67ffb1",
|
||||
"bytes": 8232
|
||||
"sha256": "07e50e6b95bd850109f27511fdff785c01e3acdfb0ad9d43fa939b4132ebd80c",
|
||||
"bytes": 9675
|
||||
},
|
||||
{
|
||||
"path": "backend/app/response_cache.py",
|
||||
"sha256": "b77d5d5a535f029eae6a19fb5a66177f3f84e800ac9d20f9a118410f77513dbc",
|
||||
"bytes": 4434
|
||||
},
|
||||
{
|
||||
"path": "backend/app/scheduler.py",
|
||||
"sha256": "9d56e72ffaf4076f278be858e7e14b3daceb7655c37a008112a8542bdb89c895",
|
||||
"bytes": 2477
|
||||
"sha256": "d4f232d95415c23955f54beb1c1781a2cecbda896bf57322e88974eceb244485",
|
||||
"bytes": 2822
|
||||
},
|
||||
{
|
||||
"path": "backend/app/semantic.py",
|
||||
"sha256": "50c5f2d745ba2becad13cb56a9055aa92e0bc8b943e067847e8ef7e8823f9444",
|
||||
"bytes": 19676
|
||||
"sha256": "16d9abe6f110af681a29d30b82abdeedb0630d4d003961ab2af0a84126e009d2",
|
||||
"bytes": 19723
|
||||
},
|
||||
{
|
||||
"path": "backend/app/store.py",
|
||||
"sha256": "261d66655ec5567fbdb2fbf1b41abf3f807e509b76a188cb8b50799cc2852a85",
|
||||
"bytes": 103326
|
||||
"sha256": "619ceeebe8236ff6135204721fc41061465c2fc7f147a03d06be5f8743a2f326",
|
||||
"bytes": 113419
|
||||
},
|
||||
{
|
||||
"path": "backend/pyproject.toml",
|
||||
"sha256": "48114fc2a566ac60bd6e9f4dc53f87059940193618d48373ee022e5847d81703",
|
||||
"sha256": "090bcedfa40fb692ede31ba38656a54eeb091110726cf5d82c57314573e64b54",
|
||||
"bytes": 498
|
||||
},
|
||||
{
|
||||
@@ -144,8 +164,8 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_api.py",
|
||||
"sha256": "be344d9ac4649de26a9c5a7c851f469c3cc397ddc63fa976ec67f06882af34eb",
|
||||
"bytes": 7148
|
||||
"sha256": "89922c9adbe3a506d0bb5883f6fcd07ffaddd64b5f7c1ada84feef391b49c647",
|
||||
"bytes": 7155
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_auth.py",
|
||||
@@ -154,18 +174,18 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_config_io.py",
|
||||
"sha256": "8e994652538ed20c35d20ed6020635017374b09e509a3f0ce3a6d40ed308732a",
|
||||
"bytes": 3553
|
||||
"sha256": "e278bb4c55915c1864093d0707e9826e8fffc8141a7a8cf48f913a600badd8df",
|
||||
"bytes": 6797
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_demo.py",
|
||||
"sha256": "1dc5d298ee23b52c55440964fab96b6b3e00f56138cd2ba85158c1a6c5cbff88",
|
||||
"bytes": 7424
|
||||
"sha256": "f9d6844f5994a7103955aa415ce6e0a9645cdcc73ec7c087db102f57fb8036dc",
|
||||
"bytes": 8605
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_discovery_v120.py",
|
||||
"sha256": "02ffcc2d06cecce44574c8c91f2d170af83ad490a984f85dd1a39d83af785f2d",
|
||||
"bytes": 15798
|
||||
"sha256": "9a9955b31407a99d13cedfcf0511cc721f1f80865f95a074feb7a7d9b494bd28",
|
||||
"bytes": 17307
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_docker_discovery.py",
|
||||
@@ -179,18 +199,18 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_health.py",
|
||||
"sha256": "391c17b69b056a4276b68f2a118339a8c5164327b3910612466dce236a3d787f",
|
||||
"sha256": "0ce949ee7adcb07e5d96ca4c5f9d09fa3369a5484d08edd8abcf5e74a33c7f9e",
|
||||
"bytes": 3884
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_probes.py",
|
||||
"sha256": "f8b9c21963e17e55abf56ab911411b4e4b86f8bc7bf84a13fb18e65e0527a613",
|
||||
"bytes": 4660
|
||||
"sha256": "a0d3d7a53a5cba12738981d4109928b5a4950d7dcbfb31f9928b0d25ae121c0c",
|
||||
"bytes": 4980
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_scheduler.py",
|
||||
"sha256": "31ab725da5d1d584784a64fa736ca1776a1bed6415bfb8bd57f08e6645545384",
|
||||
"bytes": 1865
|
||||
"sha256": "9407b748e56ad6ef525d6e5bc964c4a58f0d0af8e65d211d23e130460d04ead2",
|
||||
"bytes": 2815
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_store.py",
|
||||
@@ -204,8 +224,8 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v130_probe_reachability.py",
|
||||
"sha256": "d8fbe8f6b4dc6c3fd608986b83db260383dc0d830056de08a26d6e006336227a",
|
||||
"bytes": 11432
|
||||
"sha256": "a02987a48c488aca077702c415a51f96418f290560498b6d496f182471ccf1c9",
|
||||
"bytes": 11451
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v140_semantic.py",
|
||||
@@ -214,28 +234,88 @@
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v160_evidence_changes.py",
|
||||
"sha256": "bf37810c1776e8cf90821c32060cb5cd82c34acacd76c5a0f268ab01458b9dcf",
|
||||
"bytes": 4148
|
||||
"sha256": "d55e4b42a4aa7784e4d9db8a4e0df984106a5ceb13a633a12956341909887b0c",
|
||||
"bytes": 4146
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v161_health_resolution.py",
|
||||
"sha256": "892d0d83b17dbd279d551bd216a77835361e1b0a44be17804be9a97045c09222",
|
||||
"bytes": 15509
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_alerts.py",
|
||||
"sha256": "5d73c0376e3022ca402eaabcec901617a65b4c644a6f529e8a98c9ca58bb62b5",
|
||||
"bytes": 6590
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_backups.py",
|
||||
"sha256": "a813f0667ffa6f6891118792af8c419e0247896018f25b9b99182a9fa0982169",
|
||||
"bytes": 5380
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_data_integrity.py",
|
||||
"sha256": "193d2f31461d98e51063e4a512a28665f9a5741fd95ce78b8584409b8d37f69a",
|
||||
"bytes": 2364
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_efficiency.py",
|
||||
"sha256": "eea9a13adcd8c1a25bbfd2d35217ff282ef717263e663ee99c89929c0342813d",
|
||||
"bytes": 6665
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_health_performance.py",
|
||||
"sha256": "0ec2188dbb5bb407649b3cfe801a16bfb6ded7cb416cce5182aaeffeaf65cb7f",
|
||||
"bytes": 14241
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_loops.py",
|
||||
"sha256": "35fbd2efec00153563a04d02e4075db956f7f5789c801a6fa235a39ce27f73db",
|
||||
"bytes": 5438
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_management.py",
|
||||
"sha256": "0a28025ada6499c6071811ec08d1408bb163797553e3d19d3879520a4b31411a",
|
||||
"bytes": 5673
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_realtime.py",
|
||||
"sha256": "fa3cdd91d3ead965ffc184767a10df114f04ae3104cb000120b00661c9bd33f5",
|
||||
"bytes": 3612
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_security.py",
|
||||
"sha256": "3b154e233edff626f68a92b8eacd3bb64ae8a13792a78123f9c83ccc6617e98a",
|
||||
"bytes": 7022
|
||||
},
|
||||
{
|
||||
"path": "backend/tests/test_v163_semantic_etag.py",
|
||||
"sha256": "510362530c2bd6c6117c67f4ba2da6a8615009d1c09b8ee7f71d24b23b440432",
|
||||
"bytes": 5402
|
||||
},
|
||||
{
|
||||
"path": "compose.demo.yaml",
|
||||
"sha256": "5e31bbc6eb1e56cfd308431682427ac44c991ddb7ac7058a6406d091482ff79e",
|
||||
"bytes": 700
|
||||
},
|
||||
{
|
||||
"path": "compose.yaml",
|
||||
"sha256": "26f2744d15f1db2840c48601515cbddd59d7e710105ba965520405e4005e0da6",
|
||||
"bytes": 2129
|
||||
"sha256": "5379d454b3a0ec392416fae6646bc8524eccfd6d1ba56dbe14d64e311eb40b91",
|
||||
"bytes": 2250
|
||||
},
|
||||
{
|
||||
"path": "docker-compose.broker.yml",
|
||||
"sha256": "3213899c1a8b929388a10ed9ac52eefc6f5c4a73972ddafa08ffd26ebffdf485",
|
||||
"bytes": 3548
|
||||
},
|
||||
{
|
||||
"path": "docker-compose.yml",
|
||||
"sha256": "bb3f897d9edce88ff5a7aa863a4e3991df4f2bbb70b8506ad7acd20f1c06da69",
|
||||
"bytes": 3169
|
||||
"sha256": "e3344882fa0197dbb047fa805de2c86dc6d081325394cace11ec60708f319216",
|
||||
"bytes": 3910
|
||||
},
|
||||
{
|
||||
"path": "docs/ARCHITECTURE.md",
|
||||
"sha256": "a643ac3388ae58db587c3d9d91b169aba8cf8e904560b4c497c191b5e6e8f40a",
|
||||
"bytes": 14121
|
||||
"sha256": "aa5ed3cbbdcc1966b6e83db41527e68d84831d1d01df4cfbbab27d218d4800f2",
|
||||
"bytes": 18510
|
||||
},
|
||||
{
|
||||
"path": "docs/screenshots/demo-health.png",
|
||||
@@ -252,10 +332,15 @@
|
||||
"sha256": "c213e75d23f78f5f1bad478c0d119335c66df4e9fdc1057713fb35ddffb6843a",
|
||||
"bytes": 345
|
||||
},
|
||||
{
|
||||
"path": "frontend/e2e/a11y.spec.ts",
|
||||
"sha256": "b516fe5e8a612e1f9ff2803d36954d0b913ad6e6aa1186cbc958394a4f789f69",
|
||||
"bytes": 3332
|
||||
},
|
||||
{
|
||||
"path": "frontend/e2e/demo.spec.ts",
|
||||
"sha256": "7f64c79a0d244f680057979b38ad3891607e95442e50b77d48453bf9d4bb1e49",
|
||||
"bytes": 7681
|
||||
"sha256": "ec2849e6f232edbd115481d6ae0db71334d983f6c54c214309a01611c77798d8",
|
||||
"bytes": 8008
|
||||
},
|
||||
{
|
||||
"path": "frontend/eslint.config.js",
|
||||
@@ -264,28 +349,28 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/index.html",
|
||||
"sha256": "8ffed1c9e71561358251b68009a20c5902364690ac7cbc141ff0165559e4a372",
|
||||
"bytes": 846
|
||||
"sha256": "d85928c07739b131c2837e44f63e13383eb7443bd31d716e34999285845e0aa6",
|
||||
"bytes": 849
|
||||
},
|
||||
{
|
||||
"path": "frontend/nginx.conf",
|
||||
"sha256": "efbdd38d0aa6cec003952d001194c6dfa6450db9f9be2dcef7f5fa1f4703e608",
|
||||
"bytes": 497
|
||||
"sha256": "9b8b627487b1679b34ccfe4d63b31481ab6103dae38ce8ff2e63b21139edb15e",
|
||||
"bytes": 955
|
||||
},
|
||||
{
|
||||
"path": "frontend/package-lock.json",
|
||||
"sha256": "2e1c1a36d5198a399cd61e77c0c5f79f8cbce5ddf9b212a65ff20715e299b90e",
|
||||
"bytes": 135002
|
||||
"sha256": "343126dd503ed9e08f23b613232e314026dd87c60c8513e8fe456c81e920e836",
|
||||
"bytes": 160062
|
||||
},
|
||||
{
|
||||
"path": "frontend/package.json",
|
||||
"sha256": "d3cf704c4e5ee73c1a4a149db52ce44b7155f1021399397bf190dd3bc0fad68d",
|
||||
"bytes": 847
|
||||
"sha256": "cc22ff7ed7138703d88b257b17dbd7beaf23e3e419d49363ee0c1c6303ba0d4d",
|
||||
"bytes": 1146
|
||||
},
|
||||
{
|
||||
"path": "frontend/playwright.config.ts",
|
||||
"sha256": "cf40a43af5adb6a1e5eac91288933dcd8bffc14587e6f0d6fee61d24b4720599",
|
||||
"bytes": 828
|
||||
"sha256": "22c0242b1af59f1ef9630711ed7cab1cb4650d3df7ddc319a159e5342a934b48",
|
||||
"bytes": 1073
|
||||
},
|
||||
{
|
||||
"path": "frontend/public/brand/servicemap-dark.svg",
|
||||
@@ -349,13 +434,23 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/App.tsx",
|
||||
"sha256": "1e5810061bfbcaa690321f14c5d6137efa53689dd7e6ad9caf62d8295ac2fbea",
|
||||
"bytes": 137688
|
||||
"sha256": "00093ee16eab74a86026760f449475466dcb420398685637dcebc6de8e96c7f9",
|
||||
"bytes": 189981
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/LivingEdge.tsx",
|
||||
"sha256": "2efb46345431d63e0bd45d7a9dc297e8f88a44c045d31f2aa303890c8c93bb0a",
|
||||
"bytes": 1322
|
||||
"sha256": "ea29a94fdc91d6dc4dcea153b257a70d82210c21016f512afb06d5f7d599e1da",
|
||||
"bytes": 1402
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/activityView.test.ts",
|
||||
"sha256": "33efe2f69a22afe3fd42cdeb259813cc72fafae06b9f96ced0dc02ddbd4c853c",
|
||||
"bytes": 2049
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/activityView.ts",
|
||||
"sha256": "dbb04b6967f737a0912974f2d3b4c595dfb70f3aa01ddad33cf8aa63ece463d2",
|
||||
"bytes": 3452
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/api.test.ts",
|
||||
@@ -364,8 +459,13 @@
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/api.ts",
|
||||
"sha256": "8b0cc28dc4122c25cf4cf5e46ee26c3ba94276cdd9d2599e4b88244bf1bef7d6",
|
||||
"bytes": 26567
|
||||
"sha256": "2bdd09f8d7e1ccb93f0c84c7a242b70a66b2612eff0f12fc8e7953e62ad44c7d",
|
||||
"bytes": 31602
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/apiAuth.test.ts",
|
||||
"sha256": "064fa7b7388876e51ba04db046a3958b263a6c81b7bf2280e4e879d892762e23",
|
||||
"bytes": 3475
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/auditViewModel.test.ts",
|
||||
@@ -377,60 +477,130 @@
|
||||
"sha256": "4bb1a4fef5b539a448b1b6c6f8a3ec0032ffefe22a13ee4f72dc7a1b2d325197",
|
||||
"bytes": 1397
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/components/ActionsMenu.tsx",
|
||||
"sha256": "61fe597f50cef53739266dca2f719ecd43c708b80ed2b9bd6eaf4faa741ef81a",
|
||||
"bytes": 1872
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/components/ConfirmDialog.test.tsx",
|
||||
"sha256": "bffcc32c9757f2aae7f61c41b856affed8b27d9c11f3ebf1a4cc442cad2848ef",
|
||||
"bytes": 1658
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/components/ConfirmDialog.tsx",
|
||||
"sha256": "9df5f22d9b34e06b8342556a3cfca1c4139560c2723558fece6c2b5aa46b47bf",
|
||||
"bytes": 1783
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/components/StatusIcon.tsx",
|
||||
"sha256": "5cbab60d344423dc089de34326cc425af2317a953d5e2229a11034e99546f90e",
|
||||
"bytes": 746
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/demo/DemoWalkthrough.test.ts",
|
||||
"sha256": "57d2f80de3965e8b99e6d2df9068544d7d933490d17568b7d887b2e9672d0e33",
|
||||
"bytes": 472
|
||||
"sha256": "d392514ac764ab522e9bc81a6f8dea076c731e28fa4eece91cdd16554db1e89c",
|
||||
"bytes": 467
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/demo/DemoWalkthrough.tsx",
|
||||
"sha256": "b81ee31bee55c6db6e4061e7db3c06dcd900554b9c0de6b42266becf9877e6e5",
|
||||
"bytes": 2137
|
||||
"sha256": "2bd3103c485700b37af3a154d1298b9a8223915410dc6c9cd9b5aecd4ff8e7d1",
|
||||
"bytes": 2167
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/elk-worker-url.d.ts",
|
||||
"sha256": "a4dbd565e1a7cbb9b9d40224765ec315bc25c285c8909c509e058143d9681c6c",
|
||||
"bytes": 96
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/labels.ts",
|
||||
"sha256": "fb6e2fc2306f3d387ec77e5adada7ba5379e24a0bb1ee70b1ef07b2c6bea2db3",
|
||||
"bytes": 3649
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/main.tsx",
|
||||
"sha256": "77aaa85d0a532963cd63d1c6171a833f73b608dd83b4085f855b279dbe922939",
|
||||
"bytes": 227
|
||||
"sha256": "abf28aa30c35a5b5480fb11dba4e0a3b2e5ff8a02c4b32a1147a522fb5370a74",
|
||||
"bytes": 263
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/realtime/refreshPlan.test.ts",
|
||||
"sha256": "37c0a47289b1e0a1b2cc678c90bcbbd5c0ec28c016872ee3b996e33b37584d7d",
|
||||
"bytes": 4706
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/realtime/refreshPlan.ts",
|
||||
"sha256": "d459f51aa82e3f7d3c742815e03298ebacfcd60335e89b01c994583f4218e015",
|
||||
"bytes": 5267
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/realtime/useRealtimeEvents.ts",
|
||||
"sha256": "bc8a1e1b9991936fc7521c2e275a941468ed97a027cd001ebc664c31db7920e1",
|
||||
"bytes": 3303
|
||||
"sha256": "949299cc212789b27ea69f0d699850ae3dfc7185fae070d80299a2c956a107f1",
|
||||
"bytes": 5247
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/routing/urlState.test.ts",
|
||||
"sha256": "bdcab27c894ce50a4fdcd9231ff58ef035e023333fa54d8e4555e34c6fc222e3",
|
||||
"bytes": 2011
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/routing/urlState.ts",
|
||||
"sha256": "89f99274063cd020c0212dfa93ed09e75835280deef921879cfda3bb5810486c",
|
||||
"bytes": 4801
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/styles.css",
|
||||
"sha256": "af382edc68308fc050d1cfb5f35e0e9be4e0388acf8ccd5e10dc5d6a213015c2",
|
||||
"bytes": 31620
|
||||
"sha256": "7bfa7b1076590dcc43e954bbbbf166874c6d6dd30de08adea6d224c1abde8919",
|
||||
"bytes": 61862
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology.test.ts",
|
||||
"sha256": "80dbcbefbe5f661d78ed72c78d951691fb8a8d1741438cabb05d6a414907f735",
|
||||
"bytes": 6887
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/GraphListView.test.tsx",
|
||||
"sha256": "7988fb7159747a495fc105068c405ba39301c7161d3fc1aa8ad4f44597c50965",
|
||||
"bytes": 2263
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/GraphListView.tsx",
|
||||
"sha256": "f63b547a8a7e746d139ee249b93bceb4effb90ee245137ba8a832b7a97bbe9d1",
|
||||
"bytes": 2505
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/ServiceNode.tsx",
|
||||
"sha256": "1c188095fab61639d1d9341a2fa3eb9ce377008d6f0ccc6c128a1496438d44cd",
|
||||
"bytes": 3755
|
||||
"sha256": "28f9a2e63f1648a421be345620a135a457fcfa98fd9c5dc38826d71149d3e2e8",
|
||||
"bytes": 4417
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/TopologyCommandBar.tsx",
|
||||
"sha256": "c74509e41a2574a43907d2d9365d0c552c4534da86c9644f17b7e6da99e374a9",
|
||||
"bytes": 8184
|
||||
"sha256": "55d4abbc388bc6a55cfec7ce2683938bb00763a4b2531efe2a4644ec3d1bd904",
|
||||
"bytes": 8547
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/legacyLayout.ts",
|
||||
"sha256": "6d2af3d9a09dc1dc5f0c86623c80f2b1a2e40fd485514c66ca5101b308b9bacb",
|
||||
"bytes": 9550
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/semanticGraph.test.ts",
|
||||
"sha256": "c3e7321d57ff0b7a841894c953ff34ece5eeb302152cd5475a0a2fa2dad349fb",
|
||||
"bytes": 2792
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topology/semanticGraph.ts",
|
||||
"sha256": "88ca18c486ad119ca84a31341135f6c7a3482a9b1df6351dc316e4c12d8be754",
|
||||
"bytes": 9270
|
||||
"sha256": "74928099e36efb806d5ab843787f884f123a5551f767f4f242bb245944a0dc2b",
|
||||
"bytes": 11199
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topologyLayout.test.ts",
|
||||
"sha256": "1a364202cf4cec3c3dd341ddd566d92bfeb3924642b4afa401ee0040eb624677",
|
||||
"bytes": 1238
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topologyLayout.ts",
|
||||
"sha256": "61fcec5486324d7558deca0d3b16014589df27375fcdb3aa6dbf30bc089b4062",
|
||||
"bytes": 2754
|
||||
"sha256": "1ceeea7b6c1d69ecf0375184a6134c1e70660ccac882f19b861c45e727ce38da",
|
||||
"bytes": 4085
|
||||
},
|
||||
{
|
||||
"path": "frontend/src/topologyNavigation.test.ts",
|
||||
@@ -454,12 +624,12 @@
|
||||
},
|
||||
{
|
||||
"path": "package-lock.json",
|
||||
"sha256": "11d3ccff95db4efe5af950fa5c4d6374d5d21e62e2910d9280e0a063d5697303",
|
||||
"sha256": "c2df0fa270d2e687acf6277c99cc270d976cf87649d92f35ed0560ee3b78eea2",
|
||||
"bytes": 203
|
||||
},
|
||||
{
|
||||
"path": "package.json",
|
||||
"sha256": "a26509b2cb00f1509a64903a70e376ad5e5ae4e4284bd24ad5117bf38fe2fb38",
|
||||
"sha256": "bc4ce50c81c106ce390ce73d0c2ec259467f6dec6a3a0281fc078a74e3b64a37",
|
||||
"bytes": 478
|
||||
},
|
||||
{
|
||||
@@ -469,8 +639,8 @@
|
||||
},
|
||||
{
|
||||
"path": "unraid/my-servicemap.xml",
|
||||
"sha256": "e5faff675682a5af3a0403babc973727b1607ad6417e598a6d9922326bfa3329",
|
||||
"bytes": 3083
|
||||
"sha256": "5eff1eeb0a5aee9d706c3491b76acdd8e67a73bff1b2bad59b92e336466af312",
|
||||
"bytes": 3669
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -25,7 +25,13 @@ flowchart LR
|
||||
|
||||
## Explore safely
|
||||
|
||||
Choose **Explore demo** to open the fictional Northstar Platform: nine services, synthetic observations and a seeded PostgreSQL failure. The same incident and dependency logic identifies downstream impact. The demo contacts no fictional endpoints; **Exit demo** restores the saved topology, and **Reset demo** restores its synthetic starting state.
|
||||
Run the fictional Northstar Platform in a local instance with its own SQLite volume:
|
||||
|
||||
```bash
|
||||
docker compose -f compose.demo.yaml up --build
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:1254`, then choose **Demo verkennen**. The scenario shows nine services, a seeded PostgreSQL failure and its downstream impact. Its observations are synthetic. **Demo afsluiten** restores the sandbox's saved topology, and **Demo opnieuw starten** resets the synthetic scenario. Demo activation is disabled by default on regular installations.
|
||||
|
||||
## Demo preview
|
||||
|
||||
@@ -80,6 +86,6 @@ Vite proxies the API to port 8000. Validate changes with `python -m pytest`, `np
|
||||
|
||||
## Source distribution and licensing
|
||||
|
||||
This is the curated public source edition of ServiceMap 1.6.2. Reviewed updates flow from the private canonical repository after merges to `main`; private history, production evidence and internal CI/deployment workflows are excluded. Deployment examples use generic addresses and must be configured for your environment.
|
||||
This is the curated public source edition of ServiceMap 1.6.3. Reviewed updates flow from the private canonical repository after merges to `main`; private history, production evidence and internal CI/deployment workflows are excluded. Deployment examples use generic addresses and must be configured for your environment.
|
||||
|
||||
No project-wide license is included. Public source visibility does not grant reuse or redistribution rights; obtain the owner's terms and review third-party dependencies before redistribution.
|
||||
@@ -3,6 +3,7 @@ FROM python:3.12-slim
|
||||
WORKDIR /app
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MALLOC_ARENA_MAX=2 \
|
||||
SERVICEMAP_DB=/data/servicemap.db
|
||||
|
||||
COPY backend/requirements.lock ./requirements.lock
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
"""Incident notifications via ntfy.
|
||||
|
||||
The notifier is deliberately small and idempotent:
|
||||
|
||||
* settings live in the ``settings`` table (key ``alerts``); the optional ntfy
|
||||
access token is write-only and never returned by the API;
|
||||
* ``alert_log`` records which notification (``opened``, ``resolved``,
|
||||
``reminder:<n>``) was sent for which incident, so restarts and repeated
|
||||
cycles never send duplicates;
|
||||
* an incident is announced only after it has stayed open for
|
||||
``delay_seconds`` (short flaps stay quiet) and when its severity reaches
|
||||
``min_severity``. Maintenance never opens incidents, so it is quiet too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Literal
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from .models import Criticality, IncidentRecord, IncidentStatus
|
||||
from .store import Store
|
||||
|
||||
logger = logging.getLogger("servicemap.alerts")
|
||||
|
||||
_SEVERITY_RANK = {Criticality.LOW: 0, Criticality.MEDIUM: 1, Criticality.HIGH: 2, Criticality.CRITICAL: 3}
|
||||
_SETTINGS_KEY = "alerts"
|
||||
|
||||
|
||||
class AlertSettings(BaseModel):
|
||||
enabled: bool = False
|
||||
ntfy_server: str = Field(default="https://ntfy.sh", max_length=300)
|
||||
ntfy_topic: str = Field(default="", max_length=120)
|
||||
min_severity: Criticality = Criticality.MEDIUM
|
||||
delay_seconds: int = Field(default=60, ge=0, le=3600)
|
||||
notify_resolved: bool = True
|
||||
reminder_minutes: int = Field(default=0, ge=0, le=1440)
|
||||
public_url: str = Field(default="", max_length=300)
|
||||
|
||||
@field_validator("ntfy_server", "public_url")
|
||||
@classmethod
|
||||
def _http_url(cls, value: str) -> str:
|
||||
value = value.strip().rstrip("/")
|
||||
if value and urlparse(value).scheme not in {"http", "https"}:
|
||||
raise ValueError("moet een http(s)-URL zijn")
|
||||
return value
|
||||
|
||||
@field_validator("ntfy_topic")
|
||||
@classmethod
|
||||
def _topic(cls, value: str) -> str:
|
||||
value = value.strip()
|
||||
if value and not all(char.isalnum() or char in "-_" for char in value):
|
||||
raise ValueError("mag alleen letters, cijfers, - en _ bevatten")
|
||||
return value
|
||||
|
||||
|
||||
class AlertSettingsView(AlertSettings):
|
||||
"""What the API returns: the access token is never echoed."""
|
||||
|
||||
ntfy_token_set: bool = False
|
||||
|
||||
|
||||
class AlertSettingsUpdate(AlertSettings):
|
||||
# None keeps the stored token, "" removes it.
|
||||
ntfy_token: str | None = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class AlertTestResult(BaseModel):
|
||||
ok: bool
|
||||
detail: str
|
||||
|
||||
|
||||
class AlertManager:
|
||||
def __init__(self, store: Store) -> None:
|
||||
self.store = store
|
||||
self._init_schema()
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
return self.store._connect()
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
with self._connect() as db:
|
||||
db.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS alert_log (
|
||||
incident_id TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
sent_at TEXT NOT NULL,
|
||||
PRIMARY KEY (incident_id, kind)
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
# -- settings -----------------------------------------------------------
|
||||
def _raw(self) -> dict[str, object]:
|
||||
with self._connect() as db:
|
||||
row = db.execute("SELECT value FROM settings WHERE key = ?", (_SETTINGS_KEY,)).fetchone()
|
||||
if row is None:
|
||||
return {}
|
||||
try:
|
||||
value = json.loads(row["value"])
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
def settings(self) -> AlertSettings:
|
||||
raw = self._raw()
|
||||
return AlertSettings.model_validate({key: value for key, value in raw.items() if key != "ntfy_token"})
|
||||
|
||||
def view(self) -> AlertSettingsView:
|
||||
raw = self._raw()
|
||||
return AlertSettingsView(**self.settings().model_dump(), ntfy_token_set=bool(raw.get("ntfy_token")))
|
||||
|
||||
def update(self, update: AlertSettingsUpdate) -> AlertSettingsView:
|
||||
raw = self._raw()
|
||||
stored = update.model_dump(exclude={"ntfy_token"})
|
||||
token = raw.get("ntfy_token") if update.ntfy_token is None else update.ntfy_token.strip()
|
||||
if token:
|
||||
stored["ntfy_token"] = token
|
||||
if stored["enabled"] and not stored["ntfy_topic"]:
|
||||
raise ValueError("Stel een ntfy-topic in voor je meldingen aanzet")
|
||||
with self._connect() as db:
|
||||
db.execute(
|
||||
"INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
|
||||
(_SETTINGS_KEY, json.dumps(stored), datetime.now(UTC).isoformat()),
|
||||
)
|
||||
return self.view()
|
||||
|
||||
# -- delivery -------------------------------------------------------------
|
||||
def _send(self, title: str, message: str, *, priority: str, tags: str, click: str | None) -> None:
|
||||
settings = self.settings()
|
||||
token = self._raw().get("ntfy_token")
|
||||
headers = {"Title": title, "Priority": priority, "Tags": tags}
|
||||
if click:
|
||||
headers["Click"] = click
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
url = f"{settings.ntfy_server}/{quote(settings.ntfy_topic)}"
|
||||
with httpx.Client(timeout=10.0, trust_env=False, follow_redirects=False) as client:
|
||||
response = client.post(url, content=message.encode("utf-8"), headers=headers)
|
||||
if response.status_code >= 300:
|
||||
raise RuntimeError(f"ntfy antwoordde met HTTP {response.status_code}")
|
||||
|
||||
def send_test(self) -> AlertTestResult:
|
||||
settings = self.settings()
|
||||
if not settings.ntfy_topic:
|
||||
return AlertTestResult(ok=False, detail="Er is geen ntfy-topic ingesteld")
|
||||
try:
|
||||
self._send(
|
||||
"Testmelding van ServiceMap",
|
||||
"Meldingen van ServiceMap komen aan op dit topic.",
|
||||
priority="default",
|
||||
tags="white_check_mark",
|
||||
click=settings.public_url or None,
|
||||
)
|
||||
except (httpx.HTTPError, RuntimeError) as exc:
|
||||
return AlertTestResult(ok=False, detail=str(exc))
|
||||
return AlertTestResult(ok=True, detail=f"Verstuurd naar {settings.ntfy_server}/{settings.ntfy_topic}")
|
||||
|
||||
def _sent(self, incident_id: str) -> set[str]:
|
||||
with self._connect() as db:
|
||||
rows = db.execute("SELECT kind FROM alert_log WHERE incident_id = ?", (incident_id,)).fetchall()
|
||||
return {row["kind"] for row in rows}
|
||||
|
||||
def _mark(self, incident_id: str, kind: str, at: datetime) -> None:
|
||||
with self._connect() as db:
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO alert_log (incident_id, kind, sent_at) VALUES (?, ?, ?)",
|
||||
(incident_id, kind, at.isoformat()),
|
||||
)
|
||||
|
||||
def _link(self, settings: AlertSettings, incident: IncidentRecord) -> str | None:
|
||||
if not settings.public_url:
|
||||
return None
|
||||
return f"{settings.public_url}/#/incidents?incident={quote(incident.id)}"
|
||||
|
||||
def plan(self, incidents: list[IncidentRecord], now: datetime) -> list[tuple[IncidentRecord, Literal["opened", "resolved"] | str]]:
|
||||
"""Notifications that are due now (pure apart from reading the log)."""
|
||||
|
||||
settings = self.settings()
|
||||
due: list[tuple[IncidentRecord, str]] = []
|
||||
for incident in incidents:
|
||||
if _SEVERITY_RANK[incident.severity] < _SEVERITY_RANK[settings.min_severity]:
|
||||
continue
|
||||
sent = self._sent(incident.id)
|
||||
if incident.status == IncidentStatus.RESOLVED:
|
||||
if settings.notify_resolved and "opened" in sent and "resolved" not in sent:
|
||||
due.append((incident, "resolved"))
|
||||
continue
|
||||
open_for = now - incident.detected_at
|
||||
if "opened" not in sent:
|
||||
if open_for >= timedelta(seconds=settings.delay_seconds):
|
||||
due.append((incident, "opened"))
|
||||
continue
|
||||
if settings.reminder_minutes and incident.status == IncidentStatus.OPEN:
|
||||
count = int(open_for.total_seconds() // (settings.reminder_minutes * 60))
|
||||
if count >= 1 and f"reminder:{count}" not in sent:
|
||||
due.append((incident, f"reminder:{count}"))
|
||||
return due
|
||||
|
||||
def run_cycle(self, now: datetime | None = None) -> int:
|
||||
settings = self.settings()
|
||||
if not settings.enabled or not settings.ntfy_topic:
|
||||
return 0
|
||||
now = now or datetime.now(UTC)
|
||||
# Recently resolved incidents still need their "resolved" message.
|
||||
incidents = self.store.list_incidents(active_only=False, limit=200)
|
||||
sent = 0
|
||||
for incident, kind in self.plan(incidents, now):
|
||||
critical = incident.severity in {Criticality.HIGH, Criticality.CRITICAL}
|
||||
if kind == "resolved":
|
||||
title = f"Opgelost: {incident.title}"
|
||||
message = f"{incident.root_service_name} is hersteld."
|
||||
priority, tags = "default", "white_check_mark"
|
||||
else:
|
||||
reminder = kind.startswith("reminder")
|
||||
title = f"{'Nog steeds uitgevallen' if reminder else 'Uitgevallen'}: {incident.title}"
|
||||
affected = len(incident.affected_service_ids)
|
||||
message = (
|
||||
f"{incident.root_cause_reason}"
|
||||
+ (f"\n{affected} afhankelijke service(s) geraakt." if affected else "")
|
||||
)
|
||||
priority, tags = ("urgent" if critical else "high"), "rotating_light"
|
||||
try:
|
||||
self._send(title, message, priority=priority, tags=tags, click=self._link(settings, incident))
|
||||
except (httpx.HTTPError, RuntimeError):
|
||||
logger.exception("Sending the %s notification for incident %s failed", kind, incident.id)
|
||||
continue
|
||||
self._mark(incident.id, kind, now)
|
||||
sent += 1
|
||||
return sent
|
||||
+151
-10
@@ -1,10 +1,27 @@
|
||||
"""Optional, fail-closed OIDC bearer authorization for ServiceMap APIs."""
|
||||
"""ServiceMap API authorization.
|
||||
|
||||
Modes (``SERVICEMAP_AUTH_MODE``):
|
||||
|
||||
* ``disabled`` - no authentication (v1.5 behaviour). Cross-site mutations are
|
||||
still refused by the Origin check below.
|
||||
* ``token`` - reads stay anonymous on the LAN (integrations such as ITWorx
|
||||
Forge and monitors keep working); every mutating request needs
|
||||
``Authorization: Bearer <admin token>``. The token lives in a 0600 file
|
||||
next to the database and is generated on first start.
|
||||
* ``oidc`` - fail-closed bearer JWT validation with viewer/operator/admin
|
||||
roles mapped from claims or groups.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
@@ -36,10 +53,10 @@ class AuthConfig:
|
||||
@classmethod
|
||||
def from_environment(cls) -> AuthConfig:
|
||||
mode = os.getenv("SERVICEMAP_AUTH_MODE", "disabled").strip().casefold() or "disabled"
|
||||
if mode == "disabled":
|
||||
return cls(mode="disabled")
|
||||
if mode in {"disabled", "token"}:
|
||||
return cls(mode=mode)
|
||||
if mode != "oidc":
|
||||
raise AuthorizationError("SERVICEMAP_AUTH_MODE must be 'disabled' or 'oidc'")
|
||||
raise AuthorizationError("SERVICEMAP_AUTH_MODE must be 'disabled', 'token' or 'oidc'")
|
||||
issuer = os.getenv("SERVICEMAP_OIDC_ISSUER", "").strip().rstrip("/")
|
||||
audience = os.getenv("SERVICEMAP_OIDC_AUDIENCE", "").strip()
|
||||
parsed = urlparse(issuer)
|
||||
@@ -131,17 +148,123 @@ def verify_bearer(token: str, config: AuthConfig) -> set[str]:
|
||||
return _roles_for(claims, config)
|
||||
|
||||
|
||||
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
# Reads that expose secrets need write access even where reads are open
|
||||
# (an ntfy topic is effectively a secret on a public server).
|
||||
SECRET_READ_PREFIXES = ("/api/v1/config", "/api/v1/settings", "/api/v1/backups")
|
||||
# A backup contains every record, so listing and downloading need the token too.
|
||||
TOKEN_READ_PREFIXES = ("/api/v1/settings", "/api/v1/backups")
|
||||
_MIN_TOKEN_LENGTH = 24
|
||||
_logger = logging.getLogger("servicemap.auth")
|
||||
_token_lock = Lock()
|
||||
_token_cache: dict[str, str] = {}
|
||||
|
||||
|
||||
def admin_token_path() -> Path:
|
||||
configured = os.getenv("SERVICEMAP_ADMIN_TOKEN_FILE", "").strip()
|
||||
if configured:
|
||||
return Path(configured)
|
||||
database = Path(os.getenv("SERVICEMAP_DB", "data/servicemap.db"))
|
||||
return database.parent / "admin-token"
|
||||
|
||||
|
||||
def admin_token() -> str:
|
||||
"""Read the admin token, generating it on first use.
|
||||
|
||||
The value is never logged; only its location is. Read it on the host
|
||||
with e.g. ``docker exec servicemap cat /data/admin-token``.
|
||||
"""
|
||||
|
||||
path = admin_token_path()
|
||||
key = str(path)
|
||||
with _token_lock:
|
||||
cached = _token_cache.get(key)
|
||||
if cached:
|
||||
return cached
|
||||
if not path.exists():
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
generated = secrets.token_urlsafe(32)
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
||||
handle.write(generated + "\n")
|
||||
_logger.warning("Generated a new ServiceMap admin token at %s", path)
|
||||
token = path.read_text(encoding="utf-8").strip()
|
||||
if len(token) < _MIN_TOKEN_LENGTH:
|
||||
raise AuthorizationError(
|
||||
f"The admin token in {path} must be at least {_MIN_TOKEN_LENGTH} characters"
|
||||
)
|
||||
_token_cache[key] = token
|
||||
return token
|
||||
|
||||
|
||||
def reset_token_cache() -> None:
|
||||
with _token_lock:
|
||||
_token_cache.clear()
|
||||
|
||||
|
||||
def required_role(request: Request) -> str:
|
||||
if request.method in {"GET", "HEAD", "OPTIONS"}:
|
||||
return "viewer"
|
||||
path = request.url.path
|
||||
if request.method in SAFE_METHODS:
|
||||
# A full configuration export contains every endpoint and target;
|
||||
# settings hold notification targets.
|
||||
return "admin" if path.startswith(SECRET_READ_PREFIXES) else "viewer"
|
||||
if path.startswith(
|
||||
("/api/v1/config", "/api/v1/discovery", "/api/v1/docker", "/api/v1/maintenance")
|
||||
(
|
||||
"/api/v1/config",
|
||||
"/api/v1/discovery",
|
||||
"/api/v1/docker",
|
||||
"/api/v1/maintenance",
|
||||
# Demo replaces the whole live topology.
|
||||
"/api/v1/demo",
|
||||
"/api/v1/settings",
|
||||
"/api/v1/backups",
|
||||
)
|
||||
):
|
||||
return "admin"
|
||||
return "operator"
|
||||
|
||||
|
||||
_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
|
||||
|
||||
|
||||
def _host_name(value: str) -> str:
|
||||
value = value.strip().casefold()
|
||||
if value.startswith("["): # IPv6 literal with optional port
|
||||
return value[1:].split("]", 1)[0]
|
||||
return value.rsplit(":", 1)[0] if value.count(":") == 1 else value
|
||||
|
||||
|
||||
def check_request_origin(request: Request) -> None:
|
||||
"""Refuse DNS-rebinding hosts and cross-site mutations.
|
||||
|
||||
* ``SERVICEMAP_ALLOWED_HOSTS`` (comma separated, optional): when set,
|
||||
requests for any other Host are refused. Loopback is always allowed
|
||||
for the container healthcheck.
|
||||
* A mutating request whose ``Origin`` is not this server, or that a
|
||||
browser marks ``Sec-Fetch-Site: cross-site``, is refused. Requests
|
||||
without these headers (curl, integrations) are unaffected.
|
||||
"""
|
||||
|
||||
host_header = request.headers.get("host", "")
|
||||
# Behind a reverse proxy the public name arrives as X-Forwarded-Host.
|
||||
forwarded = request.headers.get("x-forwarded-host", "").split(",")[0].strip()
|
||||
public_host = _host_name(forwarded or host_header)
|
||||
allowed = _csv("SERVICEMAP_ALLOWED_HOSTS")
|
||||
if allowed and public_host not in allowed | _LOOPBACK_HOSTS and _host_name(host_header) not in _LOOPBACK_HOSTS:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Deze host is niet toegestaan")
|
||||
if request.method in SAFE_METHODS:
|
||||
return
|
||||
if request.headers.get("sec-fetch-site", "").casefold() == "cross-site":
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Verzoek van een andere site geweigerd")
|
||||
origin = request.headers.get("origin")
|
||||
if origin is not None:
|
||||
parsed = urlparse(origin)
|
||||
# Hostnames are compared without ports: proxies (nginx ``$host``,
|
||||
# NPM) commonly drop the port from Host while Origin keeps it.
|
||||
if origin == "null" or not parsed.hostname or parsed.hostname.casefold() != public_host:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Verzoek van een andere origin geweigerd")
|
||||
|
||||
|
||||
def authorize_request(request: Request) -> None:
|
||||
"""Authorize API requests; health and static content remain reachable.
|
||||
|
||||
@@ -150,7 +273,8 @@ def authorize_request(request: Request) -> None:
|
||||
available for recovery and deployment diagnostics.
|
||||
"""
|
||||
|
||||
if request.url.path == "/health" or not request.url.path.startswith("/api/"):
|
||||
check_request_origin(request)
|
||||
if request.url.path in {"/health", "/ready"} or not request.url.path.startswith("/api/"):
|
||||
return
|
||||
try:
|
||||
config = AuthConfig.from_environment()
|
||||
@@ -161,9 +285,26 @@ def authorize_request(request: Request) -> None:
|
||||
if config.mode == "disabled":
|
||||
return
|
||||
header = request.headers.get("Authorization", "")
|
||||
if config.mode == "token":
|
||||
if request.method in SAFE_METHODS and not request.url.path.startswith(TOKEN_READ_PREFIXES):
|
||||
return
|
||||
try:
|
||||
expected = admin_token()
|
||||
except (AuthorizationError, OSError) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Het beheerderstoken is niet beschikbaar"
|
||||
) from exc
|
||||
supplied = header.removeprefix("Bearer ").strip() if header.startswith("Bearer ") else ""
|
||||
if not supplied or not hmac.compare_digest(supplied.encode(), expected.encode()):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Bewerken vraagt het ServiceMap-beheerderstoken",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return
|
||||
if not header.startswith("Bearer "):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Bearer authentication is required"
|
||||
status_code=status.HTTP_401_UNAUTHORIZED, detail="Bearer-authenticatie is vereist"
|
||||
)
|
||||
try:
|
||||
roles = verify_bearer(header.removeprefix("Bearer ").strip(), config)
|
||||
@@ -174,5 +315,5 @@ def authorize_request(request: Request) -> None:
|
||||
< _ROLE_ORDER[required_role(request)]
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient ServiceMap role"
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Onvoldoende ServiceMap-rol"
|
||||
)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Verified, rotated SQLite backups and online restore.
|
||||
|
||||
* Backups are written with ``VACUUM INTO`` (a consistent, compacted copy
|
||||
taken inside a read transaction, safe while ServiceMap runs) to
|
||||
``<data dir>/backups`` and checked with ``PRAGMA quick_check`` before
|
||||
they count. A copy that fails the check is deleted, never kept.
|
||||
* Rotation keeps the newest ``keep`` scheduled/manual backups; pre-restore
|
||||
safety copies are rotated the same way.
|
||||
* Restore uses SQLite's online backup API from the chosen file into the
|
||||
live database: it is transactional and needs no file swapping under open
|
||||
WAL connections. A fresh ``pre-restore`` backup is taken first.
|
||||
* Legacy pre-upgrade copies (``servicemap-v*-pre-*.sqlite3`` next to the
|
||||
database) are pruned to the newest ``legacy_keep`` only after a new
|
||||
backup passed its check.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .store import Store
|
||||
|
||||
_NAME = re.compile(r"^servicemap-(?P<kind>backup|pre-restore)-(?P<stamp>\d{8}T\d{6}Z)\.db$")
|
||||
_LEGACY = re.compile(r"^servicemap-v\d+\.\d+\.\d+-pre-[A-Za-z0-9T._-]+\.sqlite3$")
|
||||
|
||||
|
||||
class BackupInfo(BaseModel):
|
||||
name: str
|
||||
kind: str
|
||||
created_at: datetime
|
||||
size_bytes: int
|
||||
|
||||
|
||||
class BackupManager:
|
||||
def __init__(self, store: Store, *, keep: int = 14, legacy_keep: int = 2) -> None:
|
||||
self.store = store
|
||||
self.keep = max(1, keep)
|
||||
self.legacy_keep = max(0, legacy_keep)
|
||||
|
||||
@property
|
||||
def directory(self) -> Path:
|
||||
return self.store.path.parent / "backups"
|
||||
|
||||
def list(self) -> list[BackupInfo]:
|
||||
if not self.directory.exists():
|
||||
return []
|
||||
items: list[BackupInfo] = []
|
||||
for path in self.directory.iterdir():
|
||||
match = _NAME.match(path.name)
|
||||
if not match or not path.is_file():
|
||||
continue
|
||||
created = datetime.strptime(match["stamp"], "%Y%m%dT%H%M%SZ").replace(tzinfo=UTC)
|
||||
items.append(
|
||||
BackupInfo(name=path.name, kind=match["kind"], created_at=created, size_bytes=path.stat().st_size)
|
||||
)
|
||||
return sorted(items, key=lambda item: item.created_at, reverse=True)
|
||||
|
||||
def path_for(self, name: str) -> Path:
|
||||
"""Resolve a listed backup name; anything else is refused."""
|
||||
|
||||
if not _NAME.match(name):
|
||||
raise ValueError("Onbekende back-up")
|
||||
path = self.directory / name
|
||||
if not path.is_file():
|
||||
raise ValueError("Onbekende back-up")
|
||||
return path
|
||||
|
||||
def create(self, kind: str = "backup", now: datetime | None = None) -> BackupInfo:
|
||||
now = now or datetime.now(UTC)
|
||||
self.directory.mkdir(parents=True, exist_ok=True)
|
||||
name = f"servicemap-{kind}-{now.strftime('%Y%m%dT%H%M%SZ')}.db"
|
||||
target = self.directory / name
|
||||
if target.exists():
|
||||
raise ValueError("Er bestaat al een back-up met dit tijdstip")
|
||||
with self.store._connect() as db:
|
||||
db.execute("VACUUM INTO ?", (str(target),))
|
||||
try:
|
||||
os.chmod(target, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
if not self._verify(target):
|
||||
target.unlink(missing_ok=True)
|
||||
raise RuntimeError("De nieuwe back-up faalde de integriteitscontrole en is verwijderd")
|
||||
self._rotate()
|
||||
self._prune_legacy()
|
||||
return next(item for item in self.list() if item.name == name)
|
||||
|
||||
def restore(self, name: str) -> BackupInfo:
|
||||
source = self.path_for(name)
|
||||
if not self._verify(source):
|
||||
raise RuntimeError("De gekozen back-up faalde de integriteitscontrole; er is niets teruggezet")
|
||||
if self.store.demo_active():
|
||||
raise ValueError("Sluit de demo af voor je een back-up terugzet")
|
||||
safety = self.create(kind="pre-restore")
|
||||
# closing(): a sqlite3 connection's own context manager only commits.
|
||||
with closing(sqlite3.connect(source)) as src, closing(sqlite3.connect(self.store.path, timeout=30)) as dst:
|
||||
src.backup(dst)
|
||||
return safety
|
||||
|
||||
@staticmethod
|
||||
def _verify(path: Path) -> bool:
|
||||
try:
|
||||
with closing(sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True)) as db:
|
||||
result = db.execute("PRAGMA quick_check").fetchone()
|
||||
tables = db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='services'").fetchone()
|
||||
except sqlite3.Error:
|
||||
return False
|
||||
return bool(result and result[0] == "ok" and tables)
|
||||
|
||||
def _rotate(self) -> None:
|
||||
for kind in ("backup", "pre-restore"):
|
||||
for stale in [item for item in self.list() if item.kind == kind][self.keep:]:
|
||||
(self.directory / stale.name).unlink(missing_ok=True)
|
||||
|
||||
def _prune_legacy(self) -> list[str]:
|
||||
folder = self.store.path.parent
|
||||
legacy = sorted(
|
||||
(path for path in folder.iterdir() if path.is_file() and _LEGACY.match(path.name)),
|
||||
key=lambda path: path.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
removed: list[str] = []
|
||||
for path in legacy[self.legacy_keep:]:
|
||||
for candidate in (path, Path(f"{path}-wal"), Path(f"{path}-shm"), Path(f"{path}-journal")):
|
||||
if candidate.exists():
|
||||
candidate.unlink()
|
||||
removed.append(path.name)
|
||||
return removed
|
||||
+50
-73
@@ -5,12 +5,44 @@ import json
|
||||
import yaml
|
||||
from pydantic import ValidationError
|
||||
|
||||
from .models import ConfigDocument, ConfigImportResult, ConfigService
|
||||
from .models import ConfigDocument, ConfigImportResult, ConfigService, Service, ServiceCreate
|
||||
from .store import Store
|
||||
|
||||
# Observed runtime state is not configuration: it is re-learned from Docker
|
||||
# and probes and must not be frozen into an exported document.
|
||||
OBSERVED_FIELDS = frozenset(
|
||||
{"runtime_state", "runtime_health", "first_seen_at", "last_seen_at", "last_discovery_status"}
|
||||
)
|
||||
CONFIG_FIELDS = frozenset(ServiceCreate.model_fields) - OBSERVED_FIELDS - {"depends_on"}
|
||||
|
||||
|
||||
def config_service(service: Service, names_by_id: dict[str, str]) -> ConfigService:
|
||||
"""Every operator-owned field of a service, dependencies by name.
|
||||
|
||||
The previous field-by-field copy omitted application/domain/role, their
|
||||
locks, category, visibility, lifecycle, monitoring and probe metadata and
|
||||
layout, so an export/import round trip silently lost them.
|
||||
"""
|
||||
|
||||
return ConfigService(
|
||||
**service.model_dump(include=CONFIG_FIELDS),
|
||||
depends_on=[names_by_id[item] for item in service.depends_on if item in names_by_id],
|
||||
)
|
||||
|
||||
|
||||
def _reject_yaml_aliases(content: str) -> None:
|
||||
"""Refuse YAML anchors/aliases: nested aliases expand exponentially
|
||||
("billion laughs") and a configuration document never needs them."""
|
||||
|
||||
for event in yaml.parse(content, Loader=yaml.SafeLoader):
|
||||
if isinstance(event, yaml.AliasEvent) or getattr(event, "anchor", None):
|
||||
raise ValueError("De configuratie mag geen YAML-anchors of -aliassen gebruiken")
|
||||
|
||||
|
||||
def parse_document(content: str, format_name: str) -> ConfigDocument:
|
||||
try:
|
||||
if format_name != "json":
|
||||
_reject_yaml_aliases(content)
|
||||
raw = json.loads(content) if format_name == "json" else yaml.safe_load(content)
|
||||
except (json.JSONDecodeError, yaml.YAMLError) as exc:
|
||||
raise ValueError(f"Invalid {format_name.upper()} configuration: {exc}") from exc
|
||||
@@ -19,22 +51,22 @@ def parse_document(content: str, format_name: str) -> ConfigDocument:
|
||||
try:
|
||||
document = ConfigDocument.model_validate(raw)
|
||||
except ValidationError as exc:
|
||||
raise ValueError(f"Configuration schema validation failed: {exc}") from exc
|
||||
raise ValueError(f"De configuratie voldoet niet aan het schema: {exc}") from exc
|
||||
if document.version == 2 and not document.services:
|
||||
# Preserve the v1 contract's explicit unsupported-empty-v2 guard while
|
||||
# accepting real v2 documents that carry the richer service schema.
|
||||
raise ValueError("Configuration version must be less than or equal to 1 for an empty document")
|
||||
raise ValueError("Voor een leeg document moet de configuratieversie 1 of lager zijn")
|
||||
|
||||
names = [service.name.casefold() for service in document.services]
|
||||
if len(names) != len(set(names)):
|
||||
raise ValueError("Service names must be unique in the configuration")
|
||||
raise ValueError("Servicenamen moeten uniek zijn in de configuratie")
|
||||
|
||||
for service in document.services:
|
||||
dependencies = [dependency.casefold() for dependency in service.depends_on]
|
||||
if len(dependencies) != len(set(dependencies)):
|
||||
raise ValueError(f"Service {service.name} has duplicate dependencies")
|
||||
raise ValueError(f"Service {service.name} heeft dubbele afhankelijkheden")
|
||||
if service.name.casefold() in dependencies:
|
||||
raise ValueError(f"Service {service.name} cannot depend on itself")
|
||||
raise ValueError(f"Service {service.name} kan niet van zichzelf afhangen")
|
||||
|
||||
# A merge document may reference services that already exist in the store,
|
||||
# so missing-reference validation belongs to import_document(). Cycles that
|
||||
@@ -53,7 +85,7 @@ def _validate_acyclic(services: list[ConfigService]) -> None:
|
||||
|
||||
def visit(node: str) -> None:
|
||||
if node in visiting:
|
||||
raise ValueError("Dependency graph contains a cycle")
|
||||
raise ValueError("De afhankelijkheidsgrafiek bevat een kring")
|
||||
if node in visited:
|
||||
return
|
||||
visiting.add(node)
|
||||
@@ -68,44 +100,22 @@ def _validate_acyclic(services: list[ConfigService]) -> None:
|
||||
|
||||
def _validate_import_graph(store: Store, document: ConfigDocument, mode: str) -> None:
|
||||
if mode not in {"merge", "replace"}:
|
||||
raise ValueError("Import mode must be merge or replace")
|
||||
raise ValueError("Importmodus moet merge of replace zijn")
|
||||
|
||||
projected: dict[str, ConfigService] = {}
|
||||
if mode == "merge":
|
||||
existing = store.list_services()
|
||||
names_by_id = {service.id: service.name for service in existing}
|
||||
for service in existing:
|
||||
projected[service.name.casefold()] = ConfigService(
|
||||
name=service.name,
|
||||
kind=service.kind,
|
||||
url=service.url,
|
||||
host=service.host,
|
||||
port=service.port,
|
||||
depends_on=[names_by_id[item] for item in service.depends_on if item in names_by_id],
|
||||
description=service.description,
|
||||
tags=service.tags,
|
||||
group=service.group,
|
||||
environment=service.environment,
|
||||
owner=service.owner,
|
||||
enabled=service.enabled,
|
||||
monitoring_enabled=service.monitoring_enabled,
|
||||
criticality=service.criticality,
|
||||
source_type=service.source_type,
|
||||
source_ref=service.source_ref,
|
||||
interval_seconds=service.interval_seconds,
|
||||
timeout_seconds=service.timeout_seconds,
|
||||
retries=service.retries,
|
||||
failure_threshold=service.failure_threshold,
|
||||
recovery_threshold=service.recovery_threshold,
|
||||
expected_status_min=service.expected_status_min,
|
||||
expected_status_max=service.expected_status_max,
|
||||
availability_target=service.availability_target,
|
||||
maintenance_enabled=service.maintenance_enabled,
|
||||
maintenance_reason=service.maintenance_reason,
|
||||
)
|
||||
projected[service.name.casefold()] = config_service(service, names_by_id)
|
||||
|
||||
for service in document.services:
|
||||
projected[service.name.casefold()] = service
|
||||
key = service.name.casefold()
|
||||
previous = projected.get(key)
|
||||
if previous is not None and "depends_on" not in service.model_fields_set:
|
||||
# A merge keeps dependencies the document does not mention.
|
||||
service = service.model_copy(update={"depends_on": previous.depends_on})
|
||||
projected[key] = service
|
||||
|
||||
available = set(projected)
|
||||
for service in projected.values():
|
||||
@@ -116,7 +126,7 @@ def _validate_import_graph(store: Store, document: ConfigDocument, mode: str) ->
|
||||
]
|
||||
if missing:
|
||||
raise ValueError(
|
||||
f"Service {service.name} references unknown dependencies: {', '.join(missing)}"
|
||||
f"Service {service.name} verwijst naar onbekende afhankelijkheden: {', '.join(missing)}"
|
||||
)
|
||||
|
||||
_validate_acyclic(list(projected.values()))
|
||||
@@ -125,44 +135,11 @@ def _validate_import_graph(store: Store, document: ConfigDocument, mode: str) ->
|
||||
def export_document(store: Store) -> ConfigDocument:
|
||||
services = store.list_services()
|
||||
names = {service.id: service.name for service in services}
|
||||
return ConfigDocument(
|
||||
version=2,
|
||||
services=[
|
||||
ConfigService(
|
||||
name=service.name,
|
||||
kind=service.kind,
|
||||
url=service.url,
|
||||
host=service.host,
|
||||
port=service.port,
|
||||
depends_on=[names[item] for item in service.depends_on if item in names],
|
||||
description=service.description,
|
||||
tags=service.tags,
|
||||
group=service.group,
|
||||
environment=service.environment,
|
||||
owner=service.owner,
|
||||
enabled=service.enabled,
|
||||
monitoring_enabled=service.monitoring_enabled,
|
||||
criticality=service.criticality,
|
||||
source_type=service.source_type,
|
||||
source_ref=service.source_ref,
|
||||
interval_seconds=service.interval_seconds,
|
||||
timeout_seconds=service.timeout_seconds,
|
||||
retries=service.retries,
|
||||
failure_threshold=service.failure_threshold,
|
||||
recovery_threshold=service.recovery_threshold,
|
||||
expected_status_min=service.expected_status_min,
|
||||
expected_status_max=service.expected_status_max,
|
||||
availability_target=service.availability_target,
|
||||
maintenance_enabled=service.maintenance_enabled,
|
||||
maintenance_reason=service.maintenance_reason,
|
||||
)
|
||||
for service in services
|
||||
],
|
||||
)
|
||||
return ConfigDocument(version=2, services=[config_service(service, names) for service in services])
|
||||
|
||||
|
||||
def serialize_document(document: ConfigDocument, format_name: str) -> str:
|
||||
payload = document.model_dump(mode="json")
|
||||
payload = document.model_dump(mode="json", exclude={"services": {"__all__": set(OBSERVED_FIELDS)}})
|
||||
if format_name == "json":
|
||||
return json.dumps(payload, indent=2, sort_keys=False)
|
||||
return yaml.safe_dump(payload, sort_keys=False, allow_unicode=True)
|
||||
|
||||
+13
-13
@@ -39,15 +39,15 @@ def build_demo_records(now: datetime | None = None) -> tuple[list[Service], list
|
||||
]
|
||||
ids_by_name = {name: _stable_id(f"service:{name}") for name, *_ in definitions}
|
||||
metadata = {
|
||||
"Public Endpoint": ("Edge", "Public Gateway", "Edge", ComponentRole.FRONTEND, DiscoveryCategory.PROXY, Criticality.CRITICAL, "Customer-facing availability check", 100.0),
|
||||
"Reverse Proxy": ("Edge", "Public Gateway", "Edge", ComponentRole.PROXY, DiscoveryCategory.PROXY, Criticality.HIGH, "Northstar ingress gateway", 100.0),
|
||||
"Web Frontend": ("Application", "Northstar App", "Application", ComponentRole.FRONTEND, DiscoveryCategory.APPLICATION, Criticality.HIGH, "Browser application", 99.0),
|
||||
"Auth Service": ("Application", "Northstar App", "Application", ComponentRole.API, DiscoveryCategory.APPLICATION, Criticality.HIGH, "Identity and session service", 100.0),
|
||||
"API Gateway": ("Application", "Northstar App", "Application", ComponentRole.API, DiscoveryCategory.APPLICATION, Criticality.CRITICAL, "Application API entry point", 99.0),
|
||||
"PostgreSQL": ("Data", "Data Platform", "Data", ComponentRole.DATABASE, DiscoveryCategory.DATABASE, Criticality.CRITICAL, "Primary relational datastore", 99.9),
|
||||
"Redis": ("Data", "Data Platform", "Data", ComponentRole.CACHE, DiscoveryCategory.CACHE, Criticality.HIGH, "Cache and queue backend", 100.0),
|
||||
"Background Worker": ("Application", "Worker Platform", "Application", ComponentRole.WORKER, DiscoveryCategory.BACKGROUND_WORKER, Criticality.HIGH, "Asynchronous job processor", 99.0),
|
||||
"Object Storage": ("Data", "Worker Platform", "Application", ComponentRole.STORAGE, DiscoveryCategory.STORAGE, Criticality.MEDIUM, "Durable object store", 100.0),
|
||||
"Public Endpoint": ("Edge", "Public Gateway", "Edge", ComponentRole.FRONTEND, DiscoveryCategory.PROXY, Criticality.CRITICAL, "Beschikbaarheidscontrole voor klanten", 100.0),
|
||||
"Reverse Proxy": ("Edge", "Public Gateway", "Edge", ComponentRole.PROXY, DiscoveryCategory.PROXY, Criticality.HIGH, "Northstar-ingangsgateway", 100.0),
|
||||
"Web Frontend": ("Application", "Northstar App", "Application", ComponentRole.FRONTEND, DiscoveryCategory.APPLICATION, Criticality.HIGH, "Browserapplicatie", 99.0),
|
||||
"Auth Service": ("Application", "Northstar App", "Application", ComponentRole.API, DiscoveryCategory.APPLICATION, Criticality.HIGH, "Identiteits- en sessieservice", 100.0),
|
||||
"API Gateway": ("Application", "Northstar App", "Application", ComponentRole.API, DiscoveryCategory.APPLICATION, Criticality.CRITICAL, "API-toegangspunt van de applicatie", 99.0),
|
||||
"PostgreSQL": ("Data", "Data Platform", "Data", ComponentRole.DATABASE, DiscoveryCategory.DATABASE, Criticality.CRITICAL, "Primaire relationele database", 99.9),
|
||||
"Redis": ("Data", "Data Platform", "Data", ComponentRole.CACHE, DiscoveryCategory.CACHE, Criticality.HIGH, "Cache- en wachtrijbackend", 100.0),
|
||||
"Background Worker": ("Application", "Worker Platform", "Application", ComponentRole.WORKER, DiscoveryCategory.BACKGROUND_WORKER, Criticality.HIGH, "Verwerker van asynchrone taken", 99.0),
|
||||
"Object Storage": ("Data", "Worker Platform", "Application", ComponentRole.STORAGE, DiscoveryCategory.STORAGE, Criticality.MEDIUM, "Duurzame objectopslag", 100.0),
|
||||
}
|
||||
services = [
|
||||
Service(
|
||||
@@ -113,9 +113,9 @@ def _history_status(name: str, index: int) -> HealthStatus:
|
||||
|
||||
def _probe_detail(name: str, status: HealthStatus, index: int) -> str:
|
||||
if name == DEMO_ROOT_CAUSE_NAME and status == HealthStatus.DOWN:
|
||||
return "Synthetic outage: PostgreSQL connection refused"
|
||||
return "Synthetische storing: PostgreSQL weigert de verbinding"
|
||||
if status == HealthStatus.DOWN:
|
||||
return f"Synthetic dependency impact observed at history point {index + 1}"
|
||||
return f"Synthetische impact via afhankelijkheid op historiekpunt {index + 1}"
|
||||
if status == HealthStatus.DEGRADED:
|
||||
return f"Synthetic elevated latency observed at history point {index + 1}"
|
||||
return "Synthetic monitoring observation"
|
||||
return f"Synthetisch verhoogde latentie op historiekpunt {index + 1}"
|
||||
return "Synthetische bewakingswaarneming"
|
||||
+32
-32
@@ -185,7 +185,7 @@ class DiscoveryManager:
|
||||
source_service_id=service_by_ref.get(source.stable_source_ref).id if source.stable_source_ref in service_by_ref else None,
|
||||
target_ref=target.stable_source_ref,
|
||||
target_service_id=service_by_ref.get(target.stable_source_ref).id if target.stable_source_ref in service_by_ref else None,
|
||||
proposed_name=f"{source.name} depends on {target.name}",
|
||||
proposed_name=f"{source.name} hangt af van {target.name}",
|
||||
relation_type=relation_type,
|
||||
confidence=confidence,
|
||||
evidence=[evidence],
|
||||
@@ -222,10 +222,10 @@ class DiscoveryManager:
|
||||
suggestion_type="relation",
|
||||
source_ref=source.stable_source_ref,
|
||||
source_service_id=service_by_ref.get(source.stable_source_ref).id if source.stable_source_ref in service_by_ref else None,
|
||||
proposed_name=f"{source.name} has an ambiguous reference to {reference}",
|
||||
proposed_name=f"{source.name} verwijst dubbelzinnig naar {reference}",
|
||||
relation_type=RelationType.DEPENDS_ON,
|
||||
confidence=DiscoveryConfidence.LOW,
|
||||
evidence=[f"{evidence}; candidates: {candidates_label}", "Manual review required; no canonical dependency was created"],
|
||||
evidence=[f"{evidence}; kandidaten: {candidates_label}", "Handmatige controle nodig; er is geen canonieke afhankelijkheid aangemaakt"],
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
),
|
||||
@@ -240,14 +240,14 @@ class DiscoveryManager:
|
||||
explicit = [item.strip() for item in labels.get("servicemap.depends_on", "").split(",") if item.strip()]
|
||||
compose = [item.split(":", 1)[0].strip() for item in labels.get("com.docker.compose.depends_on", "").split(",") if item.strip()]
|
||||
for name in sorted(set(explicit)):
|
||||
resolve_and_add(source, name, DiscoveryConfidence.CONFIRMED, "Explicit servicemap.depends_on label")
|
||||
resolve_and_add(source, name, DiscoveryConfidence.CONFIRMED, "Expliciet servicemap.depends_on-label")
|
||||
for name in sorted(set(compose)):
|
||||
resolve_and_add(source, name, DiscoveryConfidence.HIGH, "Docker Compose com.docker.compose.depends_on label", compose_only=True)
|
||||
resolve_and_add(source, name, DiscoveryConfidence.HIGH, "Docker Compose-label com.docker.compose.depends_on", compose_only=True)
|
||||
for item in source.environment_evidence:
|
||||
if "hostname=" not in item:
|
||||
continue
|
||||
hostname = item.split("hostname=", 1)[1].split(":", 1)[0].casefold()
|
||||
resolve_and_add(source, hostname, DiscoveryConfidence.MEDIUM, f"Environment endpoint reference: {item}")
|
||||
resolve_and_add(source, hostname, DiscoveryConfidence.MEDIUM, f"Endpointverwijzing in omgevingsvariabele: {item}")
|
||||
for item in source.proxy_route_evidence:
|
||||
proxies = [proxy for proxy in candidates if proxy.category == DiscoveryCategory.PROXY and set(proxy.networks).intersection(source.networks)]
|
||||
if len(proxies) == 1:
|
||||
@@ -255,12 +255,12 @@ class DiscoveryManager:
|
||||
# Shared networks are review-only hints. Cap them to avoid flooding
|
||||
# a large host with O(n²) low-confidence suggestions.
|
||||
for name in source.dependency_suggestions[:8]:
|
||||
resolve_and_add(source, name, DiscoveryConfidence.LOW, f"Shared Docker network hint: {', '.join(source.networks)}")
|
||||
resolve_and_add(source, name, DiscoveryConfidence.LOW, f"Hint via gedeeld Docker-netwerk: {', '.join(source.networks)}")
|
||||
return result
|
||||
|
||||
def run(self, request: DiscoveryRunRequest) -> DiscoveryResult:
|
||||
if not self._lock.acquire(blocking=False):
|
||||
raise ValueError("A discovery run is already in progress")
|
||||
raise ValueError("Er loopt al een detectierun")
|
||||
run = self.discovery_store.start_run()
|
||||
try:
|
||||
docker_host = self._docker_host(request.docker_host)
|
||||
@@ -278,7 +278,7 @@ class DiscoveryManager:
|
||||
status=ProviderHealth.HEALTHY,
|
||||
observed_at=observed_at,
|
||||
valid_until=observed_at + evidence_ttl,
|
||||
detail=f"Docker inventory returned {len(result.candidates)} candidates",
|
||||
detail=f"Docker-inventaris gaf {len(result.candidates)} kandidaten",
|
||||
metadata={"docker_host": docker_host},
|
||||
)
|
||||
)
|
||||
@@ -473,7 +473,7 @@ class DiscoveryManager:
|
||||
url=url,
|
||||
host=host,
|
||||
port=port,
|
||||
description=f"Discovered Docker service from {candidate.image}",
|
||||
description=f"Gevonden Docker-service op basis van {candidate.image}",
|
||||
tags=["discovered", "docker"],
|
||||
group=group,
|
||||
environment="production",
|
||||
@@ -559,7 +559,7 @@ class DiscoveryManager:
|
||||
observed_at=now,
|
||||
valid_until=now + evidence_ttl,
|
||||
received_at=now,
|
||||
summary="Docker healthcheck" if candidate.healthcheck_present else "Docker runtime state",
|
||||
summary="Docker-healthcheck" if candidate.healthcheck_present else "Docker-runtimestatus",
|
||||
metadata={"container_id": candidate.container_id, "state": candidate.state, "health": candidate.health},
|
||||
)
|
||||
)
|
||||
@@ -579,7 +579,7 @@ class DiscoveryManager:
|
||||
observed_at=now,
|
||||
valid_until=now + evidence_ttl,
|
||||
received_at=now,
|
||||
summary="AppOps application health; not used as component direct health",
|
||||
summary="Applicatiegezondheid via AppOps; niet gebruikt als directe componentgezondheid",
|
||||
metadata={
|
||||
"app_id": candidate.appops_app_id,
|
||||
"category": candidate.appops_category,
|
||||
@@ -597,7 +597,7 @@ class DiscoveryManager:
|
||||
def reconcile(self, request: DiscoveryReconcileRequest) -> ReconcileResult:
|
||||
run = self.discovery_store.get_run(request.run_id) if request.run_id else self.discovery_store.last_completed()
|
||||
if run is None or run.status != DiscoveryRunStatus.COMPLETED:
|
||||
raise ValueError("A completed discovery run is required before reconciliation")
|
||||
raise ValueError("Voor verwerking is een afgeronde detectierun nodig")
|
||||
self.discovery_store.set_run_status(run.id, DiscoveryRunStatus.RECONCILING)
|
||||
candidates = [DockerCandidate.model_validate(item.get("candidate", item)) for item in self.discovery_store.candidates_for_run(run.id)]
|
||||
by_ref = self._service_by_ref()
|
||||
@@ -727,7 +727,7 @@ class DiscoveryManager:
|
||||
payload.depends_on = [*source.depends_on, target.id]
|
||||
self.store.update_service(source.id, payload)
|
||||
self.discovery_store.set_suggestion_status(suggestion.id, SuggestionStatus.ACCEPTED)
|
||||
self.discovery_store.record_change("dependency_added", f"{source.name} depends on {target.name}", source_service_id=source.id, target_service_id=target.id)
|
||||
self.discovery_store.record_change("dependency_added", f"{source.name} hangt af van {target.name}", source_service_id=source.id, target_service_id=target.id)
|
||||
accepted_relations += 1
|
||||
|
||||
final_run = self.discovery_store.finish_run(
|
||||
@@ -767,7 +767,7 @@ class DiscoveryManager:
|
||||
|
||||
run = self.discovery_store.get_run(run_id) if run_id else self.discovery_store.last_completed()
|
||||
if run is None or run.status != DiscoveryRunStatus.COMPLETED:
|
||||
raise ValueError("A completed discovery run is required before repairing probe reachability")
|
||||
raise ValueError("Voor het herstellen van controlebereikbaarheid is een afgeronde detectierun nodig")
|
||||
candidates = [DockerCandidate.model_validate(item.get("candidate", item)) for item in self.discovery_store.candidates_for_run(run.id)]
|
||||
services = self._service_by_ref()
|
||||
changes: list[ProbeRepairChange] = []
|
||||
@@ -799,19 +799,19 @@ class DiscoveryManager:
|
||||
)
|
||||
continue
|
||||
if current.monitoring_enabled and not desired.monitoring_enabled:
|
||||
reason = "Internal container endpoint is not reachable from ServiceMap; active probe disabled"
|
||||
reason = "Intern container-endpoint is niet bereikbaar vanuit ServiceMap; actieve controle uitgeschakeld"
|
||||
disabled_unsafe += 1
|
||||
elif desired.monitoring_enabled:
|
||||
reason = "Host-published endpoint selected using the configured probe host"
|
||||
reason = "Gepubliceerd host-endpoint gekozen via de ingestelde controlehost"
|
||||
enabled_published += 1
|
||||
elif candidate.healthcheck_present:
|
||||
reason = "Docker healthcheck retained as runtime observation without a network probe"
|
||||
reason = "Docker-healthcheck behouden als runtimewaarneming zonder netwerkcontrole"
|
||||
docker_health_observed += 1
|
||||
elif desired.monitoring_state == MonitoringState.OBSERVED:
|
||||
reason = "No verified reachable endpoint; Docker runtime observation is retained without a network probe"
|
||||
reason = "Geen gecontroleerd bereikbaar endpoint; Docker-runtimewaarneming blijft behouden zonder netwerkcontrole"
|
||||
runtime_observed += 1
|
||||
else:
|
||||
reason = "No verified reachable endpoint; service remains observed as unmonitored"
|
||||
reason = "Geen gecontroleerd bereikbaar endpoint; service blijft waargenomen als niet bewaakt"
|
||||
unmonitored += 1
|
||||
changes.append(
|
||||
ProbeRepairChange(
|
||||
@@ -842,7 +842,7 @@ class DiscoveryManager:
|
||||
from .incidents import sync_incidents
|
||||
|
||||
before = len([item for item in self.store.list_incidents(active_only=True)])
|
||||
sync_incidents(self.store, resolution_reason="Monitoring endpoint superseded; active probe was replaced by reachability-safe observation")
|
||||
sync_incidents(self.store, resolution_reason="Bewakings-endpoint vervangen; de actieve controle is vervangen door een veilige waarneming")
|
||||
after = len([item for item in self.store.list_incidents(active_only=True)])
|
||||
resolved = max(0, before - after)
|
||||
return ProbeRepairReport(
|
||||
@@ -864,7 +864,7 @@ class DiscoveryManager:
|
||||
source = self.store.get_service(request.source_service_id)
|
||||
target = self.store.get_service(request.target_service_id)
|
||||
if source is None or target is None:
|
||||
raise ValueError("Both edge services must exist")
|
||||
raise ValueError("Beide services van de relatie moeten bestaan")
|
||||
if request.relation_type == RelationType.DEPENDS_ON and target.id not in source.depends_on:
|
||||
validate_dependencies([*source.depends_on, target.id], self.store, service_id=source.id)
|
||||
payload = ServiceUpdate.model_validate(source.model_dump())
|
||||
@@ -892,7 +892,7 @@ class DiscoveryManager:
|
||||
def suggestion_action(self, suggestion_id: str, action: str) -> TopologySuggestion:
|
||||
suggestion = self.discovery_store.get_suggestion(suggestion_id)
|
||||
if suggestion is None:
|
||||
raise ValueError("Suggestion not found")
|
||||
raise ValueError("Voorstel niet gevonden")
|
||||
if action == "reject":
|
||||
if suggestion.suggestion_type == "relation" and suggestion.relation_type == RelationType.DEPENDS_ON:
|
||||
source = self._service_by_ref().get(suggestion.source_ref or "")
|
||||
@@ -908,7 +908,7 @@ class DiscoveryManager:
|
||||
if action in {"confirm", "lock"}:
|
||||
if suggestion.suggestion_type == "service":
|
||||
if not suggestion.source_ref:
|
||||
raise ValueError("Service suggestion has no stable source reference")
|
||||
raise ValueError("Het servicevoorstel heeft geen stabiele bronverwijzing")
|
||||
existing = self._service_by_ref().get(suggestion.source_ref)
|
||||
if existing is None:
|
||||
candidate = next(
|
||||
@@ -920,18 +920,18 @@ class DiscoveryManager:
|
||||
None,
|
||||
)
|
||||
if candidate is None:
|
||||
raise ValueError("Discovery observation for service suggestion is no longer available")
|
||||
raise ValueError("De detectiewaarneming voor dit servicevoorstel is niet meer beschikbaar")
|
||||
existing = self.store.create_service(self._payload_for_candidate(candidate))
|
||||
source = self.discovery_store.get_source("docker", suggestion.source_ref)
|
||||
if source:
|
||||
self.discovery_store.attach_source(existing.id, source.id)
|
||||
self.discovery_store.record_change("accepted", f"Accepted discovered service {existing.name}", service_id=existing.id)
|
||||
self.discovery_store.record_change("accepted", f"Gevonden service {existing.name} aanvaard", service_id=existing.id)
|
||||
self.discovery_store.save_override("service", existing.id, "source", suggestion.source_ref, True)
|
||||
elif suggestion.suggestion_type == "relation":
|
||||
source = self._service_by_ref().get(suggestion.source_ref or "")
|
||||
target = self._service_by_ref().get(suggestion.target_ref or "")
|
||||
if source is None or target is None:
|
||||
raise ValueError("Accept the related services before accepting this relationship")
|
||||
raise ValueError("Aanvaard eerst de betrokken services voor je deze relatie aanvaardt")
|
||||
if suggestion.relation_type == RelationType.DEPENDS_ON and target.id not in source.depends_on:
|
||||
validate_dependencies([*source.depends_on, target.id], self.store, service_id=source.id)
|
||||
payload = ServiceUpdate.model_validate(source.model_dump())
|
||||
@@ -954,9 +954,9 @@ class DiscoveryManager:
|
||||
last_seen_at=now,
|
||||
)
|
||||
)
|
||||
self.discovery_store.record_change("dependency_added", f"Accepted relationship {source.name} → {target.name}", source_service_id=source.id, target_service_id=target.id)
|
||||
self.discovery_store.record_change("dependency_added", f"Relatie {source.name} → {target.name} aanvaard", source_service_id=source.id, target_service_id=target.id)
|
||||
return self.discovery_store.set_suggestion_status(suggestion_id, SuggestionStatus.ACCEPTED) or suggestion
|
||||
raise ValueError("Unsupported suggestion action")
|
||||
raise ValueError("Niet-ondersteunde actie op voorstel")
|
||||
|
||||
def record_service_override(self, before: Service, after: Service) -> None:
|
||||
for field in ("name", "group", "category", "criticality", "environment", "visibility"):
|
||||
@@ -975,16 +975,16 @@ class DiscoveryManager:
|
||||
def edge_action(self, evidence_id: str, action: str) -> RelationEvidence:
|
||||
evidence = self.discovery_store.get_evidence(evidence_id)
|
||||
if evidence is None or evidence.target_service_id is None:
|
||||
raise ValueError("Edge evidence not found")
|
||||
raise ValueError("Bewijs voor de relatie niet gevonden")
|
||||
source = self.store.get_service(evidence.source_service_id)
|
||||
if source is None:
|
||||
raise ValueError("Edge source service not found")
|
||||
raise ValueError("Bronservice van de relatie niet gevonden")
|
||||
target_id = evidence.target_service_id
|
||||
if action in {"remove", "reject"} and evidence.relation_type == RelationType.DEPENDS_ON:
|
||||
payload = ServiceUpdate.model_validate(source.model_dump())
|
||||
payload.depends_on = [item for item in source.depends_on if item != target_id]
|
||||
self.store.update_service(source.id, payload)
|
||||
self.discovery_store.record_change("dependency_removed", f"Removed relationship from {source.name}", source_service_id=source.id, target_service_id=target_id)
|
||||
self.discovery_store.record_change("dependency_removed", f"Relatie van {source.name} verwijderd", source_service_id=source.id, target_service_id=target_id)
|
||||
return self.discovery_store.set_evidence_state(evidence_id, active=False) or evidence
|
||||
if action == "confirm" and evidence.relation_type == RelationType.DEPENDS_ON and target_id not in source.depends_on:
|
||||
validate_dependencies([*source.depends_on, target_id], self.store, service_id=source.id)
|
||||
|
||||
@@ -2,7 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from hashlib import sha256
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
@@ -354,7 +354,7 @@ class DiscoveryStore:
|
||||
(
|
||||
DiscoveryRunStatus.FAILED.value,
|
||||
run.started_at.isoformat(),
|
||||
"Superseded by a newer discovery run",
|
||||
"Vervangen door een nieuwere detectierun",
|
||||
DiscoveryRunStatus.DISCOVERING.value,
|
||||
DiscoveryRunStatus.RECONCILING.value,
|
||||
),
|
||||
@@ -502,7 +502,7 @@ class DiscoveryStore:
|
||||
"INSERT INTO topology_snapshot_relations VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
[(snapshot.id, relation_id, source_id, target_id, relation_type, fingerprint, _json(payload)) for relation_id, source_id, target_id, relation_type, fingerprint, payload in relation_rows],
|
||||
)
|
||||
self.record_change("topology_snapshot", f"Topology snapshot captured ({snapshot.service_count} services)")
|
||||
self.record_change("topology_snapshot", f"Topologiesnapshot gemaakt ({snapshot.service_count} services)")
|
||||
return snapshot
|
||||
|
||||
def list_snapshots(self, *, limit: int = 50) -> list[TopologySnapshot]:
|
||||
@@ -514,7 +514,7 @@ class DiscoveryStore:
|
||||
with self._connect() as db:
|
||||
after = db.execute("SELECT * FROM topology_snapshots WHERE id=?", (after_snapshot_id,)).fetchone()
|
||||
if after is None:
|
||||
raise ValueError("Topology snapshot not found")
|
||||
raise ValueError("Topologiesnapshot niet gevonden")
|
||||
before = (
|
||||
db.execute("SELECT * FROM topology_snapshots WHERE id=?", (before_snapshot_id,)).fetchone()
|
||||
if before_snapshot_id
|
||||
@@ -758,6 +758,7 @@ class DiscoveryStore:
|
||||
if existing:
|
||||
previous = self._evidence(existing)
|
||||
evidence = evidence.model_copy(update={
|
||||
"id": previous.id,
|
||||
"confidence": _higher_confidence(previous.confidence, evidence.confidence),
|
||||
"explanation": "; ".join(dict.fromkeys(part for part in (previous.explanation, evidence.explanation) if part)),
|
||||
"source_ref": evidence.source_ref or previous.source_ref,
|
||||
@@ -765,6 +766,19 @@ class DiscoveryStore:
|
||||
"active": evidence.active,
|
||||
"first_seen_at": min(previous.first_seen_at, evidence.first_seen_at),
|
||||
})
|
||||
# Update the found row by id. The UNIQUE constraint includes
|
||||
# nullable columns (target_ref is NULL for manual edges), so
|
||||
# ON CONFLICT never matched and each save inserted a duplicate.
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE relation_evidence SET target_service_id=?, confidence=?, explanation=?,
|
||||
source_ref=?, locked=MAX(locked, ?), active=?, last_seen_at=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(evidence.target_service_id, evidence.confidence.value, evidence.explanation, evidence.source_ref, int(evidence.locked), int(evidence.active), evidence.last_seen_at.isoformat(), evidence.id),
|
||||
)
|
||||
row = db.execute("SELECT * FROM relation_evidence WHERE id=?", (evidence.id,)).fetchone()
|
||||
return self._evidence(row)
|
||||
db.execute(
|
||||
"""
|
||||
INSERT INTO relation_evidence
|
||||
@@ -884,6 +898,53 @@ class DiscoveryStore:
|
||||
def evidence_for_service(self, service_id: str) -> list[RelationEvidence]:
|
||||
return self.list_evidence(service_id, active_only=True)
|
||||
|
||||
def evidence_for_services(self, service_ids: list[str]) -> dict[str, list[RelationEvidence]]:
|
||||
"""Active relation evidence for many services in one read (no N+1)."""
|
||||
|
||||
ids = sorted(set(service_ids))
|
||||
result: dict[str, list[RelationEvidence]] = {service_id: [] for service_id in ids}
|
||||
if not ids:
|
||||
return result
|
||||
placeholders = ", ".join("?" for _ in ids)
|
||||
with self._connect() as db:
|
||||
rows = db.execute(
|
||||
f"""
|
||||
SELECT * FROM relation_evidence
|
||||
WHERE active=1
|
||||
AND (source_service_id IN ({placeholders}) OR target_service_id IN ({placeholders}))
|
||||
ORDER BY last_seen_at DESC
|
||||
""",
|
||||
[*ids, *ids],
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
evidence = self._evidence(row)
|
||||
for service_id in {row["source_service_id"], row["target_service_id"]}:
|
||||
if service_id in result:
|
||||
result[service_id].append(evidence)
|
||||
return result
|
||||
|
||||
def sources_for_services(self, service_ids: list[str]) -> dict[str, list[ServiceSource]]:
|
||||
"""Discovery sources for many services in one read (no N+1)."""
|
||||
|
||||
ids = sorted(set(service_ids))
|
||||
result: dict[str, list[ServiceSource]] = {service_id: [] for service_id in ids}
|
||||
if not ids:
|
||||
return result
|
||||
placeholders = ", ".join("?" for _ in ids)
|
||||
with self._connect() as db:
|
||||
rows = db.execute(
|
||||
f"""
|
||||
SELECT s.*, ss.service_id AS linked_service_id
|
||||
FROM discovery_sources s JOIN service_sources ss ON ss.source_id=s.id
|
||||
WHERE ss.service_id IN ({placeholders})
|
||||
ORDER BY s.source_type, s.source_name
|
||||
""",
|
||||
ids,
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
result[row["linked_service_id"]].append(self._source(row))
|
||||
return result
|
||||
|
||||
def sources_for_service(self, service_id: str) -> list[ServiceSource]:
|
||||
with self._connect() as db:
|
||||
rows = db.execute(
|
||||
@@ -925,6 +986,34 @@ class DiscoveryStore:
|
||||
with self._connect() as db:
|
||||
db.execute("UPDATE discovery_runs SET status=? WHERE id=?", (status.value, run_id))
|
||||
|
||||
def prune_observations(self, keep_runs: int = 10) -> int:
|
||||
"""Keep per-container observations only for the most recent runs.
|
||||
|
||||
Each run stores a full candidate dump per container. Runs themselves
|
||||
are kept because review decisions (suggestions) reference them.
|
||||
"""
|
||||
|
||||
if keep_runs < 1:
|
||||
return 0
|
||||
with self._connect() as db:
|
||||
cursor = db.execute(
|
||||
"""
|
||||
DELETE FROM discovery_observations WHERE run_id NOT IN (
|
||||
SELECT id FROM discovery_runs ORDER BY started_at DESC LIMIT ?
|
||||
)
|
||||
""",
|
||||
(keep_runs,),
|
||||
)
|
||||
return cursor.rowcount
|
||||
|
||||
def prune_change_events(self, retention_days: int) -> int:
|
||||
if retention_days <= 0:
|
||||
return 0
|
||||
cutoff = (_now() - timedelta(days=retention_days)).isoformat()
|
||||
with self._connect() as db:
|
||||
cursor = db.execute("DELETE FROM topology_change_events WHERE created_at < ?", (cutoff,))
|
||||
return cursor.rowcount
|
||||
|
||||
def record_change(
|
||||
self,
|
||||
event_type: str,
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import urlparse
|
||||
|
||||
@@ -233,7 +234,7 @@ def _preflight_candidate(candidate: ProbeEndpointCandidate) -> ProbeEndpointCand
|
||||
hostname = parsed.hostname if parsed else candidate.host
|
||||
port = parsed.port if parsed else candidate.port
|
||||
if not hostname or not port:
|
||||
return candidate.model_copy(update={"preflight_detail": "No host-published endpoint to preflight"})
|
||||
return candidate.model_copy(update={"preflight_detail": "Geen gepubliceerd host-endpoint om vooraf te testen"})
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
with socket.create_connection((hostname, port), timeout=0.75):
|
||||
@@ -243,7 +244,7 @@ def _preflight_candidate(candidate: ProbeEndpointCandidate) -> ProbeEndpointCand
|
||||
return candidate.model_copy(update={
|
||||
"reachability": ProbeReachability.VERIFIED,
|
||||
"primary": True,
|
||||
"preflight_detail": "TCP connect succeeded",
|
||||
"preflight_detail": "TCP-verbinding gelukt",
|
||||
"preflight_latency_ms": elapsed,
|
||||
})
|
||||
with httpx.Client(timeout=1.25, follow_redirects=False) as client:
|
||||
@@ -260,7 +261,7 @@ def _preflight_candidate(candidate: ProbeEndpointCandidate) -> ProbeEndpointCand
|
||||
return candidate.model_copy(update={
|
||||
"reachability": ProbeReachability.UNVERIFIED,
|
||||
"primary": False,
|
||||
"preflight_detail": f"Preflight failed: {type(exc).__name__}",
|
||||
"preflight_detail": f"Voorafgaande test mislukt: {type(exc).__name__}",
|
||||
})
|
||||
|
||||
|
||||
@@ -292,7 +293,7 @@ def _probe_candidates(
|
||||
kind=suggestion.kind if suggestion else ServiceKind.TCP,
|
||||
reachability=ProbeReachability.VERIFIED,
|
||||
confidence=DiscoveryConfidence.HIGH,
|
||||
evidence="Docker healthcheck present (observed without a network probe)",
|
||||
evidence="Docker-healthcheck aanwezig (waargenomen zonder netwerkcontrole)",
|
||||
)
|
||||
)
|
||||
return candidates
|
||||
@@ -327,7 +328,7 @@ def safe_environment_evidence(env: list[str]) -> list[str]:
|
||||
|
||||
def _appops_inventory(appops_url: str | None) -> AppOpsInventory:
|
||||
if not appops_url:
|
||||
return AppOpsInventory({}, False, "AppOps URL is not configured")
|
||||
return AppOpsInventory({}, False, "Er is geen AppOps-URL ingesteld")
|
||||
base = appops_url.rstrip("/")
|
||||
try:
|
||||
mappings_response = httpx.get(f"{base}/api/inventory/mappings", timeout=5)
|
||||
@@ -337,7 +338,7 @@ def _appops_inventory(appops_url: str | None) -> AppOpsInventory:
|
||||
mappings = mappings_response.json()
|
||||
apps = apps_response.json()
|
||||
except (httpx.HTTPError, ValueError) as exc:
|
||||
return AppOpsInventory({}, False, f"AppOps inventory unavailable: {type(exc).__name__}")
|
||||
return AppOpsInventory({}, False, f"AppOps-inventaris niet beschikbaar: {type(exc).__name__}")
|
||||
app_by_id = {str(item.get("id")): item for item in apps if isinstance(item, dict)}
|
||||
result: dict[str, AppOpsInfo] = {}
|
||||
for mapping in mappings if isinstance(mappings, list) else []:
|
||||
@@ -362,7 +363,7 @@ def _appops_inventory(appops_url: str | None) -> AppOpsInventory:
|
||||
app_type=str(app.get("app_type")) if app.get("app_type") else None,
|
||||
reasons=tuple(str(item) for item in (app.get("discovery_reasons") or [])[:3]),
|
||||
)
|
||||
return AppOpsInventory(result, True, f"{len(result)} container mappings loaded")
|
||||
return AppOpsInventory(result, True, f"{len(result)} containerkoppelingen geladen")
|
||||
|
||||
|
||||
def appops_inventory(appops_url: str | None) -> AppOpsInventory:
|
||||
@@ -371,6 +372,38 @@ def appops_inventory(appops_url: str | None) -> AppOpsInventory:
|
||||
return _appops_inventory(appops_url)
|
||||
|
||||
|
||||
_HEALTH_IN_STATUS = re.compile(r"\((healthy|unhealthy|health: starting)\)")
|
||||
_observer_clients: dict[str, object] = {}
|
||||
|
||||
|
||||
def _observer_client(docker_host: str):
|
||||
"""One long-lived socket client per host (no /version + /_ping per cycle)."""
|
||||
|
||||
client = _observer_clients.get(docker_host)
|
||||
if client is None:
|
||||
client = docker.DockerClient(base_url=docker_host, timeout=5, version="auto")
|
||||
_observer_clients[docker_host] = client
|
||||
return client
|
||||
|
||||
|
||||
def _drop_observer_client(docker_host: str) -> None:
|
||||
client = _observer_clients.pop(docker_host, None)
|
||||
close = getattr(client, "close", None)
|
||||
if callable(close):
|
||||
with suppress(Exception): # best effort on an already failed client
|
||||
close()
|
||||
|
||||
|
||||
def health_from_status(status_text: str) -> str | None:
|
||||
"""Docker's list summary embeds health: "Up 3 hours (healthy)"."""
|
||||
|
||||
match = _HEALTH_IN_STATUS.search(status_text or "")
|
||||
if not match:
|
||||
return None
|
||||
value = match.group(1)
|
||||
return "starting" if value == "health: starting" else value
|
||||
|
||||
|
||||
def observe_container_health(docker_host: str) -> list[DockerHealthObservation]:
|
||||
"""Read bounded Docker runtime/health facts without discovery side effects.
|
||||
|
||||
@@ -378,18 +411,48 @@ def observe_container_health(docker_host: str) -> list[DockerHealthObservation]:
|
||||
suggestion persistence, reconciliation and snapshot capture. It is safe
|
||||
to run on the observation cadence because it cannot rewrite topology or
|
||||
operator-owned configuration.
|
||||
|
||||
Socket mode uses a single low-level ``containers(all=True)`` call on a
|
||||
long-lived client: the list summary already carries id, name, state,
|
||||
labels and health. The high-level ``containers.list()`` inspected every
|
||||
container individually (1 + N API calls per minute).
|
||||
"""
|
||||
|
||||
parsed = urlparse(docker_host)
|
||||
if parsed.scheme not in ALLOWED_SCHEMES:
|
||||
raise ValueError("docker_host must use unix://, tcp://, http:// or https://")
|
||||
if docker_provider_mode() == "socket":
|
||||
try:
|
||||
summaries = _observer_client(docker_host).api.containers(all=True)
|
||||
except (DockerException, OSError) as exc:
|
||||
_drop_observer_client(docker_host)
|
||||
raise RuntimeError(f"Docker-waarneming niet beschikbaar: {type(exc).__name__}") from exc
|
||||
observations: list[DockerHealthObservation] = []
|
||||
for item in summaries:
|
||||
names = item.get("Names") or []
|
||||
name = str(names[0] if names else item.get("Id", "unknown")[:12]).lstrip("/")
|
||||
labels = {str(key): str(value) for key, value in (item.get("Labels") or {}).items()}
|
||||
health = health_from_status(str(item.get("Status", "")))
|
||||
observations.append(
|
||||
DockerHealthObservation(
|
||||
container_id=str(item.get("Id", ""))[:12],
|
||||
name=name,
|
||||
stable_source_ref=stable_source_ref(name, labels),
|
||||
state=str(item.get("State", "unknown")),
|
||||
health=health,
|
||||
healthcheck_present=health is not None,
|
||||
)
|
||||
)
|
||||
return observations
|
||||
return _observe_container_health_full(docker_host)
|
||||
|
||||
|
||||
def _observe_container_health_full(docker_host: str) -> list[DockerHealthObservation]:
|
||||
"""Broker mode: the broker client exposes only the high-level listing."""
|
||||
|
||||
client = None
|
||||
try:
|
||||
client = (
|
||||
docker.DockerClient(base_url=docker_host, timeout=5)
|
||||
if docker_provider_mode() == "socket"
|
||||
else docker_client_for_inventory(docker_host)
|
||||
)
|
||||
client = docker_client_for_inventory(docker_host)
|
||||
client.ping()
|
||||
observations: list[DockerHealthObservation] = []
|
||||
for container in client.containers.list(all=True):
|
||||
@@ -414,7 +477,7 @@ def observe_container_health(docker_host: str) -> list[DockerHealthObservation]:
|
||||
)
|
||||
return observations
|
||||
except (DockerException, DockerProviderError) as exc:
|
||||
raise RuntimeError(f"Docker observation unavailable: {type(exc).__name__}") from exc
|
||||
raise RuntimeError(f"Docker-waarneming niet beschikbaar: {type(exc).__name__}") from exc
|
||||
finally:
|
||||
close = getattr(client, "close", None)
|
||||
if callable(close):
|
||||
@@ -509,7 +572,11 @@ def discover_containers(
|
||||
client = docker.DockerClient(base_url=docker_host, timeout=5) if docker_provider_mode() == "socket" else docker_client_for_inventory(docker_host)
|
||||
try:
|
||||
client.ping()
|
||||
containers = client.containers.list(all=include_stopped)
|
||||
# Always list stopped containers: they still exist. Excluding them here
|
||||
# made every stopped service look "missing" and, after three runs,
|
||||
# retired with monitoring disabled. ``include_stopped`` only decides
|
||||
# whether a stopped container is offered as a candidate below.
|
||||
containers = client.containers.list(all=True)
|
||||
existing_services = existing_services or []
|
||||
appops_inventory = _appops_inventory(appops_url)
|
||||
appops = appops_inventory.by_container
|
||||
@@ -521,6 +588,13 @@ def discover_containers(
|
||||
attrs = container.attrs or {}
|
||||
state = attrs.get("State", {}) or {}
|
||||
config = attrs.get("Config", {}) or {}
|
||||
name = str(getattr(container, "name", "unknown")).lstrip("/")
|
||||
state_name = str(state.get("Status", getattr(container, "status", "unknown")))
|
||||
raw_labels = {str(key): str(value) for key, value in (config.get("Labels", {}) or {}).items()}
|
||||
stable_ref = stable_source_ref(name, raw_labels)
|
||||
discovered_refs.add(stable_ref)
|
||||
if not include_stopped and state_name != "running":
|
||||
continue
|
||||
network_settings = attrs.get("NetworkSettings", {}) or {}
|
||||
raw_ports = network_settings.get("Ports", {}) or {}
|
||||
ports: list[DockerPort] = []
|
||||
@@ -541,15 +615,10 @@ def discover_containers(
|
||||
|
||||
image_tags = getattr(container.image, "tags", []) or []
|
||||
image_name = image_tags[0] if image_tags else str(config.get("Image", "unknown"))
|
||||
name = str(getattr(container, "name", "unknown")).lstrip("/")
|
||||
health = state.get("Health", {}).get("Status") if isinstance(state.get("Health"), dict) else None
|
||||
state_name = str(state.get("Status", getattr(container, "status", "unknown")))
|
||||
networks = sorted((network_settings.get("Networks", {}) or {}).keys())
|
||||
raw_labels = {str(key): str(value) for key, value in (config.get("Labels", {}) or {}).items()}
|
||||
labels = _safe_labels(raw_labels)
|
||||
stable_ref = stable_source_ref(name, raw_labels)
|
||||
legacy_ref = _legacy_source_ref(container.id, image_name)
|
||||
discovered_refs.add(stable_ref)
|
||||
matching_source = next(
|
||||
(
|
||||
service
|
||||
@@ -677,6 +746,6 @@ def discover_containers(
|
||||
appops_detail=appops_inventory.detail,
|
||||
)
|
||||
except (DockerException, DockerProviderError) as exc:
|
||||
raise ValueError(f"Docker discovery failed: {exc}") from exc
|
||||
raise ValueError(f"Docker-detectie mislukt: {exc}") from exc
|
||||
finally:
|
||||
client.close()
|
||||
+68
-28
@@ -2,52 +2,90 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from queue import Empty, Full, Queue
|
||||
from threading import Lock
|
||||
from typing import Any
|
||||
|
||||
# Clients reconnect after this delay if the stream drops (SSE ``retry:``).
|
||||
SSE_RETRY_MS = 5_000
|
||||
# A comment line keeps proxies and browsers from timing out a quiet stream.
|
||||
SSE_KEEPALIVE_SECONDS = 15.0
|
||||
|
||||
|
||||
class Subscription:
|
||||
"""One connected SSE client: an asyncio queue bound to its event loop."""
|
||||
|
||||
__slots__ = ("loop", "queue")
|
||||
|
||||
def __init__(self, loop: asyncio.AbstractEventLoop, max_queue_size: int) -> None:
|
||||
self.loop = loop
|
||||
self.queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=max_queue_size)
|
||||
|
||||
def offer(self, payload: dict[str, Any]) -> None:
|
||||
"""Enqueue on the owning loop; drop the oldest wakeup when full."""
|
||||
|
||||
if self.queue.full():
|
||||
try:
|
||||
self.queue.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
pass
|
||||
try:
|
||||
self.queue.put_nowait(payload)
|
||||
except asyncio.QueueFull:
|
||||
pass
|
||||
|
||||
|
||||
class EventBus:
|
||||
"""Small bounded fan-out bus used by the SSE endpoint.
|
||||
|
||||
Persistence is handled by SQLite; this bus only wakes currently connected
|
||||
clients. A queue per client keeps one slow browser from blocking probes or
|
||||
other subscribers.
|
||||
clients. Each client owns an ``asyncio.Queue`` so a waiting stream costs no
|
||||
thread: previously every open browser tab parked one default-executor
|
||||
thread in ``queue.get``, which starved ``asyncio.to_thread`` work such as
|
||||
the observation loop. ``publish`` is safe from worker threads and from
|
||||
the event loop; delivery is scheduled with ``call_soon_threadsafe``.
|
||||
"""
|
||||
|
||||
def __init__(self, max_queue_size: int = 100) -> None:
|
||||
self.max_queue_size = max_queue_size
|
||||
self._subscribers: set[Queue[dict[str, Any]]] = set()
|
||||
self._subscribers: set[Subscription] = set()
|
||||
self._lock = Lock()
|
||||
self._revision = 0
|
||||
|
||||
def subscribe(self) -> Queue[dict[str, Any]]:
|
||||
queue: Queue[dict[str, Any]] = Queue(maxsize=self.max_queue_size)
|
||||
with self._lock:
|
||||
self._subscribers.add(queue)
|
||||
return queue
|
||||
@property
|
||||
def revision(self) -> int:
|
||||
"""Monotonic count of published events; read caches compare it."""
|
||||
|
||||
def unsubscribe(self, queue: Queue[dict[str, Any]]) -> None:
|
||||
with self._lock:
|
||||
self._subscribers.discard(queue)
|
||||
return self._revision
|
||||
|
||||
def subscribe(self) -> Subscription:
|
||||
subscription = Subscription(asyncio.get_running_loop(), self.max_queue_size)
|
||||
with self._lock:
|
||||
self._subscribers.add(subscription)
|
||||
return subscription
|
||||
|
||||
def unsubscribe(self, subscription: Subscription) -> None:
|
||||
with self._lock:
|
||||
self._subscribers.discard(subscription)
|
||||
|
||||
@property
|
||||
def subscriber_count(self) -> int:
|
||||
with self._lock:
|
||||
return len(self._subscribers)
|
||||
|
||||
def publish(self, payload: dict[str, Any]) -> None:
|
||||
with self._lock:
|
||||
self._revision += 1
|
||||
subscribers = tuple(self._subscribers)
|
||||
for queue in subscribers:
|
||||
for subscription in subscribers:
|
||||
try:
|
||||
queue.put_nowait(payload)
|
||||
except Full:
|
||||
# Drop the oldest event for a lagging client, then retain the
|
||||
# newest state notification. The durable event journal remains
|
||||
# the source of truth if a client reconnects.
|
||||
try:
|
||||
queue.get_nowait()
|
||||
except Empty:
|
||||
pass
|
||||
try:
|
||||
queue.put_nowait(payload)
|
||||
except Full:
|
||||
pass
|
||||
subscription.loop.call_soon_threadsafe(subscription.offer, payload)
|
||||
except RuntimeError:
|
||||
# The client's loop has closed (shutdown); it can no longer
|
||||
# receive anything, so forget it.
|
||||
self.unsubscribe(subscription)
|
||||
|
||||
|
||||
event_bus = EventBus()
|
||||
|
||||
|
||||
@@ -56,8 +94,10 @@ def sse_payload(payload: dict[str, Any]) -> str:
|
||||
return f"event: {event_type}\ndata: {json.dumps(payload, default=str)}\n\n"
|
||||
|
||||
|
||||
async def next_event(queue: Queue[dict[str, Any]], timeout: float = 15.0) -> dict[str, Any] | None:
|
||||
async def next_event(
|
||||
subscription: Subscription, timeout: float = SSE_KEEPALIVE_SECONDS
|
||||
) -> dict[str, Any] | None:
|
||||
try:
|
||||
return await asyncio.to_thread(queue.get, True, timeout)
|
||||
except Empty:
|
||||
return await asyncio.wait_for(subscription.queue.get(), timeout)
|
||||
except TimeoutError:
|
||||
return None
|
||||
@@ -98,10 +98,10 @@ def resolve_health(
|
||||
else:
|
||||
reason_code = HealthResolutionReason.NO_CURRENT_COMPONENT_EVIDENCE
|
||||
explanation = (
|
||||
"Only application-scoped evidence is current; it is shown for provenance and is not "
|
||||
"used as component health."
|
||||
"Alleen bewijs op applicatieniveau is actueel; het wordt getoond als herkomst en niet "
|
||||
"gebruikt als componentgezondheid."
|
||||
if app_claims
|
||||
else "No current component-scoped health evidence is available."
|
||||
else "Er is geen actueel gezondheidsbewijs op componentniveau."
|
||||
)
|
||||
return HealthResolution(reason_code=reason_code, explanation=explanation, evidence=annotated)
|
||||
|
||||
@@ -118,7 +118,7 @@ def resolve_health(
|
||||
)
|
||||
selected = ordered[0]
|
||||
conflict = len({item.status for item in eligible}) > 1
|
||||
scope_note = " Conflicting current component signals are retained below." if conflict else ""
|
||||
scope_note = " Tegenstrijdige actuele componentsignalen worden hieronder bewaard." if conflict else ""
|
||||
return HealthResolution(
|
||||
status=selected.status,
|
||||
selected_evidence_id=selected.id,
|
||||
@@ -126,8 +126,8 @@ def resolve_health(
|
||||
confidence=selected.confidence,
|
||||
reason_code=HealthResolutionReason.SELECTED_COMPONENT_EVIDENCE,
|
||||
explanation=(
|
||||
f"{selected.provider.value} selected from current component-scoped evidence "
|
||||
f"(confidence {selected.confidence:.2f}).{scope_note}"
|
||||
f"{selected.provider.value} gekozen uit actueel bewijs op componentniveau "
|
||||
f"(zekerheid {selected.confidence:.2f}).{scope_note}"
|
||||
),
|
||||
conflict=conflict,
|
||||
evidence=annotated,
|
||||
|
||||
+27
-38
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import NamedTuple
|
||||
|
||||
from .models import HealthStatus, Service
|
||||
from .store import Store
|
||||
|
||||
@@ -14,51 +16,38 @@ SEVERITY = {
|
||||
}
|
||||
|
||||
|
||||
def _direct_status(service: Service, store: Store) -> HealthStatus:
|
||||
return store.service_health(service.id)
|
||||
class TopologyHealth(NamedTuple):
|
||||
services: list[Service]
|
||||
direct: dict[str, HealthStatus]
|
||||
effective: dict[str, HealthStatus]
|
||||
dependency: dict[str, HealthStatus]
|
||||
|
||||
|
||||
def _dependency_status(service: Service, store: Store, visiting: set[str]) -> HealthStatus:
|
||||
if not service.depends_on:
|
||||
return HealthStatus.HEALTHY
|
||||
def topology_health(store: Store, *, services: list[Service] | None = None) -> TopologyHealth:
|
||||
"""Resolve direct, dependency and effective health for the whole graph.
|
||||
|
||||
states: list[HealthStatus] = []
|
||||
for dependency_id in service.depends_on:
|
||||
dependency = store.get_service(dependency_id)
|
||||
if dependency is None:
|
||||
states.append(HealthStatus.UNKNOWN)
|
||||
continue
|
||||
states.append(_effective_status(dependency, store, visiting))
|
||||
return max(states, key=lambda status: SEVERITY[status])
|
||||
One bulk evidence read plus one in-memory traversal. The former
|
||||
per-service recursive walk re-queried SQLite for every node on every
|
||||
dependency path and dominated server CPU.
|
||||
"""
|
||||
|
||||
services = store.list_services() if services is None else services
|
||||
direct, _ = store.service_healths([service.id for service in services])
|
||||
effective, dependency = status_maps(services, direct_statuses=direct)
|
||||
return TopologyHealth(services, direct, effective, dependency)
|
||||
|
||||
|
||||
def _effective_status(service: Service, store: Store, visiting: set[str]) -> HealthStatus:
|
||||
if service.id in visiting:
|
||||
return HealthStatus.UNKNOWN
|
||||
next_visiting = set(visiting)
|
||||
next_visiting.add(service.id)
|
||||
own = _direct_status(service, store)
|
||||
if own == HealthStatus.MAINTENANCE:
|
||||
return own
|
||||
dependency = _dependency_status(service, store, next_visiting)
|
||||
if own == HealthStatus.DOWN:
|
||||
return own
|
||||
if dependency == HealthStatus.DOWN:
|
||||
return HealthStatus.DEGRADED
|
||||
if dependency in {HealthStatus.DEGRADED, HealthStatus.RECOVERING} and own in {
|
||||
HealthStatus.HEALTHY,
|
||||
HealthStatus.RECOVERING,
|
||||
}:
|
||||
return HealthStatus.DEGRADED
|
||||
return own
|
||||
def _single(service: Service, store: Store) -> TopologyHealth:
|
||||
services = [item for item in store.list_services() if item.id != service.id]
|
||||
return topology_health(store, services=[*services, service])
|
||||
|
||||
|
||||
def dependency_status(service: Service, store: Store) -> HealthStatus:
|
||||
return _dependency_status(service, store, {service.id})
|
||||
return _single(service, store).dependency.get(service.id, HealthStatus.UNKNOWN)
|
||||
|
||||
|
||||
def effective_status(service: Service, store: Store) -> HealthStatus:
|
||||
return _effective_status(service, store, set())
|
||||
return _single(service, store).effective.get(service.id, HealthStatus.UNKNOWN)
|
||||
|
||||
|
||||
def status_maps(
|
||||
@@ -134,15 +123,15 @@ def validate_dependencies(
|
||||
service_id: str | None = None,
|
||||
) -> None:
|
||||
if len(depends_on) != len(set(depends_on)):
|
||||
raise ValueError("Dependencies must be unique")
|
||||
raise ValueError("Afhankelijkheden moeten uniek zijn")
|
||||
if service_id and service_id in depends_on:
|
||||
raise ValueError("A service cannot depend on itself")
|
||||
raise ValueError("Een service kan niet van zichzelf afhangen")
|
||||
|
||||
services = store.list_services()
|
||||
known_ids = {service.id for service in services}
|
||||
missing = [dependency_id for dependency_id in depends_on if dependency_id not in known_ids]
|
||||
if missing:
|
||||
raise ValueError(f"Unknown dependency ids: {', '.join(missing)}")
|
||||
raise ValueError(f"Onbekende afhankelijkheids-id's: {', '.join(missing)}")
|
||||
|
||||
if service_id is None:
|
||||
return
|
||||
@@ -154,7 +143,7 @@ def validate_dependencies(
|
||||
|
||||
def visit(node: str) -> None:
|
||||
if node in visiting:
|
||||
raise ValueError("Dependency graph contains a cycle")
|
||||
raise ValueError("De afhankelijkheidsgrafiek bevat een kring")
|
||||
if node in visited:
|
||||
return
|
||||
visiting.add(node)
|
||||
|
||||
+29
-15
@@ -1,9 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from .health import dependency_status, effective_status
|
||||
from .health import TopologyHealth, topology_health
|
||||
from .models import (
|
||||
Criticality,
|
||||
HealthStatus,
|
||||
@@ -37,11 +38,12 @@ def affected_service_ids(root_id: str, services: list[Service]) -> list[str]:
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def incident_overview(store: Store) -> IncidentOverview:
|
||||
services = store.list_services()
|
||||
def incident_overview(store: Store, *, health: TopologyHealth | None = None) -> IncidentOverview:
|
||||
health = health or topology_health(store)
|
||||
services = health.services
|
||||
by_id = {service.id: service for service in services}
|
||||
effective = {service.id: effective_status(service, store) for service in services}
|
||||
dependency = {service.id: dependency_status(service, store) for service in services}
|
||||
effective = health.effective
|
||||
dependency = health.dependency
|
||||
|
||||
down_ids = sorted(service_id for service_id, state in effective.items() if state == HealthStatus.DOWN)
|
||||
degraded_ids = sorted(
|
||||
@@ -62,9 +64,9 @@ def incident_overview(store: Store) -> IncidentOverview:
|
||||
continue
|
||||
affected_ids = affected_service_ids(service.id, services)
|
||||
affected_names = [by_id[item].name for item in affected_ids if item in by_id]
|
||||
reason = "Service is down and no configured dependency is also down"
|
||||
reason = "Service is uitgevallen en geen enkele ingestelde afhankelijkheid is ook uitgevallen"
|
||||
if dependency[service.id] == HealthStatus.UNKNOWN:
|
||||
reason += "; at least one dependency has unknown health"
|
||||
reason += "; minstens één afhankelijkheid heeft een onbekende gezondheid"
|
||||
candidates.append(
|
||||
IncidentCandidate(
|
||||
service_id=service.id,
|
||||
@@ -91,15 +93,27 @@ def _severity(service: Service) -> Criticality:
|
||||
return service.criticality
|
||||
|
||||
|
||||
def sync_incidents(store: Store, *, resolution_reason: str = "Root cause recovered; incident resolved") -> list[IncidentRecord]:
|
||||
# Probes, observation and API handlers reconcile from different threads. Two
|
||||
# concurrent passes could both see "no active incident" for a root and each
|
||||
# open one (the later duplicate cleanup then left two journal entries).
|
||||
_SYNC_LOCK = threading.RLock()
|
||||
|
||||
|
||||
def sync_incidents(store: Store, *, resolution_reason: str = "Hoofdoorzaak hersteld; incident opgelost") -> list[IncidentRecord]:
|
||||
with _SYNC_LOCK:
|
||||
return _sync_incidents_locked(store, resolution_reason=resolution_reason)
|
||||
|
||||
|
||||
def _sync_incidents_locked(store: Store, *, resolution_reason: str) -> list[IncidentRecord]:
|
||||
"""Reconcile the current graph with the durable incident journal.
|
||||
|
||||
A root service has at most one active incident. Repeated probe cycles only
|
||||
update its affected set; a later independent outage gets a new id.
|
||||
"""
|
||||
|
||||
overview = incident_overview(store)
|
||||
services = {service.id: service for service in store.list_services()}
|
||||
health = topology_health(store)
|
||||
overview = incident_overview(store, health=health)
|
||||
services = {service.id: service for service in health.services}
|
||||
now = datetime.now(UTC)
|
||||
active: dict[str, IncidentRecord] = {}
|
||||
for incident in sorted(
|
||||
@@ -115,7 +129,7 @@ def sync_incidents(store: Store, *, resolution_reason: str = "Root cause recover
|
||||
store.append_incident_event(
|
||||
incident.id,
|
||||
"incident.duplicate_resolved",
|
||||
"Duplicate active incident closed; the earliest incident remains active",
|
||||
"Dubbel actief incident gesloten; het oudste incident blijft actief",
|
||||
incident.root_service_id,
|
||||
)
|
||||
continue
|
||||
@@ -133,7 +147,7 @@ def sync_incidents(store: Store, *, resolution_reason: str = "Root cause recover
|
||||
root_service_name=candidate.service_name,
|
||||
started_at=now,
|
||||
detected_at=now,
|
||||
title=f"{candidate.service_name} is down",
|
||||
title=f"{candidate.service_name} is uitgevallen",
|
||||
root_cause_reason=candidate.reason,
|
||||
affected_service_ids=candidate.affected_service_ids,
|
||||
affected_service_names=candidate.affected_service_names,
|
||||
@@ -144,7 +158,7 @@ def sync_incidents(store: Store, *, resolution_reason: str = "Root cause recover
|
||||
store.append_incident_event(
|
||||
incident.id,
|
||||
"incident.opened",
|
||||
f"Incident opened: {candidate.service_name} is the likely root cause",
|
||||
f"Incident geopend: {candidate.service_name} is de waarschijnlijke hoofdoorzaak",
|
||||
candidate.service_id,
|
||||
)
|
||||
active[candidate.service_id] = incident
|
||||
@@ -158,14 +172,14 @@ def sync_incidents(store: Store, *, resolution_reason: str = "Root cause recover
|
||||
}
|
||||
)
|
||||
store.upsert_incident(updated)
|
||||
store.append_incident_event(incident.id, "incident.updated", "Downstream impact recalculated", candidate.service_id)
|
||||
store.append_incident_event(incident.id, "incident.updated", "Impact op afhankelijke services herberekend", candidate.service_id)
|
||||
|
||||
for root_id, incident in list(active.items()):
|
||||
if any(candidate.service_id == root_id for candidate in overview.candidates):
|
||||
continue
|
||||
root = services.get(root_id)
|
||||
if (
|
||||
(root is None or store.service_health(root_id) not in {
|
||||
(root is None or health.direct.get(root_id, HealthStatus.UNKNOWN) not in {
|
||||
HealthStatus.DOWN,
|
||||
HealthStatus.DEGRADED,
|
||||
HealthStatus.RECOVERING,
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Background loops that never die silently, and their readiness record.
|
||||
|
||||
Before v1.6.3 the observation and discovery loops caught only ``OSError``,
|
||||
``RuntimeError`` and ``ValueError``. Any other exception, for example
|
||||
``sqlite3.OperationalError: database is locked``, ended the task without a
|
||||
log line; ServiceMap then looked healthy while it no longer observed
|
||||
anything. ``run_periodic`` logs every failure, retries with bounded
|
||||
backoff and records the last success so ``/ready`` can report a stalled
|
||||
loop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
|
||||
logger = logging.getLogger("servicemap.loops")
|
||||
|
||||
|
||||
@dataclass
|
||||
class LoopStatus:
|
||||
name: str
|
||||
interval_seconds: float
|
||||
started_at: float = field(default_factory=time.time)
|
||||
last_success_at: float | None = None
|
||||
last_failure_at: float | None = None
|
||||
last_error: str | None = None
|
||||
consecutive_failures: int = 0
|
||||
paused: bool = False
|
||||
|
||||
def stale_after_seconds(self) -> float:
|
||||
# Three missed cycles, with a floor for very short intervals.
|
||||
return max(3 * self.interval_seconds, 180.0)
|
||||
|
||||
def healthy(self, now: float) -> bool:
|
||||
if self.paused:
|
||||
return True
|
||||
reference = self.last_success_at if self.last_success_at is not None else self.started_at
|
||||
return now - reference <= self.stale_after_seconds()
|
||||
|
||||
def as_dict(self, now: float) -> dict[str, object]:
|
||||
def iso(value: float | None) -> str | None:
|
||||
return None if value is None else time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(value))
|
||||
|
||||
return {
|
||||
"name": self.name,
|
||||
"healthy": self.healthy(now),
|
||||
"interval_seconds": self.interval_seconds,
|
||||
"last_success_at": iso(self.last_success_at),
|
||||
"last_failure_at": iso(self.last_failure_at),
|
||||
"last_error": self.last_error,
|
||||
"consecutive_failures": self.consecutive_failures,
|
||||
"paused": self.paused,
|
||||
}
|
||||
|
||||
|
||||
class LoopRegistry:
|
||||
def __init__(self) -> None:
|
||||
self._loops: dict[str, LoopStatus] = {}
|
||||
self._lock = Lock()
|
||||
|
||||
def register(self, name: str, interval_seconds: float) -> LoopStatus:
|
||||
with self._lock:
|
||||
status = LoopStatus(name=name, interval_seconds=interval_seconds)
|
||||
self._loops[name] = status
|
||||
return status
|
||||
|
||||
def unregister(self, name: str) -> None:
|
||||
with self._lock:
|
||||
self._loops.pop(name, None)
|
||||
|
||||
def snapshot(self) -> list[dict[str, object]]:
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
return [status.as_dict(now) for status in self._loops.values()]
|
||||
|
||||
def all_healthy(self) -> bool:
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
return all(status.healthy(now) for status in self._loops.values())
|
||||
|
||||
|
||||
loop_registry = LoopRegistry()
|
||||
|
||||
|
||||
def record_success(status: LoopStatus) -> None:
|
||||
status.last_success_at = time.time()
|
||||
status.consecutive_failures = 0
|
||||
status.paused = False
|
||||
|
||||
|
||||
def record_failure(status: LoopStatus, error: BaseException) -> None:
|
||||
status.last_failure_at = time.time()
|
||||
status.consecutive_failures += 1
|
||||
status.last_error = f"{type(error).__name__}: {str(error)[:300]}"
|
||||
|
||||
|
||||
async def run_periodic(
|
||||
name: str,
|
||||
work: Callable[[], Awaitable[object]],
|
||||
*,
|
||||
interval_seconds: float,
|
||||
initial_delay_seconds: float = 0.0,
|
||||
paused: Callable[[], bool] | None = None,
|
||||
registry: LoopRegistry = loop_registry,
|
||||
max_backoff_seconds: float = 300.0,
|
||||
) -> None:
|
||||
"""Run ``work`` every ``interval_seconds`` until cancelled.
|
||||
|
||||
A failure is logged with its traceback and retried after an exponential
|
||||
backoff capped at ``max_backoff_seconds``. ``paused`` lets a loop
|
||||
idle deliberately (for example while the synthetic demo is active)
|
||||
without being reported as stalled.
|
||||
"""
|
||||
|
||||
status = registry.register(name, interval_seconds)
|
||||
try:
|
||||
if initial_delay_seconds > 0:
|
||||
await asyncio.sleep(initial_delay_seconds)
|
||||
while True:
|
||||
delay = interval_seconds
|
||||
try:
|
||||
if paused is not None and paused():
|
||||
status.paused = True
|
||||
else:
|
||||
await work()
|
||||
record_success(status)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
record_failure(status, exc)
|
||||
# interval, 2x, 4x … capped: a persistent fault does not spin,
|
||||
# a long interval still retries within max_backoff_seconds.
|
||||
delay = min(
|
||||
max_backoff_seconds,
|
||||
max(5.0, interval_seconds) * 2 ** min(status.consecutive_failures - 1, 5),
|
||||
)
|
||||
logger.exception(
|
||||
"Background loop %s failed (%s consecutive); retrying in %.0fs",
|
||||
name,
|
||||
status.consecutive_failures,
|
||||
delay,
|
||||
)
|
||||
await asyncio.sleep(delay)
|
||||
finally:
|
||||
registry.unregister(name)
|
||||
+422
-92
@@ -1,26 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import asynccontextmanager, suppress
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Query, Response, status
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from fastapi import FastAPI, HTTPException, Query, Request, Response, status
|
||||
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .auth import AuthConfig, AuthorizationError, authorize_request
|
||||
from .alerts import AlertManager, AlertSettingsUpdate, AlertSettingsView, AlertTestResult
|
||||
from .auth import AuthConfig, AuthorizationError, admin_token, admin_token_path, authorize_request
|
||||
from .backups import BackupInfo, BackupManager
|
||||
from .config_io import export_document, import_document, parse_document, serialize_document
|
||||
from .demo import DEMO_ROOT_CAUSE_NAME, DEMO_SCENARIO_NAME, build_demo_records
|
||||
from .discovery import DiscoveryManager
|
||||
from .discovery_store import DiscoveryStore
|
||||
from .docker_discovery import discover_containers
|
||||
from .docker_provider import docker_provider_mode
|
||||
from .events import event_bus, next_event, sse_payload
|
||||
from .health import dependency_status, effective_status, status_maps, validate_dependencies
|
||||
from .events import SSE_RETRY_MS, event_bus, next_event, sse_payload
|
||||
from .health import status_maps, topology_health, validate_dependencies
|
||||
from .incidents import incident_overview, sync_incidents
|
||||
from .loops import loop_registry, run_periodic
|
||||
from .models import (
|
||||
AvailabilitySummary,
|
||||
BulkProbeResult,
|
||||
@@ -39,7 +43,10 @@ from .models import (
|
||||
EdgeMutationRequest,
|
||||
EventRecord,
|
||||
HealthResolution,
|
||||
HealthStatus,
|
||||
IncidentNoteRequest,
|
||||
IncidentOverview,
|
||||
IncidentResolveRequest,
|
||||
LogicalRelation,
|
||||
MaintenanceRequest,
|
||||
OverviewSummary,
|
||||
@@ -60,6 +67,14 @@ from .models import (
|
||||
)
|
||||
from .observation import ObservationManager
|
||||
from .probes import probe_many, probe_service
|
||||
from .response_cache import (
|
||||
GENERATED_AT_HEADER,
|
||||
CachedRepresentation,
|
||||
RepresentationCache,
|
||||
etag_matches,
|
||||
next_freshness_boundary,
|
||||
representation,
|
||||
)
|
||||
from .scheduler import scheduled_probe_loop
|
||||
from .semantic import build_semantic_topology
|
||||
from .store import Store
|
||||
@@ -83,6 +98,16 @@ def _env_float(name: str, default: float, minimum: float = 0.1) -> float:
|
||||
return default
|
||||
|
||||
|
||||
logger = logging.getLogger("servicemap")
|
||||
if not logger.handlers:
|
||||
# Uvicorn configures only its own loggers; without a handler our INFO
|
||||
# lines (maintenance results, loop recovery) were never emitted.
|
||||
_handler = logging.StreamHandler()
|
||||
_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
|
||||
logger.addHandler(_handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
PROBE_INTERVAL = _env_int("SERVICEMAP_PROBE_INTERVAL", 0)
|
||||
PROBE_TIMEOUT = _env_float("SERVICEMAP_PROBE_TIMEOUT", 5.0)
|
||||
PROBE_RETRIES = _env_int("SERVICEMAP_PROBE_RETRIES", 1)
|
||||
@@ -90,8 +115,48 @@ PROBE_CONCURRENCY = _env_int("SERVICEMAP_PROBE_CONCURRENCY", 10, minimum=1)
|
||||
RETENTION_DAYS = _env_int("SERVICEMAP_RETENTION_DAYS", 30, minimum=1)
|
||||
EVENT_RETENTION_DAYS = _env_int("SERVICEMAP_EVENT_RETENTION_DAYS", 90, minimum=1)
|
||||
DISCOVERY_INTERVAL = _env_int("SERVICEMAP_DISCOVERY_INTERVAL_SECONDS", 0, minimum=0)
|
||||
OBSERVATION_INTERVAL = _env_int("SERVICEMAP_OBSERVATION_INTERVAL_SECONDS", 60, minimum=10)
|
||||
OBSERVATION_INTERVAL = _env_int("SERVICEMAP_OBSERVATION_INTERVAL_SECONDS", 60)
|
||||
if OBSERVATION_INTERVAL > 0:
|
||||
OBSERVATION_INTERVAL = max(10, OBSERVATION_INTERVAL)
|
||||
# Superseded health-evidence history; current claims are never pruned. 0 disables.
|
||||
EVIDENCE_RETENTION_DAYS = _env_int("SERVICEMAP_EVIDENCE_RETENTION_DAYS", 7, minimum=0)
|
||||
MAINTENANCE_INTERVAL = _env_int("SERVICEMAP_MAINTENANCE_INTERVAL_SECONDS", 3600, minimum=60)
|
||||
# Discovery runs whose per-container observations are kept.
|
||||
DISCOVERY_OBSERVATION_RUNS = _env_int("SERVICEMAP_DISCOVERY_OBSERVATION_RUNS", 10, minimum=1)
|
||||
# Verified database backups in <data>/backups; 0 hours disables the schedule.
|
||||
BACKUP_INTERVAL_HOURS = _env_int("SERVICEMAP_BACKUP_INTERVAL_HOURS", 24, minimum=0)
|
||||
BACKUP_KEEP = _env_int("SERVICEMAP_BACKUP_KEEP", 14, minimum=1)
|
||||
observation_manager = ObservationManager(store, interval_seconds=OBSERVATION_INTERVAL)
|
||||
semantic_cache = RepresentationCache(max_age_seconds=10.0)
|
||||
_alert_manager: AlertManager | None = None
|
||||
|
||||
|
||||
def backup_manager() -> BackupManager:
|
||||
return BackupManager(store, keep=BACKUP_KEEP)
|
||||
|
||||
|
||||
def alert_manager() -> AlertManager:
|
||||
"""Bound to the current store (tests swap ``store``)."""
|
||||
|
||||
global _alert_manager
|
||||
if _alert_manager is None or _alert_manager.store is not store:
|
||||
_alert_manager = AlertManager(store)
|
||||
return _alert_manager
|
||||
|
||||
|
||||
def run_maintenance() -> dict[str, int]:
|
||||
"""Bounded retention for tables that otherwise grow with uptime."""
|
||||
|
||||
if store.demo_active():
|
||||
return {}
|
||||
pruned = {
|
||||
"health_evidence": store.prune_health_evidence(EVIDENCE_RETENTION_DAYS),
|
||||
"probe_results": store.prune_probes(RETENTION_DAYS, EVENT_RETENTION_DAYS),
|
||||
"discovery_observations": discovery_store.prune_observations(DISCOVERY_OBSERVATION_RUNS),
|
||||
"topology_change_events": discovery_store.prune_change_events(EVENT_RETENTION_DAYS),
|
||||
}
|
||||
store.checkpoint()
|
||||
return pruned
|
||||
|
||||
|
||||
def _require_configured_discovery_targets(
|
||||
@@ -102,16 +167,22 @@ def _require_configured_discovery_targets(
|
||||
configured_docker = os.getenv("SERVICEMAP_DOCKER_HOST", "unix:///var/run/docker.sock")
|
||||
configured_appops = os.getenv("SERVICEMAP_APPOPS_URL", "")
|
||||
if docker_host and docker_host != configured_docker:
|
||||
raise HTTPException(status_code=403, detail="Docker discovery target is not configured")
|
||||
raise HTTPException(status_code=403, detail="Er is geen Docker-detectiedoel ingesteld")
|
||||
if appops_url and appops_url.rstrip("/") != configured_appops.rstrip("/"):
|
||||
raise HTTPException(status_code=403, detail="AppOps discovery target is not configured")
|
||||
raise HTTPException(status_code=403, detail="Er is geen AppOps-detectiedoel ingesteld")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
try:
|
||||
if AuthConfig.from_environment().mode == "token":
|
||||
# Create the token on first start so its location is logged
|
||||
# before anyone needs it.
|
||||
admin_token()
|
||||
logger.info("Editing requires the admin token in %s", admin_token_path())
|
||||
except (AuthorizationError, OSError):
|
||||
logger.exception("ServiceMap admin token is unavailable; edits are refused")
|
||||
task: asyncio.Task[None] | None = None
|
||||
discovery_task: asyncio.Task[None] | None = None
|
||||
observation_task: asyncio.Task[None] | None = None
|
||||
if PROBE_INTERVAL > 0:
|
||||
task = asyncio.create_task(
|
||||
scheduled_probe_loop(
|
||||
@@ -121,37 +192,88 @@ async def lifespan(_: FastAPI):
|
||||
retries=PROBE_RETRIES,
|
||||
concurrency=PROBE_CONCURRENCY,
|
||||
retention_days=RETENTION_DAYS,
|
||||
event_retention_days=EVENT_RETENTION_DAYS,
|
||||
)
|
||||
)
|
||||
background: list[asyncio.Task[None]] = []
|
||||
if DISCOVERY_INTERVAL > 0:
|
||||
async def discovery_loop() -> None:
|
||||
while True:
|
||||
await asyncio.sleep(DISCOVERY_INTERVAL)
|
||||
if store.demo_active():
|
||||
continue
|
||||
try:
|
||||
request = DiscoveryRunRequest()
|
||||
result = await asyncio.to_thread(discovery_manager.run, request)
|
||||
async def discovery_cycle() -> None:
|
||||
result = await asyncio.to_thread(discovery_manager.run, DiscoveryRunRequest())
|
||||
await asyncio.to_thread(
|
||||
discovery_manager.reconcile,
|
||||
DiscoveryReconcileRequest(run_id=result.run.id, apply_high_confidence=False),
|
||||
)
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
# Discovery is review-first; a failed background run is
|
||||
# persisted and must not take down the monitoring loop.
|
||||
continue
|
||||
discovery_task = asyncio.create_task(discovery_loop())
|
||||
async def observation_loop() -> None:
|
||||
while True:
|
||||
if not store.demo_active():
|
||||
try:
|
||||
|
||||
background.append(asyncio.create_task(run_periodic(
|
||||
"discovery",
|
||||
discovery_cycle,
|
||||
interval_seconds=DISCOVERY_INTERVAL,
|
||||
initial_delay_seconds=DISCOVERY_INTERVAL,
|
||||
paused=store.demo_active,
|
||||
)))
|
||||
|
||||
if OBSERVATION_INTERVAL > 0:
|
||||
async def observation_cycle() -> None:
|
||||
await asyncio.to_thread(observation_manager.refresh)
|
||||
except (OSError, RuntimeError, ValueError):
|
||||
# Provider availability is persisted by the observer; an
|
||||
# unavailable provider must not stop scheduled probing.
|
||||
pass
|
||||
await asyncio.sleep(OBSERVATION_INTERVAL)
|
||||
observation_task = asyncio.create_task(observation_loop())
|
||||
|
||||
background.append(asyncio.create_task(run_periodic(
|
||||
"observation",
|
||||
observation_cycle,
|
||||
interval_seconds=OBSERVATION_INTERVAL,
|
||||
paused=store.demo_active,
|
||||
)))
|
||||
|
||||
async def alert_cycle() -> None:
|
||||
sent = await asyncio.to_thread(alert_manager().run_cycle)
|
||||
if sent:
|
||||
logger.info("Sent %s incident notification(s)", sent)
|
||||
|
||||
background.append(asyncio.create_task(run_periodic(
|
||||
"alerts",
|
||||
alert_cycle,
|
||||
interval_seconds=30,
|
||||
paused=store.demo_active,
|
||||
)))
|
||||
|
||||
if BACKUP_INTERVAL_HOURS > 0:
|
||||
async def backup_cycle() -> None:
|
||||
info = await asyncio.to_thread(backup_manager().create)
|
||||
logger.info("Backup %s written (%s bytes, verified)", info.name, info.size_bytes)
|
||||
|
||||
background.append(asyncio.create_task(run_periodic(
|
||||
"backups",
|
||||
backup_cycle,
|
||||
interval_seconds=BACKUP_INTERVAL_HOURS * 3600,
|
||||
# First backup shortly after start, then on the schedule.
|
||||
initial_delay_seconds=120,
|
||||
paused=store.demo_active,
|
||||
)))
|
||||
|
||||
async def maintenance_window_cycle() -> None:
|
||||
ended = await asyncio.to_thread(store.expire_maintenance_windows)
|
||||
if ended:
|
||||
logger.info("Maintenance windows ended for %s service(s)", len(ended))
|
||||
|
||||
background.append(asyncio.create_task(run_periodic(
|
||||
"maintenance-windows",
|
||||
maintenance_window_cycle,
|
||||
interval_seconds=60,
|
||||
paused=store.demo_active,
|
||||
)))
|
||||
|
||||
async def maintenance_cycle() -> None:
|
||||
pruned = await asyncio.to_thread(run_maintenance)
|
||||
if any(pruned.values()):
|
||||
logger.info("Maintenance pruned %s", pruned)
|
||||
|
||||
# Start shortly after boot so a long-running deployment sheds its backlog
|
||||
# without delaying startup, then repeat on a slow cadence.
|
||||
background.append(asyncio.create_task(run_periodic(
|
||||
"maintenance",
|
||||
maintenance_cycle,
|
||||
interval_seconds=MAINTENANCE_INTERVAL,
|
||||
initial_delay_seconds=30,
|
||||
)))
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
@@ -159,38 +281,74 @@ async def lifespan(_: FastAPI):
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
if discovery_task:
|
||||
discovery_task.cancel()
|
||||
for background_task in background:
|
||||
background_task.cancel()
|
||||
for background_task in background:
|
||||
with suppress(asyncio.CancelledError):
|
||||
await discovery_task
|
||||
if observation_task:
|
||||
observation_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await observation_task
|
||||
await background_task
|
||||
|
||||
|
||||
app = FastAPI(title="ServiceMap API", version="1.6.2", lifespan=lifespan)
|
||||
app = FastAPI(title="ServiceMap API", version="1.6.3", lifespan=lifespan)
|
||||
|
||||
|
||||
# Bounded request bodies: the largest legitimate payload is a config import.
|
||||
MAX_REQUEST_BYTES = 4 * 1024 * 1024
|
||||
|
||||
SECURITY_HEADERS = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"X-Frame-Options": "DENY",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Cross-Origin-Opener-Policy": "same-origin",
|
||||
# The SPA ships no inline scripts or third-party assets; React Flow and
|
||||
# the layout use inline style attributes.
|
||||
"Content-Security-Policy": (
|
||||
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
|
||||
"img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; "
|
||||
"object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def authorization_boundary(request, call_next):
|
||||
declared = request.headers.get("content-length", "")
|
||||
if declared.isdigit() and int(declared) > MAX_REQUEST_BYTES:
|
||||
response = JSONResponse(status_code=413, content={"detail": "De aanvraag is te groot"})
|
||||
else:
|
||||
try:
|
||||
authorize_request(request)
|
||||
except HTTPException as exc:
|
||||
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
||||
return await call_next(request)
|
||||
response = JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={"detail": exc.detail},
|
||||
headers=dict(exc.headers or {}),
|
||||
)
|
||||
else:
|
||||
response = await call_next(request)
|
||||
for name, value in SECURITY_HEADERS.items():
|
||||
response.headers.setdefault(name, value)
|
||||
path = request.url.path
|
||||
if path.startswith("/assets/"):
|
||||
# Vite fingerprints asset names, so they never change in place.
|
||||
response.headers.setdefault("Cache-Control", "public, max-age=31536000, immutable")
|
||||
elif not path.startswith("/api/") and path not in {"/health", "/ready"}:
|
||||
# index.html (and other unhashed files) must be revalidated, or a
|
||||
# browser keeps running the previous release after a deploy.
|
||||
response.headers.setdefault("Cache-Control", "no-cache")
|
||||
return response
|
||||
|
||||
|
||||
def _snapshot(service: Service) -> ServiceSnapshot:
|
||||
services = store.list_services()
|
||||
services = [item for item in store.list_services() if item.id != service.id]
|
||||
health = topology_health(store, services=[*services, service])
|
||||
dependents = [item.name for item in services if service.id in item.depends_on]
|
||||
return ServiceSnapshot(
|
||||
service=service,
|
||||
latest_probe=store.latest_probe(service.id),
|
||||
availability_24h=store.availability_summary(service.id, 24),
|
||||
dependency_status=dependency_status(service, store),
|
||||
effective_status=effective_status(service, store),
|
||||
direct_status=store.service_health(service.id),
|
||||
dependency_status=health.dependency.get(service.id, HealthStatus.UNKNOWN),
|
||||
effective_status=health.effective.get(service.id, HealthStatus.UNKNOWN),
|
||||
direct_status=health.direct.get(service.id, HealthStatus.UNKNOWN),
|
||||
flapping=service.flapping,
|
||||
flap_count=service.flap_count,
|
||||
next_probe_at=store.next_probe_at(service, PROBE_INTERVAL),
|
||||
@@ -199,6 +357,7 @@ def _snapshot(service: Service) -> ServiceSnapshot:
|
||||
evidence=discovery_store.evidence_for_service(service.id),
|
||||
health_evidence=store.health_evidence_for_service(service.id),
|
||||
health_resolution=store.health_resolution(service.id),
|
||||
maintenance_until=store.maintenance_windows().get(service.id),
|
||||
)
|
||||
|
||||
|
||||
@@ -209,9 +368,34 @@ def _name_conflict(name: str, *, exclude_id: str | None = None) -> bool:
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
"""Liveness: the process answers. Used by the container healthcheck."""
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/ready")
|
||||
def ready() -> JSONResponse:
|
||||
"""Readiness: the database takes writes and no background loop stalled.
|
||||
|
||||
A loop is stalled when it has not completed a cycle for three intervals
|
||||
(at least three minutes); its last error is included for diagnosis.
|
||||
"""
|
||||
|
||||
checks: dict[str, object] = {"loops": loop_registry.snapshot()}
|
||||
database_ok = True
|
||||
try:
|
||||
store.ready_check()
|
||||
except sqlite3.Error as exc:
|
||||
database_ok = False
|
||||
checks["database_error"] = f"{type(exc).__name__}: {exc}"
|
||||
checks["database"] = "ok" if database_ok else "unavailable"
|
||||
ok = database_ok and loop_registry.all_healthy()
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK if ok else status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
content={"status": "ready" if ok else "not_ready", **checks},
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/v1/meta")
|
||||
def meta() -> dict[str, str | int | float | bool]:
|
||||
try:
|
||||
@@ -220,7 +404,7 @@ def meta() -> dict[str, str | int | float | bool]:
|
||||
auth_mode = "misconfigured"
|
||||
return {
|
||||
"name": "ServiceMap",
|
||||
"version": "1.6.2",
|
||||
"version": "1.6.3",
|
||||
"stage": "v1",
|
||||
"scheduled_probing": PROBE_INTERVAL > 0,
|
||||
"probe_interval_seconds": PROBE_INTERVAL,
|
||||
@@ -237,9 +421,73 @@ def meta() -> dict[str, str | int | float | bool]:
|
||||
"docker_provider": docker_provider_mode(),
|
||||
"appops_configured": bool(os.getenv("SERVICEMAP_APPOPS_URL")),
|
||||
"auth_mode": auth_mode,
|
||||
# What a browser needs before it may change anything.
|
||||
"write_auth": {"token": "admin_token", "oidc": "oidc"}.get(auth_mode, "none"),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/settings/alerts", response_model=AlertSettingsView)
|
||||
def get_alert_settings() -> AlertSettingsView:
|
||||
return alert_manager().view()
|
||||
|
||||
|
||||
@app.put("/api/v1/settings/alerts", response_model=AlertSettingsView)
|
||||
def put_alert_settings(payload: AlertSettingsUpdate) -> AlertSettingsView:
|
||||
try:
|
||||
return alert_manager().update(payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.post("/api/v1/settings/alerts/test", response_model=AlertTestResult)
|
||||
def test_alert() -> AlertTestResult:
|
||||
return alert_manager().send_test()
|
||||
|
||||
|
||||
@app.get("/api/v1/backups", response_model=list[BackupInfo])
|
||||
def list_backups() -> list[BackupInfo]:
|
||||
return backup_manager().list()
|
||||
|
||||
|
||||
@app.post("/api/v1/backups", response_model=BackupInfo, status_code=status.HTTP_201_CREATED)
|
||||
def create_backup() -> BackupInfo:
|
||||
try:
|
||||
return backup_manager().create()
|
||||
except (ValueError, RuntimeError, sqlite3.Error) as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/v1/backups/{name}")
|
||||
def download_backup(name: str) -> FileResponse:
|
||||
try:
|
||||
path = backup_manager().path_for(name)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
return FileResponse(path, media_type="application/vnd.sqlite3", filename=name)
|
||||
|
||||
|
||||
@app.post("/api/v1/backups/{name}/restore", response_model=BackupInfo)
|
||||
def restore_backup(name: str) -> BackupInfo:
|
||||
"""Restore ``name`` into the live database; returns the safety copy taken first."""
|
||||
|
||||
try:
|
||||
safety = backup_manager().restore(name)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
except (RuntimeError, sqlite3.Error) as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
semantic_cache.clear()
|
||||
event_bus.publish({"event_type": "topology.changed", "message": f"Database teruggezet vanaf {name}"})
|
||||
return safety
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/verify")
|
||||
def verify_write_access() -> dict[str, bool]:
|
||||
"""Succeeds only for a caller allowed to mutate (checked by the middleware)."""
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def _service_snapshots(
|
||||
*, include_hidden: bool = False, include_context: bool = True
|
||||
) -> list[ServiceSnapshot]:
|
||||
@@ -268,6 +516,10 @@ def _service_snapshots(
|
||||
service.id: [item.name for item in services if service.id in item.depends_on]
|
||||
for service in services
|
||||
}
|
||||
visible_ids = [service.id for service in services]
|
||||
windows = store.maintenance_windows()
|
||||
sources_by_service = discovery_store.sources_for_services(visible_ids) if include_context else {}
|
||||
relations_by_service = discovery_store.evidence_for_services(visible_ids) if include_context else {}
|
||||
return [
|
||||
ServiceSnapshot(
|
||||
service=service,
|
||||
@@ -284,10 +536,11 @@ def _service_snapshots(
|
||||
else None
|
||||
),
|
||||
dependents=dependent_names.get(service.id, []),
|
||||
sources=discovery_store.sources_for_service(service.id) if include_context else [],
|
||||
evidence=discovery_store.evidence_for_service(service.id) if include_context else [],
|
||||
sources=sources_by_service.get(service.id, []),
|
||||
evidence=relations_by_service.get(service.id, []),
|
||||
health_evidence=evidence_by_service.get(service.id, []),
|
||||
health_resolution=resolutions.get(service.id, HealthResolution()),
|
||||
maintenance_until=windows.get(service.id),
|
||||
)
|
||||
for service in services
|
||||
]
|
||||
@@ -301,21 +554,21 @@ def list_services(include_hidden: bool = Query(default=False)) -> list[ServiceSn
|
||||
@app.post("/api/v1/services", response_model=Service, status_code=status.HTTP_201_CREATED)
|
||||
def create_service(payload: ServiceCreate) -> Service:
|
||||
if _name_conflict(payload.name):
|
||||
raise HTTPException(status_code=409, detail="Service name already exists")
|
||||
raise HTTPException(status_code=409, detail="Er bestaat al een service met deze naam")
|
||||
try:
|
||||
validate_dependencies(payload.depends_on, store)
|
||||
return store.create_service(payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise HTTPException(status_code=409, detail="Service name already exists") from exc
|
||||
raise HTTPException(status_code=409, detail="Er bestaat al een service met deze naam") from exc
|
||||
|
||||
|
||||
@app.get("/api/v1/services/{service_id}", response_model=ServiceSnapshot)
|
||||
def get_service(service_id: str) -> ServiceSnapshot:
|
||||
service = store.get_service(service_id)
|
||||
if service is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
return _snapshot(service)
|
||||
|
||||
|
||||
@@ -323,18 +576,18 @@ def get_service(service_id: str) -> ServiceSnapshot:
|
||||
def update_service(service_id: str, payload: ServiceUpdate) -> Service:
|
||||
before = store.get_service(service_id)
|
||||
if before is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
if _name_conflict(payload.name, exclude_id=service_id):
|
||||
raise HTTPException(status_code=409, detail="Service name already exists")
|
||||
raise HTTPException(status_code=409, detail="Er bestaat al een service met deze naam")
|
||||
try:
|
||||
validate_dependencies(payload.depends_on, store, service_id=service_id)
|
||||
updated = store.update_service(service_id, payload)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise HTTPException(status_code=409, detail="Service name already exists") from exc
|
||||
raise HTTPException(status_code=409, detail="Er bestaat al een service met deze naam") from exc
|
||||
if updated is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
if before.source_type:
|
||||
discovery_manager.record_service_override(before, updated)
|
||||
return updated
|
||||
@@ -343,7 +596,7 @@ def update_service(service_id: str, payload: ServiceUpdate) -> Service:
|
||||
@app.delete("/api/v1/services/{service_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_service(service_id: str) -> None:
|
||||
if not store.delete_service(service_id):
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
|
||||
|
||||
@app.post("/api/v1/services/{service_id}/probe", response_model=ProbeResult)
|
||||
@@ -353,10 +606,10 @@ async def run_probe(
|
||||
retries: int | None = Query(default=None, ge=0, le=5),
|
||||
) -> ProbeResult:
|
||||
if store.demo_active():
|
||||
raise HTTPException(status_code=409, detail="Explore demo uses synthetic probe data; live probing is paused")
|
||||
raise HTTPException(status_code=409, detail="De demo gebruikt synthetische controlegegevens; live controles zijn gepauzeerd")
|
||||
service = store.get_service(service_id)
|
||||
if service is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
result = await probe_service(
|
||||
service,
|
||||
timeout_seconds=timeout_seconds,
|
||||
@@ -394,21 +647,21 @@ async def run_all_probes(
|
||||
@app.get("/api/v1/services/{service_id}/history", response_model=list[ProbeResult])
|
||||
def probe_history(service_id: str, limit: int = Query(default=50, ge=1, le=500)) -> list[ProbeResult]:
|
||||
if store.get_service(service_id) is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
return store.probe_history(service_id, limit)
|
||||
|
||||
|
||||
@app.get("/api/v1/services/{service_id}/availability", response_model=AvailabilitySummary)
|
||||
def availability(service_id: str, hours: int = Query(default=24, ge=1, le=24 * 90)) -> AvailabilitySummary:
|
||||
if store.get_service(service_id) is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
return store.availability_summary(service_id, hours)
|
||||
|
||||
|
||||
@app.get("/api/v1/services/{service_id}/evidence", response_model=HealthResolution)
|
||||
def service_evidence(service_id: str) -> HealthResolution:
|
||||
if store.get_service(service_id) is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
return store.health_resolution(service_id)
|
||||
|
||||
|
||||
@@ -419,9 +672,12 @@ def providers() -> list[ProviderStatus]:
|
||||
|
||||
@app.post("/api/v1/services/{service_id}/maintenance", response_model=Service)
|
||||
def maintenance(service_id: str, payload: MaintenanceRequest) -> Service:
|
||||
updated = store.set_maintenance(service_id, payload.enabled, payload.reason)
|
||||
try:
|
||||
updated = store.set_maintenance(service_id, payload.enabled, payload.reason, payload.until)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
if updated is None:
|
||||
raise HTTPException(status_code=404, detail="Service not found")
|
||||
raise HTTPException(status_code=404, detail="Service niet gevonden")
|
||||
return updated
|
||||
|
||||
|
||||
@@ -437,7 +693,7 @@ def incidents() -> IncidentOverview:
|
||||
def get_incident(incident_id: str) -> dict[str, object]:
|
||||
incident = store.get_incident(incident_id)
|
||||
if incident is None:
|
||||
raise HTTPException(status_code=404, detail="Incident not found")
|
||||
raise HTTPException(status_code=404, detail="Incident niet gevonden")
|
||||
return {"incident": incident.model_dump(mode="json"), "timeline": [item.model_dump(mode="json") for item in store.incident_timeline(incident_id)]}
|
||||
|
||||
|
||||
@@ -448,30 +704,60 @@ def acknowledge_incident(incident_id: str) -> dict[str, object]:
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
if incident is None:
|
||||
raise HTTPException(status_code=404, detail="Incident not found")
|
||||
raise HTTPException(status_code=404, detail="Incident niet gevonden")
|
||||
return {"incident": incident.model_dump(mode="json"), "timeline": [item.model_dump(mode="json") for item in store.incident_timeline(incident_id)]}
|
||||
|
||||
|
||||
def _incident_payload(incident_id: str) -> dict[str, object]:
|
||||
incident = store.get_incident(incident_id)
|
||||
if incident is None:
|
||||
raise HTTPException(status_code=404, detail="Incident niet gevonden")
|
||||
return {
|
||||
"incident": incident.model_dump(mode="json"),
|
||||
"timeline": [item.model_dump(mode="json") for item in store.incident_timeline(incident_id)],
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/v1/incidents/{incident_id}/resolve")
|
||||
def resolve_incident(incident_id: str, payload: IncidentResolveRequest | None = None) -> dict[str, object]:
|
||||
if store.resolve_incident(incident_id, payload.note if payload else None) is None:
|
||||
raise HTTPException(status_code=404, detail="Incident niet gevonden")
|
||||
return _incident_payload(incident_id)
|
||||
|
||||
|
||||
@app.post("/api/v1/incidents/{incident_id}/notes")
|
||||
def add_incident_note(incident_id: str, payload: IncidentNoteRequest) -> dict[str, object]:
|
||||
if store.add_incident_note(incident_id, payload.text.strip()) is None:
|
||||
raise HTTPException(status_code=404, detail="Incident niet gevonden")
|
||||
return _incident_payload(incident_id)
|
||||
|
||||
|
||||
@app.get("/api/v1/events", response_model=list[EventRecord])
|
||||
def events(limit: int = Query(default=50, ge=1, le=500), service_id: str | None = None) -> list[EventRecord]:
|
||||
return store.list_events(limit=limit, service_id=service_id)
|
||||
def events(
|
||||
limit: int = Query(default=50, ge=1, le=500),
|
||||
service_id: str | None = None,
|
||||
event_type: str | None = Query(default=None, max_length=80),
|
||||
before: datetime | None = None,
|
||||
) -> list[EventRecord]:
|
||||
return store.list_events(limit=limit, service_id=service_id, event_type=event_type, before=before)
|
||||
|
||||
|
||||
@app.get("/api/v1/events/stream")
|
||||
async def event_stream() -> StreamingResponse:
|
||||
queue = event_bus.subscribe()
|
||||
subscription = event_bus.subscribe()
|
||||
|
||||
async def stream():
|
||||
try:
|
||||
yield ": connected\n\n"
|
||||
# ``retry`` tells EventSource how long to wait before reconnecting.
|
||||
yield f"retry: {SSE_RETRY_MS}\n: connected\n\n"
|
||||
while True:
|
||||
payload = await next_event(queue)
|
||||
payload = await next_event(subscription)
|
||||
if payload is None:
|
||||
yield ": keepalive\n\n"
|
||||
else:
|
||||
yield sse_payload(payload)
|
||||
finally:
|
||||
event_bus.unsubscribe(queue)
|
||||
event_bus.unsubscribe(subscription)
|
||||
|
||||
return StreamingResponse(
|
||||
stream(),
|
||||
@@ -483,7 +769,8 @@ async def event_stream() -> StreamingResponse:
|
||||
@app.get("/api/v1/overview", response_model=OverviewSummary)
|
||||
def overview() -> OverviewSummary:
|
||||
sync_incidents(store)
|
||||
snapshots = _service_snapshots(include_hidden=False)
|
||||
# Only status and coverage are counted; discovery context is not needed.
|
||||
snapshots = _service_snapshots(include_hidden=False, include_context=False)
|
||||
overview_state = incident_overview(store)
|
||||
counts: dict[str, int] = {}
|
||||
coverage: dict[str, int] = {}
|
||||
@@ -521,14 +808,20 @@ def import_config(payload: ConfigImportRequest) -> ConfigImportResult:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
|
||||
def _demo_enabled() -> bool:
|
||||
return os.getenv("SERVICEMAP_DEMO_ENABLED", "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _demo_state() -> DemoState:
|
||||
enabled = _demo_enabled()
|
||||
if not store.demo_active():
|
||||
return DemoState(active=False)
|
||||
return DemoState(active=False, enabled=enabled)
|
||||
sync_incidents(store)
|
||||
overview_state = incident_overview(store)
|
||||
candidate = overview_state.candidates[0] if overview_state.candidates else None
|
||||
return DemoState(
|
||||
active=True,
|
||||
enabled=enabled,
|
||||
synthetic=True,
|
||||
scenario_name=DEMO_SCENARIO_NAME,
|
||||
service_count=len(store.list_services()),
|
||||
@@ -557,15 +850,10 @@ def demo_state() -> DemoState:
|
||||
|
||||
|
||||
@app.post("/api/v1/demo", response_model=DemoMutationResult)
|
||||
def load_demo() -> DemoMutationResult:
|
||||
services, probes = build_demo_records()
|
||||
result = store.activate_demo(services, probes)
|
||||
sync_incidents(store)
|
||||
return _demo_result(result)
|
||||
|
||||
|
||||
@app.post("/api/v1/demo/reset", response_model=DemoMutationResult)
|
||||
def reset_demo() -> DemoMutationResult:
|
||||
def load_demo() -> DemoMutationResult:
|
||||
if not _demo_enabled():
|
||||
raise HTTPException(status_code=409, detail="Start de demo in een aparte ServiceMap-instantie")
|
||||
services, probes = build_demo_records()
|
||||
result = store.activate_demo(services, probes)
|
||||
sync_incidents(store)
|
||||
@@ -578,7 +866,7 @@ async def exit_demo() -> DemoMutationResult:
|
||||
# Refresh live provider evidence immediately after restoring the saved
|
||||
# production topology. Test stores intentionally do not inherit the
|
||||
# process-global observer, but production always does.
|
||||
if restored and observation_manager.store is store:
|
||||
if restored and OBSERVATION_INTERVAL > 0 and observation_manager.store is store:
|
||||
await asyncio.to_thread(observation_manager.refresh)
|
||||
return _demo_result(restored=restored)
|
||||
|
||||
@@ -586,7 +874,7 @@ async def exit_demo() -> DemoMutationResult:
|
||||
@app.post("/api/v1/discovery/run", response_model=DiscoveryResult)
|
||||
def run_discovery(payload: DiscoveryRunRequest | None = None) -> DiscoveryResult:
|
||||
if store.demo_active():
|
||||
raise HTTPException(status_code=409, detail="Exit Explore demo before discovering production infrastructure")
|
||||
raise HTTPException(status_code=409, detail="Sluit de demo af voor je de productie-infrastructuur detecteert")
|
||||
request = payload or DiscoveryRunRequest()
|
||||
_require_configured_discovery_targets(request.docker_host, request.appops_url)
|
||||
try:
|
||||
@@ -613,7 +901,7 @@ def discovery_suggestions(
|
||||
try:
|
||||
suggestion_status = SuggestionStatus(status_filter) if status_filter else None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail="Unknown suggestion status") from exc
|
||||
raise HTTPException(status_code=422, detail="Onbekende status van het voorstel") from exc
|
||||
return discovery_store.list_suggestions(status=suggestion_status)
|
||||
|
||||
|
||||
@@ -636,7 +924,7 @@ def reject_discovery_suggestion(suggestion_id: str) -> TopologySuggestion:
|
||||
@app.post("/api/v1/discovery/reconcile", response_model=ReconcileResult)
|
||||
def reconcile_discovery(payload: DiscoveryReconcileRequest | None = None) -> ReconcileResult:
|
||||
if store.demo_active():
|
||||
raise HTTPException(status_code=409, detail="Exit Explore demo before reconciling production infrastructure")
|
||||
raise HTTPException(status_code=409, detail="Sluit de demo af voor je de productie-infrastructuur verwerkt")
|
||||
try:
|
||||
return discovery_manager.reconcile(payload or DiscoveryReconcileRequest())
|
||||
except ValueError as exc:
|
||||
@@ -649,7 +937,7 @@ def repair_discovered_probes(
|
||||
run_id: str | None = Query(default=None),
|
||||
) -> ProbeRepairReport:
|
||||
if store.demo_active():
|
||||
raise HTTPException(status_code=409, detail="Exit Explore demo before repairing production probe endpoints")
|
||||
raise HTTPException(status_code=409, detail="Sluit de demo af voor je controle-endpoints in productie herstelt")
|
||||
try:
|
||||
return discovery_manager.repair_probe_reachability(run_id=run_id, dry_run=dry_run)
|
||||
except ValueError as exc:
|
||||
@@ -686,8 +974,14 @@ def topology_diff(
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/api/v1/topology/semantic", response_model=SemanticTopology)
|
||||
def semantic_topology(include_hidden: bool = Query(default=False)) -> SemanticTopology:
|
||||
def _semantic_representation(include_hidden: bool) -> CachedRepresentation:
|
||||
revision = event_bus.revision
|
||||
# The store identity keeps a swapped store (tests, demo restore paths)
|
||||
# from ever reading another database's cached topology.
|
||||
cache_key = (id(store), include_hidden)
|
||||
cached = semantic_cache.get(cache_key, revision)
|
||||
if cached is not None:
|
||||
return cached
|
||||
snapshots = _service_snapshots(include_hidden=include_hidden, include_context=False)
|
||||
incident_state = incident_overview(store)
|
||||
root_ids = {candidate.service_id for candidate in incident_state.candidates}
|
||||
@@ -696,12 +990,48 @@ def semantic_topology(include_hidden: bool = Query(default=False)) -> SemanticTo
|
||||
for candidate in incident_state.candidates
|
||||
for service_id in candidate.affected_service_ids
|
||||
}
|
||||
return build_semantic_topology(
|
||||
topology = build_semantic_topology(
|
||||
snapshots,
|
||||
discovery_store.list_logical_relations(),
|
||||
root_service_ids=root_ids,
|
||||
affected_service_ids=affected_ids,
|
||||
)
|
||||
value = representation(topology)
|
||||
boundary = next_freshness_boundary(
|
||||
[item for snapshot in snapshots for item in snapshot.health_evidence],
|
||||
topology.generated_at,
|
||||
)
|
||||
semantic_cache.put(
|
||||
cache_key,
|
||||
revision,
|
||||
value,
|
||||
valid_for_seconds=(
|
||||
(boundary - topology.generated_at).total_seconds() if boundary is not None else None
|
||||
),
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
@app.get("/api/v1/topology/semantic", response_model=SemanticTopology)
|
||||
def semantic_topology(
|
||||
request: Request, include_hidden: bool = Query(default=False)
|
||||
) -> Response:
|
||||
"""Semantic topology with a content ETag and conditional GET support.
|
||||
|
||||
Clients that send ``If-None-Match`` receive ``304`` without a body while
|
||||
the topology is unchanged; ``X-ServiceMap-Generated-At`` then states when
|
||||
the server last verified it. Browsers revalidate automatically.
|
||||
"""
|
||||
|
||||
value = _semantic_representation(include_hidden)
|
||||
headers = {
|
||||
"ETag": value.etag,
|
||||
"Cache-Control": "no-cache",
|
||||
GENERATED_AT_HEADER: value.generated_at,
|
||||
}
|
||||
if etag_matches(request.headers.get("if-none-match"), value.etag):
|
||||
return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers=headers)
|
||||
return Response(content=value.body, media_type="application/json", headers=headers)
|
||||
|
||||
|
||||
@app.post("/api/v1/topology/edges", response_model=RelationEvidence, status_code=status.HTTP_201_CREATED)
|
||||
|
||||
+28
-14
@@ -190,8 +190,8 @@ class RelationType(StrEnum):
|
||||
class ServiceCreate(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
kind: ServiceKind
|
||||
url: str | None = None
|
||||
host: str | None = Field(default=None, validation_alias=AliasChoices("host", "hostname"))
|
||||
url: str | None = Field(default=None, max_length=2048)
|
||||
host: str | None = Field(default=None, max_length=253, validation_alias=AliasChoices("host", "hostname"))
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
depends_on: list[str] = Field(default_factory=list)
|
||||
description: str | None = Field(default=None, max_length=500)
|
||||
@@ -243,27 +243,27 @@ class ServiceCreate(BaseModel):
|
||||
if not self.monitoring_enabled and not self.url and not self.host and self.port is None:
|
||||
return self
|
||||
if self.kind == ServiceKind.HTTP and not self.url:
|
||||
raise ValueError("HTTP services require url")
|
||||
raise ValueError("HTTP-services vragen een url")
|
||||
if self.kind == ServiceKind.HTTP:
|
||||
parsed = urlparse(self.url or "")
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("HTTP services require an absolute http(s) url")
|
||||
raise ValueError("HTTP-services vragen een absolute http(s)-url")
|
||||
if self.host or self.port:
|
||||
raise ValueError("HTTP services must use url instead of host/port")
|
||||
raise ValueError("HTTP-services gebruiken url in plaats van host/poort")
|
||||
if self.kind in {ServiceKind.TCP, ServiceKind.TLS} and (not self.host or self.port is None):
|
||||
raise ValueError(f"{self.kind.value.upper()} services require host and port")
|
||||
raise ValueError(f"{self.kind.value.upper()} services vragen een host en poort")
|
||||
if self.kind == ServiceKind.DNS and not self.host:
|
||||
raise ValueError("DNS services require hostname in host")
|
||||
raise ValueError("DNS-services vragen een hostnaam in host")
|
||||
if self.kind in {ServiceKind.TCP, ServiceKind.TLS, ServiceKind.DNS} and self.url:
|
||||
raise ValueError(f"{self.kind.value.upper()} services must use host/port instead of url")
|
||||
raise ValueError(f"{self.kind.value.upper()} services gebruiken host/poort in plaats van url")
|
||||
if self.kind == ServiceKind.DNS and self.port is not None:
|
||||
raise ValueError("DNS services use a hostname without a port")
|
||||
raise ValueError("DNS-services gebruiken een hostnaam zonder poort")
|
||||
if (
|
||||
self.expected_status_min is not None
|
||||
and self.expected_status_max is not None
|
||||
and self.expected_status_min > self.expected_status_max
|
||||
):
|
||||
raise ValueError("expected_status_min cannot exceed expected_status_max")
|
||||
raise ValueError("expected_status_min mag niet groter zijn dan expected_status_max")
|
||||
return self
|
||||
|
||||
|
||||
@@ -327,7 +327,7 @@ class HealthResolution(BaseModel):
|
||||
selected_provider: EvidenceProvider | None = None
|
||||
confidence: float | None = Field(default=None, ge=0, le=1)
|
||||
reason_code: HealthResolutionReason = HealthResolutionReason.NO_CURRENT_COMPONENT_EVIDENCE
|
||||
explanation: str = "No current component-scoped health evidence is available."
|
||||
explanation: str = "Er is geen actueel gezondheidsbewijs op componentniveau."
|
||||
conflict: bool = False
|
||||
evidence: list[HealthEvidence] = Field(default_factory=list)
|
||||
|
||||
@@ -337,7 +337,7 @@ class ApplicationHealthResolution(BaseModel):
|
||||
|
||||
status: HealthStatus = HealthStatus.UNKNOWN
|
||||
confidence: float | None = Field(default=None, ge=0, le=1)
|
||||
explanation: str = "No current application or component health evidence is available."
|
||||
explanation: str = "Er is geen actueel gezondheidsbewijs voor applicatie of componenten."
|
||||
reason_code: HealthResolutionReason = HealthResolutionReason.NO_APPLICATION_EVIDENCE
|
||||
selected_evidence_id: str | None = None
|
||||
selected_provider: EvidenceProvider | None = None
|
||||
@@ -372,6 +372,8 @@ class ServiceSnapshot(BaseModel):
|
||||
evidence: list[RelationEvidence] = Field(default_factory=list)
|
||||
health_evidence: list[HealthEvidence] = Field(default_factory=list)
|
||||
health_resolution: HealthResolution = Field(default_factory=HealthResolution)
|
||||
# End of a scheduled maintenance window, if one is set.
|
||||
maintenance_until: datetime | None = None
|
||||
|
||||
|
||||
class AvailabilitySummary(BaseModel):
|
||||
@@ -658,7 +660,7 @@ class EdgeMutationRequest(BaseModel):
|
||||
target_service_id: str
|
||||
relation_type: RelationType = RelationType.DEPENDS_ON
|
||||
lock: bool = True
|
||||
explanation: str = Field(default="Manual topology relationship", max_length=500)
|
||||
explanation: str = Field(default="Handmatige topologierelatie", max_length=500)
|
||||
|
||||
|
||||
class EdgeActionRequest(BaseModel):
|
||||
@@ -678,7 +680,8 @@ class ConfigDocument(BaseModel):
|
||||
|
||||
|
||||
class ConfigImportRequest(BaseModel):
|
||||
content: str
|
||||
# About 2 MB of YAML/JSON is far beyond any real topology.
|
||||
content: str = Field(max_length=2_000_000)
|
||||
format: str = Field(pattern="^(yaml|json)$")
|
||||
mode: str = Field(default="merge", pattern="^(merge|replace)$")
|
||||
|
||||
@@ -691,6 +694,7 @@ class ConfigImportResult(BaseModel):
|
||||
|
||||
class DemoState(BaseModel):
|
||||
active: bool
|
||||
enabled: bool = False
|
||||
synthetic: bool = False
|
||||
scenario_name: str | None = None
|
||||
service_count: int = 0
|
||||
@@ -860,3 +864,13 @@ class OverviewSummary(BaseModel):
|
||||
class MaintenanceRequest(BaseModel):
|
||||
enabled: bool
|
||||
reason: str | None = Field(default=None, max_length=240)
|
||||
# Optional end of the window; maintenance ends automatically afterwards.
|
||||
until: datetime | None = None
|
||||
|
||||
|
||||
class IncidentNoteRequest(BaseModel):
|
||||
text: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
class IncidentResolveRequest(BaseModel):
|
||||
note: str | None = Field(default=None, max_length=2000)
|
||||
@@ -111,14 +111,14 @@ class ObservationManager:
|
||||
and not docker_observations
|
||||
and any(ref.startswith("docker:") for ref in services_by_ref)
|
||||
):
|
||||
raise ValueError("Docker broker returned no containers for configured services")
|
||||
raise ValueError("De Docker-broker gaf geen containers terug voor de ingestelde services")
|
||||
self.store.set_provider_status(
|
||||
ProviderStatus(
|
||||
provider=EvidenceProvider.DOCKER,
|
||||
status=ProviderHealth.HEALTHY,
|
||||
observed_at=now,
|
||||
valid_until=valid_until,
|
||||
detail=f"{len(docker_observations)} containers observed",
|
||||
detail=f"{len(docker_observations)} containers waargenomen",
|
||||
metadata={"container_count": len(docker_observations)},
|
||||
)
|
||||
)
|
||||
@@ -147,7 +147,7 @@ class ObservationManager:
|
||||
observed_at=now,
|
||||
valid_until=valid_until,
|
||||
received_at=now,
|
||||
summary="Docker healthcheck" if observation.healthcheck_present else "Docker runtime state",
|
||||
summary="Docker-healthcheck" if observation.healthcheck_present else "Docker-runtimestatus",
|
||||
metadata={
|
||||
"container_id": observation.container_id,
|
||||
"state": observation.state,
|
||||
@@ -190,7 +190,7 @@ class ObservationManager:
|
||||
observed_at=now,
|
||||
valid_until=valid_until,
|
||||
received_at=now,
|
||||
summary="AppOps application health; never used as component direct health",
|
||||
summary="Applicatiegezondheid via AppOps; nooit gebruikt als directe componentgezondheid",
|
||||
metadata={
|
||||
"app_id": app_id,
|
||||
"category": info.category,
|
||||
|
||||
+41
-8
@@ -41,10 +41,36 @@ def _http_status(status_code: int, service: Service) -> HealthStatus:
|
||||
return HealthStatus.DOWN
|
||||
|
||||
|
||||
_MAX_BODY_BYTES = 64 * 1024
|
||||
_SSL_CONTEXT: ssl.SSLContext | None = None
|
||||
|
||||
|
||||
def _ssl_context() -> ssl.SSLContext:
|
||||
"""Build the CA bundle context once instead of on every HTTP probe."""
|
||||
|
||||
global _SSL_CONTEXT
|
||||
if _SSL_CONTEXT is None:
|
||||
import certifi
|
||||
|
||||
_SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
|
||||
return _SSL_CONTEXT
|
||||
|
||||
|
||||
async def _probe_once_with_metadata(service: Service, timeout_seconds: float) -> tuple[HealthStatus, str, dict[str, object]]:
|
||||
if service.kind == ServiceKind.HTTP:
|
||||
async with httpx.AsyncClient(timeout=timeout_seconds, follow_redirects=True) as client:
|
||||
response = await client.get(service.url or "")
|
||||
# One overall deadline (httpx timeouts are per phase, so a slow-drip
|
||||
# body could run for many times the timeout) and a bounded body read:
|
||||
# the status line answers the health question.
|
||||
async with asyncio.timeout(timeout_seconds):
|
||||
async with httpx.AsyncClient(
|
||||
timeout=timeout_seconds, follow_redirects=True, max_redirects=5, verify=_ssl_context()
|
||||
) as client:
|
||||
async with client.stream("GET", service.url or "") as response:
|
||||
received = 0
|
||||
async for chunk in response.aiter_raw():
|
||||
received += len(chunk)
|
||||
if received >= _MAX_BODY_BYTES:
|
||||
break
|
||||
status = _http_status(response.status_code, service)
|
||||
return status, f"HTTP {response.status_code}", {"status_code": response.status_code}
|
||||
|
||||
@@ -72,7 +98,7 @@ async def _probe_once_with_metadata(service: Service, timeout_seconds: float) ->
|
||||
del reader
|
||||
ssl_object = writer.get_extra_info("ssl_object")
|
||||
metadata: dict[str, object] = {"hostname": service.host, "port": service.port}
|
||||
detail = f"TLS {service.host}:{service.port} certificate reachable"
|
||||
detail = f"TLS-certificaat van {service.host}:{service.port} bereikbaar"
|
||||
status = HealthStatus.HEALTHY
|
||||
if ssl_object is not None:
|
||||
certificate = ssl_object.getpeercert() or {}
|
||||
@@ -84,10 +110,10 @@ async def _probe_once_with_metadata(service: Service, timeout_seconds: float) ->
|
||||
warning_days = max(1, int(os.getenv("SERVICEMAP_TLS_WARNING_DAYS", "30")))
|
||||
if days_remaining <= 0:
|
||||
status = HealthStatus.DOWN
|
||||
detail = f"TLS certificate expired on {expires_at.date().isoformat()}"
|
||||
detail = f"TLS-certificaat verlopen op {expires_at.date().isoformat()}"
|
||||
elif days_remaining <= warning_days:
|
||||
status = HealthStatus.DEGRADED
|
||||
detail = f"TLS certificate expires in {round(days_remaining, 1)} days"
|
||||
detail = f"TLS-certificaat verloopt over {round(days_remaining, 1)} dagen"
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return status, detail, metadata
|
||||
@@ -122,7 +148,7 @@ async def probe_service(
|
||||
service_id=service.id,
|
||||
status=HealthStatus.UNKNOWN,
|
||||
latency_ms=None,
|
||||
detail="Monitoring disabled for service",
|
||||
detail="Bewaking uitgeschakeld voor deze service",
|
||||
checked_at=datetime.now(UTC),
|
||||
trigger=trigger,
|
||||
)
|
||||
@@ -132,7 +158,7 @@ async def probe_service(
|
||||
retry_count = retry_count if retry_count is not None else default_retries
|
||||
attempts = max(1, retry_count + 1)
|
||||
status = HealthStatus.DOWN
|
||||
detail = "Probe failed"
|
||||
detail = "Controle mislukt"
|
||||
latency_ms: float | None = None
|
||||
metadata: dict[str, object] = {}
|
||||
|
||||
@@ -152,9 +178,16 @@ async def probe_service(
|
||||
detail = f"{type(exc).__name__}: {exc}"
|
||||
if isinstance(exc, ssl.CertificateError):
|
||||
status = HealthStatus.DOWN
|
||||
detail = f"TLS hostname mismatch: {exc}"
|
||||
detail = f"TLS-hostnaam komt niet overeen: {exc}"
|
||||
if attempt < attempts:
|
||||
await asyncio.sleep(min(0.2 * attempt, 1.0))
|
||||
except Exception as exc: # noqa: BLE001 - one bad target must not fail a whole cycle
|
||||
# e.g. httpx.InvalidURL or an IDNA UnicodeError: a permanent
|
||||
# configuration error, reported as down without retrying.
|
||||
latency_ms = round((perf_counter() - started) * 1000, 2)
|
||||
status = HealthStatus.DOWN
|
||||
detail = f"Controlefout ({type(exc).__name__}): {exc}"
|
||||
break
|
||||
|
||||
return ProbeResult(
|
||||
id=str(uuid4()),
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Validated, briefly cached JSON representations for hot read endpoints.
|
||||
|
||||
The semantic topology is read by the UI after every event burst and by
|
||||
integrations such as ITWorx Forge on a fixed poll. Its content changes far
|
||||
less often than it is read: in production only ``generated_at`` differed
|
||||
between polls. Two mechanisms make an unchanged read nearly free:
|
||||
|
||||
* A strong ``ETag`` computed over the content *excluding* ``generated_at``.
|
||||
A client that sends ``If-None-Match`` gets ``304 Not Modified`` with no
|
||||
body. Because the tag is derived from the content itself it is always
|
||||
correct, including after writes that publish no event.
|
||||
* A short-lived computation cache. It is reused only while no event has
|
||||
been published since it was built, no evidence freshness boundary
|
||||
(fresh→stale→expired) has been crossed, and it is younger than
|
||||
``max_age_seconds``. The age cap bounds staleness for the few write paths
|
||||
that publish no event (for example discovery relation evidence).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from threading import Lock
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .models import HealthEvidence
|
||||
|
||||
GENERATED_AT_HEADER = "X-ServiceMap-Generated-At"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CachedRepresentation:
|
||||
body: bytes
|
||||
etag: str
|
||||
generated_at: str
|
||||
|
||||
|
||||
def representation(model: BaseModel, *, timestamp_field: str = "generated_at") -> CachedRepresentation:
|
||||
"""Serialize once and tag the content independent of its timestamp."""
|
||||
|
||||
content = model.model_dump_json(exclude={timestamp_field})
|
||||
stamp = model.model_dump_json(include={timestamp_field})
|
||||
# Splice ``{"generated_at": ...}`` in front of the remaining fields: one
|
||||
# serialization for the body, the hash covers everything but the stamp.
|
||||
body = stamp if content == "{}" else f"{stamp[:-1]},{content[1:]}"
|
||||
digest = hashlib.sha256(content.encode()).hexdigest()[:32]
|
||||
generated_at = str(getattr(model, timestamp_field).isoformat())
|
||||
return CachedRepresentation(body=body.encode(), etag=f'"{digest}"', generated_at=generated_at)
|
||||
|
||||
|
||||
def etag_matches(if_none_match: str | None, etag: str) -> bool:
|
||||
if not if_none_match:
|
||||
return False
|
||||
for candidate in if_none_match.split(","):
|
||||
value = candidate.strip()
|
||||
if value == "*" or value.removeprefix("W/") == etag:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def next_freshness_boundary(evidence: list[HealthEvidence], now: datetime) -> datetime | None:
|
||||
"""Earliest future instant at which any claim changes freshness."""
|
||||
|
||||
boundary: datetime | None = None
|
||||
for item in evidence:
|
||||
ttl = max(item.valid_until - item.observed_at, timedelta(seconds=1))
|
||||
for instant in (item.valid_until, item.valid_until + ttl):
|
||||
if instant > now and (boundary is None or instant < boundary):
|
||||
boundary = instant
|
||||
return boundary
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Entry:
|
||||
value: CachedRepresentation
|
||||
revision: int
|
||||
expires_at: float
|
||||
|
||||
|
||||
class RepresentationCache:
|
||||
"""Thread-safe cache keyed by request variant and event revision."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
max_age_seconds: float = 10.0,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
) -> None:
|
||||
self.max_age_seconds = max_age_seconds
|
||||
self._clock = clock
|
||||
self._entries: dict[object, _Entry] = {}
|
||||
self._lock = Lock()
|
||||
|
||||
def get(self, key: object, revision: int) -> CachedRepresentation | None:
|
||||
with self._lock:
|
||||
entry = self._entries.get(key)
|
||||
if entry is None:
|
||||
return None
|
||||
if entry.revision != revision or self._clock() >= entry.expires_at:
|
||||
del self._entries[key]
|
||||
return None
|
||||
return entry.value
|
||||
|
||||
def put(
|
||||
self,
|
||||
key: object,
|
||||
revision: int,
|
||||
value: CachedRepresentation,
|
||||
*,
|
||||
valid_for_seconds: float | None = None,
|
||||
) -> None:
|
||||
ttl = self.max_age_seconds if valid_for_seconds is None else min(self.max_age_seconds, valid_for_seconds)
|
||||
if ttl <= 0:
|
||||
return
|
||||
with self._lock:
|
||||
self._entries[key] = _Entry(value=value, revision=revision, expires_at=self._clock() + ttl)
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._entries.clear()
|
||||
@@ -7,7 +7,7 @@ from time import monotonic
|
||||
from .probes import probe_many
|
||||
from .store import Store
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger = logging.getLogger("servicemap.scheduler")
|
||||
|
||||
|
||||
async def scheduled_probe_loop(
|
||||
@@ -18,6 +18,7 @@ async def scheduled_probe_loop(
|
||||
retries: int,
|
||||
concurrency: int,
|
||||
retention_days: int,
|
||||
event_retention_days: int | None = None,
|
||||
) -> None:
|
||||
next_due: dict[str, float] = {}
|
||||
while True:
|
||||
@@ -58,7 +59,12 @@ async def scheduled_probe_loop(
|
||||
sleep_seconds = min([interval_seconds, *next_intervals]) if next_intervals else interval_seconds
|
||||
else:
|
||||
sleep_seconds = interval_seconds
|
||||
if event_retention_days is None:
|
||||
store.prune_probes(retention_days)
|
||||
else:
|
||||
# Events have their own (longer) retention; pruning them at the
|
||||
# probe retention silently shortened the journal.
|
||||
store.prune_probes(retention_days, event_retention_days)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception: # pragma: no cover - defensive daemon boundary
|
||||
|
||||
@@ -214,7 +214,7 @@ def _application_resolution(
|
||||
return ApplicationHealthResolution(
|
||||
status=status,
|
||||
confidence=max((item.health_resolution.confidence or 1.0 for item in direct_down), default=None),
|
||||
explanation=f"{names} has current component failure evidence; aggregate health does not override it.",
|
||||
explanation=f"{names} heeft actueel bewijs van een componentstoring; de totale gezondheid overschrijft dat niet.",
|
||||
reason_code=HealthResolutionReason.COMPONENT_FAILURE,
|
||||
**common,
|
||||
)
|
||||
@@ -223,7 +223,7 @@ def _application_resolution(
|
||||
return ApplicationHealthResolution(
|
||||
status=HealthStatus.DEGRADED,
|
||||
confidence=selected.confidence if selected else None,
|
||||
explanation=f"{names} is impacted through a dependency health signal.",
|
||||
explanation=f"{names} wordt geraakt via het gezondheidssignaal van een afhankelijkheid.",
|
||||
reason_code=HealthResolutionReason.COMPONENT_IMPACT,
|
||||
**common,
|
||||
)
|
||||
@@ -232,8 +232,8 @@ def _application_resolution(
|
||||
status=selected.status,
|
||||
confidence=selected.confidence,
|
||||
explanation=(
|
||||
f"{selected.provider.value} application observation selected "
|
||||
f"(confidence {selected.confidence:.2f}); component coverage is {coverage:.0f}% ."
|
||||
f"{selected.provider.value} applicatiewaarneming gekozen "
|
||||
f"(zekerheid {selected.confidence:.2f}); componentdekking is {coverage:.0f}%."
|
||||
),
|
||||
reason_code=HealthResolutionReason.SELECTED_APPLICATION_EVIDENCE,
|
||||
**common,
|
||||
@@ -244,7 +244,7 @@ def _application_resolution(
|
||||
status = HealthStatus.DEGRADED
|
||||
return ApplicationHealthResolution(
|
||||
status=status,
|
||||
explanation=f"{len(resolved)} of {len(members)} components have current direct health evidence.",
|
||||
explanation=f"{len(resolved)} van {len(members)} componenten hebben actueel direct gezondheidsbewijs.",
|
||||
reason_code=HealthResolutionReason.COMPONENT_COVERAGE,
|
||||
**common,
|
||||
)
|
||||
@@ -257,20 +257,20 @@ def _application_resolution(
|
||||
)
|
||||
return ApplicationHealthResolution(
|
||||
status=HealthStatus.UNKNOWN,
|
||||
explanation="Application evidence is no longer current; waiting for a provider refresh.",
|
||||
explanation="Het applicatiebewijs is niet meer actueel; wachten op een nieuwe meting van de bron.",
|
||||
reason_code=reason,
|
||||
**common,
|
||||
)
|
||||
if members and all(item.direct_status == HealthStatus.UNMONITORED for item in members):
|
||||
return ApplicationHealthResolution(
|
||||
status=HealthStatus.UNMONITORED,
|
||||
explanation="No active health signal is configured for this application.",
|
||||
explanation="Voor deze applicatie is geen actief gezondheidssignaal ingesteld.",
|
||||
reason_code=HealthResolutionReason.NO_APPLICATION_EVIDENCE,
|
||||
**common,
|
||||
)
|
||||
return ApplicationHealthResolution(
|
||||
status=HealthStatus.UNKNOWN,
|
||||
explanation="No current application or component health evidence is available.",
|
||||
explanation="Er is geen actueel gezondheidsbewijs voor applicatie of componenten.",
|
||||
reason_code=HealthResolutionReason.NO_APPLICATION_EVIDENCE,
|
||||
**common,
|
||||
)
|
||||
|
||||
+267
-46
@@ -52,6 +52,16 @@ def _iso(value: datetime | None) -> str | None:
|
||||
return value.isoformat() if value is not None else None
|
||||
|
||||
|
||||
# Per-observation bookkeeping that changes on every probe. It is stored, but a
|
||||
# change in only these keys is not a material evidence change and must not
|
||||
# publish an SSE wakeup (that turned every probe into a full UI refresh).
|
||||
VOLATILE_EVIDENCE_METADATA = frozenset({"probe_id", "latency_ms", "trigger"})
|
||||
|
||||
|
||||
def _stable_metadata(metadata: dict[str, object]) -> dict[str, object]:
|
||||
return {key: value for key, value in metadata.items() if key not in VOLATILE_EVIDENCE_METADATA}
|
||||
|
||||
|
||||
def _bool(value: object, default: bool = False) -> bool:
|
||||
if value is None:
|
||||
return default
|
||||
@@ -70,14 +80,24 @@ class Store:
|
||||
connection.row_factory = sqlite3.Row
|
||||
connection.execute("PRAGMA foreign_keys = ON")
|
||||
connection.execute("PRAGMA busy_timeout = 5000")
|
||||
# Per connection, not persistent: without this every commit ran at
|
||||
# the FULL default (an fsync per write). NORMAL is durable under WAL.
|
||||
connection.execute("PRAGMA synchronous = NORMAL")
|
||||
return connection
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
with self._connect() as db:
|
||||
db.execute("PRAGMA journal_mode = WAL")
|
||||
db.execute("PRAGMA synchronous = NORMAL")
|
||||
# Bound the WAL file after checkpoints (64 MiB).
|
||||
db.execute("PRAGMA journal_size_limit = 67108864")
|
||||
db.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS maintenance_windows (
|
||||
service_id TEXT PRIMARY KEY,
|
||||
ends_at TEXT NOT NULL,
|
||||
FOREIGN KEY(service_id) REFERENCES services(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS services (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
@@ -770,7 +790,7 @@ class Store:
|
||||
with self._connect() as db:
|
||||
self._upsert_service(db, updated)
|
||||
self._insert_event_db(db, "topology.changed", service_id, None, None, None, f"Service {updated.name} updated", {})
|
||||
event_bus.publish({"event_type": "topology.changed", "service_id": service_id, "message": "Service updated"})
|
||||
event_bus.publish({"event_type": "topology.changed", "service_id": service_id, "message": "Service bijgewerkt"})
|
||||
return updated
|
||||
|
||||
def delete_service(self, service_id: str) -> bool:
|
||||
@@ -787,14 +807,24 @@ class Store:
|
||||
"UPDATE services SET depends_on = ?, updated_at = ? WHERE id = ?",
|
||||
(json.dumps([value for value in dependencies if value != service_id]), _now().isoformat(), item["id"]),
|
||||
)
|
||||
db.execute("UPDATE incidents SET affected_service_ids = replace(affected_service_ids, ?, '') WHERE status != 'resolved'", (service_id,))
|
||||
# Remove the id as a JSON element. A textual replace() left an
|
||||
# empty-string entry behind (["a","b"] -> ["","b"]).
|
||||
for incident in db.execute(
|
||||
"SELECT id, affected_service_ids FROM incidents WHERE status != 'resolved'"
|
||||
).fetchall():
|
||||
affected = self._json_list(incident["affected_service_ids"])
|
||||
if service_id in affected:
|
||||
db.execute(
|
||||
"UPDATE incidents SET affected_service_ids = ? WHERE id = ?",
|
||||
(json.dumps([value for value in affected if value != service_id]), incident["id"]),
|
||||
)
|
||||
self._insert_event_db(db, "topology.changed", service_id, None, None, None, f"Service {row['name']} deleted", {})
|
||||
event_bus.publish({"event_type": "topology.changed", "service_id": service_id, "message": "Service deleted"})
|
||||
event_bus.publish({"event_type": "topology.changed", "service_id": service_id, "message": "Service verwijderd"})
|
||||
return True
|
||||
|
||||
def import_config_services(self, definitions: list[ConfigService], mode: str) -> ConfigImportResult:
|
||||
if mode not in {"merge", "replace"}:
|
||||
raise ValueError("Import mode must be merge or replace")
|
||||
raise ValueError("Importmodus moet merge of replace zijn")
|
||||
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
@@ -813,7 +843,7 @@ class Store:
|
||||
missing = [item for item in definition.depends_on if item.casefold() not in ids_by_name]
|
||||
if missing:
|
||||
raise ValueError(
|
||||
f"Service {definition.name} references unknown dependencies: {', '.join(missing)}"
|
||||
f"Service {definition.name} verwijst naar onbekende afhankelijkheden: {', '.join(missing)}"
|
||||
)
|
||||
|
||||
created = 0
|
||||
@@ -822,8 +852,16 @@ class Store:
|
||||
for definition in definitions:
|
||||
key = definition.name.casefold()
|
||||
current = existing.get(key)
|
||||
if current is None:
|
||||
payload = definition.model_dump()
|
||||
payload["depends_on"] = [ids_by_name[item.casefold()] for item in definition.depends_on]
|
||||
else:
|
||||
# Merge: only fields the document states change. Rebuilding
|
||||
# from model_dump() reset every omitted field to its default.
|
||||
payload = current.model_dump(include=set(ServiceCreate.model_fields))
|
||||
payload.update(definition.model_dump(exclude_unset=True, exclude={"depends_on"}))
|
||||
if "depends_on" in definition.model_fields_set:
|
||||
payload["depends_on"] = [ids_by_name[item.casefold()] for item in definition.depends_on]
|
||||
if current is None:
|
||||
service = Service(id=ids_by_name[key], created_at=now, updated_at=now, **payload)
|
||||
created += 1
|
||||
@@ -845,8 +883,8 @@ class Store:
|
||||
self._insert_service(db, service)
|
||||
else:
|
||||
self._upsert_service(db, service)
|
||||
self._insert_event_db(db, "topology.changed", None, None, None, None, "Configuration imported", {"mode": mode})
|
||||
event_bus.publish({"event_type": "topology.changed", "message": "Configuration imported"})
|
||||
self._insert_event_db(db, "topology.changed", None, None, None, None, "Configuratie geïmporteerd", {"mode": mode})
|
||||
event_bus.publish({"event_type": "topology.changed", "message": "Configuratie geïmporteerd"})
|
||||
return ConfigImportResult(created=created, updated=updated, total=len(definitions))
|
||||
|
||||
def replace_all_services(self, definitions: list[ServiceCreate]) -> list[Service]:
|
||||
@@ -916,12 +954,29 @@ class Store:
|
||||
("status", evidence.status.value),
|
||||
("confidence", evidence.confidence),
|
||||
("summary", evidence.summary),
|
||||
("metadata", json.dumps(evidence.metadata, sort_keys=True)),
|
||||
)
|
||||
)
|
||||
)
|
||||
) or _stable_metadata(self._json_object(prior["metadata"])) != _stable_metadata(evidence.metadata)
|
||||
if prior is not None and prior["status"] == evidence.status.value:
|
||||
saved = evidence.model_copy(update={"id": prior["id"], "active": True, "superseded_by": None})
|
||||
ttl = evidence.valid_until - evidence.observed_at
|
||||
prior_valid_until = datetime.fromisoformat(prior["valid_until"])
|
||||
if (
|
||||
not materially_changed
|
||||
and prior["service_id"] == evidence.service_id
|
||||
and prior_valid_until - _now() > ttl / 2
|
||||
):
|
||||
# Unchanged and comfortably fresh: skip the timestamp-only
|
||||
# rewrite. It is renewed once less than half the TTL is
|
||||
# left, so the claim never goes stale, with about half
|
||||
# the writes of renewing on every observation cycle.
|
||||
saved = self._row_to_health_evidence(prior)
|
||||
for service_id in links:
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO health_evidence_service_links (evidence_id, service_id) VALUES (?, ?)",
|
||||
(saved.id, service_id),
|
||||
)
|
||||
return saved
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE health_evidence SET service_id = ?, confidence = ?, observed_at = ?, valid_until = ?,
|
||||
@@ -980,18 +1035,24 @@ class Store:
|
||||
"service_id": evidence.service_id,
|
||||
"provider": evidence.provider.value,
|
||||
"status": evidence.status.value,
|
||||
"message": "Health evidence changed",
|
||||
"message": "Gezondheidsbewijs gewijzigd",
|
||||
}
|
||||
)
|
||||
return saved
|
||||
|
||||
def health_evidence_for_service(self, service_id: str, *, limit: int = 100) -> list[HealthEvidence]:
|
||||
# A direct claim and a linked claim are matched by two independently
|
||||
# indexed lookups. An ``OR`` across the LEFT JOIN cannot use either
|
||||
# index and forced a full ``health_evidence`` scan on every call.
|
||||
with self._connect() as db:
|
||||
rows = db.execute(
|
||||
"""
|
||||
SELECT DISTINCT e.* FROM health_evidence e
|
||||
LEFT JOIN health_evidence_service_links link ON link.evidence_id = e.id
|
||||
WHERE e.service_id = ? OR link.service_id = ?
|
||||
SELECT e.* FROM health_evidence e
|
||||
WHERE e.id IN (
|
||||
SELECT id FROM health_evidence WHERE service_id = ?
|
||||
UNION
|
||||
SELECT evidence_id FROM health_evidence_service_links WHERE service_id = ?
|
||||
)
|
||||
ORDER BY e.observed_at DESC, e.rowid DESC LIMIT ?
|
||||
""",
|
||||
(service_id, service_id, limit),
|
||||
@@ -1015,27 +1076,41 @@ class Store:
|
||||
return result
|
||||
placeholders = ", ".join("?" for _ in ids)
|
||||
with self._connect() as db:
|
||||
# Both match paths use their own index; the per-service limit is
|
||||
# applied in SQL so superseded history is not materialised.
|
||||
rows = db.execute(
|
||||
f"""
|
||||
SELECT e.*, e.service_id AS direct_service_id, link.service_id AS linked_service_id
|
||||
FROM health_evidence e
|
||||
LEFT JOIN health_evidence_service_links link ON link.evidence_id = e.id
|
||||
WHERE e.service_id IN ({placeholders}) OR link.service_id IN ({placeholders})
|
||||
WITH matched(evidence_id, matched_service_id) AS (
|
||||
SELECT id, service_id FROM health_evidence WHERE service_id IN ({placeholders})
|
||||
UNION
|
||||
SELECT evidence_id, service_id FROM health_evidence_service_links
|
||||
WHERE service_id IN ({placeholders})
|
||||
),
|
||||
ranked AS (
|
||||
SELECT e.*, m.matched_service_id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY m.matched_service_id
|
||||
ORDER BY e.observed_at DESC, e.rowid DESC
|
||||
) AS rank_in_service
|
||||
FROM matched m
|
||||
JOIN health_evidence e ON e.id = m.evidence_id
|
||||
)
|
||||
SELECT * FROM ranked
|
||||
WHERE rank_in_service <= ?
|
||||
ORDER BY matched_service_id, rank_in_service
|
||||
""",
|
||||
[*ids, *ids],
|
||||
[*ids, *ids, limit_per_service],
|
||||
).fetchall()
|
||||
seen: dict[str, set[str]] = {service_id: set() for service_id in ids}
|
||||
parsed: dict[str, HealthEvidence] = {}
|
||||
for row in rows:
|
||||
service_id = row["matched_service_id"]
|
||||
if service_id not in result:
|
||||
continue
|
||||
evidence = parsed.get(row["id"])
|
||||
if evidence is None:
|
||||
evidence = self._row_to_health_evidence(row)
|
||||
for service_id in {row["direct_service_id"], row["linked_service_id"]}:
|
||||
if (
|
||||
service_id in result
|
||||
and evidence.id not in seen[service_id]
|
||||
and len(result[service_id]) < limit_per_service
|
||||
):
|
||||
parsed[row["id"]] = evidence
|
||||
result[service_id].append(evidence)
|
||||
seen[service_id].add(evidence.id)
|
||||
return result
|
||||
|
||||
def application_evidence_links(self, provider: EvidenceProvider) -> dict[str, set[str]]:
|
||||
@@ -1098,7 +1173,7 @@ class Store:
|
||||
"event_type": "provider.status_changed",
|
||||
"provider": value.provider.value,
|
||||
"status": value.status.value,
|
||||
"message": "Provider availability changed",
|
||||
"message": "Beschikbaarheid van de bron gewijzigd",
|
||||
}
|
||||
)
|
||||
return value
|
||||
@@ -1205,10 +1280,37 @@ class Store:
|
||||
status_by_id[service_id] = self._legacy_health_from_row(row)
|
||||
return status_by_id, resolutions
|
||||
|
||||
def set_maintenance(self, service_id: str, enabled: bool, reason: str | None = None) -> Service | None:
|
||||
def maintenance_windows(self) -> dict[str, datetime]:
|
||||
with self._connect() as db:
|
||||
rows = db.execute("SELECT service_id, ends_at FROM maintenance_windows").fetchall()
|
||||
return {row["service_id"]: datetime.fromisoformat(row["ends_at"]) for row in rows}
|
||||
|
||||
def expire_maintenance_windows(self, now: datetime | None = None) -> list[str]:
|
||||
"""End maintenance for every window whose end time has passed."""
|
||||
|
||||
now = now or _now()
|
||||
with self._connect() as db:
|
||||
rows = db.execute(
|
||||
"SELECT service_id FROM maintenance_windows WHERE ends_at <= ?", (now.isoformat(),)
|
||||
).fetchall()
|
||||
ended: list[str] = []
|
||||
for row in rows:
|
||||
if self.set_maintenance(row["service_id"], False, "Maintenance window ended") is not None:
|
||||
ended.append(row["service_id"])
|
||||
return ended
|
||||
|
||||
def set_maintenance(
|
||||
self,
|
||||
service_id: str,
|
||||
enabled: bool,
|
||||
reason: str | None = None,
|
||||
until: datetime | None = None,
|
||||
) -> Service | None:
|
||||
service = self.get_service(service_id)
|
||||
if service is None:
|
||||
return None
|
||||
if enabled and until is not None and until <= _now():
|
||||
raise ValueError("Het einde van het onderhoud moet in de toekomst liggen")
|
||||
updated = service.model_copy(
|
||||
update={
|
||||
"maintenance_enabled": enabled,
|
||||
@@ -1221,6 +1323,14 @@ class Store:
|
||||
)
|
||||
with self._connect() as db:
|
||||
self._upsert_service(db, updated)
|
||||
if enabled and until is not None:
|
||||
db.execute(
|
||||
"INSERT INTO maintenance_windows (service_id, ends_at) VALUES (?, ?) "
|
||||
"ON CONFLICT(service_id) DO UPDATE SET ends_at = excluded.ends_at",
|
||||
(service_id, until.isoformat()),
|
||||
)
|
||||
else:
|
||||
db.execute("DELETE FROM maintenance_windows WHERE service_id = ?", (service_id,))
|
||||
self._insert_event_db(
|
||||
db,
|
||||
"service.maintenance_changed",
|
||||
@@ -1228,15 +1338,18 @@ class Store:
|
||||
None,
|
||||
service.state.value,
|
||||
HealthStatus.MAINTENANCE.value if enabled else HealthStatus.UNKNOWN.value,
|
||||
f"Maintenance {'enabled' if enabled else 'disabled'} for {service.name}",
|
||||
{"reason": reason} if reason else {},
|
||||
f"Onderhoud {'gestart' if enabled else 'beëindigd'} voor {service.name}",
|
||||
{
|
||||
**({"reason": reason} if reason else {}),
|
||||
**({"until": until.isoformat()} if enabled and until else {}),
|
||||
},
|
||||
)
|
||||
event_bus.publish(
|
||||
{
|
||||
"event_type": "service.maintenance_changed",
|
||||
"service_id": service_id,
|
||||
"status": HealthStatus.MAINTENANCE.value if enabled else HealthStatus.UNKNOWN.value,
|
||||
"message": f"Maintenance {'enabled' if enabled else 'disabled'}",
|
||||
"message": f"Onderhoud {'gestart' if enabled else 'beëindigd'}",
|
||||
}
|
||||
)
|
||||
from .incidents import sync_incidents
|
||||
@@ -1330,11 +1443,11 @@ class Store:
|
||||
None,
|
||||
service.state.value,
|
||||
status.value,
|
||||
f"Docker runtime observation updated for {service.name}",
|
||||
f"Docker-runtimewaarneming bijgewerkt voor {service.name}",
|
||||
{"runtime_state": runtime_state, "runtime_health": runtime_health, "monitoring_state": state_kind.value},
|
||||
)
|
||||
if service.state != status:
|
||||
event_bus.publish({"event_type": "service.runtime_observed", "service_id": service_id, "status": status.value, "message": "Docker runtime observation updated"})
|
||||
event_bus.publish({"event_type": "service.runtime_observed", "service_id": service_id, "status": status.value, "message": "Docker-runtimewaarneming bijgewerkt"})
|
||||
observed_at = _now()
|
||||
self.record_health_evidence(
|
||||
HealthEvidence(
|
||||
@@ -1350,7 +1463,7 @@ class Store:
|
||||
observed_at=observed_at,
|
||||
valid_until=observed_at + timedelta(seconds=max(60, int(service.interval_seconds or 60) * 2)),
|
||||
received_at=observed_at,
|
||||
summary="Docker runtime observation" if provider == EvidenceProvider.DOCKER else "Runtime observation",
|
||||
summary="Docker-runtimewaarneming" if provider == EvidenceProvider.DOCKER else "Runtimewaarneming",
|
||||
metadata={"runtime_state": runtime_state, "runtime_health": runtime_health},
|
||||
)
|
||||
)
|
||||
@@ -1389,7 +1502,7 @@ class Store:
|
||||
"service_id": probe.service_id,
|
||||
"from_status": previous.value,
|
||||
"to_status": next_state.value,
|
||||
"message": f"Service changed from {previous.value} to {next_state.value}",
|
||||
"message": f"Service gewijzigd van {previous.value} to {next_state.value}",
|
||||
"metadata": {"trigger": probe.trigger, "probe_id": probe.id},
|
||||
}
|
||||
self._insert_event_db(
|
||||
@@ -1420,11 +1533,11 @@ class Store:
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
f"Flapping detected: {flap_count} state changes in 30 minutes",
|
||||
f"Wisselvalligheid vastgesteld: {flap_count} statuswijzigingen in 30 minuten",
|
||||
{"state_changes": flap_count, "window_minutes": 30},
|
||||
created_at=now,
|
||||
)
|
||||
events.append({"event_type": "flapping.detected", "service_id": probe.service_id, "message": "Flapping detected"})
|
||||
events.append({"event_type": "flapping.detected", "service_id": probe.service_id, "message": "Wisselvalligheid vastgesteld"})
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE services
|
||||
@@ -1449,7 +1562,7 @@ class Store:
|
||||
"service_id": probe.service_id,
|
||||
"status": probe.status.value,
|
||||
"trigger": probe.trigger,
|
||||
"message": "Probe completed",
|
||||
"message": "Controle voltooid",
|
||||
}
|
||||
)
|
||||
for event in events:
|
||||
@@ -1618,6 +1731,52 @@ class Store:
|
||||
db.execute("DELETE FROM events WHERE created_at < ? AND event_type NOT LIKE 'incident.%'", (event_cutoff.isoformat(),))
|
||||
return cursor.rowcount
|
||||
|
||||
def checkpoint(self) -> None:
|
||||
"""Fold the WAL back into the database and refresh planner statistics.
|
||||
|
||||
Without a TRUNCATE checkpoint the WAL file keeps its high-water size.
|
||||
"""
|
||||
|
||||
with self._connect() as db:
|
||||
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
db.execute("PRAGMA optimize")
|
||||
|
||||
def ready_check(self) -> None:
|
||||
"""Raise if the database cannot take a write lock right now."""
|
||||
|
||||
connection = self._connect()
|
||||
try:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
connection.execute("ROLLBACK")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def prune_health_evidence(self, retention_days: int) -> int:
|
||||
"""Delete superseded evidence history older than the retention window.
|
||||
|
||||
Only inactive rows are removed. A row becomes inactive exclusively
|
||||
when a newer claim for the same provider/subject supersedes it, so
|
||||
every subject keeps its current (active) claim and health resolution
|
||||
is unaffected. Without this, every status flip leaves a permanent row
|
||||
and evidence reads grow linearly with uptime.
|
||||
"""
|
||||
|
||||
if retention_days <= 0:
|
||||
return 0
|
||||
cutoff = _now() - timedelta(days=retention_days)
|
||||
with self._connect() as db:
|
||||
cursor = db.execute(
|
||||
"DELETE FROM health_evidence WHERE active = 0 AND superseded_by IS NOT NULL AND received_at < ?",
|
||||
(cutoff.isoformat(),),
|
||||
)
|
||||
# Links cascade through the foreign key; also remove any orphan
|
||||
# links left by databases that predate enforced foreign keys.
|
||||
db.execute(
|
||||
"DELETE FROM health_evidence_service_links "
|
||||
"WHERE evidence_id NOT IN (SELECT id FROM health_evidence)"
|
||||
)
|
||||
return cursor.rowcount
|
||||
|
||||
def _insert_event_db(
|
||||
self,
|
||||
db: sqlite3.Connection,
|
||||
@@ -1669,12 +1828,37 @@ class Store:
|
||||
event_bus.publish(result.model_dump(mode="json"))
|
||||
return result
|
||||
|
||||
def list_events(self, limit: int = 50, service_id: str | None = None) -> list[EventRecord]:
|
||||
with self._connect() as db:
|
||||
def list_events(
|
||||
self,
|
||||
limit: int = 50,
|
||||
service_id: str | None = None,
|
||||
event_type: str | None = None,
|
||||
before: datetime | None = None,
|
||||
) -> list[EventRecord]:
|
||||
"""Newest first. ``event_type`` ending in ``.`` matches a family
|
||||
(``incident.``); ``before`` pages to older events."""
|
||||
|
||||
clauses: list[str] = []
|
||||
params: list[object] = []
|
||||
if service_id:
|
||||
rows = db.execute("SELECT * FROM events WHERE service_id = ? ORDER BY created_at DESC LIMIT ?", (service_id, limit)).fetchall()
|
||||
clauses.append("service_id = ?")
|
||||
params.append(service_id)
|
||||
if event_type:
|
||||
if event_type.endswith("."):
|
||||
# Exact prefix match without LIKE wildcards.
|
||||
clauses.append("substr(event_type, 1, ?) = ?")
|
||||
params.extend([len(event_type), event_type])
|
||||
else:
|
||||
rows = db.execute("SELECT * FROM events ORDER BY created_at DESC LIMIT ?", (limit,)).fetchall()
|
||||
clauses.append("event_type = ?")
|
||||
params.append(event_type)
|
||||
if before is not None:
|
||||
clauses.append("created_at < ?")
|
||||
params.append(before.isoformat())
|
||||
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
with self._connect() as db:
|
||||
rows = db.execute(
|
||||
f"SELECT * FROM events {where} ORDER BY created_at DESC LIMIT ?", [*params, limit]
|
||||
).fetchall()
|
||||
return [self._row_to_event(row) for row in rows]
|
||||
|
||||
def demo_active(self) -> bool:
|
||||
@@ -1928,7 +2112,7 @@ class Store:
|
||||
""",
|
||||
(snapshot_services, snapshot_probes, snapshot_events, snapshot_incidents, snapshot_discovery, snapshot_health_evidence, json.dumps([service.id for service in services]), started_at),
|
||||
)
|
||||
event_bus.publish({"event_type": "topology.changed", "message": "Synthetic demo loaded"})
|
||||
event_bus.publish({"event_type": "topology.changed", "message": "Synthetische demo geladen"})
|
||||
return ConfigImportResult(created=len(services), updated=0, total=len(services))
|
||||
|
||||
def exit_demo(self) -> bool:
|
||||
@@ -1947,7 +2131,7 @@ class Store:
|
||||
session["snapshot_health_evidence"] or "{}",
|
||||
)
|
||||
db.execute("DELETE FROM demo_sessions WHERE id = 1")
|
||||
event_bus.publish({"event_type": "topology.changed", "message": "Synthetic demo exited"})
|
||||
event_bus.publish({"event_type": "topology.changed", "message": "Synthetische demo afgesloten"})
|
||||
return True
|
||||
|
||||
def list_incidents(self, active_only: bool = False, limit: int = 100) -> list[IncidentRecord]:
|
||||
@@ -1999,14 +2183,51 @@ class Store:
|
||||
event_bus.publish(payload)
|
||||
return IncidentEvent(id=event_id, incident_id=incident_id, event_type=event_type, message=message, created_at=created_at, service_id=service_id)
|
||||
|
||||
def resolve_incident(self, incident_id: str, note: str | None = None) -> IncidentRecord | None:
|
||||
"""Close an incident by hand (e.g. a stale one).
|
||||
|
||||
If its root is still down, the next incident sync opens a new one.
|
||||
"""
|
||||
|
||||
incident = self.get_incident(incident_id)
|
||||
if incident is None:
|
||||
return None
|
||||
if incident.status == IncidentStatus.RESOLVED:
|
||||
return incident
|
||||
now = _now()
|
||||
updated = incident.model_copy(
|
||||
update={"status": IncidentStatus.RESOLVED, "resolved_at": now, "latest_update_at": now}
|
||||
)
|
||||
self.upsert_incident(updated)
|
||||
self.append_incident_event(
|
||||
incident_id,
|
||||
"incident.resolved",
|
||||
f"Incident handmatig opgelost{f': {note}' if note else ''}",
|
||||
incident.root_service_id,
|
||||
)
|
||||
return updated
|
||||
|
||||
def add_incident_note(self, incident_id: str, text: str) -> IncidentRecord | None:
|
||||
incident = self.get_incident(incident_id)
|
||||
if incident is None:
|
||||
return None
|
||||
self.append_incident_event(incident_id, "incident.note", text, incident.root_service_id)
|
||||
updated = incident.model_copy(update={"latest_update_at": _now()})
|
||||
self.upsert_incident(updated)
|
||||
return updated
|
||||
|
||||
def acknowledge_incident(self, incident_id: str) -> IncidentRecord | None:
|
||||
incident = self.get_incident(incident_id)
|
||||
if incident is None:
|
||||
return None
|
||||
if incident.status == IncidentStatus.RESOLVED:
|
||||
raise ValueError("Resolved incidents cannot be acknowledged")
|
||||
raise ValueError("Opgeloste incidenten kunnen niet bevestigd worden")
|
||||
if incident.status == IncidentStatus.ACKNOWLEDGED:
|
||||
# Idempotent: a repeated acknowledge keeps the original time and
|
||||
# adds no duplicate timeline entry.
|
||||
return incident
|
||||
now = _now()
|
||||
updated = incident.model_copy(update={"status": IncidentStatus.ACKNOWLEDGED, "acknowledged_at": now, "latest_update_at": now})
|
||||
self.upsert_incident(updated)
|
||||
self.append_incident_event(incident_id, "incident.acknowledged", "Incident acknowledged", incident.root_service_id)
|
||||
self.append_incident_event(incident_id, "incident.acknowledged", "Incident bevestigd", incident.root_service_id)
|
||||
return updated
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "servicemap-backend"
|
||||
version = "1.6.2"
|
||||
version = "1.6.3"
|
||||
description = "ServiceMap API, topology intelligence and probe engine"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
|
||||
@@ -62,7 +62,7 @@ def test_service_api_crud_cycle_guard_and_export(tmp_path: Path) -> None:
|
||||
},
|
||||
)
|
||||
assert cycle_response.status_code == 422
|
||||
assert "cycle" in cycle_response.json()["detail"].lower()
|
||||
assert "kring" in cycle_response.json()["detail"].lower()
|
||||
|
||||
listing = client.get("/api/v1/services")
|
||||
assert listing.status_code == 200
|
||||
@@ -141,7 +141,7 @@ def test_service_api_rejects_invalid_endpoint_and_dependency_references(tmp_path
|
||||
},
|
||||
)
|
||||
assert missing_dependency.status_code == 422
|
||||
assert "unknown dependency" in missing_dependency.json()["detail"].lower()
|
||||
assert "onbekende afhankelijkheid" in missing_dependency.json()["detail"].lower()
|
||||
|
||||
|
||||
def test_semantic_topology_and_logical_relations_are_backend_derived(tmp_path: Path) -> None:
|
||||
|
||||
@@ -79,7 +79,7 @@ services:
|
||||
""",
|
||||
"yaml",
|
||||
)
|
||||
with pytest.raises(ValueError, match="unknown dependencies"):
|
||||
with pytest.raises(ValueError, match="onbekende afhankelijkheden"):
|
||||
import_document(store, missing, "replace")
|
||||
|
||||
cyclic = """
|
||||
@@ -94,10 +94,10 @@ services:
|
||||
url: https://b.local
|
||||
depends_on: [A]
|
||||
"""
|
||||
with pytest.raises(ValueError, match="cycle"):
|
||||
with pytest.raises(ValueError, match="kring"):
|
||||
parse_document(cyclic, "yaml")
|
||||
|
||||
with pytest.raises(ValueError, match="less than or equal to 1"):
|
||||
with pytest.raises(ValueError, match="1 of lager"):
|
||||
parse_document("version: 2\nservices: []", "yaml")
|
||||
|
||||
|
||||
@@ -131,3 +131,76 @@ services:
|
||||
|
||||
remaining = store.list_services()
|
||||
assert [(service.id, service.name) for service in remaining] == [(original.id, "Original")]
|
||||
|
||||
|
||||
def test_export_keeps_operator_fields_and_merge_preserves_unmentioned_ones(tmp_path: Path) -> None:
|
||||
from app.models import (
|
||||
ComponentRole,
|
||||
Criticality,
|
||||
DiscoveryCategory,
|
||||
DiscoveryLifecycle,
|
||||
DiscoveryVisibility,
|
||||
)
|
||||
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
database = store.create_service(ServiceCreate(name="Database", kind=ServiceKind.TCP, host="db.local", port=5432))
|
||||
api = store.create_service(
|
||||
ServiceCreate(
|
||||
name="API",
|
||||
kind=ServiceKind.HTTP,
|
||||
url="https://api.local",
|
||||
depends_on=[database.id],
|
||||
owner="platform-team",
|
||||
application="Northstar",
|
||||
application_locked=True,
|
||||
domain="Commerce",
|
||||
domain_locked=True,
|
||||
component_role=ComponentRole.API,
|
||||
component_role_locked=True,
|
||||
criticality=Criticality.HIGH,
|
||||
category=DiscoveryCategory.APPLICATION,
|
||||
visibility=DiscoveryVisibility.HIDDEN,
|
||||
lifecycle=DiscoveryLifecycle.ACTIVE,
|
||||
expected_status_min=200,
|
||||
expected_status_max=204,
|
||||
layout_x=120.0,
|
||||
layout_y=40.0,
|
||||
layout_pinned=True,
|
||||
runtime_state="running",
|
||||
)
|
||||
)
|
||||
|
||||
exported = export_document(store)
|
||||
exported_api = next(item for item in exported.services if item.name == "API")
|
||||
assert exported_api.application == "Northstar" and exported_api.application_locked
|
||||
assert exported_api.domain == "Commerce" and exported_api.component_role == ComponentRole.API
|
||||
assert exported_api.visibility == DiscoveryVisibility.HIDDEN and exported_api.layout_pinned
|
||||
assert exported_api.depends_on == ["Database"]
|
||||
# Observed runtime state is not configuration.
|
||||
assert "runtime_state" not in serialize_document(exported, "yaml")
|
||||
|
||||
# Round trip into an empty store keeps every operator field.
|
||||
other = Store(str(tmp_path / "other.db"))
|
||||
import_document(other, parse_document(serialize_document(exported, "yaml"), "yaml"), "replace")
|
||||
restored = next(item for item in other.list_services() if item.name == "API")
|
||||
for field in ("owner", "application", "application_locked", "domain", "component_role", "criticality",
|
||||
"category", "visibility", "expected_status_min", "expected_status_max",
|
||||
"layout_x", "layout_y", "layout_pinned"):
|
||||
assert getattr(restored, field) == getattr(api, field), field
|
||||
|
||||
# A merge that mentions only one field changes only that field.
|
||||
result = import_document(
|
||||
store,
|
||||
parse_document(
|
||||
"version: 2\nservices:\n - name: API\n kind: http\n url: https://api.local\n description: Public API\n",
|
||||
"yaml",
|
||||
),
|
||||
"merge",
|
||||
)
|
||||
assert result.updated == 1
|
||||
merged = store.get_service(api.id)
|
||||
assert merged.description == "Public API"
|
||||
for field in ("owner", "application", "application_locked", "domain", "component_role", "criticality",
|
||||
"visibility", "expected_status_min", "layout_x", "layout_pinned", "url", "runtime_state"):
|
||||
assert getattr(merged, field) == getattr(api, field), field
|
||||
assert merged.depends_on == [database.id]
|
||||
@@ -1,6 +1,8 @@
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main as main_module
|
||||
@@ -9,6 +11,11 @@ from app.models import HealthStatus, ProbeResult, ServiceCreate, ServiceKind
|
||||
from app.store import Store
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def enable_demo(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("SERVICEMAP_DEMO_ENABLED", "1")
|
||||
|
||||
|
||||
def _client(tmp_path: Path) -> tuple[Store, TestClient]:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
main_module.store = store
|
||||
@@ -33,6 +40,26 @@ def _assert_acyclic(graph: dict[str, set[str]]) -> None:
|
||||
visit(service_id)
|
||||
|
||||
|
||||
def test_production_cannot_start_or_reset_demo_but_can_restore_existing_session(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
store, client = _client(tmp_path)
|
||||
service = store.create_service(ServiceCreate(name="Live API", kind=ServiceKind.HTTP, url="https://api.test"))
|
||||
monkeypatch.delenv("SERVICEMAP_DEMO_ENABLED", raising=False)
|
||||
|
||||
assert client.post("/api/v1/demo").status_code == 409
|
||||
assert client.post("/api/v1/demo/reset").status_code == 409
|
||||
assert client.get("/api/v1/demo").json()["enabled"] is False
|
||||
assert [saved.id for saved in store.list_services()] == [service.id]
|
||||
|
||||
monkeypatch.setenv("SERVICEMAP_DEMO_ENABLED", "1")
|
||||
assert client.post("/api/v1/demo").status_code == 200
|
||||
monkeypatch.delenv("SERVICEMAP_DEMO_ENABLED")
|
||||
assert client.post("/api/v1/demo/reset").status_code == 409
|
||||
assert client.post("/api/v1/demo/exit").json()["restored"] is True
|
||||
assert [saved.id for saved in store.list_services()] == [service.id]
|
||||
|
||||
|
||||
def test_demo_seeds_topology_health_history_availability_and_incident(tmp_path: Path) -> None:
|
||||
store, client = _client(tmp_path)
|
||||
|
||||
@@ -135,6 +162,7 @@ def test_demo_reset_is_deterministic_and_exit_restores_topology_and_probes(tmp_p
|
||||
assert exited["restored"] is True
|
||||
assert client.get("/api/v1/demo").json() == {
|
||||
"active": False,
|
||||
"enabled": True,
|
||||
"synthetic": False,
|
||||
"scenario_name": None,
|
||||
"service_count": 0,
|
||||
|
||||
@@ -75,7 +75,9 @@ class _DockerClient:
|
||||
return True
|
||||
|
||||
def list(self, all: bool) -> list[_Container]:
|
||||
assert all is False
|
||||
# Stopped containers must always be listed so they are never
|
||||
# mistaken for removed ones.
|
||||
assert all is True
|
||||
return self.current
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -290,6 +292,31 @@ def test_missing_identity_progresses_to_stale_then_retired_without_delete(tmp_pa
|
||||
assert len(manager.store.list_services()) == 1
|
||||
|
||||
|
||||
def test_stopped_container_is_not_retired_when_stopped_candidates_are_hidden(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
container = _Container("api", "a" * 64, "northstar/api:1", "api")
|
||||
_DockerClient.current = [container]
|
||||
monkeypatch.setattr(docker_discovery.docker, "DockerClient", lambda **kwargs: _DockerClient(**kwargs))
|
||||
manager = _manager(tmp_path)
|
||||
first = manager.run(DiscoveryRunRequest(docker_host="tcp://docker.local:2375"))
|
||||
manager.reconcile(DiscoveryReconcileRequest(run_id=first.run.id, apply_high_confidence=True))
|
||||
before = next(item for item in manager.store.list_services() if item.source_ref == "docker:compose:northstar:api")
|
||||
|
||||
# The container is stopped, not removed. The default request hides
|
||||
# stopped candidates, but must not treat the identity as missing.
|
||||
container.status = "exited"
|
||||
container.attrs["State"] = {"Status": "exited"}
|
||||
for _ in range(4):
|
||||
run = manager.run(DiscoveryRunRequest(docker_host="tcp://docker.local:2375"))
|
||||
assert all(item.name != "api" for item in run.candidates)
|
||||
manager.reconcile(DiscoveryReconcileRequest(run_id=run.run.id))
|
||||
|
||||
service = next(item for item in manager.store.list_services() if item.source_ref == "docker:compose:northstar:api")
|
||||
assert service.lifecycle == before.lifecycle
|
||||
assert service.monitoring_enabled == before.monitoring_enabled
|
||||
|
||||
|
||||
def test_low_confidence_network_hint_is_evidence_only(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
_DockerClient.current = [
|
||||
_Container("frontend", "a" * 64, "northstar/frontend:1", "frontend"),
|
||||
|
||||
@@ -59,7 +59,7 @@ def test_cycle_validation_rejects_recursive_dependencies(tmp_path: Path) -> None
|
||||
ServiceCreate(name="API", kind=ServiceKind.HTTP, url="https://example.test", depends_on=[database.id])
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="cycle"):
|
||||
with pytest.raises(ValueError, match="kring"):
|
||||
validate_dependencies([api.id], store, service_id=database.id)
|
||||
|
||||
validate_dependencies([database.id], store, service_id=api.id)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import asyncio
|
||||
from datetime import UTC, datetime
|
||||
from typing import Self
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app import probes
|
||||
@@ -47,22 +47,17 @@ def test_http_status_classification(
|
||||
status_code: int,
|
||||
expected: HealthStatus,
|
||||
) -> None:
|
||||
class FakeResponse:
|
||||
def __init__(self, code: int) -> None:
|
||||
self.status_code = code
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert str(request.url) == "https://api.local"
|
||||
return httpx.Response(status_code, stream=httpx.ByteStream(b"x" * 200_000))
|
||||
|
||||
class FakeClient:
|
||||
async def __aenter__(self) -> Self:
|
||||
return self
|
||||
real_client = httpx.AsyncClient
|
||||
|
||||
async def __aexit__(self, *args: object) -> None:
|
||||
return None
|
||||
def fake_client(**kwargs: object) -> httpx.AsyncClient:
|
||||
kwargs.pop("verify", None)
|
||||
return real_client(transport=httpx.MockTransport(handler), **kwargs)
|
||||
|
||||
async def get(self, url: str) -> FakeResponse:
|
||||
assert url == "https://api.local"
|
||||
return FakeResponse(status_code)
|
||||
|
||||
monkeypatch.setattr(probes.httpx, "AsyncClient", lambda **kwargs: FakeClient())
|
||||
monkeypatch.setattr(probes.httpx, "AsyncClient", fake_client)
|
||||
|
||||
status, detail = asyncio.run(probes._probe_once(_service(), 1.0))
|
||||
|
||||
@@ -154,3 +149,11 @@ def test_probe_many_respects_concurrency_boundary(monkeypatch: pytest.MonkeyPatc
|
||||
|
||||
assert len(results) == len(services)
|
||||
assert maximum <= 2
|
||||
|
||||
|
||||
def test_an_invalid_target_is_reported_down_instead_of_failing_the_cycle() -> None:
|
||||
broken = _service().model_copy(update={"url": "http://[invalid"})
|
||||
healthy_cycle = asyncio.run(probes.probe_many([broken], concurrency=1, retries=0))
|
||||
assert len(healthy_cycle) == 1
|
||||
assert healthy_cycle[0].status == HealthStatus.DOWN
|
||||
assert healthy_cycle[0].detail
|
||||
@@ -47,6 +47,35 @@ def test_scheduler_runs_first_cycle_before_initial_sleep() -> None:
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_scheduler_prunes_events_with_their_own_retention() -> None:
|
||||
calls: list[tuple[int, int | None]] = []
|
||||
|
||||
class RetentionStore(EmptyStore):
|
||||
def prune_probes(self, retention_days: int, event_retention_days: int | None = None) -> int: # type: ignore[override]
|
||||
calls.append((retention_days, event_retention_days))
|
||||
return 0
|
||||
|
||||
async def scenario() -> None:
|
||||
task = asyncio.create_task(
|
||||
scheduled_probe_loop(
|
||||
RetentionStore(), # type: ignore[arg-type]
|
||||
interval_seconds=3600,
|
||||
timeout_seconds=1.0,
|
||||
retries=0,
|
||||
concurrency=1,
|
||||
retention_days=30,
|
||||
event_retention_days=90,
|
||||
)
|
||||
)
|
||||
await asyncio.sleep(0)
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
asyncio.run(scenario())
|
||||
assert calls == [(30, 90)]
|
||||
|
||||
|
||||
def test_scheduler_pauses_live_probes_for_synthetic_demo() -> None:
|
||||
async def scenario() -> None:
|
||||
store = SyntheticStore()
|
||||
|
||||
@@ -143,7 +143,7 @@ def test_appops_application_health_is_provenance_not_component_health(tmp_path:
|
||||
|
||||
assert resolution.selected_evidence_id is None
|
||||
assert resolution.evidence[0].scope.value == "application"
|
||||
assert "not used as component" in resolution.explanation
|
||||
assert "niet gebruikt als componentgezondheid" in resolution.explanation
|
||||
|
||||
|
||||
def test_compose_reference_prefers_same_project_over_duplicate_stack_name(tmp_path: Path) -> None:
|
||||
@@ -182,7 +182,7 @@ def test_ambiguous_global_name_stays_review_only(tmp_path: Path) -> None:
|
||||
assert len(suggestions) == 1
|
||||
assert suggestions[0].target_ref is None
|
||||
assert suggestions[0].confidence == DiscoveryConfidence.LOW
|
||||
assert "Manual review required" in " ".join(suggestions[0].evidence)
|
||||
assert "Handmatige controle nodig" in " ".join(suggestions[0].evidence)
|
||||
|
||||
|
||||
def test_reachability_repair_is_dry_run_first_and_preserves_probe_history(tmp_path: Path) -> None:
|
||||
@@ -282,7 +282,7 @@ def test_published_preflight_requires_a_real_tcp_connection(monkeypatch) -> None
|
||||
|
||||
assert verified.primary is True
|
||||
assert verified.reachability == ProbeReachability.VERIFIED
|
||||
assert verified.preflight_detail == "TCP connect succeeded"
|
||||
assert verified.preflight_detail == "TCP-verbinding gelukt"
|
||||
|
||||
|
||||
def test_http_preflight_records_response_without_scanning_paths(monkeypatch) -> None:
|
||||
|
||||
@@ -60,7 +60,7 @@ def test_application_scope_evidence_never_becomes_component_direct_health(tmp_pa
|
||||
|
||||
assert resolution.selected_evidence_id is None
|
||||
assert resolution.status == HealthStatus.UNKNOWN
|
||||
assert "application-scoped" in resolution.explanation
|
||||
assert "applicatieniveau" in resolution.explanation
|
||||
|
||||
|
||||
def test_evidence_conflict_and_priority_are_visible(tmp_path) -> None:
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
"""v1.6.3 ntfy incident notifications."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import alerts as alerts_module
|
||||
from app import auth
|
||||
from app import main as main_module
|
||||
from app.alerts import AlertManager, AlertSettingsUpdate
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.models import Criticality, IncidentRecord, IncidentStatus
|
||||
from app.store import Store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def sent(monkeypatch: pytest.MonkeyPatch) -> list[httpx.Request]:
|
||||
requests: list[httpx.Request] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
return httpx.Response(200, json={"id": "x"})
|
||||
|
||||
real_client = httpx.Client
|
||||
|
||||
def fake_client(*args, **kwargs):
|
||||
kwargs["transport"] = httpx.MockTransport(handler)
|
||||
return real_client(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(alerts_module.httpx, "Client", fake_client)
|
||||
return requests
|
||||
|
||||
|
||||
def _incident(
|
||||
store: Store,
|
||||
*,
|
||||
status: IncidentStatus = IncidentStatus.OPEN,
|
||||
severity: Criticality = Criticality.HIGH,
|
||||
detected: datetime,
|
||||
) -> IncidentRecord:
|
||||
record = IncidentRecord(
|
||||
id="inc-1",
|
||||
status=status,
|
||||
root_service_id="svc",
|
||||
root_service_name="Payments",
|
||||
started_at=detected,
|
||||
detected_at=detected,
|
||||
resolved_at=detected + timedelta(minutes=5) if status == IncidentStatus.RESOLVED else None,
|
||||
title="Payments is down",
|
||||
root_cause_reason="Service is down and no configured dependency is also down",
|
||||
affected_service_ids=["a", "b"],
|
||||
severity=severity,
|
||||
latest_update_at=detected,
|
||||
)
|
||||
store.upsert_incident(record)
|
||||
return record
|
||||
|
||||
|
||||
def _manager(tmp_path: Path, **settings) -> AlertManager:
|
||||
manager = AlertManager(Store(str(tmp_path / "servicemap.db")))
|
||||
manager.update(AlertSettingsUpdate(enabled=True, ntfy_topic="sm-alerts", public_url="http://sm.lan:1253", **settings))
|
||||
return manager
|
||||
|
||||
|
||||
def test_opened_after_delay_once_then_resolved(tmp_path: Path, sent: list[httpx.Request]) -> None:
|
||||
manager = _manager(tmp_path, delay_seconds=60)
|
||||
detected = datetime.now(UTC)
|
||||
_incident(manager.store, detected=detected)
|
||||
|
||||
# Within the delay: a short flap stays quiet.
|
||||
assert manager.run_cycle(detected + timedelta(seconds=30)) == 0
|
||||
assert manager.run_cycle(detected + timedelta(seconds=61)) == 1
|
||||
# Never twice.
|
||||
assert manager.run_cycle(detected + timedelta(seconds=120)) == 0
|
||||
request = sent[0]
|
||||
assert str(request.url) == "https://ntfy.sh/sm-alerts"
|
||||
assert request.headers["Title"] == "Uitgevallen: Payments is down"
|
||||
assert request.headers["Priority"] == "urgent"
|
||||
assert request.headers["Click"].startswith("http://sm.lan:1253/#/incidents?incident=inc-1")
|
||||
assert "2 afhankelijke service(s) geraakt" in request.content.decode()
|
||||
|
||||
_incident(manager.store, status=IncidentStatus.RESOLVED, detected=detected)
|
||||
assert manager.run_cycle(detected + timedelta(minutes=6)) == 1
|
||||
assert sent[-1].headers["Title"] == "Opgelost: Payments is down"
|
||||
assert manager.run_cycle(detected + timedelta(minutes=7)) == 0
|
||||
|
||||
|
||||
def test_severity_threshold_reminders_and_disabled(tmp_path: Path, sent: list[httpx.Request]) -> None:
|
||||
manager = _manager(tmp_path, delay_seconds=0, min_severity=Criticality.CRITICAL, reminder_minutes=10)
|
||||
detected = datetime.now(UTC)
|
||||
_incident(manager.store, severity=Criticality.HIGH, detected=detected)
|
||||
assert manager.run_cycle(detected + timedelta(minutes=30)) == 0 # below threshold
|
||||
|
||||
_incident(manager.store, severity=Criticality.CRITICAL, detected=detected)
|
||||
assert manager.run_cycle(detected + timedelta(seconds=1)) == 1 # opened
|
||||
assert manager.run_cycle(detected + timedelta(minutes=10, seconds=1)) == 1 # reminder 1
|
||||
assert manager.run_cycle(detected + timedelta(minutes=12)) == 0
|
||||
assert sent[-1].headers["Title"].startswith("Nog steeds uitgevallen")
|
||||
|
||||
manager.update(AlertSettingsUpdate(enabled=False, ntfy_topic="sm-alerts"))
|
||||
assert manager.run_cycle(detected + timedelta(minutes=50)) == 0
|
||||
|
||||
|
||||
def test_settings_validation_and_secret_token(tmp_path: Path) -> None:
|
||||
manager = AlertManager(Store(str(tmp_path / "servicemap.db")))
|
||||
with pytest.raises(ValueError, match="topic"):
|
||||
manager.update(AlertSettingsUpdate(enabled=True, ntfy_topic=""))
|
||||
with pytest.raises(ValueError):
|
||||
AlertSettingsUpdate(ntfy_topic="bad topic!")
|
||||
with pytest.raises(ValueError):
|
||||
AlertSettingsUpdate(ntfy_server="file:///etc/passwd")
|
||||
|
||||
view = manager.update(AlertSettingsUpdate(ntfy_topic="t", ntfy_token="secret-value"))
|
||||
assert view.ntfy_token_set and "secret-value" not in view.model_dump_json()
|
||||
# None keeps the token, "" removes it.
|
||||
assert manager.update(AlertSettingsUpdate(ntfy_topic="t")).ntfy_token_set
|
||||
assert not manager.update(AlertSettingsUpdate(ntfy_topic="t", ntfy_token="")).ntfy_token_set
|
||||
|
||||
|
||||
def test_settings_routes_need_the_token_even_to_read(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, sent: list[httpx.Request]
|
||||
) -> None:
|
||||
main_module.store = Store(str(tmp_path / "servicemap.db"))
|
||||
main_module.discovery_store = DiscoveryStore(main_module.store)
|
||||
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
|
||||
monkeypatch.setenv("SERVICEMAP_DB", str(tmp_path / "servicemap.db"))
|
||||
monkeypatch.setenv("SERVICEMAP_AUTH_MODE", "token")
|
||||
monkeypatch.delenv("SERVICEMAP_ADMIN_TOKEN_FILE", raising=False)
|
||||
auth.reset_token_cache()
|
||||
client = TestClient(main_module.app)
|
||||
try:
|
||||
assert client.get("/api/v1/settings/alerts").status_code == 401
|
||||
assert client.get("/api/v1/services").status_code == 200 # ordinary reads stay open
|
||||
token = auth.admin_token()
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
saved = client.put(
|
||||
"/api/v1/settings/alerts",
|
||||
json={"enabled": True, "ntfy_topic": "sm-test", "ntfy_token": "tk-123"},
|
||||
headers=headers,
|
||||
)
|
||||
assert saved.status_code == 200 and saved.json()["ntfy_token_set"] is True
|
||||
assert "tk-123" not in client.get("/api/v1/settings/alerts", headers=headers).text
|
||||
result = client.post("/api/v1/settings/alerts/test", headers=headers).json()
|
||||
assert result["ok"] is True
|
||||
assert sent[-1].headers["Authorization"] == "Bearer tk-123"
|
||||
finally:
|
||||
auth.reset_token_cache()
|
||||
@@ -0,0 +1,124 @@
|
||||
"""v1.6.3 verified backups, rotation, legacy cleanup and online restore."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import auth
|
||||
from app import main as main_module
|
||||
from app.backups import BackupManager
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.models import ServiceCreate, ServiceKind
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def _store(tmp_path: Path) -> Store:
|
||||
return Store(str(tmp_path / "servicemap.db"))
|
||||
|
||||
|
||||
def _add(store: Store, name: str) -> None:
|
||||
store.create_service(ServiceCreate(name=name, kind=ServiceKind.HTTP, url=f"https://{name.lower()}.test"))
|
||||
|
||||
|
||||
def test_backup_is_verified_listed_and_rotated(tmp_path: Path) -> None:
|
||||
store = _store(tmp_path)
|
||||
_add(store, "API")
|
||||
manager = BackupManager(store, keep=2)
|
||||
start = datetime(2026, 11, 18, 3, 0, tzinfo=UTC)
|
||||
names = [manager.create(now=start + timedelta(days=day)).name for day in range(3)]
|
||||
|
||||
listed = manager.list()
|
||||
assert [item.name for item in listed] == list(reversed(names))[:2] # newest two kept
|
||||
assert not (manager.directory / names[0]).exists()
|
||||
copy = Store(str(manager.directory / names[-1]))
|
||||
assert [item.name for item in copy.list_services()] == ["API"]
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
manager.path_for("../servicemap.db")
|
||||
with pytest.raises(ValueError):
|
||||
manager.path_for("servicemap-backup-20990101T000000Z.db")
|
||||
|
||||
|
||||
def test_legacy_preupgrade_copies_are_pruned_to_the_newest_two(tmp_path: Path) -> None:
|
||||
store = _store(tmp_path)
|
||||
legacy = [
|
||||
"servicemap-v1.2.0-pre-discovery.sqlite3",
|
||||
"servicemap-v1.5.0-pre-7ecd9df.sqlite3",
|
||||
"servicemap-v1.6.1-pre-20260914.sqlite3",
|
||||
"servicemap-v1.6.2-pre-20260923T040250Z.sqlite3",
|
||||
]
|
||||
for index, name in enumerate(legacy):
|
||||
path = tmp_path / name
|
||||
path.write_bytes(b"legacy")
|
||||
stamp = time.time() - 10_000 + index * 100
|
||||
os.utime(path, (stamp, stamp))
|
||||
(tmp_path / "servicemap-v1.6.1-pre-20260914.sqlite3-wal").write_bytes(b"")
|
||||
(tmp_path / "servicemap-v1.2.0-pre-discovery.sqlite3-shm").write_bytes(b"")
|
||||
unrelated = tmp_path / "notes-v1.0.0-pre-x.sqlite3"
|
||||
unrelated.write_bytes(b"keep")
|
||||
|
||||
BackupManager(store, legacy_keep=2).create()
|
||||
|
||||
remaining = sorted(path.name for path in tmp_path.iterdir() if path.is_file())
|
||||
assert "servicemap-v1.6.2-pre-20260923T040250Z.sqlite3" in remaining
|
||||
assert "servicemap-v1.6.1-pre-20260914.sqlite3" in remaining
|
||||
assert "servicemap-v1.6.1-pre-20260914.sqlite3-wal" in remaining # sidecar of a kept copy
|
||||
assert "servicemap-v1.2.0-pre-discovery.sqlite3" not in remaining
|
||||
assert "servicemap-v1.2.0-pre-discovery.sqlite3-shm" not in remaining
|
||||
assert "servicemap-v1.5.0-pre-7ecd9df.sqlite3" not in remaining
|
||||
assert unrelated.exists()
|
||||
assert "servicemap.db" in remaining
|
||||
|
||||
|
||||
def test_restore_replaces_live_data_after_a_safety_copy(tmp_path: Path) -> None:
|
||||
store = _store(tmp_path)
|
||||
_add(store, "API")
|
||||
manager = BackupManager(store)
|
||||
backup = manager.create(now=datetime(2026, 11, 18, 3, 0, tzinfo=UTC))
|
||||
_add(store, "Added later")
|
||||
assert len(store.list_services()) == 2
|
||||
|
||||
safety = manager.restore(backup.name)
|
||||
|
||||
assert [item.name for item in store.list_services()] == ["API"]
|
||||
assert safety.kind == "pre-restore"
|
||||
safety_copy = Store(str(manager.directory / safety.name))
|
||||
assert sorted(item.name for item in safety_copy.list_services()) == ["API", "Added later"]
|
||||
|
||||
|
||||
def test_backup_routes_need_the_token(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
main_module.store = _store(tmp_path)
|
||||
main_module.discovery_store = DiscoveryStore(main_module.store)
|
||||
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
|
||||
main_module.semantic_cache.clear()
|
||||
monkeypatch.setenv("SERVICEMAP_DB", str(tmp_path / "servicemap.db"))
|
||||
monkeypatch.setenv("SERVICEMAP_AUTH_MODE", "token")
|
||||
monkeypatch.delenv("SERVICEMAP_ADMIN_TOKEN_FILE", raising=False)
|
||||
auth.reset_token_cache()
|
||||
client = TestClient(main_module.app)
|
||||
try:
|
||||
assert client.get("/api/v1/backups").status_code == 401
|
||||
headers = {"Authorization": f"Bearer {auth.admin_token()}"}
|
||||
_add(main_module.store, "API")
|
||||
created = client.post("/api/v1/backups", headers=headers)
|
||||
assert created.status_code == 201
|
||||
name = created.json()["name"]
|
||||
assert [item["name"] for item in client.get("/api/v1/backups", headers=headers).json()] == [name]
|
||||
assert client.get(f"/api/v1/backups/{name}").status_code == 401
|
||||
download = client.get(f"/api/v1/backups/{name}", headers=headers)
|
||||
assert download.status_code == 200 and download.content[:15] == b"SQLite format 3"
|
||||
assert client.get("/api/v1/backups/..%2Fservicemap.db", headers=headers).status_code == 404
|
||||
|
||||
_add(main_module.store, "Temporary")
|
||||
restored = client.post(f"/api/v1/backups/{name}/restore", headers=headers)
|
||||
assert restored.status_code == 200 and restored.json()["kind"] == "pre-restore"
|
||||
assert [item["service"]["name"] for item in client.get("/api/v1/services").json()] == ["API"]
|
||||
finally:
|
||||
auth.reset_token_cache()
|
||||
@@ -0,0 +1,70 @@
|
||||
"""v1.6.3 guards against silent data corruption."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.models import (
|
||||
EdgeMutationRequest,
|
||||
IncidentRecord,
|
||||
IncidentStatus,
|
||||
ServiceCreate,
|
||||
ServiceKind,
|
||||
)
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def _service(store: Store, name: str):
|
||||
return store.create_service(ServiceCreate(name=name, kind=ServiceKind.HTTP, url=f"https://{name.lower()}.test"))
|
||||
|
||||
|
||||
def test_deleting_a_service_removes_it_from_open_incidents_as_a_json_element(tmp_path: Path) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
root = _service(store, "Root")
|
||||
first = _service(store, "First")
|
||||
second = _service(store, "Second")
|
||||
now = datetime.now(UTC)
|
||||
store.upsert_incident(
|
||||
IncidentRecord(
|
||||
id="inc-1",
|
||||
status=IncidentStatus.OPEN,
|
||||
root_service_id=root.id,
|
||||
root_service_name=root.name,
|
||||
started_at=now,
|
||||
detected_at=now,
|
||||
title="Root is down",
|
||||
root_cause_reason="test",
|
||||
affected_service_ids=[first.id, second.id],
|
||||
latest_update_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
assert store.delete_service(first.id)
|
||||
|
||||
incident = next(item for item in store.list_incidents(active_only=True) if item.id == "inc-1")
|
||||
# Previously a textual replace() left an empty-string element behind.
|
||||
assert incident.affected_service_ids == [second.id]
|
||||
|
||||
|
||||
def test_repeating_a_manual_edge_does_not_create_duplicate_evidence(tmp_path: Path) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
discovery = DiscoveryStore(store)
|
||||
manager = DiscoveryManager(store, discovery)
|
||||
api = _service(store, "API")
|
||||
database = _service(store, "Database")
|
||||
|
||||
request = EdgeMutationRequest(source_service_id=api.id, target_service_id=database.id)
|
||||
first = manager.apply_edge(request)
|
||||
second = manager.apply_edge(request)
|
||||
|
||||
assert first.id == second.id
|
||||
with sqlite3.connect(store.path) as db:
|
||||
count = db.execute(
|
||||
"SELECT COUNT(*) FROM relation_evidence WHERE source_service_id=? AND target_service_id=? AND evidence_type='manual'",
|
||||
(api.id, database.id),
|
||||
).fetchone()[0]
|
||||
assert count == 1
|
||||
@@ -0,0 +1,170 @@
|
||||
"""v1.6.3 efficiency guards: one Docker call per observation, fewer evidence writes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import docker_discovery
|
||||
from app import store as store_module
|
||||
from app.models import (
|
||||
EvidenceProvider,
|
||||
EvidenceScope,
|
||||
HealthEvidence,
|
||||
HealthStatus,
|
||||
ServiceCreate,
|
||||
ServiceKind,
|
||||
)
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def test_health_is_read_from_the_list_status_text() -> None:
|
||||
assert docker_discovery.health_from_status("Up 3 hours (healthy)") == "healthy"
|
||||
assert docker_discovery.health_from_status("Up 2 minutes (unhealthy)") == "unhealthy"
|
||||
assert docker_discovery.health_from_status("Up 5 seconds (health: starting)") == "starting"
|
||||
assert docker_discovery.health_from_status("Exited (0) 2 days ago") is None
|
||||
assert docker_discovery.health_from_status("") is None
|
||||
|
||||
|
||||
def test_socket_observer_uses_one_list_call_on_a_long_lived_client(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
created: list[object] = []
|
||||
calls: list[bool] = []
|
||||
|
||||
class _Api:
|
||||
def containers(self, all: bool) -> list[dict[str, object]]:
|
||||
calls.append(all)
|
||||
return [
|
||||
{
|
||||
"Id": "a" * 64,
|
||||
"Names": ["/shop-api"],
|
||||
"State": "running",
|
||||
"Status": "Up 1 hour (healthy)",
|
||||
"Labels": {"com.docker.compose.project": "shop", "com.docker.compose.service": "api"},
|
||||
},
|
||||
{"Id": "b" * 64, "Names": ["/batch"], "State": "exited", "Status": "Exited (1) 3 minutes ago", "Labels": {}},
|
||||
]
|
||||
|
||||
class _Client:
|
||||
def __init__(self, **_: object) -> None:
|
||||
self.api = _Api()
|
||||
created.append(self)
|
||||
|
||||
def close(self) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(docker_discovery.docker, "DockerClient", _Client)
|
||||
monkeypatch.setenv("SERVICEMAP_DOCKER_PROVIDER", "socket")
|
||||
docker_discovery._observer_clients.clear()
|
||||
|
||||
first = docker_discovery.observe_container_health("unix:///var/run/docker.sock")
|
||||
docker_discovery.observe_container_health("unix:///var/run/docker.sock")
|
||||
|
||||
assert len(created) == 1 # reused across cycles
|
||||
assert calls == [True, True] # exactly one API call per cycle
|
||||
api, batch = first
|
||||
assert (api.name, api.state, api.health, api.healthcheck_present) == ("shop-api", "running", "healthy", True)
|
||||
assert api.stable_source_ref == "docker:compose:shop:api"
|
||||
assert (batch.state, batch.health, batch.healthcheck_present) == ("exited", None, False)
|
||||
docker_discovery._observer_clients.clear()
|
||||
|
||||
|
||||
def test_unchanged_fresh_evidence_is_not_rewritten_until_half_its_ttl(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
service = store.create_service(ServiceCreate(name="API", kind=ServiceKind.HTTP, url="https://api.test"))
|
||||
clock = [datetime(2026, 11, 18, 12, 0, tzinfo=UTC)]
|
||||
monkeypatch.setattr(store_module, "_now", lambda: clock[0])
|
||||
|
||||
def claim(status: HealthStatus = HealthStatus.HEALTHY) -> HealthEvidence:
|
||||
now = clock[0]
|
||||
return HealthEvidence(
|
||||
id=f"ev-{now.timestamp()}",
|
||||
subject_type="service",
|
||||
subject_id=service.id,
|
||||
service_id=service.id,
|
||||
provider=EvidenceProvider.DOCKER,
|
||||
provider_ref="api",
|
||||
status=status,
|
||||
scope=EvidenceScope.COMPONENT,
|
||||
confidence=0.95,
|
||||
observed_at=now,
|
||||
valid_until=now + timedelta(seconds=180),
|
||||
received_at=now,
|
||||
summary="Docker healthcheck",
|
||||
)
|
||||
|
||||
store.record_health_evidence(claim())
|
||||
first = store.health_evidence_for_service(service.id)[0]
|
||||
|
||||
clock[0] += timedelta(seconds=60) # 120 s of 180 s left: skip
|
||||
store.record_health_evidence(claim())
|
||||
assert store.health_evidence_for_service(service.id)[0].observed_at == first.observed_at
|
||||
|
||||
clock[0] += timedelta(seconds=40) # 80 s left (< half): renew
|
||||
store.record_health_evidence(claim())
|
||||
renewed = store.health_evidence_for_service(service.id)[0]
|
||||
assert renewed.observed_at == clock[0]
|
||||
assert renewed.id == first.id # same row, no history growth
|
||||
|
||||
clock[0] += timedelta(seconds=10) # a material change is always written
|
||||
store.record_health_evidence(claim(HealthStatus.DOWN))
|
||||
assert store.health_evidence_for_service(service.id)[0].status == HealthStatus.DOWN
|
||||
|
||||
|
||||
def test_every_connection_uses_normal_synchronous_under_wal(tmp_path: Path) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
with store._connect() as db:
|
||||
assert db.execute("PRAGMA journal_mode").fetchone()[0] == "wal"
|
||||
assert db.execute("PRAGMA synchronous").fetchone()[0] == 1 # NORMAL
|
||||
|
||||
|
||||
def test_concurrent_incident_sync_opens_one_incident_per_root(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
import threading
|
||||
|
||||
from app import incidents
|
||||
from app.models import ProbeResult
|
||||
|
||||
real_sync = incidents.sync_incidents
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
database = store.create_service(ServiceCreate(name="Database", kind=ServiceKind.TCP, host="db.local", port=5432))
|
||||
api = store.create_service(
|
||||
ServiceCreate(name="API", kind=ServiceKind.HTTP, url="https://api.local", depends_on=[database.id])
|
||||
)
|
||||
# Record the outage without the automatic reconciliation in save_probe.
|
||||
monkeypatch.setattr(incidents, "sync_incidents", lambda *_args, **_kwargs: [])
|
||||
for number, (service_id, status) in enumerate(
|
||||
[(database.id, HealthStatus.DOWN), (database.id, HealthStatus.DOWN), (api.id, HealthStatus.HEALTHY)]
|
||||
):
|
||||
store.save_probe(
|
||||
ProbeResult(
|
||||
id=f"probe-{number}",
|
||||
service_id=service_id,
|
||||
status=status,
|
||||
latency_ms=4.0,
|
||||
detail=status.value,
|
||||
checked_at=datetime.now(UTC) + timedelta(microseconds=number),
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(incidents, "sync_incidents", real_sync)
|
||||
assert store.list_incidents(active_only=True) == []
|
||||
|
||||
barrier = threading.Barrier(6)
|
||||
|
||||
def run() -> None:
|
||||
barrier.wait()
|
||||
real_sync(store)
|
||||
|
||||
threads = [threading.Thread(target=run) for _ in range(6)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
assert len(store.list_incidents(active_only=True)) == 1
|
||||
opened = [event for event in store.list_events(100) if event.event_type == "incident.opened"]
|
||||
assert len(opened) == 1
|
||||
@@ -0,0 +1,375 @@
|
||||
"""v1.6.3 regression guards for health-evidence reads and graph resolution.
|
||||
|
||||
Production profiling showed 78% of server CPU in a full ``health_evidence``
|
||||
scan, issued once per node of a recursive, un-memoised health walk. These
|
||||
tests pin the indexed query shape, equivalence of the bulk and single reads,
|
||||
the batched graph result and the bounded query count.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import random
|
||||
import sqlite3
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from statistics import quantiles
|
||||
from time import perf_counter
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main as main_module
|
||||
from app.discovery_store import DiscoveryStore
|
||||
|
||||
from app.health import SEVERITY, status_maps, topology_health
|
||||
from app.incidents import incident_overview, sync_incidents
|
||||
from app.models import (
|
||||
ConfigService,
|
||||
EvidenceProvider,
|
||||
EvidenceScope,
|
||||
HealthEvidence,
|
||||
HealthStatus,
|
||||
ServiceCreate,
|
||||
ServiceKind,
|
||||
)
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def _service(store: Store, name: str, depends_on: list[str] | None = None):
|
||||
return store.create_service(
|
||||
ServiceCreate(
|
||||
name=name,
|
||||
kind=ServiceKind.HTTP,
|
||||
url=f"https://{name.lower()}.test",
|
||||
depends_on=depends_on or [],
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _component(
|
||||
evidence_id: str,
|
||||
service_id: str,
|
||||
status: HealthStatus,
|
||||
*,
|
||||
at: datetime | None = None,
|
||||
) -> HealthEvidence:
|
||||
now = at or datetime.now(UTC)
|
||||
return HealthEvidence(
|
||||
id=evidence_id,
|
||||
subject_type="service",
|
||||
subject_id=service_id,
|
||||
service_id=service_id,
|
||||
provider=EvidenceProvider.DOCKER,
|
||||
provider_ref=service_id,
|
||||
status=status,
|
||||
scope=EvidenceScope.COMPONENT,
|
||||
confidence=0.95,
|
||||
observed_at=now,
|
||||
valid_until=datetime.now(UTC) + timedelta(minutes=5),
|
||||
received_at=now,
|
||||
summary="Docker healthcheck",
|
||||
)
|
||||
|
||||
|
||||
def _application(evidence_id: str, status: HealthStatus) -> HealthEvidence:
|
||||
now = datetime.now(UTC)
|
||||
return HealthEvidence(
|
||||
id=evidence_id,
|
||||
subject_type="application",
|
||||
subject_id="appops:northstar",
|
||||
provider=EvidenceProvider.APPOPS,
|
||||
provider_ref="northstar",
|
||||
status=status,
|
||||
scope=EvidenceScope.APPLICATION,
|
||||
confidence=0.9,
|
||||
observed_at=now,
|
||||
valid_until=now + timedelta(minutes=5),
|
||||
received_at=now,
|
||||
summary="AppOps aggregate",
|
||||
)
|
||||
|
||||
|
||||
def _plan(store: Store, sql: str, params: list[object]) -> list[str]:
|
||||
with sqlite3.connect(store.path) as db:
|
||||
return [row[3] for row in db.execute(f"EXPLAIN QUERY PLAN {sql}", params)]
|
||||
|
||||
|
||||
def test_evidence_reads_use_indexes_instead_of_full_scans(tmp_path: Path, monkeypatch) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
service = _service(store, "API")
|
||||
store.record_health_evidence(_component("ev-1", service.id, HealthStatus.HEALTHY))
|
||||
|
||||
captured: list[str] = []
|
||||
original = sqlite3.Connection.execute
|
||||
|
||||
class Recording(sqlite3.Connection):
|
||||
def execute(self, sql, parameters=(), /): # type: ignore[override]
|
||||
if "health_evidence" in sql and sql.lstrip().upper().startswith(("SELECT", "WITH")):
|
||||
captured.append(sql)
|
||||
return original(self, sql, parameters)
|
||||
|
||||
real_connect = sqlite3.connect
|
||||
monkeypatch.setattr(
|
||||
"app.store.sqlite3.connect",
|
||||
lambda *args, **kwargs: real_connect(*args, factory=Recording, **kwargs),
|
||||
)
|
||||
store.health_evidence_for_service(service.id)
|
||||
store.health_evidence_for_services([service.id])
|
||||
monkeypatch.setattr("app.store.sqlite3.connect", real_connect)
|
||||
|
||||
single, bulk = captured[-2], captured[-1]
|
||||
for sql, params in (
|
||||
(single, [service.id, service.id, 100]),
|
||||
(bulk, [service.id, service.id, 100]),
|
||||
):
|
||||
details = _plan(store, sql, params)
|
||||
assert not any(detail in {"SCAN e", "SCAN health_evidence"} for detail in details), details
|
||||
|
||||
|
||||
def test_bulk_and_single_evidence_reads_return_the_same_rows(tmp_path: Path) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
api = _service(store, "API")
|
||||
worker = _service(store, "Worker")
|
||||
base = datetime.now(UTC) - timedelta(hours=2)
|
||||
# Status flips create superseded history for the direct claim.
|
||||
for index, status in enumerate([HealthStatus.HEALTHY, HealthStatus.DOWN, HealthStatus.HEALTHY]):
|
||||
store.record_health_evidence(
|
||||
_component(f"api-{index}", api.id, status, at=base + timedelta(minutes=index))
|
||||
)
|
||||
store.record_health_evidence(_component("worker-0", worker.id, HealthStatus.DOWN, at=base))
|
||||
# One application claim linked to both components.
|
||||
store.record_health_evidence(_application("app-0", HealthStatus.HEALTHY), service_ids=[api.id, worker.id])
|
||||
|
||||
bulk = store.health_evidence_for_services([api.id, worker.id])
|
||||
for service in (api, worker):
|
||||
single = store.health_evidence_for_service(service.id)
|
||||
assert [item.id for item in bulk[service.id]] == [item.id for item in single]
|
||||
assert {item.id for item in bulk[api.id]} == {"api-0", "api-1", "api-2", "app-0"}
|
||||
assert {item.id for item in bulk[worker.id]} == {"worker-0", "app-0"}
|
||||
|
||||
limited = store.health_evidence_for_services([api.id], limit_per_service=2)
|
||||
assert [item.id for item in limited[api.id]] == [
|
||||
item.id for item in store.health_evidence_for_service(api.id, limit=2)
|
||||
]
|
||||
|
||||
|
||||
def test_prune_removes_only_old_superseded_history(tmp_path: Path) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
api = _service(store, "API")
|
||||
old = datetime.now(UTC) - timedelta(days=30)
|
||||
store.record_health_evidence(_component("old-down", api.id, HealthStatus.DOWN, at=old))
|
||||
store.record_health_evidence(
|
||||
_component("old-up", api.id, HealthStatus.HEALTHY, at=old + timedelta(minutes=1))
|
||||
)
|
||||
store.record_health_evidence(_component("recent-down", api.id, HealthStatus.DOWN))
|
||||
store.record_health_evidence(_application("app-0", HealthStatus.HEALTHY), service_ids=[api.id])
|
||||
before = store.service_health(api.id)
|
||||
|
||||
assert store.prune_health_evidence(7) == 2
|
||||
|
||||
remaining = {item.id for item in store.health_evidence_for_service(api.id)}
|
||||
assert remaining == {"recent-down", "app-0"}
|
||||
assert store.service_health(api.id) == before == HealthStatus.DOWN
|
||||
with sqlite3.connect(store.path) as db:
|
||||
orphans = db.execute(
|
||||
"SELECT COUNT(*) FROM health_evidence_service_links "
|
||||
"WHERE evidence_id NOT IN (SELECT id FROM health_evidence)"
|
||||
).fetchone()[0]
|
||||
assert orphans == 0
|
||||
assert store.prune_health_evidence(0) == 0
|
||||
|
||||
|
||||
def test_batched_discovery_context_matches_per_service_reads(tmp_path: Path) -> None:
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.models import DiscoveryConfidence, DiscoveryLifecycle, RelationEvidence
|
||||
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
discovery = DiscoveryStore(store)
|
||||
api = _service(store, "API")
|
||||
database = _service(store, "Database")
|
||||
lonely = _service(store, "Lonely")
|
||||
for index, service in enumerate((api, database)):
|
||||
source = discovery.save_source(
|
||||
source_type="docker",
|
||||
source_id=f"container-{index}",
|
||||
source_name=service.name,
|
||||
lifecycle=DiscoveryLifecycle.ACTIVE,
|
||||
metadata={},
|
||||
)
|
||||
discovery.attach_source(service.id, source.id)
|
||||
now = datetime.now(UTC)
|
||||
discovery.save_evidence(
|
||||
RelationEvidence(
|
||||
id="rel-1",
|
||||
source_service_id=api.id,
|
||||
target_service_id=database.id,
|
||||
evidence_type="compose",
|
||||
confidence=DiscoveryConfidence.HIGH,
|
||||
explanation="depends_on",
|
||||
first_seen_at=now,
|
||||
last_seen_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
ids = [api.id, database.id, lonely.id]
|
||||
sources = discovery.sources_for_services(ids)
|
||||
relations = discovery.evidence_for_services(ids)
|
||||
for service_id in ids:
|
||||
assert sources[service_id] == discovery.sources_for_service(service_id)
|
||||
assert relations[service_id] == discovery.evidence_for_service(service_id)
|
||||
assert [item.id for item in relations[database.id]] == ["rel-1"]
|
||||
assert relations[lonely.id] == [] and sources[lonely.id] == []
|
||||
|
||||
|
||||
def _reference_effective(
|
||||
graph: dict[str, list[str]], direct: dict[str, HealthStatus]
|
||||
) -> dict[str, HealthStatus]:
|
||||
"""The pre-v1.6.3 recursive per-path algorithm, kept as an oracle."""
|
||||
|
||||
def dependency(node: str, visiting: set[str]) -> HealthStatus:
|
||||
if not graph[node]:
|
||||
return HealthStatus.HEALTHY
|
||||
states = [
|
||||
effective(item, visiting) if item in graph else HealthStatus.UNKNOWN
|
||||
for item in graph[node]
|
||||
]
|
||||
return max(states, key=lambda status: SEVERITY[status])
|
||||
|
||||
def effective(node: str, visiting: set[str]) -> HealthStatus:
|
||||
if node in visiting:
|
||||
return HealthStatus.UNKNOWN
|
||||
own = direct[node]
|
||||
if own == HealthStatus.MAINTENANCE:
|
||||
return own
|
||||
dep = dependency(node, {*visiting, node})
|
||||
if own == HealthStatus.DOWN:
|
||||
return own
|
||||
if dep == HealthStatus.DOWN:
|
||||
return HealthStatus.DEGRADED
|
||||
if dep in {HealthStatus.DEGRADED, HealthStatus.RECOVERING} and own in {
|
||||
HealthStatus.HEALTHY,
|
||||
HealthStatus.RECOVERING,
|
||||
}:
|
||||
return HealthStatus.DEGRADED
|
||||
return own
|
||||
|
||||
return {node: effective(node, set()) for node in graph}
|
||||
|
||||
|
||||
def test_batched_graph_matches_recursive_reference_on_random_dags() -> None:
|
||||
rng = random.Random(163)
|
||||
statuses = list(HealthStatus)
|
||||
for _ in range(200):
|
||||
size = rng.randint(1, 14)
|
||||
nodes = [f"n{index}" for index in range(size)]
|
||||
# Acyclic by construction: a node only depends on lower indexes.
|
||||
graph = {
|
||||
node: rng.sample(nodes[:index], k=rng.randint(0, min(3, index)))
|
||||
for index, node in enumerate(nodes)
|
||||
}
|
||||
if rng.random() < 0.2:
|
||||
graph[nodes[-1]].append("missing")
|
||||
direct = {node: rng.choice(statuses) for node in nodes}
|
||||
services = [_fake_service(node, graph[node]) for node in nodes]
|
||||
effective, _ = status_maps(services, direct_statuses=direct)
|
||||
assert effective == _reference_effective(graph, direct), (graph, direct)
|
||||
|
||||
|
||||
def _fake_service(identifier: str, depends_on: list[str]):
|
||||
from app.models import Service
|
||||
|
||||
now = datetime.now(UTC)
|
||||
return Service(
|
||||
id=identifier,
|
||||
name=identifier,
|
||||
kind=ServiceKind.HTTP,
|
||||
url="https://example.test",
|
||||
depends_on=depends_on,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
|
||||
|
||||
def test_incident_resolution_uses_a_bounded_number_of_queries(tmp_path: Path, monkeypatch) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
# A deep chain plus a fan-in reproduces the shape that made the old walk
|
||||
# re-read every shared dependency once per path.
|
||||
previous: list[str] = []
|
||||
for index in range(40):
|
||||
service = _service(store, f"S{index:02d}", depends_on=previous[-2:])
|
||||
status = HealthStatus.DOWN if index == 0 else HealthStatus.HEALTHY
|
||||
store.record_health_evidence(_component(f"ev-{index}", service.id, status))
|
||||
previous.append(service.id)
|
||||
|
||||
connections = 0
|
||||
original = store._connect
|
||||
|
||||
def counting_connect():
|
||||
nonlocal connections
|
||||
connections += 1
|
||||
return original()
|
||||
|
||||
monkeypatch.setattr(store, "_connect", counting_connect)
|
||||
overview = incident_overview(store)
|
||||
assert connections <= 4, connections
|
||||
assert [candidate.service_id for candidate in overview.candidates] == [previous[0]]
|
||||
assert len(overview.candidates[0].affected_service_ids) == 39
|
||||
|
||||
health = topology_health(store)
|
||||
assert health.effective[previous[0]] == HealthStatus.DOWN
|
||||
assert health.effective[previous[-1]] == HealthStatus.DEGRADED
|
||||
|
||||
connections = 0
|
||||
sync_incidents(store)
|
||||
# One graph resolution plus incident journal writes; never one per node.
|
||||
assert connections < 20, connections
|
||||
|
||||
|
||||
def test_topology_request_budget_at_300_services(tmp_path: Path, monkeypatch) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
definitions = [
|
||||
ConfigService(
|
||||
name=f"Service {index}",
|
||||
kind=ServiceKind.HTTP,
|
||||
url=f"https://service-{index}.test",
|
||||
domain="Benchmark",
|
||||
application=f"Application {index // 10}",
|
||||
depends_on=[f"Service {index - 1}"] if index % 10 else [],
|
||||
)
|
||||
for index in range(300)
|
||||
]
|
||||
assert store.import_config_services(definitions, "merge").created == 300
|
||||
for service in store.list_services():
|
||||
store.record_health_evidence(_component(f"ev-{service.id}", service.id, HealthStatus.HEALTHY))
|
||||
monkeypatch.setattr(main_module, "store", store)
|
||||
monkeypatch.setattr(main_module, "discovery_store", DiscoveryStore(store))
|
||||
|
||||
connections = 0
|
||||
original = store._connect
|
||||
|
||||
def counting_connect():
|
||||
nonlocal connections
|
||||
connections += 1
|
||||
return original()
|
||||
|
||||
monkeypatch.setattr(store, "_connect", counting_connect)
|
||||
client = TestClient(main_module.app)
|
||||
budget_ms = os.environ.get("SERVICEMAP_API_P95_BUDGET_MS")
|
||||
|
||||
for endpoint in ("/api/v1/topology/semantic", "/api/v1/overview"):
|
||||
connections = 0
|
||||
assert client.get(endpoint).status_code == 200
|
||||
assert connections <= 30, (endpoint, connections)
|
||||
elapsed_ms = []
|
||||
for _ in range(20):
|
||||
if endpoint.endswith("/semantic"):
|
||||
# A provider or topology change invalidates this representation in production.
|
||||
main_module.semantic_cache.clear()
|
||||
started = perf_counter()
|
||||
response = client.get(endpoint)
|
||||
elapsed_ms.append((perf_counter() - started) * 1000)
|
||||
assert response.status_code == 200
|
||||
p95_ms = quantiles(elapsed_ms, n=20, method="inclusive")[-1]
|
||||
print(f"{endpoint} recompute p95: {p95_ms:.1f} ms")
|
||||
if budget_ms is not None:
|
||||
assert p95_ms <= float(budget_ms), (endpoint, p95_ms, budget_ms)
|
||||
@@ -0,0 +1,130 @@
|
||||
"""v1.6.3 background loops survive any failure and report readiness."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main as main_module
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.loops import LoopRegistry, run_periodic
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def test_a_failing_cycle_is_logged_and_the_loop_keeps_running(caplog) -> None:
|
||||
calls: list[int] = []
|
||||
|
||||
async def work() -> None:
|
||||
calls.append(len(calls))
|
||||
if len(calls) == 1:
|
||||
# The failure that used to end the observation loop silently.
|
||||
raise sqlite3.OperationalError("database is locked")
|
||||
|
||||
async def scenario() -> LoopRegistry:
|
||||
registry = LoopRegistry()
|
||||
task = asyncio.create_task(
|
||||
run_periodic("observation", work, interval_seconds=0.01, registry=registry, max_backoff_seconds=0.01)
|
||||
)
|
||||
while len(calls) < 3:
|
||||
await asyncio.sleep(0.005)
|
||||
status = registry.snapshot()[0]
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
assert registry.snapshot() == [] # unregistered on shutdown
|
||||
return status
|
||||
|
||||
loop_logger = logging.getLogger("servicemap.loops")
|
||||
loop_logger.addHandler(caplog.handler)
|
||||
try:
|
||||
status = asyncio.run(scenario())
|
||||
finally:
|
||||
loop_logger.removeHandler(caplog.handler)
|
||||
assert len(calls) >= 3
|
||||
assert status["healthy"] is True
|
||||
assert status["consecutive_failures"] == 0
|
||||
assert "OperationalError: database is locked" in status["last_error"]
|
||||
assert "Background loop observation failed" in caplog.text
|
||||
|
||||
|
||||
def test_a_loop_without_recent_success_is_reported_unhealthy() -> None:
|
||||
registry = LoopRegistry()
|
||||
status = registry.register("observation", 60)
|
||||
status.started_at -= 10_000
|
||||
assert registry.all_healthy() is False
|
||||
status.paused = True # e.g. demo mode: idle on purpose, not stalled
|
||||
assert registry.all_healthy() is True
|
||||
|
||||
|
||||
def test_ready_endpoint_reports_database_and_loops(tmp_path: Path) -> None:
|
||||
main_module.store = Store(str(tmp_path / "servicemap.db"))
|
||||
main_module.discovery_store = DiscoveryStore(main_module.store)
|
||||
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
|
||||
client = TestClient(main_module.app)
|
||||
|
||||
response = client.get("/ready")
|
||||
assert response.status_code == 200
|
||||
assert response.json()["database"] == "ok"
|
||||
|
||||
stalled = main_module.loop_registry.register("observation-test", 60)
|
||||
stalled.started_at -= 10_000
|
||||
try:
|
||||
response = client.get("/ready")
|
||||
assert response.status_code == 503
|
||||
body = response.json()
|
||||
assert body["status"] == "not_ready"
|
||||
assert any(item["name"] == "observation-test" and not item["healthy"] for item in body["loops"])
|
||||
finally:
|
||||
main_module.loop_registry.unregister("observation-test")
|
||||
|
||||
|
||||
def test_zero_observation_interval_does_not_register_observer(tmp_path: Path, monkeypatch) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
monkeypatch.setattr(main_module, "store", store)
|
||||
monkeypatch.setattr(main_module, "OBSERVATION_INTERVAL", 0)
|
||||
monkeypatch.setattr(main_module, "DISCOVERY_INTERVAL", 0)
|
||||
monkeypatch.setattr(main_module, "PROBE_INTERVAL", 0)
|
||||
monkeypatch.setattr(main_module, "BACKUP_INTERVAL_HOURS", 0)
|
||||
with TestClient(main_module.app) as client:
|
||||
assert all(item["name"] != "observation" for item in client.get("/ready").json()["loops"])
|
||||
|
||||
|
||||
def test_maintenance_prunes_observations_of_old_runs_and_checkpoints(tmp_path: Path) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
discovery = DiscoveryStore(store)
|
||||
with sqlite3.connect(store.path) as db:
|
||||
for index in range(12):
|
||||
db.execute(
|
||||
"INSERT INTO discovery_runs (id, status, started_at) VALUES (?, 'completed', ?)",
|
||||
(f"run-{index:02d}", f"2026-11-{index + 1:02d}T00:00:00+00:00"),
|
||||
)
|
||||
db.execute(
|
||||
"INSERT INTO discovery_sources (id, source_type, source_id, first_seen_at, last_seen_at) "
|
||||
"VALUES ('src', 'docker', 'c1', '2026-11-01T00:00:00+00:00', '2026-11-01T00:00:00+00:00')"
|
||||
)
|
||||
for index in range(12):
|
||||
db.execute(
|
||||
"INSERT INTO discovery_observations (id, run_id, source_id, source_type, source_name, lifecycle, "
|
||||
"change_type, observed_at) VALUES (?, ?, 'src', 'docker', 'c1', 'active', 'unchanged', ?)",
|
||||
(f"obs-{index}", f"run-{index:02d}", f"2026-11-{index + 1:02d}T00:00:00+00:00"),
|
||||
)
|
||||
db.execute(
|
||||
"INSERT INTO topology_change_events (id, event_type, detail, created_at) "
|
||||
"VALUES ('old', 'dependency_added', 'x', '2020-01-01T00:00:00+00:00')"
|
||||
)
|
||||
|
||||
assert discovery.prune_observations(10) == 2
|
||||
assert discovery.prune_change_events(90) == 1
|
||||
store.checkpoint()
|
||||
with sqlite3.connect(store.path) as db:
|
||||
remaining = {row[0] for row in db.execute("SELECT run_id FROM discovery_observations")}
|
||||
runs = db.execute("SELECT COUNT(*) FROM discovery_runs").fetchone()[0]
|
||||
assert remaining == {f"run-{index:02d}" for index in range(2, 12)}
|
||||
assert runs == 12 # runs are kept; suggestions reference them
|
||||
@@ -0,0 +1,131 @@
|
||||
"""v1.6.3 operator management: maintenance windows, incident lifecycle, events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main as main_module
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.models import IncidentRecord, IncidentStatus, ServiceCreate, ServiceKind
|
||||
from app.store import Store
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def store(tmp_path: Path) -> Store:
|
||||
return Store(str(tmp_path / "servicemap.db"))
|
||||
|
||||
|
||||
def _service(store: Store, name: str = "API"):
|
||||
return store.create_service(ServiceCreate(name=name, kind=ServiceKind.HTTP, url=f"https://{name.lower()}.test"))
|
||||
|
||||
|
||||
def _incident(store: Store, root_id: str) -> IncidentRecord:
|
||||
now = datetime.now(UTC)
|
||||
record = IncidentRecord(
|
||||
id="inc-1",
|
||||
status=IncidentStatus.OPEN,
|
||||
root_service_id=root_id,
|
||||
root_service_name="API",
|
||||
started_at=now,
|
||||
detected_at=now,
|
||||
title="API is down",
|
||||
root_cause_reason="test",
|
||||
latest_update_at=now,
|
||||
)
|
||||
store.upsert_incident(record)
|
||||
return record
|
||||
|
||||
|
||||
def test_maintenance_window_ends_automatically(store: Store) -> None:
|
||||
service = _service(store)
|
||||
until = datetime.now(UTC) + timedelta(minutes=30)
|
||||
store.set_maintenance(service.id, True, "Patching", until)
|
||||
assert store.maintenance_windows()[service.id] == until
|
||||
assert store.get_service(service.id).maintenance_enabled
|
||||
|
||||
# Not yet due.
|
||||
assert store.expire_maintenance_windows(datetime.now(UTC)) == []
|
||||
# Due: maintenance ends and the window disappears.
|
||||
assert store.expire_maintenance_windows(until + timedelta(seconds=1)) == [service.id]
|
||||
assert not store.get_service(service.id).maintenance_enabled
|
||||
assert store.maintenance_windows() == {}
|
||||
|
||||
# Ending maintenance by hand also removes a pending window.
|
||||
store.set_maintenance(service.id, True, None, datetime.now(UTC) + timedelta(hours=1))
|
||||
store.set_maintenance(service.id, False)
|
||||
assert store.maintenance_windows() == {}
|
||||
|
||||
with pytest.raises(ValueError, match="toekomst"):
|
||||
store.set_maintenance(service.id, True, None, datetime.now(UTC) - timedelta(minutes=1))
|
||||
|
||||
|
||||
def test_incident_acknowledge_is_idempotent_and_can_be_resolved_with_notes(store: Store) -> None:
|
||||
service = _service(store)
|
||||
_incident(store, service.id)
|
||||
|
||||
first = store.acknowledge_incident("inc-1")
|
||||
second = store.acknowledge_incident("inc-1")
|
||||
assert second.acknowledged_at == first.acknowledged_at
|
||||
timeline = [item.event_type for item in store.incident_timeline("inc-1")]
|
||||
assert timeline.count("incident.acknowledged") == 1
|
||||
|
||||
store.add_incident_note("inc-1", "Restarted the container")
|
||||
resolved = store.resolve_incident("inc-1", "false alarm")
|
||||
assert resolved.status == IncidentStatus.RESOLVED and resolved.resolved_at is not None
|
||||
messages = [item.message for item in store.incident_timeline("inc-1")]
|
||||
assert "Restarted the container" in messages
|
||||
assert any("handmatig opgelost: false alarm" in message for message in messages)
|
||||
# Resolving again changes nothing.
|
||||
assert store.resolve_incident("inc-1").resolved_at == resolved.resolved_at
|
||||
|
||||
|
||||
def test_event_journal_filters_by_family_and_pages(store: Store) -> None:
|
||||
service = _service(store)
|
||||
_incident(store, service.id)
|
||||
store.add_incident_note("inc-1", "one")
|
||||
store.add_incident_note("inc-1", "two")
|
||||
store.set_maintenance(service.id, True)
|
||||
|
||||
family = store.list_events(event_type="incident.")
|
||||
assert family and all(item.event_type.startswith("incident.") for item in family)
|
||||
exact = store.list_events(event_type="service.maintenance_changed")
|
||||
assert [item.event_type for item in exact] == ["service.maintenance_changed"]
|
||||
|
||||
page = store.list_events(limit=2)
|
||||
older = store.list_events(limit=50, before=page[-1].created_at)
|
||||
assert all(item.created_at < page[-1].created_at for item in older)
|
||||
assert {item.id for item in page}.isdisjoint({item.id for item in older})
|
||||
|
||||
|
||||
def test_management_routes(tmp_path: Path) -> None:
|
||||
main_module.store = Store(str(tmp_path / "servicemap.db"))
|
||||
main_module.discovery_store = DiscoveryStore(main_module.store)
|
||||
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
|
||||
client = TestClient(main_module.app)
|
||||
service = _service(main_module.store)
|
||||
_incident(main_module.store, service.id)
|
||||
|
||||
until = (datetime.now(UTC) + timedelta(hours=2)).isoformat()
|
||||
response = client.post(f"/api/v1/services/{service.id}/maintenance", json={"enabled": True, "until": until})
|
||||
assert response.status_code == 200
|
||||
snapshot = client.get(f"/api/v1/services/{service.id}").json()
|
||||
assert snapshot["maintenance_until"] is not None
|
||||
past = (datetime.now(UTC) - timedelta(hours=1)).isoformat()
|
||||
assert client.post(
|
||||
f"/api/v1/services/{service.id}/maintenance", json={"enabled": True, "until": past}
|
||||
).status_code == 422
|
||||
|
||||
note = client.post("/api/v1/incidents/inc-1/notes", json={"text": "Investigating"})
|
||||
assert note.status_code == 200
|
||||
assert any(item["message"] == "Investigating" for item in note.json()["timeline"])
|
||||
resolved = client.post("/api/v1/incidents/inc-1/resolve", json={"note": "stale"})
|
||||
assert resolved.json()["incident"]["status"] == "resolved"
|
||||
assert client.post("/api/v1/incidents/missing/resolve").status_code == 404
|
||||
|
||||
events = client.get("/api/v1/events", params={"event_type": "incident."}).json()
|
||||
assert events and all(item["event_type"].startswith("incident.") for item in events)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""v1.6.3 realtime guards: thread-free SSE fan-out and material evidence events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
from app import store as store_module
|
||||
from app.events import EventBus, next_event
|
||||
from app.models import HealthStatus, ProbeResult, ServiceCreate, ServiceKind
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def test_waiting_subscribers_do_not_hold_threads_and_receive_cross_thread_publishes() -> None:
|
||||
async def scenario() -> None:
|
||||
bus = EventBus()
|
||||
subscriptions = [bus.subscribe() for _ in range(25)]
|
||||
threads_before = threading.active_count()
|
||||
waiters = [asyncio.create_task(next_event(item, timeout=2.0)) for item in subscriptions]
|
||||
await asyncio.sleep(0.05)
|
||||
# 25 parked SSE clients must not occupy 25 executor threads.
|
||||
assert threading.active_count() <= threads_before + 1
|
||||
|
||||
publisher = threading.Thread(target=bus.publish, args=({"event_type": "probe.completed"},))
|
||||
publisher.start()
|
||||
publisher.join()
|
||||
received = await asyncio.gather(*waiters)
|
||||
assert all(item == {"event_type": "probe.completed"} for item in received)
|
||||
assert bus.subscriber_count == 25
|
||||
for item in subscriptions:
|
||||
bus.unsubscribe(item)
|
||||
assert bus.subscriber_count == 0
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_idle_stream_times_out_to_keepalive_and_overflow_keeps_newest() -> None:
|
||||
async def scenario() -> None:
|
||||
bus = EventBus(max_queue_size=2)
|
||||
subscription = bus.subscribe()
|
||||
assert await next_event(subscription, timeout=0.01) is None
|
||||
|
||||
for index in range(5):
|
||||
bus.publish({"event_type": "probe.completed", "n": index})
|
||||
await asyncio.sleep(0) # let call_soon_threadsafe deliveries run
|
||||
first = await next_event(subscription, timeout=0.1)
|
||||
second = await next_event(subscription, timeout=0.1)
|
||||
assert [first["n"], second["n"]] == [3, 4]
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_repeated_probe_with_only_latency_change_is_not_a_material_evidence_event(
|
||||
tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
store = Store(str(tmp_path / "servicemap.db"))
|
||||
service = store.create_service(
|
||||
ServiceCreate(name="API", kind=ServiceKind.HTTP, url="https://api.test")
|
||||
)
|
||||
published: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(store_module.event_bus, "publish", published.append)
|
||||
|
||||
for index, latency in enumerate((12.0, 48.0, 7.5)):
|
||||
store.save_probe(
|
||||
ProbeResult(
|
||||
id=f"probe-{index}",
|
||||
service_id=service.id,
|
||||
status=HealthStatus.HEALTHY,
|
||||
latency_ms=latency,
|
||||
detail="HTTP 200",
|
||||
checked_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
|
||||
evidence_events = [item for item in published if item["event_type"] == "health.evidence_changed"]
|
||||
# The first claim is new; later identical claims differ only in volatile keys.
|
||||
assert len(evidence_events) == 1
|
||||
# Probe completion itself is still announced every time.
|
||||
assert sum(item["event_type"] == "probe.completed" for item in published) == 3
|
||||
|
||||
store.save_probe(
|
||||
ProbeResult(
|
||||
id="probe-down",
|
||||
service_id=service.id,
|
||||
status=HealthStatus.DOWN,
|
||||
latency_ms=None,
|
||||
detail="Connection refused",
|
||||
checked_at=datetime.now(UTC),
|
||||
)
|
||||
)
|
||||
evidence_events = [item for item in published if item["event_type"] == "health.evidence_changed"]
|
||||
assert len(evidence_events) == 2
|
||||
@@ -0,0 +1,156 @@
|
||||
"""v1.6.3 security baseline: admin token for writes, origin/host checks, limits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.requests import Request
|
||||
|
||||
from app import auth
|
||||
from app import main as main_module
|
||||
from app.config_io import parse_document
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.store import Store
|
||||
|
||||
SERVICE = {"name": "API", "kind": "http", "url": "https://api.test"}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
|
||||
main_module.store = Store(str(tmp_path / "servicemap.db"))
|
||||
main_module.discovery_store = DiscoveryStore(main_module.store)
|
||||
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
|
||||
monkeypatch.setenv("SERVICEMAP_DB", str(tmp_path / "servicemap.db"))
|
||||
monkeypatch.delenv("SERVICEMAP_ADMIN_TOKEN_FILE", raising=False)
|
||||
monkeypatch.delenv("SERVICEMAP_ALLOWED_HOSTS", raising=False)
|
||||
auth.reset_token_cache()
|
||||
yield TestClient(main_module.app)
|
||||
auth.reset_token_cache()
|
||||
|
||||
|
||||
def test_token_mode_keeps_reads_open_and_requires_the_token_for_writes(
|
||||
client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("SERVICEMAP_AUTH_MODE", "token")
|
||||
|
||||
assert client.get("/api/v1/services").status_code == 200
|
||||
assert client.get("/api/v1/topology/semantic").status_code == 200
|
||||
|
||||
refused = client.post("/api/v1/services", json=SERVICE)
|
||||
assert refused.status_code == 401
|
||||
assert refused.headers["www-authenticate"] == "Bearer"
|
||||
assert client.post(
|
||||
"/api/v1/services", json=SERVICE, headers={"Authorization": "Bearer wrong-token-value-123456789"}
|
||||
).status_code == 401
|
||||
|
||||
token_file = tmp_path / "admin-token"
|
||||
assert token_file.exists() # generated on first use, next to the database
|
||||
token = token_file.read_text(encoding="utf-8").strip()
|
||||
assert len(token) >= 24
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
assert client.post("/api/v1/services", json=SERVICE, headers=headers).status_code == 201
|
||||
assert client.post("/api/v1/auth/verify", headers=headers).json() == {"ok": True}
|
||||
assert client.get("/api/v1/meta").json()["write_auth"] == "admin_token"
|
||||
|
||||
# The token is stable across reads and never regenerated over a file.
|
||||
auth.reset_token_cache()
|
||||
assert auth.admin_token() == token
|
||||
|
||||
|
||||
def test_too_short_admin_token_file_refuses_writes(
|
||||
client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("SERVICEMAP_AUTH_MODE", "token")
|
||||
short = tmp_path / "short-token"
|
||||
short.write_text("too-short\n", encoding="utf-8")
|
||||
monkeypatch.setenv("SERVICEMAP_ADMIN_TOKEN_FILE", str(short))
|
||||
response = client.post("/api/v1/services", json=SERVICE, headers={"Authorization": "Bearer too-short"})
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_cross_site_mutations_are_refused_even_without_authentication(client: TestClient) -> None:
|
||||
# disabled mode: no token, but a browser on another site cannot write.
|
||||
assert client.post(
|
||||
"/api/v1/services", json=SERVICE, headers={"Origin": "https://evil.example"}
|
||||
).status_code == 403
|
||||
assert client.post(
|
||||
"/api/v1/maintenance/prune", headers={"Sec-Fetch-Site": "cross-site"}
|
||||
).status_code == 403
|
||||
assert client.post("/api/v1/services", json=SERVICE, headers={"Origin": "null"}).status_code == 403
|
||||
# Same origin and header-less clients (curl, integrations) still work.
|
||||
assert client.post(
|
||||
"/api/v1/services", json=SERVICE, headers={"Origin": "http://testserver"}
|
||||
).status_code == 201
|
||||
assert client.post(
|
||||
"/api/v1/services", json={**SERVICE, "name": "Worker"}
|
||||
).status_code == 201
|
||||
# Behind nginx/NPM the Host may lose the port while Origin keeps it, or
|
||||
# the public name arrives as X-Forwarded-Host.
|
||||
assert client.post(
|
||||
"/api/v1/services",
|
||||
json={**SERVICE, "name": "Proxied"},
|
||||
headers={"Host": "192.0.2.10", "Origin": "http://192.0.2.10:1253"},
|
||||
).status_code == 201
|
||||
assert client.post(
|
||||
"/api/v1/services",
|
||||
json={**SERVICE, "name": "Forwarded"},
|
||||
headers={"Host": "backend:8000", "X-Forwarded-Host": "servicemap.lan", "Origin": "https://servicemap.lan"},
|
||||
).status_code == 201
|
||||
assert client.post(
|
||||
"/api/v1/services",
|
||||
json={**SERVICE, "name": "Spoofed"},
|
||||
headers={"Host": "192.0.2.10:1253", "Origin": "http://192.0.2.11:1253"},
|
||||
).status_code == 403
|
||||
# Reads are not affected by the Origin rule.
|
||||
assert client.get("/api/v1/services", headers={"Origin": "https://evil.example"}).status_code == 200
|
||||
|
||||
|
||||
def test_optional_host_allowlist_blocks_rebinding_but_keeps_loopback(
|
||||
client: TestClient, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setenv("SERVICEMAP_ALLOWED_HOSTS", "servicemap.lan,192.0.2.10")
|
||||
assert client.get("/api/v1/services", headers={"Host": "attacker.example"}).status_code == 400
|
||||
assert client.get("/api/v1/services", headers={"Host": "192.0.2.10:1253"}).status_code == 200
|
||||
assert client.get("/health", headers={"Host": "127.0.0.1:8000"}).status_code == 200
|
||||
|
||||
|
||||
def test_security_headers_body_limit_and_yaml_aliases(client: TestClient) -> None:
|
||||
response = client.get("/health")
|
||||
assert response.headers["x-content-type-options"] == "nosniff"
|
||||
assert response.headers["x-frame-options"] == "DENY"
|
||||
assert "frame-ancestors 'none'" in response.headers["content-security-policy"]
|
||||
|
||||
oversized = client.post(
|
||||
"/api/v1/config/import",
|
||||
content=b"x",
|
||||
headers={"Content-Length": str(5 * 1024 * 1024), "Content-Type": "application/json"},
|
||||
)
|
||||
assert oversized.status_code == 413
|
||||
|
||||
bomb = "a: &a [x, x]\nb: &b [*a, *a]\nc: [*b, *b]\n"
|
||||
with pytest.raises(ValueError, match="anchors of -aliassen"):
|
||||
parse_document(bomb, "yaml")
|
||||
|
||||
|
||||
def _request(method: str, path: str) -> Request:
|
||||
return Request({"type": "http", "method": method, "path": path, "headers": [], "query_string": b""})
|
||||
|
||||
|
||||
def test_oidc_role_requirements_cover_export_and_demo() -> None:
|
||||
assert auth.required_role(_request("GET", "/api/v1/services")) == "viewer"
|
||||
assert auth.required_role(_request("GET", "/api/v1/config")) == "admin"
|
||||
assert auth.required_role(_request("POST", "/api/v1/demo")) == "admin"
|
||||
assert auth.required_role(_request("POST", "/api/v1/demo/reset")) == "admin"
|
||||
assert auth.required_role(_request("PUT", "/api/v1/services/x")) == "operator"
|
||||
|
||||
|
||||
def test_cache_headers_keep_the_ui_current_after_a_deploy(client: TestClient) -> None:
|
||||
# index.html (served by the SPA fallback / static mount) must revalidate.
|
||||
response = client.get("/", follow_redirects=True)
|
||||
if response.status_code == 200:
|
||||
assert response.headers.get("cache-control") == "no-cache"
|
||||
api = client.get("/api/v1/services")
|
||||
assert "immutable" not in api.headers.get("cache-control", "")
|
||||
@@ -0,0 +1,133 @@
|
||||
"""v1.6.3 conditional GET and short-lived cache for the semantic topology."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import main as main_module
|
||||
from app.discovery import DiscoveryManager
|
||||
from app.discovery_store import DiscoveryStore
|
||||
from app.models import (
|
||||
EvidenceProvider,
|
||||
EvidenceScope,
|
||||
HealthEvidence,
|
||||
HealthStatus,
|
||||
SemanticTopology,
|
||||
)
|
||||
from app.response_cache import (
|
||||
GENERATED_AT_HEADER,
|
||||
RepresentationCache,
|
||||
etag_matches,
|
||||
next_freshness_boundary,
|
||||
representation,
|
||||
)
|
||||
from app.store import Store
|
||||
|
||||
|
||||
def _topology(at: datetime, coverage: dict[str, int]) -> SemanticTopology:
|
||||
return SemanticTopology(generated_at=at, monitoring_coverage=coverage)
|
||||
|
||||
|
||||
def test_representation_body_is_the_model_and_etag_ignores_generated_at() -> None:
|
||||
first = representation(_topology(datetime(2026, 11, 15, 10, tzinfo=UTC), {"docker": 3}))
|
||||
later = representation(_topology(datetime(2026, 11, 15, 11, tzinfo=UTC), {"docker": 3}))
|
||||
changed = representation(_topology(datetime(2026, 11, 15, 11, tzinfo=UTC), {"docker": 4}))
|
||||
|
||||
body = json.loads(first.body)
|
||||
assert body == json.loads(_topology(datetime(2026, 11, 15, 10, tzinfo=UTC), {"docker": 3}).model_dump_json())
|
||||
assert first.etag == later.etag
|
||||
assert first.etag != changed.etag
|
||||
assert first.generated_at.startswith("2026-11-15T10:00:00")
|
||||
|
||||
|
||||
def test_if_none_match_parsing() -> None:
|
||||
tag = '"abc"'
|
||||
assert etag_matches('"abc"', tag)
|
||||
assert etag_matches('W/"abc"', tag)
|
||||
assert etag_matches('"zzz", "abc"', tag)
|
||||
assert etag_matches("*", tag)
|
||||
assert not etag_matches('"zzz"', tag)
|
||||
assert not etag_matches(None, tag)
|
||||
assert not etag_matches("", tag)
|
||||
|
||||
|
||||
def test_freshness_boundary_is_the_next_fresh_stale_or_expired_transition() -> None:
|
||||
now = datetime(2026, 11, 15, 12, tzinfo=UTC)
|
||||
|
||||
def claim(observed_offset: int, valid_offset: int) -> HealthEvidence:
|
||||
return HealthEvidence(
|
||||
id=f"ev-{observed_offset}-{valid_offset}",
|
||||
subject_type="service",
|
||||
subject_id="svc",
|
||||
provider=EvidenceProvider.DOCKER,
|
||||
status=HealthStatus.HEALTHY,
|
||||
scope=EvidenceScope.COMPONENT,
|
||||
confidence=0.9,
|
||||
observed_at=now + timedelta(seconds=observed_offset),
|
||||
valid_until=now + timedelta(seconds=valid_offset),
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
# Fresh until +90 s; a stale claim expires at +20 s (valid_until -40 + ttl 60).
|
||||
assert next_freshness_boundary([claim(-60, 90), claim(-100, -40)], now) == now + timedelta(seconds=20)
|
||||
# Long expired claims never produce a boundary.
|
||||
assert next_freshness_boundary([claim(-500, -400)], now) is None
|
||||
assert next_freshness_boundary([], now) is None
|
||||
|
||||
|
||||
def test_cache_is_invalidated_by_events_age_and_boundaries() -> None:
|
||||
clock = [100.0]
|
||||
cache = RepresentationCache(max_age_seconds=10.0, clock=lambda: clock[0])
|
||||
value = representation(_topology(datetime(2026, 11, 15, tzinfo=UTC), {}))
|
||||
|
||||
cache.put("k", revision=5, value=value)
|
||||
assert cache.get("k", 5) is value
|
||||
assert cache.get("k", 6) is None # an event was published since
|
||||
cache.put("k", revision=6, value=value)
|
||||
clock[0] += 10.0
|
||||
assert cache.get("k", 6) is None # aged out
|
||||
cache.put("k", revision=6, value=value, valid_for_seconds=2.0)
|
||||
clock[0] += 2.5
|
||||
assert cache.get("k", 6) is None # freshness boundary crossed
|
||||
cache.put("k", revision=6, value=value, valid_for_seconds=0.0)
|
||||
assert cache.get("k", 6) is None # already at a boundary: not cached
|
||||
|
||||
|
||||
def test_semantic_endpoint_supports_conditional_get(tmp_path: Path) -> None:
|
||||
main_module.store = Store(str(tmp_path / "servicemap.db"))
|
||||
main_module.discovery_store = DiscoveryStore(main_module.store)
|
||||
main_module.discovery_manager = DiscoveryManager(main_module.store, main_module.discovery_store)
|
||||
main_module.semantic_cache.clear()
|
||||
client = TestClient(main_module.app)
|
||||
created = client.post(
|
||||
"/api/v1/services", json={"name": "API", "kind": "http", "url": "https://api.test"}
|
||||
)
|
||||
assert created.status_code == 201
|
||||
|
||||
first = client.get("/api/v1/topology/semantic")
|
||||
assert first.status_code == 200
|
||||
etag = first.headers["etag"]
|
||||
assert first.headers["cache-control"] == "no-cache"
|
||||
assert first.headers[GENERATED_AT_HEADER]
|
||||
assert [item["name"] for item in first.json()["components"]] == ["API"]
|
||||
|
||||
# Unchanged: 304 without a body, even after the short cache would expire.
|
||||
main_module.semantic_cache.clear()
|
||||
unchanged = client.get("/api/v1/topology/semantic", headers={"If-None-Match": etag})
|
||||
assert unchanged.status_code == 304
|
||||
assert unchanged.content == b""
|
||||
assert unchanged.headers["etag"] == etag
|
||||
assert unchanged.headers[GENERATED_AT_HEADER]
|
||||
|
||||
# A topology change publishes an event, invalidates the cache and the tag.
|
||||
assert client.post(
|
||||
"/api/v1/services", json={"name": "Worker", "kind": "http", "url": "https://worker.test"}
|
||||
).status_code == 201
|
||||
changed = client.get("/api/v1/topology/semantic", headers={"If-None-Match": etag})
|
||||
assert changed.status_code == 200
|
||||
assert changed.headers["etag"] != etag
|
||||
assert sorted(item["name"] for item in changed.json()["components"]) == ["API", "Worker"]
|
||||
@@ -0,0 +1,29 @@
|
||||
name: servicemap-demo
|
||||
|
||||
services:
|
||||
demo:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.unraid
|
||||
environment:
|
||||
SERVICEMAP_DEMO_ENABLED: "1"
|
||||
SERVICEMAP_PROBE_INTERVAL: "0"
|
||||
SERVICEMAP_DISCOVERY_INTERVAL_SECONDS: "0"
|
||||
SERVICEMAP_OBSERVATION_INTERVAL_SECONDS: "0"
|
||||
SERVICEMAP_BACKUP_INTERVAL_HOURS: "0"
|
||||
SERVICEMAP_AUTH_MODE: disabled
|
||||
SERVICEMAP_ALLOWED_HOSTS: "localhost,127.0.0.1"
|
||||
ports:
|
||||
- "127.0.0.1:${SERVICEMAP_DEMO_PORT:-1254}:8000"
|
||||
volumes:
|
||||
- demo_data:/data
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,size=32m
|
||||
|
||||
volumes:
|
||||
demo_data:
|
||||
@@ -19,6 +19,8 @@ services:
|
||||
SERVICEMAP_FLAP_THRESHOLD: ${SERVICEMAP_FLAP_THRESHOLD:-6}
|
||||
SERVICEMAP_OBSERVATION_INTERVAL_SECONDS: ${SERVICEMAP_OBSERVATION_INTERVAL_SECONDS:-60}
|
||||
SERVICEMAP_PROBE_HOST: ${SERVICEMAP_PROBE_HOST:-}
|
||||
SERVICEMAP_AUTH_MODE: ${SERVICEMAP_AUTH_MODE:-token}
|
||||
SERVICEMAP_ALLOWED_HOSTS: ${SERVICEMAP_ALLOWED_HOSTS:-}
|
||||
volumes:
|
||||
- ./data:/data
|
||||
healthcheck:
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
name: servicemap
|
||||
|
||||
services:
|
||||
servicemap:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.unraid
|
||||
container_name: servicemap
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
SERVICEMAP_DB: /data/servicemap.db
|
||||
SERVICEMAP_STATIC_DIR: /app/static
|
||||
SERVICEMAP_PROBE_INTERVAL: ${SERVICEMAP_PROBE_INTERVAL:-60}
|
||||
SERVICEMAP_PROBE_TIMEOUT: ${SERVICEMAP_PROBE_TIMEOUT:-5}
|
||||
SERVICEMAP_PROBE_RETRIES: ${SERVICEMAP_PROBE_RETRIES:-1}
|
||||
SERVICEMAP_PROBE_CONCURRENCY: ${SERVICEMAP_PROBE_CONCURRENCY:-10}
|
||||
SERVICEMAP_RETENTION_DAYS: ${SERVICEMAP_RETENTION_DAYS:-30}
|
||||
SERVICEMAP_EVENT_RETENTION_DAYS: ${SERVICEMAP_EVENT_RETENTION_DAYS:-90}
|
||||
SERVICEMAP_TLS_WARNING_DAYS: ${SERVICEMAP_TLS_WARNING_DAYS:-30}
|
||||
SERVICEMAP_FLAP_THRESHOLD: ${SERVICEMAP_FLAP_THRESHOLD:-6}
|
||||
SERVICEMAP_DISCOVERY_INTERVAL_SECONDS: ${SERVICEMAP_DISCOVERY_INTERVAL_SECONDS:-0}
|
||||
SERVICEMAP_OBSERVATION_INTERVAL_SECONDS: ${SERVICEMAP_OBSERVATION_INTERVAL_SECONDS:-60}
|
||||
# Broker mode is forced here. There is deliberately no Docker socket
|
||||
# environment or volume fallback in this deployment contract.
|
||||
SERVICEMAP_DOCKER_PROVIDER: broker
|
||||
SERVICEMAP_DOCKER_BROKER_URL: ${SERVICEMAP_DOCKER_BROKER_URL:?set SERVICEMAP_DOCKER_BROKER_URL}
|
||||
SERVICEMAP_DOCKER_BROKER_TOKEN_FILE: /run/secrets/servicemap-docker-broker.token
|
||||
SERVICEMAP_APPOPS_URL: ${SERVICEMAP_APPOPS_URL:-}
|
||||
SERVICEMAP_PROBE_HOST: ${SERVICEMAP_PROBE_HOST:-}
|
||||
SERVICEMAP_AUTH_MODE: ${SERVICEMAP_AUTH_MODE:-token}
|
||||
SERVICEMAP_ADMIN_TOKEN_FILE: ${SERVICEMAP_ADMIN_TOKEN_FILE:-}
|
||||
SERVICEMAP_ALLOWED_HOSTS: ${SERVICEMAP_ALLOWED_HOSTS:-}
|
||||
SERVICEMAP_BACKUP_INTERVAL_HOURS: ${SERVICEMAP_BACKUP_INTERVAL_HOURS:-24}
|
||||
SERVICEMAP_BACKUP_KEEP: ${SERVICEMAP_BACKUP_KEEP:-14}
|
||||
SERVICEMAP_OIDC_ISSUER: ${SERVICEMAP_OIDC_ISSUER:-}
|
||||
SERVICEMAP_OIDC_AUDIENCE: ${SERVICEMAP_OIDC_AUDIENCE:-}
|
||||
SERVICEMAP_OIDC_ROLE_CLAIMS: ${SERVICEMAP_OIDC_ROLE_CLAIMS:-groups,roles}
|
||||
SERVICEMAP_OIDC_VIEWER_GROUPS: ${SERVICEMAP_OIDC_VIEWER_GROUPS:-}
|
||||
SERVICEMAP_OIDC_OPERATOR_GROUPS: ${SERVICEMAP_OIDC_OPERATOR_GROUPS:-}
|
||||
SERVICEMAP_OIDC_ADMIN_GROUPS: ${SERVICEMAP_OIDC_ADMIN_GROUPS:-}
|
||||
volumes:
|
||||
- servicemap_data:/data
|
||||
- type: bind
|
||||
source: ${SERVICEMAP_DOCKER_BROKER_TOKEN_HOST_FILE:?set SERVICEMAP_DOCKER_BROKER_TOKEN_HOST_FILE}
|
||||
target: /run/secrets/servicemap-docker-broker.token
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
networks:
|
||||
- broker
|
||||
ports:
|
||||
- "${SERVICEMAP_PORT:-1253}:8000"
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=3).read()"]
|
||||
interval: 20s
|
||||
timeout: 5s
|
||||
start_period: 10s
|
||||
retries: 5
|
||||
labels:
|
||||
net.unraid.docker.managed: "dockerman"
|
||||
net.unraid.docker.webui: "http://${SERVICEMAP_WEBUI_HOST:-localhost}:${SERVICEMAP_PORT:-1253}"
|
||||
net.unraid.docker.icon: "http://${SERVICEMAP_WEBUI_HOST:-localhost}:${SERVICEMAP_PORT:-1253}/icons/servicemap-dockerman-256.png"
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,size=32m
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "20m"
|
||||
max-file: "3"
|
||||
|
||||
networks:
|
||||
broker:
|
||||
external: true
|
||||
name: ${SERVICEMAP_DOCKER_BROKER_NETWORK:?set SERVICEMAP_DOCKER_BROKER_NETWORK}
|
||||
|
||||
volumes:
|
||||
servicemap_data:
|
||||
name: servicemap_data
|
||||
+14
-2
@@ -7,6 +7,8 @@ services:
|
||||
dockerfile: Dockerfile.unraid
|
||||
container_name: servicemap
|
||||
restart: unless-stopped
|
||||
mem_limit: 2048m
|
||||
memswap_limit: 2048m
|
||||
environment:
|
||||
SERVICEMAP_DB: /data/servicemap.db
|
||||
SERVICEMAP_STATIC_DIR: /app/static
|
||||
@@ -28,9 +30,19 @@ services:
|
||||
SERVICEMAP_DOCKER_BROKER_TOKEN_FILE: ${SERVICEMAP_DOCKER_BROKER_TOKEN_FILE:-}
|
||||
SERVICEMAP_APPOPS_URL: ${SERVICEMAP_APPOPS_URL:-}
|
||||
SERVICEMAP_PROBE_HOST: ${SERVICEMAP_PROBE_HOST:-}
|
||||
# Disabled is backwards-compatible. OIDC mode is fail-closed and needs
|
||||
# "token" (default): reads stay open on the LAN, every change needs the
|
||||
# admin token generated in /data/admin-token on first start
|
||||
# (docker exec servicemap cat /data/admin-token). "disabled" restores
|
||||
# the unauthenticated v1.5 behaviour. OIDC mode is fail-closed and needs
|
||||
# issuer, audience and explicit role-group mappings before activation.
|
||||
SERVICEMAP_AUTH_MODE: ${SERVICEMAP_AUTH_MODE:-disabled}
|
||||
SERVICEMAP_AUTH_MODE: ${SERVICEMAP_AUTH_MODE:-token}
|
||||
# Verified daily backups in /data/backups (0 disables), newest N kept.
|
||||
SERVICEMAP_BACKUP_INTERVAL_HOURS: ${SERVICEMAP_BACKUP_INTERVAL_HOURS:-24}
|
||||
SERVICEMAP_BACKUP_KEEP: ${SERVICEMAP_BACKUP_KEEP:-14}
|
||||
SERVICEMAP_ADMIN_TOKEN_FILE: ${SERVICEMAP_ADMIN_TOKEN_FILE:-}
|
||||
# Optional DNS-rebinding guard: comma-separated host names, e.g.
|
||||
# 127.0.0.1,servicemap.lan. Empty accepts any Host.
|
||||
SERVICEMAP_ALLOWED_HOSTS: ${SERVICEMAP_ALLOWED_HOSTS:-}
|
||||
SERVICEMAP_OIDC_ISSUER: ${SERVICEMAP_OIDC_ISSUER:-}
|
||||
SERVICEMAP_OIDC_AUDIENCE: ${SERVICEMAP_OIDC_AUDIENCE:-}
|
||||
SERVICEMAP_OIDC_ROLE_CLAIMS: ${SERVICEMAP_OIDC_ROLE_CLAIMS:-groups,roles}
|
||||
|
||||
+34
-6
@@ -35,9 +35,11 @@ v1.6.1 adds no schema migration. Its health-only observation loop is distinct fr
|
||||
|
||||
v1.6.2 keeps the same schema and evidence scopes. An AppOps `warning` observation is degraded application evidence; it cannot resolve a component. Evidence freshness is recomputed when persisted claims are read, so an expired claim cannot appear fresh in the raw inspector/API payload. The current MCP Hub Docker read broker cannot replace the production socket provider yet: its registration covers two unrelated projects, its ServiceMap-scoped inventory is empty, and its short-lived HMAC service-token contract rejects a raw bearer secret. Cutover requires a dedicated ServiceMap read identity, full bounded inventory parity and an explicit network path; broker mode remains fail-closed with no socket fallback.
|
||||
|
||||
The HTTP discovery routes accept only the Docker host and AppOps URL selected in deployment configuration. A request body cannot turn the container into a general-purpose client for another Docker daemon or internal HTTP endpoint. The private-LAN deployment currently keeps OIDC disabled because it has no dedicated browser client or tested owner login path; mutation APIs therefore depend on the LAN perimeter. Broker mode must be deployed without the legacy Docker socket bind even though the current socket-mode Compose file retains it.
|
||||
The HTTP discovery routes accept only the Docker host and AppOps URL selected in deployment configuration. A request body cannot turn the container into a general-purpose client for another Docker daemon or internal HTTP endpoint. The private-LAN deployment keeps OIDC disabled because it has no dedicated browser client or tested owner login path. Since v1.6.3 it runs in `token` mode, so mutation APIs need the admin token instead of depending on the LAN perimeter. Broker mode must be deployed without the legacy Docker socket bind even though the current socket-mode Compose file retains it.
|
||||
|
||||
The v1.4 semantic projection is deliberately not a parallel datastore. `semantic.py` derives Domain → Application → Component from canonical services, relations, runtime/monitoring state and incident analysis. Logical relations are grouped at query time so one graph edge retains all independent evidence records and their first/last-seen provenance. v1.6.1 resolves application health separately: fresh aggregate AppOps evidence can answer an application but never a component; direct component failures override weak aggregate health and conflicting claims remain visible. Semantic application identity uses locked operator grouping, Compose provenance and stable source references before a display name, preventing generic provider labels from collapsing unrelated services. Bulk evidence lookup serves the complete semantic projection in one bounded SQL query rather than an application-by-application scan.
|
||||
The v1.4 semantic projection is deliberately not a parallel datastore. `semantic.py` derives Domain → Application → Component from canonical services, relations, runtime/monitoring state and incident analysis. Logical relations are grouped at query time so one graph edge retains all independent evidence records and their first/last-seen provenance. v1.6.1 resolves application health separately: fresh aggregate AppOps evidence can answer an application but never a component; direct component failures override weak aggregate health and conflicting claims remain visible. Semantic application identity uses locked operator grouping, Compose provenance and stable source references before a display name, preventing generic provider labels from collapsing unrelated services. Bulk evidence lookup serves the complete semantic projection in one bounded SQL query rather than an application-by-application scan. v1.6.3 matches direct and linked claims through two separately indexed lookups (a `UNION`) and applies the per-service limit with a window function, because an `OR` across the link join forced a full `health_evidence` scan. Direct, dependency and effective health for incidents, the overview and service detail all come from one bulk read and one in-memory traversal (`health.topology_health`), never a per-node recursive SQLite walk. Snapshot discovery context (sources and relation evidence) is also read in bulk.
|
||||
|
||||
`GET /api/v1/topology/semantic` sends a strong `ETag` computed over the content without `generated_at`, together with `Cache-Control: no-cache` and `X-ServiceMap-Generated-At`. A client that sends `If-None-Match` while nothing has changed receives `304 Not Modified` without a body. Browsers revalidate on their own, and integrations such as ITWorx Forge send the header explicitly. The serialized response is also cached for at most 10 seconds. The cache is dropped as soon as any event is published or any evidence crosses a fresh→stale→expired boundary. The age cap bounds staleness for the few write paths that publish no event, such as discovery relation evidence; the ETag is always derived from content, so it is correct regardless.
|
||||
|
||||
The service record stores descriptive metadata, group/environment/tags, criticality, source reference, application, runtime state/health, monitoring state, probe source/reachability/confidence, enablement, maintenance state, probe policy and state-machine counters. Probe rows remain immutable and retain `trigger` and bounded JSON `metadata` fields. `HealthEvidence` retains provider, subject, scope, confidence, observation/receipt/expiry timestamps, metadata and supersession. Application-scoped claims may be linked to component inspectors but cannot resolve a component's direct health.
|
||||
|
||||
@@ -86,11 +88,20 @@ Per-service interval, timeout and retry settings override the global defaults. S
|
||||
|
||||
Incident timeline entries are events tied to an incident. Raw probe rows are retained independently under the configured probe retention; non-incident events use `SERVICEMAP_EVENT_RETENTION_DAYS` (default 90). Incident lifecycle events are retained with the incident record.
|
||||
|
||||
A maintenance task runs 30 seconds after startup and then every `SERVICEMAP_MAINTENANCE_INTERVAL_SECONDS` (default 3600). It applies probe and event retention independently of scheduled probing, and deletes superseded health evidence older than `SERVICEMAP_EVIDENCE_RETENTION_DAYS` (default 7; `0` disables). Only inactive rows are deleted. A row becomes inactive only when a newer claim from the same provider and subject replaces it, so every subject keeps its current claim and health resolution is unchanged.
|
||||
|
||||
## SSE and frontend refresh
|
||||
|
||||
The durable SQLite event journal is the source of truth. A small thread-safe bounded queue is allocated per SSE client and receives notifications for probe completion, state changes, topology changes and incident lifecycle changes. Slow clients lose only transient wakeups, not durable history. The stream emits keepalives and unregisters queues on disconnect/shutdown.
|
||||
The durable SQLite event journal is the source of truth. Each SSE client gets a bounded `asyncio.Queue` (size 100) bound to the event loop. A parked stream therefore holds no thread, and publishers on worker threads deliver to it through `call_soon_threadsafe`. Clients receive notifications for probe completion, state changes, health-evidence and provider changes, topology changes and incident lifecycle changes. A slow client loses only transient wakeups, never durable history. The stream starts with a `retry:` hint, sends a keepalive every 15 seconds, and unregisters its queue on disconnect or shutdown. A health-evidence update counts as material only when status, confidence, summary or stable metadata change; per-probe bookkeeping (`probe_id`, `latency_ms`, `trigger`) is stored but publishes nothing.
|
||||
|
||||
React subscribes with SSE, debounces event refreshes and reconnects with backoff. It enables bounded fallback refresh only while the stream is unavailable; a healthy quiet stream does not trigger periodic full reloads. Authenticated clients use the same SSE protocol through `fetch` with a bearer header. The frontend never invents monitoring state optimistically; every node, counter and inspector value comes from the API.
|
||||
React maps each event type to the smallest set of data slices it can affect:
|
||||
|
||||
- core reads: services, incidents, overview, events, demo state and the semantic topology;
|
||||
- discovery reads: only on `topology.changed`;
|
||||
- provider status: only on `provider.status_changed`;
|
||||
- the selected service's history: only for events about that service.
|
||||
|
||||
A single-flight scheduler merges bursts (250 ms debounce, 2 s maximum wait), so refreshes never overlap and never apply out of order. Reconnects use exponential backoff with jitter. The backoff resets only after a connection has been stable for 30 seconds, and every reopen after a gap triggers one full resync. A hidden tab keeps its stream for 60 seconds before it disconnects. The fallback poll runs only while the stream is down, and the UI shows a live, connecting or paused state. Authenticated clients use the same SSE protocol through `fetch` with a bearer header. The frontend never invents monitoring state optimistically; every node, counter and inspector value comes from the API.
|
||||
|
||||
## Production discovery and reconciliation
|
||||
|
||||
@@ -114,6 +125,23 @@ The Northstar demo is built from deterministic UUIDs and synthetic probe records
|
||||
|
||||
The Unraid target uses `/data` on the named `servicemap_data` volume, port mapping `1253:8000`, a healthcheck on `/health`, `no-new-privileges`, dropped capabilities, a read-only root filesystem and bounded `/tmp` tmpfs. Managed validation gates exact-SHA autoredeploy. Socket discovery remains a high-trust Docker API boundary even with a read-only bind. The opt-in broker provider requires a dedicated short-lived ServiceMap token, registration-scoped read capability and shared network, and never falls back to the socket. AppOps access is read-only enrichment.
|
||||
|
||||
## Optional authorization
|
||||
## Authorization
|
||||
|
||||
`SERVICEMAP_AUTH_MODE=disabled` preserves the deployed v1.5 behavior. In `oidc` mode FastAPI validates issuer/audience/signed bearer JWTs against OIDC discovery and JWKS; it maps explicit roles or configured Authentik groups to viewer, operator and admin. `/health` remains anonymous for deployment recovery, while APIs fail closed when OIDC configuration is incomplete. No client credentials, issuer secrets or tokens are stored in ServiceMap's SQLite database or frontend configuration.
|
||||
`SERVICEMAP_AUTH_MODE` selects one of three modes:
|
||||
|
||||
- **`token`** is the default since v1.6.3. Reads stay anonymous, so integrations such as ITWorx Forge and monitors keep working. Every mutating request needs `Authorization: Bearer <admin token>`.
|
||||
- On first start ServiceMap writes a random token with mode 0600 to `admin-token` next to the database, or to `SERVICEMAP_ADMIN_TOKEN_FILE` when that is set.
|
||||
- Only the file's location is logged, never the token itself.
|
||||
- The comparison is constant-time.
|
||||
- The UI asks for the token once per browser tab, checks it with `POST /api/v1/auth/verify` and keeps it in `sessionStorage`. A 401 clears the stored token and asks again.
|
||||
- **`disabled`** preserves the v1.5 behavior.
|
||||
- **`oidc`** is described below.
|
||||
|
||||
Two guards apply in every mode:
|
||||
|
||||
- A mutating request is refused when its `Origin` hostname differs from the public host (`X-Forwarded-Host`, otherwise `Host`), when the `Origin` is `null`, or when the browser marks it `Sec-Fetch-Site: cross-site`. Clients that send none of these headers, such as curl and integrations, are unaffected.
|
||||
- The optional `SERVICEMAP_ALLOWED_HOSTS` list refuses every other `Host`, which guards against DNS rebinding. Loopback is always allowed for the healthcheck.
|
||||
|
||||
Every response carries `nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and a strict CSP. Request bodies are limited to 4 MiB, a config import to 2 MB, and YAML anchors and aliases are refused.
|
||||
|
||||
In `oidc` mode the role mapping also applies: a configuration export and the demo routes need the admin role. In `oidc` mode FastAPI validates issuer/audience/signed bearer JWTs against OIDC discovery and JWKS; it maps explicit roles or configured Authentik groups to viewer, operator and admin. `/health` remains anonymous for deployment recovery, while APIs fail closed when OIDC configuration is incomplete. No client credentials, issuer secrets or tokens are stored in ServiceMap's SQLite database or frontend configuration.
|
||||
@@ -0,0 +1,68 @@
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test, type APIRequestContext } from "@playwright/test";
|
||||
|
||||
async function ensureServices(request: APIRequestContext) {
|
||||
await request.post("/api/v1/demo/exit");
|
||||
const existing = (await (await request.get("/api/v1/services")).json()) as { service: { name: string } }[];
|
||||
const names = new Set(existing.map((item) => item.service.name));
|
||||
for (const name of ["A11y Database", "A11y API"]) {
|
||||
if (names.has(name)) continue;
|
||||
const response = await request.post("/api/v1/services", {
|
||||
data: { name, kind: "tcp", host: "127.0.0.1", port: 9, environment: "test" },
|
||||
});
|
||||
expect(response.ok(), await response.text()).toBeTruthy();
|
||||
}
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await ensureServices(request);
|
||||
});
|
||||
|
||||
const PANELS = ["topology", "overview", "incidents", "services", "discovery", "changes", "activity", "config", "settings"];
|
||||
|
||||
for (const panel of PANELS) {
|
||||
test(`${panel} has no serious or critical axe violations`, async ({ page }) => {
|
||||
await page.goto(`/#/${panel}`);
|
||||
await expect(page.getByRole("navigation", { name: "ServiceMap-werkruimtes" })).toBeVisible();
|
||||
await expect(page.locator("main#main-content")).toBeVisible();
|
||||
await page.waitForLoadState("networkidle");
|
||||
const results = await new AxeBuilder({ page })
|
||||
.withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"])
|
||||
.analyze();
|
||||
const blocking = results.violations
|
||||
.filter((violation) => violation.impact === "serious" || violation.impact === "critical")
|
||||
.map((violation) => `${violation.id}: ${violation.nodes.map((node) => node.target.join(" ")).slice(0, 5).join(" | ")}`);
|
||||
expect(blocking, blocking.join("\n")).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test("navigation marks the current workspace and the skip link reaches content", async ({ page }) => {
|
||||
await page.goto("/#/services");
|
||||
await expect(page.getByRole("button", { name: "Services", exact: true })).toHaveAttribute("aria-current", "page");
|
||||
await page.keyboard.press("Tab");
|
||||
const skip = page.getByRole("link", { name: "Naar inhoud springen" });
|
||||
await expect(skip).toBeFocused();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.locator("main#main-content")).toBeFocused();
|
||||
});
|
||||
|
||||
test("the topology can be explored with the keyboard alone", async ({ page }) => {
|
||||
await page.goto("/#/topology");
|
||||
// Canvas nodes are focusable, labelled, and open the inspector on Enter.
|
||||
const node = page.locator(".react-flow__node").first();
|
||||
// The first layout can take a while on a busy machine; wait for it, not for a fixed delay.
|
||||
await expect(node).toHaveAttribute("aria-label", /, (Gezond|Verminderd|Uitgevallen|Onbekend|Niet bewaakt|Herstellend|Onderhoud)/, {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await node.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page).toHaveURL(/(service|in_domain|in_app)=/);
|
||||
|
||||
// The list alternative offers the same with plain buttons.
|
||||
await page.getByRole("button", { name: "Als lijst tonen" }).click();
|
||||
const list = page.getByRole("region", { name: "Topologie als lijst" });
|
||||
await expect(list).toBeVisible();
|
||||
await list.getByRole("button").first().focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(page.getByRole("button", { name: "Grafiek tonen" })).toHaveAttribute("aria-pressed", "true");
|
||||
});
|
||||
+30
-27
@@ -39,17 +39,18 @@ test("Explore demo exposes evidence-backed root cause and reset-safe exit", asyn
|
||||
const baselineTopology = topologyOf(await baselineResponse.json());
|
||||
|
||||
await page.goto("/");
|
||||
const explore = page.getByRole("button", { name: "Explore demo", exact: true });
|
||||
// Secondary actions live in the header's overflow menu.
|
||||
await page.getByRole("button", { name: "Meer acties" }).click();
|
||||
const explore = page.getByRole("button", { name: "Demo verkennen", exact: true });
|
||||
await expect(explore).toBeEnabled({ timeout: 30_000 });
|
||||
|
||||
const loadResponsePromise = page.waitForResponse(isDemoMutation("/api/v1/demo"));
|
||||
await explore.click();
|
||||
if (baselineTopology.length > 0) {
|
||||
const confirmation = page
|
||||
.getByRole("alert")
|
||||
.filter({ hasText: "temporarily replace this topology" });
|
||||
.getByRole("dialog", { name: /vervangt deze topologie tijdelijk/ });
|
||||
await expect(confirmation).toBeVisible();
|
||||
await confirmation.getByRole("button", { name: "Explore demo", exact: true }).click();
|
||||
await confirmation.getByRole("button", { name: "Snapshot maken en verkennen", exact: true }).click();
|
||||
}
|
||||
const loadResponse = await loadResponsePromise;
|
||||
expect(loadResponse.ok()).toBeTruthy();
|
||||
@@ -99,37 +100,38 @@ test("Explore demo exposes evidence-backed root cause and reset-safe exit", asyn
|
||||
uptime_percent: 91.67,
|
||||
});
|
||||
|
||||
const demoBanner = page.getByRole("status", { name: "Explore demo scenario" });
|
||||
const demoBanner = page.getByRole("status", { name: "Demoscenario verkennen" });
|
||||
await expect(demoBanner).toBeVisible();
|
||||
await expect(demoBanner).toHaveAttribute("aria-busy", "false", { timeout: 30_000 });
|
||||
await expect(page.getByText("Demoscenario", { exact: false })).toBeVisible();
|
||||
await expect(page.getByText("PostgreSQL", { exact: true }).first()).toBeVisible();
|
||||
await expect(page.getByText("Likely root cause", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Health evidence", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Waarschijnlijke hoofdoorzaak", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("Gezondheidsbewijs", { exact: true })).toBeVisible();
|
||||
|
||||
const workspaces = page.getByRole("navigation", { name: "ServiceMap workspaces" });
|
||||
await workspaces.getByRole("button", { name: "Overview" }).click();
|
||||
await expect(page.getByRole("heading", { name: "9/9 with current health evidence" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Review unresolved" })).toBeDisabled();
|
||||
await page.locator(".overview-lead").getByRole("button", { name: /1 down/i }).click();
|
||||
const workspaces = page.getByRole("navigation", { name: "ServiceMap-werkruimtes" });
|
||||
await workspaces.getByRole("button", { name: "Overzicht" }).click();
|
||||
await expect(page.getByRole("heading", { name: "9/9 met actueel gezondheidsbewijs" })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Onopgeloste nakijken" })).toBeDisabled();
|
||||
await page.locator(".overview-lead").getByRole("button", { name: /1 uitgevallen/i }).click();
|
||||
await expect(page.getByRole("combobox", { name: "Status", exact: true })).toHaveValue("down");
|
||||
await workspaces.getByRole("button", { name: "Incidents" }).click();
|
||||
await workspaces.getByRole("button", { name: "Incidenten" }).click();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "Active and historical incidents" }),
|
||||
page.getByRole("heading", { name: "Actieve en eerdere incidenten" }),
|
||||
).toBeVisible();
|
||||
await page.getByLabel("Search incidents").fill("does not exist");
|
||||
await expect(page.getByText("No incidents match these filters.")).toBeVisible();
|
||||
await page.getByLabel("Search incidents").fill("");
|
||||
await workspaces.getByRole("button", { name: "Topology", exact: true }).click();
|
||||
await expect(page.getByRole("region", { name: "Topology commands" })).toBeVisible();
|
||||
await page.getByRole("region", { name: "Topology commands" }).locator("summary").filter({ hasText: "Filters" }).click();
|
||||
await expect(page.getByRole("combobox", { name: "Filter topology by status" })).toBeVisible();
|
||||
await page.getByLabel("Incidenten zoeken").fill("does not exist");
|
||||
await expect(page.getByText("Geen incidenten voor deze filters.")).toBeVisible();
|
||||
await page.getByLabel("Incidenten zoeken").fill("");
|
||||
await workspaces.getByRole("button", { name: "Topologie", exact: true }).click();
|
||||
await expect(page.getByRole("region", { name: "Topologieopdrachten" })).toBeVisible();
|
||||
await page.getByRole("region", { name: "Topologieopdrachten" }).locator("summary").filter({ hasText: "Filters" }).click();
|
||||
await expect(page.getByRole("combobox", { name: "Topologie filteren op status" })).toBeVisible();
|
||||
const inspector = page.getByRole("complementary");
|
||||
await expect(inspector.getByRole("heading", { name: "PostgreSQL" })).toBeVisible();
|
||||
await expect(inspector.getByText("Likely root cause", { exact: true })).toBeVisible();
|
||||
await expect(inspector.getByText("Health evidence", { exact: true })).toBeVisible();
|
||||
await expect(inspector.getByText("Waarschijnlijke hoofdoorzaak", { exact: true })).toBeVisible();
|
||||
await expect(inspector.getByText("Gezondheidsbewijs", { exact: true })).toBeVisible();
|
||||
|
||||
const reset = page.locator("header").getByRole("button", { name: "Reset demo" });
|
||||
await page.getByRole("button", { name: "Meer acties" }).click();
|
||||
const reset = page.locator("header").getByRole("button", { name: "Demo opnieuw starten" });
|
||||
const resetResponsePromise = page.waitForResponse(isDemoMutation("/api/v1/demo/reset"));
|
||||
await reset.click();
|
||||
const resetResponse = await resetResponsePromise;
|
||||
@@ -143,7 +145,7 @@ test("Explore demo exposes evidence-backed root cause and reset-safe exit", asyn
|
||||
// Wait for the demo region to leave its busy state before attempting Exit.
|
||||
await expect(demoBanner).toHaveAttribute("aria-busy", "false", { timeout: 30_000 });
|
||||
await expect(page.getByText("PostgreSQL", { exact: true }).first()).toBeVisible();
|
||||
const exit = page.getByRole("button", { name: "Exit demo", exact: true });
|
||||
const exit = page.getByRole("button", { name: "Demo afsluiten", exact: true });
|
||||
await expect(exit).toBeEnabled();
|
||||
|
||||
const exitResponsePromise = page.waitForResponse(isDemoMutation("/api/v1/demo/exit"));
|
||||
@@ -154,10 +156,11 @@ test("Explore demo exposes evidence-backed root cause and reset-safe exit", asyn
|
||||
|
||||
await expect(demoBanner).toBeHidden({ timeout: 30_000 });
|
||||
await expect(
|
||||
page.getByText("Demo closed. Your previous topology was restored.", { exact: true }),
|
||||
page.getByText("Demo afgesloten. Je vorige topologie is hersteld.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await page.getByRole("button", { name: "Meer acties" }).click();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Explore demo", exact: true }),
|
||||
page.getByRole("button", { name: "Demo verkennen", exact: true }),
|
||||
).toBeEnabled({ timeout: 30_000 });
|
||||
|
||||
const restoredDemoResponse = await request.get("/api/v1/demo");
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="nl-BE">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
||||
+11
-1
@@ -8,7 +8,9 @@ server {
|
||||
location /api/ {
|
||||
proxy_pass http://backend:8000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
# $http_host keeps the port so the API's Origin check sees the public address.
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-Host $http_host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
@@ -17,7 +19,15 @@ server {
|
||||
proxy_pass http://backend:8000/health;
|
||||
}
|
||||
|
||||
# Fingerprinted bundles never change in place; index.html must be
|
||||
# revalidated or browsers keep running the previous release.
|
||||
location /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
}
|
||||
Generated
+709
-2
@@ -1,33 +1,77 @@
|
||||
{
|
||||
"name": "servicemap-frontend",
|
||||
"version": "1.6.2",
|
||||
"version": "1.6.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "servicemap-frontend",
|
||||
"version": "1.6.2",
|
||||
"version": "1.6.3",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@xyflow/react": "^12.8.5",
|
||||
"elkjs": "^0.12.0",
|
||||
"lucide-react": "^0.577.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.14.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.57.0",
|
||||
"@testing-library/dom": "^10.4.2",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
"@types/react": "^19.1.12",
|
||||
"@types/react-dom": "^19.1.9",
|
||||
"@vitejs/plugin-react": "^5.0.2",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"globals": "^17.12.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.70.1",
|
||||
"vite": "^7.1.5",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@asamuzakjp/css-color": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
|
||||
"integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@csstools/css-calc": "^2.1.3",
|
||||
"@csstools/css-color-parser": "^3.0.9",
|
||||
"@csstools/css-parser-algorithms": "^3.0.4",
|
||||
"@csstools/css-tokenizer": "^3.0.3",
|
||||
"lru-cache": "^10.4.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@asamuzakjp/css-color/node_modules/lru-cache": {
|
||||
"version": "10.4.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/@axe-core/playwright": {
|
||||
"version": "4.14.0",
|
||||
"resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.14.0.tgz",
|
||||
"integrity": "sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"dependencies": {
|
||||
"axe-core": "~4.14.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.12.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"playwright-core": ">= 1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
|
||||
@@ -262,6 +306,16 @@
|
||||
"@babel/core": "^7.0.0-0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.29.14",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.14.tgz",
|
||||
"integrity": "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/template": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
|
||||
@@ -334,6 +388,121 @@
|
||||
"keyv": "^5.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/color-helpers": {
|
||||
"version": "5.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz",
|
||||
"integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-calc": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
|
||||
"integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@csstools/css-parser-algorithms": "^3.0.5",
|
||||
"@csstools/css-tokenizer": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-color-parser": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz",
|
||||
"integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@csstools/color-helpers": "^5.1.0",
|
||||
"@csstools/css-calc": "^2.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@csstools/css-parser-algorithms": "^3.0.5",
|
||||
"@csstools/css-tokenizer": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-parser-algorithms": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
|
||||
"integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@csstools/css-tokenizer": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-tokenizer": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
|
||||
"integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
@@ -904,6 +1073,15 @@
|
||||
"node": "^20.19.0 || ^22.13.0 || >=24"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/inter": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
|
||||
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@humanfs/core": {
|
||||
"version": "0.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
|
||||
@@ -1476,6 +1654,75 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@testing-library/dom": {
|
||||
"version": "10.4.2",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz",
|
||||
"integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.10.4",
|
||||
"@babel/runtime": "^7.12.5",
|
||||
"@types/aria-query": "^5.0.1",
|
||||
"aria-query": "5.3.0",
|
||||
"dom-accessibility-api": "^0.5.9",
|
||||
"lz-string": "^1.5.0",
|
||||
"picocolors": "1.1.1",
|
||||
"pretty-format": "^27.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@testing-library/react": {
|
||||
"version": "16.3.3",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz",
|
||||
"integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@testing-library/dom": "^10.0.0",
|
||||
"@types/react": "^18.0.0 || ^19.0.0",
|
||||
"@types/react-dom": "^18.0.0 || ^19.0.0",
|
||||
"react": "^18.0.0 || ^19.0.0",
|
||||
"react-dom": "^18.0.0 || ^19.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@testing-library/user-event": {
|
||||
"version": "14.6.13",
|
||||
"resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.13.tgz",
|
||||
"integrity": "sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@testing-library/dom": ">=7.21.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/aria-query": {
|
||||
"version": "5.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
|
||||
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/babel__core": {
|
||||
"version": "7.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||
@@ -2073,6 +2320,16 @@
|
||||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "6.15.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
|
||||
@@ -2090,6 +2347,39 @@
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
|
||||
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/aria-query": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",
|
||||
"integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"dequal": "^2.0.3"
|
||||
}
|
||||
},
|
||||
"node_modules/assertion-error": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
|
||||
@@ -2100,6 +2390,16 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/axe-core": {
|
||||
"version": "4.14.1",
|
||||
"resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.1.tgz",
|
||||
"integrity": "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==",
|
||||
"dev": true,
|
||||
"license": "MPL-2.0",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
@@ -2270,6 +2570,20 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/cssstyle": {
|
||||
"version": "4.6.0",
|
||||
"resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz",
|
||||
"integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@asamuzakjp/css-color": "^3.2.0",
|
||||
"rrweb-cssom": "^0.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
@@ -2382,6 +2696,20 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/data-urls": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
|
||||
"integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-mimetype": "^4.0.0",
|
||||
"whatwg-url": "^14.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
@@ -2400,6 +2728,13 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js": {
|
||||
"version": "10.6.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
|
||||
"integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/deep-eql": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
|
||||
@@ -2417,6 +2752,23 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dequal": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
|
||||
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/dom-accessibility-api": {
|
||||
"version": "0.5.16",
|
||||
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
|
||||
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.427",
|
||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.427.tgz",
|
||||
@@ -2430,6 +2782,19 @@
|
||||
"integrity": "sha512-YZcKynxVxYoKIOEpywEPwCFdg+BTbxQRNf3pbwdDCvc8O3kQD8bmIwSxKU1eOTVc4Xo+VG9Te+575mlfvOrhEQ==",
|
||||
"license": "EPL-2.0 OR GPL-3.0-or-later"
|
||||
},
|
||||
"node_modules/entities": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
|
||||
"integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/es-module-lexer": {
|
||||
"version": "1.7.0",
|
||||
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
|
||||
@@ -2870,6 +3235,60 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/html-encoding-sniffer": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
|
||||
"integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-encoding": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/http-proxy-agent": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
|
||||
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"agent-base": "^7.1.0",
|
||||
"debug": "^4.3.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/https-proxy-agent": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
|
||||
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"agent-base": "^7.1.2",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
@@ -2913,6 +3332,13 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/is-potential-custom-element-name": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
|
||||
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||
@@ -2927,6 +3353,46 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/jsdom": {
|
||||
"version": "26.1.0",
|
||||
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
"decimal.js": "^10.5.0",
|
||||
"html-encoding-sniffer": "^4.0.0",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"is-potential-custom-element-name": "^1.0.1",
|
||||
"nwsapi": "^2.2.16",
|
||||
"parse5": "^7.2.1",
|
||||
"rrweb-cssom": "^0.8.0",
|
||||
"saxes": "^6.0.0",
|
||||
"symbol-tree": "^3.2.4",
|
||||
"tough-cookie": "^5.1.1",
|
||||
"w3c-xmlserializer": "^5.0.0",
|
||||
"webidl-conversions": "^7.0.0",
|
||||
"whatwg-encoding": "^3.1.1",
|
||||
"whatwg-mimetype": "^4.0.0",
|
||||
"whatwg-url": "^14.1.1",
|
||||
"ws": "^8.18.0",
|
||||
"xml-name-validator": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"canvas": "^3.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"canvas": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/jsesc": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
|
||||
@@ -3024,6 +3490,25 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/lucide-react": {
|
||||
"version": "0.577.0",
|
||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.577.0.tgz",
|
||||
"integrity": "sha512-4LjoFv2eEPwYDPg/CUdBJQSDfPyzXCRrVW1X7jrx/trgxnxkHFjnVZINbzvzxjN70dxychOfg+FTYwBiS3pQ5A==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/lz-string": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
|
||||
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"lz-string": "bin/bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/magic-string": {
|
||||
"version": "0.30.21",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
|
||||
@@ -3093,6 +3578,13 @@
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/nwsapi": {
|
||||
"version": "2.2.28",
|
||||
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz",
|
||||
"integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
@@ -3143,6 +3635,19 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/parse5": {
|
||||
"version": "7.3.0",
|
||||
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
|
||||
"integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"entities": "^6.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
@@ -3268,6 +3773,21 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/pretty-format": {
|
||||
"version": "27.5.1",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
|
||||
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1",
|
||||
"ansi-styles": "^5.0.0",
|
||||
"react-is": "^17.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/punycode": {
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
@@ -3319,6 +3839,13 @@
|
||||
"react": "^19.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
"version": "17.0.2",
|
||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
|
||||
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/react-refresh": {
|
||||
"version": "0.18.0",
|
||||
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz",
|
||||
@@ -3375,6 +3902,33 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/rrweb-cssom": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
|
||||
"integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"xmlchars": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=v12.22.7"
|
||||
}
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.28.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
|
||||
@@ -3465,6 +4019,13 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/symbol-tree": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
|
||||
"integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
@@ -3526,6 +4087,52 @@
|
||||
"node": ">=14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tldts": {
|
||||
"version": "6.1.86",
|
||||
"resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
|
||||
"integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tldts-core": "^6.1.86"
|
||||
},
|
||||
"bin": {
|
||||
"tldts": "bin/cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/tldts-core": {
|
||||
"version": "6.1.86",
|
||||
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
|
||||
"integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tough-cookie": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
|
||||
"integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tldts": "^6.1.32"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/tr46": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
|
||||
"integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"punycode": "^2.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-api-utils": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz",
|
||||
@@ -3811,6 +4418,67 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/w3c-xmlserializer": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
|
||||
"integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xml-name-validator": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
|
||||
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-encoding": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
|
||||
"integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
|
||||
"deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"iconv-lite": "0.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-mimetype": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
|
||||
"integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "14.2.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
|
||||
"integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tr46": "^5.1.0",
|
||||
"webidl-conversions": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
@@ -3854,6 +4522,45 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.23.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
|
||||
"integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlchars": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
|
||||
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "servicemap-frontend",
|
||||
"private": true,
|
||||
"version": "1.6.2",
|
||||
"version": "1.6.3",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
@@ -9,23 +9,31 @@
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"pretest:e2e": "vite build",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@xyflow/react": "^12.8.5",
|
||||
"elkjs": "^0.12.0",
|
||||
"lucide-react": "^0.577.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "^4.14.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@playwright/test": "^1.57.0",
|
||||
"@testing-library/dom": "^10.4.2",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
"@types/react": "^19.1.12",
|
||||
"@types/react-dom": "^19.1.9",
|
||||
"@vitejs/plugin-react": "^5.0.2",
|
||||
"eslint": "^10.11.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"globals": "^17.12.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.70.1",
|
||||
"vite": "^7.1.5",
|
||||
|
||||
@@ -2,19 +2,24 @@ import { defineConfig, devices } from "@playwright/test";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
// Override when another dev server already holds the default port.
|
||||
const port = Number(process.env.E2E_PORT ?? 4173);
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
timeout: 30_000,
|
||||
fullyParallel: false,
|
||||
// All specs share one server database; run them one at a time.
|
||||
workers: 1,
|
||||
reporter: "list",
|
||||
use: {
|
||||
baseURL: "http://127.0.0.1:4173",
|
||||
baseURL: `http://127.0.0.1:${port}`,
|
||||
trace: "retain-on-failure",
|
||||
},
|
||||
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
|
||||
webServer: {
|
||||
command: "python -m uvicorn app.main:app --app-dir ../backend --host 127.0.0.1 --port 4173",
|
||||
url: "http://127.0.0.1:4173/health",
|
||||
command: `python -m uvicorn app.main:app --app-dir ../backend --host 127.0.0.1 --port ${port}`,
|
||||
url: `http://127.0.0.1:${port}/health`,
|
||||
reuseExistingServer: !process.env.CI,
|
||||
env: {
|
||||
...process.env,
|
||||
@@ -22,6 +27,7 @@ export default defineConfig({
|
||||
SERVICEMAP_STATIC_DIR: "dist",
|
||||
SERVICEMAP_AUTH_MODE: "disabled",
|
||||
SERVICEMAP_PROBE_INTERVAL: "0",
|
||||
SERVICEMAP_DEMO_ENABLED: "1",
|
||||
},
|
||||
},
|
||||
});
|
||||
+1887
-638
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,7 @@ export type LivingEdgeData = {
|
||||
signal?: boolean;
|
||||
selected?: boolean;
|
||||
route?: { x: number; y: number }[];
|
||||
dimmed?: boolean;
|
||||
};
|
||||
|
||||
function LivingEdgeView({
|
||||
@@ -32,6 +33,7 @@ function LivingEdgeView({
|
||||
`living-edge-${relation}`,
|
||||
edgeData.selected ? "is-selected" : "",
|
||||
edgeData.signal ? "has-signal" : "",
|
||||
edgeData.dimmed ? "is-dimmed" : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
@@ -39,7 +41,7 @@ function LivingEdgeView({
|
||||
return (
|
||||
<g className="living-edge" aria-hidden="true">
|
||||
<BaseEdge path={path} markerEnd={markerEnd} className={classes} />
|
||||
{edgeData.signal && (
|
||||
{edgeData.signal && !edgeData.dimmed && (
|
||||
<path d={path} className="living-edge-signal" markerEnd={markerEnd} />
|
||||
)}
|
||||
</g>
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { dayLabel, eventMeta, groupActivity, type ActivityEvent } from "./activityView";
|
||||
|
||||
const event = (id: string, at: string, type: string, message: string, service?: string): ActivityEvent => ({
|
||||
id,
|
||||
created_at: at,
|
||||
event_type: type,
|
||||
message,
|
||||
service_id: service ?? null,
|
||||
});
|
||||
|
||||
describe("activity journal view", () => {
|
||||
it("collapses a burst of identical events into one row with every service", () => {
|
||||
const days = groupActivity(
|
||||
[
|
||||
event("1", "2026-11-19T21:19:00.100Z", "incident.resolved", "Root cause recovered", "a"),
|
||||
event("2", "2026-11-19T21:19:00.200Z", "incident.resolved", "Root cause recovered", "b"),
|
||||
event("3", "2026-11-19T21:19:00.300Z", "incident.resolved", "Root cause recovered", "a"),
|
||||
event("4", "2026-11-19T21:18:10.000Z", "incident.opened", "Incident opened", "c"),
|
||||
],
|
||||
new Date("2026-11-19T22:00:00Z"),
|
||||
);
|
||||
expect(days).toHaveLength(1);
|
||||
expect(days[0].rows).toHaveLength(2);
|
||||
expect(days[0].rows[0]).toMatchObject({ count: 3, serviceIds: ["a", "b"] });
|
||||
expect(days[0].rows[1]).toMatchObject({ type: "incident.opened", count: 1 });
|
||||
});
|
||||
|
||||
it("starts a new day group and does not merge across days or minutes", () => {
|
||||
const days = groupActivity([
|
||||
event("1", "2026-11-19T10:00:00Z", "topology.changed", "Changed"),
|
||||
event("2", "2026-11-19T09:58:00Z", "topology.changed", "Changed"),
|
||||
event("3", "2026-11-17T10:00:00Z", "topology.changed", "Changed"),
|
||||
]);
|
||||
expect(days.map((day) => day.rows.length)).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it("labels days relative to now and humanises unknown event types", () => {
|
||||
const now = new Date(2026, 10, 19, 12);
|
||||
expect(dayLabel(new Date(2026, 10, 19, 8), now)).toBe("Vandaag");
|
||||
expect(dayLabel(new Date(2026, 10, 18, 23), now)).toBe("Gisteren");
|
||||
expect(eventMeta("incident.opened")).toEqual({ label: "Incident geopend", tone: "bad" });
|
||||
expect(eventMeta("backup.created_ok").label).toBe("Backup created ok");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { dayKey, formatDay, formatTime } from "./labels";
|
||||
|
||||
export type ActivityEvent = {
|
||||
id: string;
|
||||
created_at: string;
|
||||
event_type: string;
|
||||
message: string;
|
||||
service_id?: string | null;
|
||||
};
|
||||
|
||||
export type ActivityTone = "ok" | "warn" | "bad" | "maint" | "accent" | "neutral";
|
||||
|
||||
export type ActivityRow = {
|
||||
id: string;
|
||||
type: string;
|
||||
message: string;
|
||||
createdAt: string;
|
||||
serviceIds: string[];
|
||||
count: number;
|
||||
};
|
||||
|
||||
export type ActivityDay = { key: string; label: string; rows: ActivityRow[] };
|
||||
|
||||
const EVENT_LABELS: Record<string, { label: string; tone: ActivityTone }> = {
|
||||
"incident.opened": { label: "Incident geopend", tone: "bad" },
|
||||
"incident.resolved": { label: "Incident opgelost", tone: "ok" },
|
||||
"incident.duplicate_resolved": { label: "Dubbel incident gesloten", tone: "neutral" },
|
||||
"incident.acknowledged": { label: "Incident bevestigd", tone: "warn" },
|
||||
"incident.updated": { label: "Impact herberekend", tone: "neutral" },
|
||||
"incident.note": { label: "Incidentnotitie", tone: "neutral" },
|
||||
"service.state_changed": { label: "Gezondheid gewijzigd", tone: "neutral" },
|
||||
"service.runtime_observed": { label: "Runtime waargenomen", tone: "neutral" },
|
||||
"service.maintenance_changed": { label: "Onderhoud", tone: "maint" },
|
||||
"topology.changed": { label: "Topologie gewijzigd", tone: "accent" },
|
||||
"flapping.detected": { label: "Wisselvalligheid vastgesteld", tone: "warn" },
|
||||
};
|
||||
|
||||
/** A readable label and tone for an event type; unknown types are humanised. */
|
||||
export function eventMeta(type: string): { label: string; tone: ActivityTone } {
|
||||
const known = EVENT_LABELS[type];
|
||||
if (known) return known;
|
||||
const words = type.replace(/[._]+/g, " ").trim();
|
||||
return { label: words ? words[0].toUpperCase() + words.slice(1) : "Gebeurtenis", tone: "neutral" };
|
||||
}
|
||||
|
||||
export function dayLabel(date: Date, now: Date = new Date()): string {
|
||||
const today = dayKey(now);
|
||||
const yesterday = new Date(now);
|
||||
yesterday.setDate(now.getDate() - 1);
|
||||
if (dayKey(date) === today) return "Vandaag";
|
||||
if (dayKey(date) === dayKey(yesterday)) return "Gisteren";
|
||||
return formatDay(date);
|
||||
}
|
||||
|
||||
export function timeOf(value: string): string {
|
||||
return formatTime(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups the journal per calendar day and collapses bursts: consecutive
|
||||
* events with the same type and message within the same minute become one
|
||||
* row that lists every affected service.
|
||||
*/
|
||||
export function groupActivity(events: ActivityEvent[], now: Date = new Date()): ActivityDay[] {
|
||||
const days: ActivityDay[] = [];
|
||||
for (const event of events) {
|
||||
const date = new Date(event.created_at);
|
||||
const key = dayKey(date);
|
||||
let day = days[days.length - 1];
|
||||
if (!day || day.key !== key) {
|
||||
day = { key, label: dayLabel(date, now), rows: [] };
|
||||
days.push(day);
|
||||
}
|
||||
const last = day.rows[day.rows.length - 1];
|
||||
const sameBurst =
|
||||
last &&
|
||||
last.type === event.event_type &&
|
||||
last.message === event.message &&
|
||||
Math.abs(new Date(last.createdAt).getTime() - date.getTime()) < 60_000;
|
||||
if (sameBurst) {
|
||||
last.count += 1;
|
||||
if (event.service_id && !last.serviceIds.includes(event.service_id)) last.serviceIds.push(event.service_id);
|
||||
} else {
|
||||
day.rows.push({
|
||||
id: event.id,
|
||||
type: event.event_type,
|
||||
message: event.message,
|
||||
createdAt: event.created_at,
|
||||
serviceIds: event.service_id ? [event.service_id] : [],
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
return days;
|
||||
}
|
||||
+148
-30
@@ -1,3 +1,5 @@
|
||||
import { SSE_EVENT_TYPES } from "./realtime/refreshPlan";
|
||||
|
||||
export type HealthStatus =
|
||||
| "healthy"
|
||||
| "degraded"
|
||||
@@ -198,6 +200,7 @@ export type ServiceSnapshot = {
|
||||
evidence: RelationEvidence[];
|
||||
health_evidence: HealthEvidence[];
|
||||
health_resolution: HealthResolution;
|
||||
maintenance_until?: string | null;
|
||||
};
|
||||
|
||||
export type ServiceSource = {
|
||||
@@ -485,6 +488,7 @@ export type OverviewSummary = {
|
||||
|
||||
export type DemoState = {
|
||||
active: boolean;
|
||||
enabled: boolean;
|
||||
synthetic: boolean;
|
||||
scenario_name: string | null;
|
||||
service_count: number;
|
||||
@@ -682,37 +686,145 @@ export type ReconcileResult = {
|
||||
service_ids: string[];
|
||||
};
|
||||
|
||||
let accessToken: string | null = null;
|
||||
// The admin token is kept per browser tab (sessionStorage): it survives a
|
||||
// reload but not closing the tab, and never reaches topology config.
|
||||
const TOKEN_KEY = "servicemap.adminToken";
|
||||
export const AUTH_REQUIRED_EVENT = "servicemap:auth-required";
|
||||
|
||||
function readStoredToken(): string | null {
|
||||
try {
|
||||
return window.sessionStorage.getItem(TOKEN_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
let accessToken: string | null = typeof window === "undefined" ? null : readStoredToken();
|
||||
|
||||
/** An optional in-memory OIDC bearer token; never persisted in topology config. */
|
||||
export function setApiAccessToken(token: string | null): void {
|
||||
accessToken = token?.trim() || null;
|
||||
try {
|
||||
if (accessToken) window.sessionStorage.setItem(TOKEN_KEY, accessToken);
|
||||
else window.sessionStorage.removeItem(TOKEN_KEY);
|
||||
} catch {
|
||||
// Storage may be unavailable (private mode); the token stays in memory.
|
||||
}
|
||||
}
|
||||
|
||||
function requestHeaders(init?: RequestInit): HeadersInit {
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
|
||||
...init?.headers,
|
||||
};
|
||||
export function hasApiAccessToken(): boolean {
|
||||
return accessToken !== null;
|
||||
}
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
headers: requestHeaders(init),
|
||||
...init,
|
||||
});
|
||||
/** An API failure that keeps the HTTP status, e.g. 401 for a locked editor. */
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(detail: unknown, status: number): string {
|
||||
if (typeof detail === "string" && detail) return detail;
|
||||
if (Array.isArray(detail)) {
|
||||
// FastAPI validation errors: [{loc: [...], msg: "..."}]
|
||||
const parts = detail
|
||||
.map((item) => {
|
||||
const entry = item as { loc?: unknown[]; msg?: string };
|
||||
const field = Array.isArray(entry.loc) ? entry.loc.filter((part) => part !== "body").join(".") : "";
|
||||
return entry.msg ? (field ? `${field}: ${entry.msg}` : entry.msg) : "";
|
||||
})
|
||||
.filter(Boolean);
|
||||
if (parts.length) return parts.join("; ");
|
||||
}
|
||||
return `Verzoek mislukt (${status})`;
|
||||
}
|
||||
|
||||
function requestHeaders(init?: RequestInit, token: string | null = accessToken): Headers {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (init?.body !== undefined && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
if (token && !headers.has("Authorization")) headers.set("Authorization", `Bearer ${token}`);
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function request<T>(url: string, init?: RequestInit, token: string | null = accessToken): Promise<T> {
|
||||
// Spread init first: a caller's headers are merged above, never dropped.
|
||||
const response = await fetch(url, { ...init, headers: requestHeaders(init, token) });
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
throw new Error(payload?.detail || `Request failed (${response.status})`);
|
||||
if (response.status === 401 && token === accessToken && typeof window !== "undefined") {
|
||||
// The tab's token is missing or no longer valid: forget it and let the
|
||||
// UI ask for it. Explicit candidate tokens (verifyWriteAccess) don't.
|
||||
if (accessToken) setApiAccessToken(null);
|
||||
window.dispatchEvent(new Event(AUTH_REQUIRED_EVENT));
|
||||
}
|
||||
throw new ApiError(errorMessage(payload?.detail, response.status), response.status);
|
||||
}
|
||||
|
||||
if (response.status === 204) return undefined as T;
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export type AlertSettings = {
|
||||
enabled: boolean;
|
||||
ntfy_server: string;
|
||||
ntfy_topic: string;
|
||||
min_severity: Criticality;
|
||||
delay_seconds: number;
|
||||
notify_resolved: boolean;
|
||||
reminder_minutes: number;
|
||||
public_url: string;
|
||||
ntfy_token_set?: boolean;
|
||||
};
|
||||
|
||||
export type BackupInfo = {
|
||||
name: string;
|
||||
kind: "backup" | "pre-restore";
|
||||
created_at: string;
|
||||
size_bytes: number;
|
||||
};
|
||||
|
||||
/** Download a backup with the tab's token (a plain link carries none). */
|
||||
export async function downloadBackupFile(name: string): Promise<Blob> {
|
||||
const response = await fetch(`/api/v1/backups/${encodeURIComponent(name)}`, {
|
||||
headers: requestHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null);
|
||||
throw new ApiError(errorMessage(payload?.detail, response.status), response.status);
|
||||
}
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
export type ServiceMapMeta = {
|
||||
version: string;
|
||||
auth_mode: string;
|
||||
write_auth?: "none" | "admin_token" | "oidc";
|
||||
};
|
||||
|
||||
export const api = {
|
||||
alertSettings: () => request<AlertSettings>("/api/v1/settings/alerts"),
|
||||
/** ``ntfyToken``: undefined keeps the stored token, "" removes it. */
|
||||
saveAlertSettings: (settings: AlertSettings, ntfyToken?: string) =>
|
||||
request<AlertSettings>("/api/v1/settings/alerts", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ ...settings, ntfy_token_set: undefined, ntfy_token: ntfyToken }),
|
||||
}),
|
||||
backups: () => request<BackupInfo[]>("/api/v1/backups"),
|
||||
createBackup: () => request<BackupInfo>("/api/v1/backups", { method: "POST" }),
|
||||
restoreBackup: (name: string) =>
|
||||
request<BackupInfo>(`/api/v1/backups/${encodeURIComponent(name)}/restore`, { method: "POST" }),
|
||||
testAlert: () =>
|
||||
request<{ ok: boolean; detail: string }>("/api/v1/settings/alerts/test", { method: "POST" }),
|
||||
meta: () => request<ServiceMapMeta>("/api/v1/meta"),
|
||||
/** Resolves only when ``token`` may change ServiceMap. */
|
||||
verifyWriteAccess: (token: string) =>
|
||||
request<{ ok: boolean }>("/api/v1/auth/verify", { method: "POST" }, token.trim()),
|
||||
listServices: (includeHidden = false) =>
|
||||
request<ServiceSnapshot[]>(
|
||||
`/api/v1/services?include_hidden=${includeHidden}`,
|
||||
@@ -756,13 +868,27 @@ export const api = {
|
||||
request<IncidentDetail>(`/api/v1/incidents/${incidentId}/acknowledge`, {
|
||||
method: "POST",
|
||||
}),
|
||||
events: (limit = 50) =>
|
||||
request<EventRecord[]>(`/api/v1/events?limit=${limit}`),
|
||||
events: (limit = 50, options: { eventType?: string; before?: string } = {}) => {
|
||||
const params = new URLSearchParams({ limit: String(limit) });
|
||||
if (options.eventType) params.set("event_type", options.eventType);
|
||||
if (options.before) params.set("before", options.before);
|
||||
return request<EventRecord[]>(`/api/v1/events?${params.toString()}`);
|
||||
},
|
||||
resolveIncident: (incidentId: string, note?: string) =>
|
||||
request<IncidentDetail>(`/api/v1/incidents/${encodeURIComponent(incidentId)}/resolve`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ note: note || null }),
|
||||
}),
|
||||
addIncidentNote: (incidentId: string, text: string) =>
|
||||
request<IncidentDetail>(`/api/v1/incidents/${encodeURIComponent(incidentId)}/notes`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ text }),
|
||||
}),
|
||||
overview: () => request<OverviewSummary>("/api/v1/overview"),
|
||||
maintenance: (serviceId: string, enabled: boolean, reason?: string) =>
|
||||
maintenance: (serviceId: string, enabled: boolean, reason?: string, until?: string | null) =>
|
||||
request<Service>(`/api/v1/services/${serviceId}/maintenance`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ enabled, reason }),
|
||||
body: JSON.stringify({ enabled, reason, until: until ?? null }),
|
||||
}),
|
||||
demoState: () => request<DemoState>("/api/v1/demo"),
|
||||
loadDemo: () =>
|
||||
@@ -782,7 +908,7 @@ export const api = {
|
||||
),
|
||||
exportConfig: async (format: "yaml" | "json") => {
|
||||
const response = await fetch(`/api/v1/config?format=${format}`, { headers: requestHeaders() });
|
||||
if (!response.ok) throw new Error(`Export failed (${response.status})`);
|
||||
if (!response.ok) throw new Error(`Exporteren mislukt (${response.status})`);
|
||||
return response.text();
|
||||
},
|
||||
discoverDocker: (dockerHost: string) =>
|
||||
@@ -921,17 +1047,9 @@ export function subscribeToEvents(
|
||||
}
|
||||
};
|
||||
source.onmessage = emit;
|
||||
for (const eventType of [
|
||||
"probe.completed",
|
||||
"service.state_changed",
|
||||
"service.maintenance_changed",
|
||||
"flapping.detected",
|
||||
"incident.opened",
|
||||
"incident.updated",
|
||||
"incident.acknowledged",
|
||||
"incident.resolved",
|
||||
"topology.changed",
|
||||
]) {
|
||||
// Named SSE events are only delivered to explicit listeners; a type missing
|
||||
// here is silently dropped by EventSource.
|
||||
for (const eventType of SSE_EVENT_TYPES) {
|
||||
source.addEventListener(eventType, emit);
|
||||
}
|
||||
source.onerror = () => onError?.();
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
api,
|
||||
ApiError,
|
||||
AUTH_REQUIRED_EVENT,
|
||||
hasApiAccessToken,
|
||||
setApiAccessToken,
|
||||
} from "./api";
|
||||
|
||||
function fakeWindow() {
|
||||
const target = new EventTarget();
|
||||
const storage = new Map<string, string>();
|
||||
return Object.assign(target, {
|
||||
sessionStorage: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => void storage.set(key, value),
|
||||
removeItem: (key: string) => void storage.delete(key),
|
||||
},
|
||||
storage,
|
||||
});
|
||||
}
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin token handling", () => {
|
||||
let win: ReturnType<typeof fakeWindow>;
|
||||
|
||||
beforeEach(() => {
|
||||
win = fakeWindow();
|
||||
vi.stubGlobal("window", win);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setApiAccessToken(null);
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("keeps the token per tab and sends it with every request", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(json([]));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
setApiAccessToken(" token-value ");
|
||||
expect(hasApiAccessToken()).toBe(true);
|
||||
expect(win.storage.get("servicemap.adminToken")).toBe("token-value");
|
||||
|
||||
await api.listServices();
|
||||
const headers = fetchMock.mock.calls[0][1].headers as Headers;
|
||||
expect(headers.get("Authorization")).toBe("Bearer token-value");
|
||||
// A GET without a body sends no JSON Content-Type (no CORS preflight).
|
||||
expect(headers.has("Content-Type")).toBe(false);
|
||||
});
|
||||
|
||||
it("forgets a rejected token and asks the UI to unlock again", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(json({ detail: "Editing requires the ServiceMap admin token" }, 401)),
|
||||
);
|
||||
const asked = vi.fn();
|
||||
win.addEventListener(AUTH_REQUIRED_EVENT, asked);
|
||||
setApiAccessToken("expired-token");
|
||||
|
||||
const failure = await api.deleteService("svc-1").catch((error: unknown) => error);
|
||||
expect(failure).toBeInstanceOf(ApiError);
|
||||
expect((failure as ApiError).status).toBe(401);
|
||||
expect(asked).toHaveBeenCalledTimes(1);
|
||||
expect(hasApiAccessToken()).toBe(false);
|
||||
expect(win.storage.has("servicemap.adminToken")).toBe(false);
|
||||
});
|
||||
|
||||
it("verifies a candidate token without touching the stored one", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(json({ detail: "nope" }, 401));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const asked = vi.fn();
|
||||
win.addEventListener(AUTH_REQUIRED_EVENT, asked);
|
||||
setApiAccessToken("current-token");
|
||||
|
||||
await expect(api.verifyWriteAccess("candidate")).rejects.toBeInstanceOf(ApiError);
|
||||
const headers = fetchMock.mock.calls[0][1].headers as Headers;
|
||||
expect(headers.get("Authorization")).toBe("Bearer candidate");
|
||||
expect(asked).not.toHaveBeenCalled();
|
||||
expect(hasApiAccessToken()).toBe(true);
|
||||
});
|
||||
|
||||
it("turns FastAPI validation errors into a readable message", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue(
|
||||
json({ detail: [{ loc: ["body", "port"], msg: "Input should be less than or equal to 65535" }] }, 422),
|
||||
),
|
||||
);
|
||||
const failure = (await api.deleteService("svc-1").catch((error: unknown) => error)) as ApiError;
|
||||
expect(failure.message).toBe("port: Input should be less than or equal to 65535");
|
||||
expect(failure.status).toBe(422);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Ellipsis } from "lucide-react";
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
type Props = {
|
||||
label: string;
|
||||
children: (close: () => void) => ReactNode;
|
||||
footer?: ReactNode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Overflow menu for secondary actions. Items stay ordinary buttons so they
|
||||
* keep their accessible names; the menu closes on Escape, outside click and
|
||||
* after an item is used.
|
||||
*/
|
||||
export function ActionsMenu({ label, children, footer }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const panelId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onPointer = (event: PointerEvent) => {
|
||||
if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setOpen(false);
|
||||
triggerRef.current?.focus();
|
||||
}
|
||||
};
|
||||
document.addEventListener("pointerdown", onPointer);
|
||||
document.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointer);
|
||||
document.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const close = () => setOpen(false);
|
||||
|
||||
return (
|
||||
<div className="actions-menu" ref={rootRef}>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
className="ghost icon-button"
|
||||
aria-label={label}
|
||||
aria-expanded={open}
|
||||
aria-controls={panelId}
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
<Ellipsis size={18} aria-hidden="true" />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="actions-menu-panel" id={panelId} role="group" aria-label={label}>
|
||||
{children(close)}
|
||||
{footer && <div className="actions-menu-footer">{footer}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ConfirmDialog } from "./ConfirmDialog";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
function renderDialog(open: boolean, handlers = { onConfirm: vi.fn(), onCancel: vi.fn() }) {
|
||||
render(
|
||||
<ConfirmDialog open={open} title="Replace topology?" confirmLabel="Replace" {...handlers}>
|
||||
<p>This cannot be undone.</p>
|
||||
</ConfirmDialog>,
|
||||
);
|
||||
return handlers;
|
||||
}
|
||||
|
||||
describe("ConfirmDialog", () => {
|
||||
it("is labelled by its title and description and focuses Cancel", () => {
|
||||
renderDialog(true);
|
||||
const dialog = screen.getByRole("dialog", { name: "Replace topology?" });
|
||||
expect(dialog.getAttribute("aria-describedby")).toBeTruthy();
|
||||
expect(screen.getByText("This cannot be undone.")).toBeTruthy();
|
||||
expect(document.activeElement?.textContent).toBe("Annuleren");
|
||||
});
|
||||
|
||||
it("confirms, cancels and treats Escape as cancel", async () => {
|
||||
const handlers = renderDialog(true);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByRole("button", { name: "Replace" }));
|
||||
expect(handlers.onConfirm).toHaveBeenCalledTimes(1);
|
||||
await user.click(screen.getByRole("button", { name: "Annuleren" }));
|
||||
fireEvent(screen.getByRole("dialog"), new Event("cancel", { cancelable: true }));
|
||||
expect(handlers.onCancel).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("renders nothing interactive while closed", () => {
|
||||
renderDialog(false);
|
||||
expect(screen.queryByRole("button", { name: "Replace" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useEffect, useId, useRef, type ReactNode } from "react";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
confirmLabel: string;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
busy?: boolean;
|
||||
danger?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* A real modal: the native <dialog> traps focus, makes the page behind it
|
||||
* inert, closes on Escape and returns focus to the opener when it closes.
|
||||
*/
|
||||
export function ConfirmDialog({ open, title, children, confirmLabel, onConfirm, onCancel, busy, danger }: Props) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
const titleId = useId();
|
||||
const bodyId = useId();
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = ref.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) {
|
||||
if (typeof dialog.showModal === "function") dialog.showModal();
|
||||
else dialog.setAttribute("open", "");
|
||||
} else if (!open && dialog.open) {
|
||||
if (typeof dialog.close === "function") dialog.close();
|
||||
else dialog.removeAttribute("open");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
className="confirm-dialog"
|
||||
aria-labelledby={titleId}
|
||||
aria-describedby={bodyId}
|
||||
onCancel={(event) => {
|
||||
event.preventDefault();
|
||||
onCancel();
|
||||
}}
|
||||
>
|
||||
{open && (
|
||||
<>
|
||||
<h2 id={titleId}>{title}</h2>
|
||||
<div id={bodyId} className="confirm-dialog-body">
|
||||
{children}
|
||||
</div>
|
||||
<div className="button-row wrap">
|
||||
<button className="ghost" onClick={onCancel} autoFocus>
|
||||
Annuleren
|
||||
</button>
|
||||
<button className={danger ? "danger" : "primary"} onClick={onConfirm} disabled={busy}>
|
||||
{confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import {
|
||||
CircleCheck,
|
||||
CircleDashed,
|
||||
CircleHelp,
|
||||
CircleX,
|
||||
RefreshCw,
|
||||
TriangleAlert,
|
||||
Wrench,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import type { HealthStatus } from "../api";
|
||||
|
||||
const ICONS: Record<HealthStatus, LucideIcon> = {
|
||||
healthy: CircleCheck,
|
||||
degraded: TriangleAlert,
|
||||
down: CircleX,
|
||||
recovering: RefreshCw,
|
||||
maintenance: Wrench,
|
||||
unknown: CircleHelp,
|
||||
unmonitored: CircleDashed,
|
||||
};
|
||||
|
||||
/** Status is never colour alone: this icon always sits next to a text label. */
|
||||
export function StatusIcon({ status, size = 14 }: { status: HealthStatus; size?: number }) {
|
||||
const Icon = ICONS[status] ?? CircleHelp;
|
||||
return <Icon className="status-icon" size={size} strokeWidth={2.25} aria-hidden="true" focusable="false" />;
|
||||
}
|
||||
@@ -6,10 +6,10 @@ describe("demo walkthrough", () => {
|
||||
it("keeps the semantic incident story ordered and compact", () => {
|
||||
expect(demoWalkthroughSteps).toHaveLength(4);
|
||||
expect(demoWalkthroughSteps.map((step) => step.title)).toEqual([
|
||||
"See the infrastructure",
|
||||
"Follow the data layer",
|
||||
"Trace the impact",
|
||||
"Inspect the root cause",
|
||||
"Bekijk de infrastructuur",
|
||||
"Volg de datalaag",
|
||||
"Volg de impact",
|
||||
"Bekijk de hoofdoorzaak",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,23 +1,23 @@
|
||||
export const demoWalkthroughSteps = [
|
||||
{
|
||||
title: "See the infrastructure",
|
||||
title: "Bekijk de infrastructuur",
|
||||
description:
|
||||
"Start with the semantic domain landscape: Edge, Application and Data.",
|
||||
"Begin bij het landschap van domeinen: Edge, Application en Data.",
|
||||
},
|
||||
{
|
||||
title: "Follow the data layer",
|
||||
title: "Volg de datalaag",
|
||||
description:
|
||||
"Open Data Platform to compare PostgreSQL with its healthy Redis sibling.",
|
||||
"Open Data Platform om PostgreSQL te vergelijken met zijn gezonde Redis-buur.",
|
||||
},
|
||||
{
|
||||
title: "Trace the impact",
|
||||
title: "Volg de impact",
|
||||
description:
|
||||
"Follow the dependency path from the unavailable database to affected applications.",
|
||||
"Volg het afhankelijkheidspad van de onbeschikbare database naar de geraakte applicaties.",
|
||||
},
|
||||
{
|
||||
title: "Inspect the root cause",
|
||||
title: "Bekijk de hoofdoorzaak",
|
||||
description:
|
||||
"Review PostgreSQL direct health, effective health, probe history and downstream impact.",
|
||||
"Bekijk de directe en effectieve gezondheid van PostgreSQL, de controlegeschiedenis en de impact.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
@@ -38,15 +38,15 @@ export function DemoWalkthrough({
|
||||
}: DemoWalkthroughProps) {
|
||||
const current = demoWalkthroughSteps[step] ?? demoWalkthroughSteps[0];
|
||||
return (
|
||||
<section className="demo-walkthrough" aria-label="Demo walkthrough">
|
||||
<section className="demo-walkthrough" aria-label="Demorondleiding">
|
||||
<div className="demo-walkthrough-copy">
|
||||
<span className="eyebrow">
|
||||
Demo walkthrough · {step + 1} / {demoWalkthroughSteps.length}
|
||||
Demorondleiding · {step + 1} / {demoWalkthroughSteps.length}
|
||||
</span>
|
||||
<strong>{current.title}</strong>
|
||||
<p>
|
||||
{current.description} PostgreSQL is the likely root cause affecting{" "}
|
||||
{affectedCount} downstream services.
|
||||
{current.description} PostgreSQL is de waarschijnlijke hoofdoorzaak; het raakt{" "}
|
||||
{affectedCount} afhankelijke services.
|
||||
</p>
|
||||
</div>
|
||||
<div className="demo-walkthrough-actions">
|
||||
@@ -55,7 +55,7 @@ export function DemoWalkthrough({
|
||||
onClick={() => onStepChange(Math.max(0, step - 1))}
|
||||
disabled={step === 0 || busy}
|
||||
>
|
||||
Back
|
||||
Terug
|
||||
</button>
|
||||
<button
|
||||
className="ghost"
|
||||
@@ -66,10 +66,10 @@ export function DemoWalkthrough({
|
||||
}
|
||||
disabled={busy}
|
||||
>
|
||||
{step === demoWalkthroughSteps.length - 1 ? "Restart" : "Next"}
|
||||
{step === demoWalkthroughSteps.length - 1 ? "Opnieuw" : "Volgende"}
|
||||
</button>
|
||||
<button onClick={onExit} disabled={busy}>
|
||||
Exit demo
|
||||
Demo afsluiten
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
declare module "elkjs/lib/elk-worker.min.js?url" {
|
||||
const url: string;
|
||||
export default url;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { Criticality, HealthStatus } from "./api";
|
||||
import type { Panel } from "./routing/urlState";
|
||||
|
||||
/** The UI speaks Belgian Dutch and shows times in Brussels, whatever the browser says. */
|
||||
export const LOCALE = "nl-BE";
|
||||
export const TIME_ZONE = "Europe/Brussels";
|
||||
|
||||
export const STATUS_LABELS: Record<HealthStatus, string> = {
|
||||
healthy: "Gezond",
|
||||
degraded: "Verminderd",
|
||||
down: "Uitgevallen",
|
||||
recovering: "Herstellend",
|
||||
maintenance: "Onderhoud",
|
||||
unknown: "Onbekend",
|
||||
unmonitored: "Niet bewaakt",
|
||||
};
|
||||
|
||||
export const statusText = (status: HealthStatus): string => STATUS_LABELS[status] ?? status;
|
||||
|
||||
const CRITICALITY_LABELS: Record<Criticality, string> = {
|
||||
low: "laag",
|
||||
medium: "gemiddeld",
|
||||
high: "hoog",
|
||||
critical: "kritiek",
|
||||
};
|
||||
|
||||
export const criticalityText = (value: string): string =>
|
||||
CRITICALITY_LABELS[value as Criticality] ?? value;
|
||||
|
||||
const LIFECYCLE_LABELS: Record<string, string> = {
|
||||
active: "actief",
|
||||
missing: "ontbrekend",
|
||||
stale: "verouderd",
|
||||
retired: "uitgefaseerd",
|
||||
ignored: "genegeerd",
|
||||
};
|
||||
|
||||
export const lifecycleText = (value: string): string => LIFECYCLE_LABELS[value] ?? value;
|
||||
|
||||
export const MONITORING_LABELS: Record<string, string> = {
|
||||
active_probe: "Actieve controle",
|
||||
docker_health: "Docker-gezondheid",
|
||||
appops_observation: "Waargenomen via AppOps",
|
||||
observed: "Runtime waargenomen",
|
||||
unmonitored: "Niet bewaakt",
|
||||
disabled: "Bewaking uitgeschakeld",
|
||||
};
|
||||
|
||||
const PROVIDER_LABELS: Record<string, string> = {
|
||||
active_probe: "Actieve controle",
|
||||
docker: "Docker",
|
||||
appops: "AppOps",
|
||||
runtime: "Runtime",
|
||||
manual: "Handmatig",
|
||||
};
|
||||
|
||||
export const providerText = (value: string): string => PROVIDER_LABELS[value] ?? value.replace("_", " ");
|
||||
|
||||
const PROVIDER_HEALTH_LABELS: Record<string, string> = {
|
||||
healthy: "gezond",
|
||||
degraded: "verminderd",
|
||||
unavailable: "niet beschikbaar",
|
||||
unknown: "onbekend",
|
||||
};
|
||||
|
||||
export const providerHealthText = (value: string): string => PROVIDER_HEALTH_LABELS[value] ?? value;
|
||||
|
||||
export const PANEL_LABELS: Record<Panel, string> = {
|
||||
overview: "Overzicht",
|
||||
topology: "Topologie",
|
||||
incidents: "Incidenten",
|
||||
services: "Services",
|
||||
discovery: "Detectie",
|
||||
changes: "Wijzigingen",
|
||||
activity: "Activiteit",
|
||||
config: "Configuratie",
|
||||
settings: "Instellingen",
|
||||
};
|
||||
|
||||
const MODE_LABELS: Record<string, string> = {
|
||||
landscape: "Landschap",
|
||||
dependencies: "Afhankelijkheden",
|
||||
impact: "Impact",
|
||||
};
|
||||
|
||||
export const modeText = (mode: string): string => MODE_LABELS[mode] ?? mode;
|
||||
|
||||
/** 19-11-2026 21:19:00 in Brussels time. */
|
||||
export function formatDateTime(value: string | Date): string {
|
||||
return new Date(value).toLocaleString(LOCALE, { timeZone: TIME_ZONE, dateStyle: "short", timeStyle: "medium" });
|
||||
}
|
||||
|
||||
/** 21:19 in Brussels time. */
|
||||
export function formatTime(value: string | Date): string {
|
||||
return new Date(value).toLocaleTimeString(LOCALE, { timeZone: TIME_ZONE, hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
/** "donderdag 19 november 2026" in Brussels time. */
|
||||
export function formatDay(value: string | Date): string {
|
||||
return new Date(value).toLocaleDateString(LOCALE, {
|
||||
timeZone: TIME_ZONE,
|
||||
weekday: "long",
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
/** Calendar day in Brussels, as a sortable key. */
|
||||
export function dayKey(value: string | Date): string {
|
||||
return new Intl.DateTimeFormat("en-CA", { timeZone: TIME_ZONE, year: "numeric", month: "2-digit", day: "2-digit" }).format(
|
||||
new Date(value),
|
||||
);
|
||||
}
|
||||
|
||||
/** 99,5 with a decimal comma. */
|
||||
export function formatNumber(value: number, digits = 0): string {
|
||||
return value.toLocaleString(LOCALE, { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import App from './App'
|
||||
import '@fontsource-variable/inter'
|
||||
import './styles.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createRefreshScheduler,
|
||||
reconnectDelay,
|
||||
scopesForEvent,
|
||||
SSE_EVENT_TYPES,
|
||||
type RefreshRequest,
|
||||
} from "./refreshPlan";
|
||||
|
||||
describe("scopesForEvent", () => {
|
||||
it("never reloads discovery for probe or health events", () => {
|
||||
for (const type of [
|
||||
"probe.completed",
|
||||
"service.state_changed",
|
||||
"health.evidence_changed",
|
||||
"incident.opened",
|
||||
"service.maintenance_changed",
|
||||
]) {
|
||||
expect(scopesForEvent({ event_type: type })).not.toContain("discovery");
|
||||
expect(scopesForEvent({ event_type: type })).toContain("core");
|
||||
}
|
||||
});
|
||||
|
||||
it("reloads discovery only when the topology changes", () => {
|
||||
expect(scopesForEvent({ event_type: "topology.changed" })).toEqual(["core", "discovery"]);
|
||||
expect(scopesForEvent({ event_type: "provider.status_changed" })).toEqual(["providers", "core"]);
|
||||
});
|
||||
|
||||
it("falls back to a core refresh for unknown events", () => {
|
||||
expect(scopesForEvent({ event_type: "something.new" })).toEqual(["core"]);
|
||||
expect(scopesForEvent({})).toEqual(["core"]);
|
||||
});
|
||||
|
||||
it("listens to every type the backend publishes", () => {
|
||||
expect(SSE_EVENT_TYPES).toContain("health.evidence_changed");
|
||||
expect(SSE_EVENT_TYPES).toContain("provider.status_changed");
|
||||
expect(SSE_EVENT_TYPES).toContain("incident.duplicate_resolved");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRefreshScheduler", () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("collapses a burst of events into one merged run", async () => {
|
||||
const runs: RefreshRequest[] = [];
|
||||
const scheduler = createRefreshScheduler(async (request) => {
|
||||
runs.push(request);
|
||||
});
|
||||
for (let index = 0; index < 40; index += 1) {
|
||||
scheduler.requestForEvent({ event_type: "probe.completed", service_id: `svc-${index % 3}` });
|
||||
}
|
||||
scheduler.requestForEvent({ event_type: "topology.changed" });
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
|
||||
expect(runs).toHaveLength(1);
|
||||
expect([...runs[0].scopes].sort()).toEqual(["core", "discovery", "history"]);
|
||||
expect([...runs[0].serviceIds].sort()).toEqual(["svc-0", "svc-1", "svc-2"]);
|
||||
});
|
||||
|
||||
it("never overlaps runs and replays requests made during a run once", async () => {
|
||||
let active = 0;
|
||||
let maxActive = 0;
|
||||
const runs: RefreshRequest[] = [];
|
||||
let release: () => void = () => undefined;
|
||||
const scheduler = createRefreshScheduler(async (request) => {
|
||||
active += 1;
|
||||
maxActive = Math.max(maxActive, active);
|
||||
runs.push(request);
|
||||
await new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
active -= 1;
|
||||
});
|
||||
|
||||
scheduler.request(["core"]);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(runs).toHaveLength(1);
|
||||
|
||||
// Requests while the first run is still in flight.
|
||||
scheduler.request(["core"]);
|
||||
scheduler.request(["discovery"]);
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(runs).toHaveLength(1);
|
||||
|
||||
release();
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(runs).toHaveLength(2);
|
||||
expect([...runs[1].scopes].sort()).toEqual(["core", "discovery"]);
|
||||
release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(maxActive).toBe(1);
|
||||
});
|
||||
|
||||
it("still runs during a continuous stream thanks to maxWait", async () => {
|
||||
const run = vi.fn(async () => undefined);
|
||||
const scheduler = createRefreshScheduler(run, { delayMs: 250, maxWaitMs: 1_000 });
|
||||
for (let elapsed = 0; elapsed < 1_100; elapsed += 100) {
|
||||
scheduler.request(["core"]);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
}
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps working after a failed run and stops after dispose", async () => {
|
||||
const run = vi
|
||||
.fn<(request: RefreshRequest) => Promise<void>>()
|
||||
.mockRejectedValueOnce(new Error("network"))
|
||||
.mockResolvedValue(undefined);
|
||||
const scheduler = createRefreshScheduler(run);
|
||||
scheduler.request(["core"]);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
scheduler.request(["core"]);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(run).toHaveBeenCalledTimes(2);
|
||||
|
||||
scheduler.dispose();
|
||||
scheduler.request(["core"]);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
expect(run).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconnectDelay", () => {
|
||||
it("backs off exponentially, caps at 30 s and jitters ±20%", () => {
|
||||
expect(reconnectDelay(0, () => 0.5)).toBe(1_000);
|
||||
expect(reconnectDelay(3, () => 0.5)).toBe(8_000);
|
||||
expect(reconnectDelay(20, () => 0.5)).toBe(30_000);
|
||||
expect(reconnectDelay(0, () => 0)).toBe(800);
|
||||
expect(reconnectDelay(0, () => 1)).toBe(1_200);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Event-driven refresh planning.
|
||||
*
|
||||
* Every SSE event used to trigger a full reload (services, incidents,
|
||||
* overview, events, demo, six discovery reads, the semantic topology and the
|
||||
* selected service's history): about sixteen requests per probe. The server
|
||||
* event already says what changed, so each event type maps to the smallest
|
||||
* set of data slices that can be affected, and a single-flight scheduler
|
||||
* coalesces bursts into one run per slice set.
|
||||
*/
|
||||
|
||||
export type RefreshScope = "core" | "discovery" | "providers" | "history";
|
||||
|
||||
export type RealtimeEvent = {
|
||||
event_type?: unknown;
|
||||
service_id?: unknown;
|
||||
};
|
||||
|
||||
/** Every event type the backend publishes on the SSE stream. */
|
||||
export const SSE_EVENT_TYPES = [
|
||||
"probe.completed",
|
||||
"service.state_changed",
|
||||
"service.maintenance_changed",
|
||||
"flapping.detected",
|
||||
"health.evidence_changed",
|
||||
"provider.status_changed",
|
||||
"incident.opened",
|
||||
"incident.updated",
|
||||
"incident.acknowledged",
|
||||
"incident.resolved",
|
||||
"incident.duplicate_resolved",
|
||||
"topology.changed",
|
||||
] as const;
|
||||
|
||||
const CORE: RefreshScope[] = ["core"];
|
||||
|
||||
/**
|
||||
* Data slices an event can affect. ``core`` is the topology/health/incident
|
||||
* read set; ``history`` only matters for the selected service and is
|
||||
* resolved by the caller against ``service_id``.
|
||||
*/
|
||||
export function scopesForEvent(event: RealtimeEvent): RefreshScope[] {
|
||||
const type = typeof event.event_type === "string" ? event.event_type : "";
|
||||
switch (type) {
|
||||
case "probe.completed":
|
||||
case "service.state_changed":
|
||||
case "flapping.detected":
|
||||
return ["core", "history"];
|
||||
case "service.maintenance_changed":
|
||||
case "health.evidence_changed":
|
||||
return CORE;
|
||||
case "provider.status_changed":
|
||||
return ["providers", "core"];
|
||||
case "topology.changed":
|
||||
return ["core", "discovery"];
|
||||
default:
|
||||
if (type.startsWith("incident.")) return CORE;
|
||||
// Unknown or future event types: stay correct with a core refresh.
|
||||
return CORE;
|
||||
}
|
||||
}
|
||||
|
||||
type Timers = {
|
||||
setTimeout: (callback: () => void, ms: number) => unknown;
|
||||
clearTimeout: (handle: unknown) => void;
|
||||
};
|
||||
|
||||
export type RefreshRequest = {
|
||||
scopes: Set<RefreshScope>;
|
||||
serviceIds: Set<string>;
|
||||
};
|
||||
|
||||
export type RefreshScheduler = {
|
||||
/** Queue a refresh; bursts within ``delayMs`` collapse into one run. */
|
||||
request: (scopes: Iterable<RefreshScope>, serviceId?: string | null) => void;
|
||||
/** Queue the refresh an SSE event implies. */
|
||||
requestForEvent: (event: RealtimeEvent) => void;
|
||||
dispose: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Single-flight, trailing-debounced scheduler with a maximum wait.
|
||||
*
|
||||
* - Requests arriving within ``delayMs`` merge into one run.
|
||||
* - A continuous stream still runs at least every ``maxWaitMs``.
|
||||
* - Only one run is in flight; requests made meanwhile are merged and run
|
||||
* once afterwards, so slow responses can never overlap or arrive out of
|
||||
* order and overwrite newer state.
|
||||
*/
|
||||
export function createRefreshScheduler(
|
||||
run: (request: RefreshRequest) => Promise<void>,
|
||||
{
|
||||
delayMs = 250,
|
||||
maxWaitMs = 2_000,
|
||||
timers = globalThis as unknown as Timers,
|
||||
}: { delayMs?: number; maxWaitMs?: number; timers?: Timers } = {},
|
||||
): RefreshScheduler {
|
||||
let pendingScopes = new Set<RefreshScope>();
|
||||
let pendingServices = new Set<string>();
|
||||
let timer: unknown;
|
||||
let firstQueuedAt: number | null = null;
|
||||
let inFlight = false;
|
||||
let disposed = false;
|
||||
|
||||
const hasPending = () => pendingScopes.size > 0;
|
||||
|
||||
const flush = async () => {
|
||||
timer = undefined;
|
||||
firstQueuedAt = null;
|
||||
if (disposed || inFlight || !hasPending()) return;
|
||||
const request: RefreshRequest = { scopes: pendingScopes, serviceIds: pendingServices };
|
||||
pendingScopes = new Set();
|
||||
pendingServices = new Set();
|
||||
inFlight = true;
|
||||
try {
|
||||
await run(request);
|
||||
} catch {
|
||||
// ``run`` reports its own errors; the scheduler must keep working.
|
||||
} finally {
|
||||
inFlight = false;
|
||||
if (!disposed && hasPending()) arm();
|
||||
}
|
||||
};
|
||||
|
||||
const arm = () => {
|
||||
const now = Date.now();
|
||||
if (firstQueuedAt === null) firstQueuedAt = now;
|
||||
if (timer !== undefined) timers.clearTimeout(timer);
|
||||
const remainingMaxWait = Math.max(0, firstQueuedAt + maxWaitMs - now);
|
||||
timer = timers.setTimeout(() => void flush(), Math.min(delayMs, remainingMaxWait));
|
||||
};
|
||||
|
||||
const request = (scopes: Iterable<RefreshScope>, serviceId?: string | null) => {
|
||||
if (disposed) return;
|
||||
for (const scope of scopes) pendingScopes.add(scope);
|
||||
if (serviceId) pendingServices.add(serviceId);
|
||||
// While a run is in flight the merged request is armed when it ends.
|
||||
if (!inFlight) arm();
|
||||
};
|
||||
|
||||
return {
|
||||
request,
|
||||
requestForEvent(event) {
|
||||
const serviceId = typeof event.service_id === "string" ? event.service_id : null;
|
||||
request(scopesForEvent(event), serviceId);
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
if (timer !== undefined) timers.clearTimeout(timer);
|
||||
timer = undefined;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Exponential reconnect delay with ±20% jitter so tabs do not reconnect in lockstep. */
|
||||
export function reconnectDelay(attempt: number, random: () => number = Math.random): number {
|
||||
const base = Math.min(1_000 * 2 ** Math.max(0, attempt), 30_000);
|
||||
return Math.round(base * (0.8 + random() * 0.4));
|
||||
}
|
||||
@@ -1,47 +1,74 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { subscribeToEvents } from "../api";
|
||||
import { reconnectDelay, type RealtimeEvent } from "./refreshPlan";
|
||||
|
||||
type Options = {
|
||||
onEvent: () => void;
|
||||
/** A server event arrived; the payload says what changed. */
|
||||
onEvent: (event: RealtimeEvent) => void;
|
||||
/** The stream (re)opened after a gap; anything may have been missed. */
|
||||
onResync: () => void;
|
||||
/** Periodic recovery while the stream is unavailable. */
|
||||
onFallback: () => void;
|
||||
fallbackIntervalMs?: number;
|
||||
/** A connection must stay up this long before backoff resets. */
|
||||
stableAfterMs?: number;
|
||||
/** A hidden tab keeps its stream this long before disconnecting. */
|
||||
hiddenGraceMs?: number;
|
||||
};
|
||||
|
||||
export type RealtimeStatus = "connecting" | "live" | "offline";
|
||||
|
||||
/**
|
||||
* Event-driven refresh with bounded recovery when SSE is unavailable.
|
||||
*
|
||||
* The fallback is intentionally active only while disconnected. That avoids
|
||||
* continuously reloading a healthy dashboard every few seconds just because
|
||||
* it happens to be open in a browser tab.
|
||||
* - The fallback poll runs only while disconnected and the tab is visible.
|
||||
* - Reconnects use exponential backoff with jitter; the backoff resets only
|
||||
* after a connection has been stable, so a proxy that accepts and then
|
||||
* immediately drops the stream cannot cause a reconnect storm.
|
||||
* - After any gap (reconnect, or a tab that was hidden long enough to
|
||||
* disconnect) one resync refresh recovers missed events.
|
||||
* - Briefly switching tabs keeps the stream: it closes only after
|
||||
* ``hiddenGraceMs`` hidden, which avoids a reconnect plus a full refresh
|
||||
* on every tab switch.
|
||||
*/
|
||||
export function useRealtimeEvents({
|
||||
onEvent,
|
||||
onResync,
|
||||
onFallback,
|
||||
fallbackIntervalMs = 60_000,
|
||||
}: Options): void {
|
||||
stableAfterMs = 30_000,
|
||||
hiddenGraceMs = 60_000,
|
||||
}: Options): RealtimeStatus {
|
||||
const eventRef = useRef(onEvent);
|
||||
const resyncRef = useRef(onResync);
|
||||
const fallbackRef = useRef(onFallback);
|
||||
const [status, setStatus] = useState<RealtimeStatus>("connecting");
|
||||
|
||||
useEffect(() => {
|
||||
eventRef.current = onEvent;
|
||||
resyncRef.current = onResync;
|
||||
fallbackRef.current = onFallback;
|
||||
}, [onEvent, onFallback]);
|
||||
}, [onEvent, onResync, onFallback]);
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
let connected = false;
|
||||
let retryMs = 1_000;
|
||||
let everOpened = false;
|
||||
let attempt = 0;
|
||||
let close: (() => void) | null = null;
|
||||
let reconnectTimer: number | undefined;
|
||||
let fallbackTimer: number | undefined;
|
||||
let stableTimer: number | undefined;
|
||||
let hiddenTimer: number | undefined;
|
||||
|
||||
const stop = () => {
|
||||
close?.();
|
||||
close = null;
|
||||
if (reconnectTimer !== undefined) window.clearTimeout(reconnectTimer);
|
||||
if (fallbackTimer !== undefined) window.clearInterval(fallbackTimer);
|
||||
reconnectTimer = undefined;
|
||||
const clear = (handle: number | undefined, interval = false) => {
|
||||
if (handle === undefined) return;
|
||||
if (interval) window.clearInterval(handle);
|
||||
else window.clearTimeout(handle);
|
||||
};
|
||||
const disableFallback = () => {
|
||||
clear(fallbackTimer, true);
|
||||
fallbackTimer = undefined;
|
||||
};
|
||||
const enableFallback = () => {
|
||||
@@ -50,60 +77,76 @@ export function useRealtimeEvents({
|
||||
if (!connected && !document.hidden) fallbackRef.current();
|
||||
}, fallbackIntervalMs);
|
||||
};
|
||||
const connect = () => {
|
||||
if (disposed || document.hidden || typeof EventSource === "undefined") {
|
||||
const disconnect = () => {
|
||||
close?.();
|
||||
close = null;
|
||||
connected = false;
|
||||
clear(stableTimer);
|
||||
stableTimer = undefined;
|
||||
};
|
||||
const scheduleReconnect = () => {
|
||||
if (disposed || reconnectTimer !== undefined) return;
|
||||
const delay = reconnectDelay(attempt);
|
||||
attempt += 1;
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = undefined;
|
||||
connect();
|
||||
}, delay);
|
||||
};
|
||||
const opened = () => {
|
||||
if (disposed || connected) return;
|
||||
connected = true;
|
||||
setStatus("live");
|
||||
disableFallback();
|
||||
clear(stableTimer);
|
||||
stableTimer = window.setTimeout(() => {
|
||||
attempt = 0;
|
||||
}, stableAfterMs);
|
||||
// The initial page load already fetched everything; any later open
|
||||
// follows a gap in which events may have been missed.
|
||||
if (everOpened) resyncRef.current();
|
||||
everOpened = true;
|
||||
};
|
||||
const connect = () => {
|
||||
if (disposed || document.hidden) return;
|
||||
disconnect();
|
||||
if (typeof EventSource === "undefined") {
|
||||
setStatus("offline");
|
||||
enableFallback();
|
||||
return;
|
||||
}
|
||||
close?.();
|
||||
close = subscribeToEvents(
|
||||
() => {
|
||||
connected = true;
|
||||
retryMs = 1_000;
|
||||
if (fallbackTimer !== undefined) {
|
||||
window.clearInterval(fallbackTimer);
|
||||
fallbackTimer = undefined;
|
||||
}
|
||||
eventRef.current();
|
||||
(event) => {
|
||||
opened();
|
||||
eventRef.current(event as RealtimeEvent);
|
||||
},
|
||||
() => {
|
||||
if (disposed) return;
|
||||
connected = false;
|
||||
close?.();
|
||||
close = null;
|
||||
disconnect();
|
||||
setStatus("offline");
|
||||
enableFallback();
|
||||
if (reconnectTimer === undefined) {
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = undefined;
|
||||
retryMs = Math.min(retryMs * 2, 30_000);
|
||||
connect();
|
||||
}, retryMs);
|
||||
}
|
||||
},
|
||||
() => {
|
||||
connected = true;
|
||||
retryMs = 1_000;
|
||||
if (fallbackTimer !== undefined) {
|
||||
window.clearInterval(fallbackTimer);
|
||||
fallbackTimer = undefined;
|
||||
}
|
||||
scheduleReconnect();
|
||||
},
|
||||
opened,
|
||||
);
|
||||
};
|
||||
const onVisibility = () => {
|
||||
if (document.hidden) {
|
||||
connected = false;
|
||||
close?.();
|
||||
close = null;
|
||||
enableFallback();
|
||||
} else {
|
||||
if (fallbackTimer !== undefined) {
|
||||
window.clearInterval(fallbackTimer);
|
||||
fallbackTimer = undefined;
|
||||
clear(hiddenTimer);
|
||||
hiddenTimer = window.setTimeout(() => {
|
||||
hiddenTimer = undefined;
|
||||
clear(reconnectTimer);
|
||||
reconnectTimer = undefined;
|
||||
disconnect();
|
||||
setStatus("offline");
|
||||
}, hiddenGraceMs);
|
||||
return;
|
||||
}
|
||||
clear(hiddenTimer);
|
||||
hiddenTimer = undefined;
|
||||
if (!connected && reconnectTimer === undefined) {
|
||||
attempt = 0;
|
||||
connect();
|
||||
eventRef.current();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -112,7 +155,12 @@ export function useRealtimeEvents({
|
||||
return () => {
|
||||
disposed = true;
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
stop();
|
||||
disconnect();
|
||||
disableFallback();
|
||||
clear(reconnectTimer);
|
||||
clear(hiddenTimer);
|
||||
};
|
||||
}, [fallbackIntervalMs]);
|
||||
}, [fallbackIntervalMs, stableAfterMs, hiddenGraceMs]);
|
||||
|
||||
return status;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
defaultUrlState,
|
||||
navigationKey,
|
||||
parseUrlState,
|
||||
serializeUrlState,
|
||||
type UrlState,
|
||||
} from "./urlState";
|
||||
|
||||
describe("URL state", () => {
|
||||
it("round-trips every field and omits defaults", () => {
|
||||
const state: UrlState = {
|
||||
...defaultUrlState(),
|
||||
panel: "services",
|
||||
serviceId: "svc-1",
|
||||
incidentId: "inc-9",
|
||||
snapshotId: "snap-2",
|
||||
topology: { level: "components", domainId: "commerce", applicationId: "billing" },
|
||||
filters: { ...defaultUrlState().filters, search: "api gateway", status: "down", environment: "prod" },
|
||||
};
|
||||
const hash = serializeUrlState(state);
|
||||
expect(hash).toBe(
|
||||
"#/services?service=svc-1&incident=inc-9&snapshot=snap-2&in_domain=commerce&in_app=billing&q=api+gateway&status=down&env=prod",
|
||||
);
|
||||
expect(parseUrlState(hash)).toEqual(state);
|
||||
expect(serializeUrlState(defaultUrlState())).toBe("#/topology");
|
||||
});
|
||||
|
||||
it("falls back to defaults for unknown or hostile input", () => {
|
||||
expect(parseUrlState("")).toEqual(defaultUrlState());
|
||||
expect(parseUrlState("#/not-a-panel?service=")).toEqual(defaultUrlState());
|
||||
const long = parseUrlState(`#/topology?service=${"x".repeat(500)}`);
|
||||
expect(long.serviceId).toBeNull();
|
||||
});
|
||||
|
||||
it("derives the topology level from the scope parameters", () => {
|
||||
expect(parseUrlState("#/topology?in_domain=commerce").topology).toEqual({
|
||||
level: "applications",
|
||||
domainId: "commerce",
|
||||
applicationId: null,
|
||||
});
|
||||
expect(parseUrlState("#/topology?in_app=billing").topology.level).toBe("components");
|
||||
});
|
||||
|
||||
it("separates navigation from filter changes", () => {
|
||||
const base = parseUrlState("#/services?service=svc-1");
|
||||
const filtered = { ...base, filters: { ...base.filters, search: "db" } };
|
||||
const navigated = { ...base, serviceId: "svc-2" };
|
||||
expect(navigationKey(filtered)).toBe(navigationKey(base));
|
||||
expect(navigationKey(navigated)).not.toBe(navigationKey(base));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* Shareable URL state for the single-page app.
|
||||
*
|
||||
* Hash routing (``#/services?service=…``) works in both deployments without
|
||||
* a server-side SPA fallback: the Unraid image serves the bundle from
|
||||
* FastAPI StaticFiles, where a path route would 404 on refresh.
|
||||
*
|
||||
* Navigation (workspace, selection, incident, topology level, snapshot)
|
||||
* creates a history entry so Back/Forward move through it. Filters and the
|
||||
* search text replace the current entry so Back does not replay keystrokes.
|
||||
*/
|
||||
|
||||
import type { TopologyLocation } from "../topologyNavigation";
|
||||
|
||||
export const PANELS = [
|
||||
"overview",
|
||||
"topology",
|
||||
"incidents",
|
||||
"services",
|
||||
"discovery",
|
||||
"changes",
|
||||
"activity",
|
||||
"config",
|
||||
"settings",
|
||||
] as const;
|
||||
export type Panel = (typeof PANELS)[number];
|
||||
|
||||
export type UrlFilters = {
|
||||
search: string;
|
||||
status: string;
|
||||
monitoring: string;
|
||||
group: string;
|
||||
environment: string;
|
||||
criticality: string;
|
||||
domain: string;
|
||||
application: string;
|
||||
lifecycle: string;
|
||||
mode: string;
|
||||
};
|
||||
|
||||
export type UrlState = {
|
||||
panel: Panel;
|
||||
serviceId: string | null;
|
||||
edgeId: string | null;
|
||||
incidentId: string | null;
|
||||
snapshotId: string | null;
|
||||
topology: TopologyLocation;
|
||||
filters: UrlFilters;
|
||||
};
|
||||
|
||||
export const DEFAULT_FILTERS: UrlFilters = {
|
||||
search: "",
|
||||
status: "all",
|
||||
monitoring: "all",
|
||||
group: "all",
|
||||
environment: "all",
|
||||
criticality: "all",
|
||||
domain: "all",
|
||||
application: "all",
|
||||
lifecycle: "all",
|
||||
mode: "landscape",
|
||||
};
|
||||
|
||||
const FILTER_PARAMS: Record<keyof UrlFilters, string> = {
|
||||
search: "q",
|
||||
status: "status",
|
||||
monitoring: "monitoring",
|
||||
group: "group",
|
||||
environment: "env",
|
||||
criticality: "criticality",
|
||||
domain: "domain",
|
||||
application: "application",
|
||||
lifecycle: "lifecycle",
|
||||
mode: "mode",
|
||||
};
|
||||
|
||||
export const defaultUrlState = (): UrlState => ({
|
||||
panel: "topology",
|
||||
serviceId: null,
|
||||
edgeId: null,
|
||||
incidentId: null,
|
||||
snapshotId: null,
|
||||
topology: { level: "domains", domainId: null, applicationId: null },
|
||||
filters: { ...DEFAULT_FILTERS },
|
||||
});
|
||||
|
||||
const isPanel = (value: string): value is Panel => (PANELS as readonly string[]).includes(value);
|
||||
|
||||
function bounded(value: string | null, max = 200): string | null {
|
||||
if (!value) return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed && trimmed.length <= max ? trimmed : null;
|
||||
}
|
||||
|
||||
/** Parse ``#/panel?key=value``; anything unknown falls back to defaults. */
|
||||
export function parseUrlState(hash: string): UrlState {
|
||||
const state = defaultUrlState();
|
||||
const raw = hash.replace(/^#/, "");
|
||||
const [path, query = ""] = raw.split("?", 2);
|
||||
const panel = path.replace(/^\/+/, "").split("/")[0];
|
||||
if (isPanel(panel)) state.panel = panel;
|
||||
const params = new URLSearchParams(query);
|
||||
|
||||
state.serviceId = bounded(params.get("service"));
|
||||
state.edgeId = bounded(params.get("edge"));
|
||||
state.incidentId = bounded(params.get("incident"));
|
||||
state.snapshotId = bounded(params.get("snapshot"));
|
||||
|
||||
const domainId = bounded(params.get("in_domain"));
|
||||
const applicationId = bounded(params.get("in_app"));
|
||||
if (applicationId) state.topology = { level: "components", domainId, applicationId };
|
||||
else if (domainId) state.topology = { level: "applications", domainId, applicationId: null };
|
||||
|
||||
for (const [key, param] of Object.entries(FILTER_PARAMS) as [keyof UrlFilters, string][]) {
|
||||
const value = params.get(param);
|
||||
if (value !== null) state.filters[key] = value.slice(0, 200);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Serialize to ``#/panel?…``, omitting defaults so links stay short. */
|
||||
export function serializeUrlState(state: UrlState): string {
|
||||
const params = new URLSearchParams();
|
||||
if (state.serviceId) params.set("service", state.serviceId);
|
||||
if (state.edgeId) params.set("edge", state.edgeId);
|
||||
if (state.incidentId) params.set("incident", state.incidentId);
|
||||
if (state.snapshotId) params.set("snapshot", state.snapshotId);
|
||||
if (state.topology.level !== "domains" && state.topology.domainId)
|
||||
params.set("in_domain", state.topology.domainId);
|
||||
if (state.topology.level === "components" && state.topology.applicationId)
|
||||
params.set("in_app", state.topology.applicationId);
|
||||
for (const [key, param] of Object.entries(FILTER_PARAMS) as [keyof UrlFilters, string][]) {
|
||||
if (state.filters[key] !== DEFAULT_FILTERS[key]) params.set(param, state.filters[key]);
|
||||
}
|
||||
const query = params.toString();
|
||||
return `#/${state.panel}${query ? `?${query}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of the state that deserves its own history entry. Two states
|
||||
* with the same key differ only in filters and replace each other.
|
||||
*/
|
||||
export function navigationKey(state: UrlState): string {
|
||||
return JSON.stringify([
|
||||
state.panel,
|
||||
state.serviceId,
|
||||
state.edgeId,
|
||||
state.incidentId,
|
||||
state.snapshotId,
|
||||
state.topology.level,
|
||||
state.topology.domainId,
|
||||
state.topology.applicationId,
|
||||
]);
|
||||
}
|
||||
+518
-197
@@ -1,30 +1,74 @@
|
||||
:root {
|
||||
--surface: #091725;
|
||||
--surface-raised: #0d2033;
|
||||
--line: #203d59;
|
||||
--ink-muted: #91a6bf;
|
||||
--accent: #78a8d5;
|
||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
color: #eef4ff;
|
||||
background: #07111d;
|
||||
/* Layered dark theme: each surface one step lighter than the one below. */
|
||||
--bg: #0f1216;
|
||||
--surface-1: #151a21;
|
||||
--surface-2: #1b212a;
|
||||
--surface-3: #232b36;
|
||||
--line: #2a333f;
|
||||
--line-strong: #3b4654;
|
||||
--text: #e8edf3;
|
||||
--text-2: #b9c4d0;
|
||||
--text-3: #8f9cab;
|
||||
/* One accent for interaction and selection. */
|
||||
--accent: #5fb0ec;
|
||||
--accent-strong: #8ccaf7;
|
||||
--accent-soft: rgba(95, 176, 236, .14);
|
||||
--accent-line: #2f6390;
|
||||
--accent-fill: #2a6ea3;
|
||||
--accent-fill-hover: #3582bd;
|
||||
/* Status: same meaning everywhere, always paired with an icon or label. */
|
||||
--ok: #5ad68f;
|
||||
--ok-line: #2f6b4b;
|
||||
--ok-bg: #14261d;
|
||||
--warn: #f2bf4f;
|
||||
--warn-line: #7a5d22;
|
||||
--warn-bg: #2a2214;
|
||||
--bad: #f57f8d;
|
||||
--bad-line: #7c3a44;
|
||||
--bad-bg: #2c161b;
|
||||
--maint: #b3a6e0;
|
||||
--maint-line: #4d4675;
|
||||
--maint-bg: #1f1c33;
|
||||
--unknown: #9aa6b4;
|
||||
/* Shape and rhythm. */
|
||||
--radius-sm: 6px;
|
||||
--radius-md: 10px;
|
||||
--radius-lg: 14px;
|
||||
--radius-pill: 999px;
|
||||
--fs-xs: 11px;
|
||||
--fs-sm: 12px;
|
||||
--fs-md: 13px;
|
||||
--fs-base: 14px;
|
||||
--fs-lg: 16px;
|
||||
--fs-xl: 20px;
|
||||
--fs-2xl: 26px;
|
||||
font-family: "Inter Variable", Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: var(--fs-base);
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 320px; min-height: 100vh; background: radial-gradient(circle at top, #162843 0, #08111f 42%, #050a12 100%); }
|
||||
body { margin: 0; min-width: 320px; min-height: 100vh; background: radial-gradient(1200px 500px at 50% -10%, var(--surface-1) 0, var(--bg) 70%); }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { border: 1px solid #355779; border-radius: 11px; padding: 10px 14px; background: #17324f; color: #f4f8ff; cursor: pointer; transition: border-color .15s ease, background .15s ease, transform .15s ease; }
|
||||
button:hover:not(:disabled) { border-color: #5d84ad; background: #1b3a5c; }
|
||||
button { border: 1px solid var(--line-strong); border-radius: var(--radius-md); padding: 10px 14px; background: var(--surface-3); color: var(--text); cursor: pointer; transition: border-color .15s ease, background .15s ease, transform .15s ease; }
|
||||
button:hover:not(:disabled) { border-color: var(--text-3); background: #2a3340; }
|
||||
button.primary { border-color: var(--accent-fill); background: var(--accent-fill); color: #fff; font-weight: 600; }
|
||||
button.primary:hover:not(:disabled) { border-color: var(--accent-fill-hover); background: var(--accent-fill-hover); }
|
||||
button:active:not(:disabled) { transform: translateY(1px); }
|
||||
button:disabled { cursor: wait; opacity: .6; }
|
||||
button.ghost { background: #0b1a2b; }
|
||||
button.danger { color: #ffb1ba; border-color: #6d3944; background: #29151c; }
|
||||
button.text-button { padding: 0; border: 0; background: transparent; color: #8da9c9; font-size: 12px; }
|
||||
input, select, textarea { width: 100%; margin-top: 6px; border: 1px solid #29435f; border-radius: 10px; padding: 10px 11px; color: #eef4ff; background: #0a1625; outline: none; }
|
||||
textarea { min-height: 270px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12px; line-height: 1.5; }
|
||||
input:focus, select:focus, textarea:focus { border-color: #638ab4; box-shadow: 0 0 0 3px rgba(99, 138, 180, .12); }
|
||||
label { color: #98abc3; font-size: 13px; }
|
||||
button:disabled { cursor: not-allowed; opacity: .6; }
|
||||
button.ghost { background: var(--surface-1); }
|
||||
button.ghost:hover:not(:disabled) { background: var(--surface-2); }
|
||||
button.danger { color: var(--bad); border-color: var(--bad-line); background: var(--bad-bg); }
|
||||
button.text-button { padding: 0; border: 0; background: transparent; color: var(--text-3); font-size: var(--fs-sm); }
|
||||
input, select, textarea { width: 100%; margin-top: 6px; border: 1px solid var(--line); border-radius: var(--radius-md); padding: 10px 11px; color: var(--text); background: var(--surface-1); }
|
||||
textarea { min-height: 270px; resize: vertical; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: var(--fs-sm); line-height: 1.5; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 3px rgba(95, 176, 236, .55); }
|
||||
label { color: var(--text-3); font-size: var(--fs-md); }
|
||||
fieldset { min-width: 0; }
|
||||
|
||||
.shell { width: min(1540px, calc(100% - 40px)); margin: 0 auto; padding: 26px 0 42px; }
|
||||
@@ -34,153 +78,193 @@ fieldset { min-width: 0; }
|
||||
.brand-lockup img { width: 38px; height: 38px; }
|
||||
.toolbar, .button-row { display: flex; align-items: center; gap: 9px; }
|
||||
.button-row.wrap { flex-wrap: wrap; }
|
||||
.eyebrow, .kicker { text-transform: uppercase; letter-spacing: .14em; font-size: 11px; color: #87a1c2; }
|
||||
.eyebrow, .kicker { text-transform: uppercase; letter-spacing: .08em; font-weight: 600; font-size: var(--fs-xs); color: var(--text-3); }
|
||||
h1, h2, h3, p { margin-top: 0; }
|
||||
h1 { margin-bottom: 0; font-size: 27px; letter-spacing: -.02em; }
|
||||
h1 small { color: #7e97b7; font-size: 12px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; }
|
||||
h1 { margin-bottom: 0; font-size: var(--fs-2xl); letter-spacing: -.02em; }
|
||||
h1 small { color: var(--text-3); font-size: var(--fs-sm); font-weight: 600; letter-spacing: .08em; text-transform: uppercase; }
|
||||
h2 { max-width: 760px; margin-bottom: 9px; font-size: clamp(29px, 3.6vw, 46px); line-height: 1.04; letter-spacing: -.035em; }
|
||||
h3 { margin: 6px 0 12px; font-size: 22px; letter-spacing: -.02em; }
|
||||
.hero { margin-bottom: 12px; padding: 14px 18px; border: 1px solid #1f3550; border-radius: 14px; background: linear-gradient(135deg, rgba(14, 30, 51, .92), rgba(9, 21, 36, .86)); }
|
||||
.operations-strip { display: flex; align-items: center; justify-content: space-between; gap: 22px; margin-bottom: 12px; padding: 12px 16px; border: 1px solid #1f3550; border-radius: 14px; background: #0b1b2e; }
|
||||
h3 { margin: 6px 0 12px; font-size: var(--fs-xl); letter-spacing: -.02em; }
|
||||
.hero { margin-bottom: 12px; padding: 14px 18px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: linear-gradient(135deg, rgba(21, 26, 33, .92), rgba(21, 26, 33, .86)); }
|
||||
.operations-strip { display: flex; align-items: center; justify-content: space-between; gap: 22px; margin-bottom: 12px; padding: 12px 16px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--surface-1); }
|
||||
.operations-strip > div:first-child { display: grid; gap: 3px; }
|
||||
.operations-strip strong { font-size: 16px; }
|
||||
.operations-strip small { color: #8fa6c2; font-size: 12px; }
|
||||
.operations-strip strong { font-size: var(--fs-lg); }
|
||||
.operations-strip small { color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.canvas-card { position: relative; }
|
||||
.canvas-toolbar { position: absolute; z-index: 5; top: 10px; right: 10px; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; max-width: calc(100% - 20px); pointer-events: none; }
|
||||
.canvas-toolbar > * { pointer-events: auto; }
|
||||
.canvas-note { padding: 4px 10px; border-radius: var(--radius-pill); background: rgba(21, 26, 33, .9); border: 1px solid var(--line); color: var(--text-2); font-size: var(--fs-sm); }
|
||||
.service-row-wrap { display: flex; align-items: center; gap: 8px; }
|
||||
.service-row-wrap > input[type="checkbox"] { flex: 0 0 auto; width: 16px; height: 16px; }
|
||||
.service-row-wrap > .service-table-row, .service-row-wrap > .service-table-head { flex: 1 1 auto; }
|
||||
.bulk-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 8px 0; padding: 8px 12px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-2); }
|
||||
.checkbox-field { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.inline-form { display: grid; gap: 8px; margin-top: 10px; }
|
||||
.inline-form label { display: grid; gap: 4px; }
|
||||
.activity-list { list-style: none; margin: 12px 0; padding: 0; display: grid; gap: 6px; }
|
||||
.activity-list li { display: grid; grid-template-columns: 150px minmax(140px, 220px) 1fr auto; gap: 10px; align-items: center; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); font-size: var(--fs-md); }
|
||||
.activity-type { color: var(--text-3); font-family: ui-monospace, monospace; font-size: var(--fs-sm); }
|
||||
@media (max-width: 760px) { .activity-list li { grid-template-columns: 1fr; } }
|
||||
.backup-list { list-style: none; margin: 8px 0; padding: 0; display: grid; gap: 6px; max-width: 640px; }
|
||||
.backup-list li { display: flex; align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.backup-list li > span { flex: 1; display: grid; }
|
||||
.backup-list small { color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.settings-form { display: grid; gap: 12px; max-width: 560px; }
|
||||
.settings-form label { display: grid; gap: 4px; }
|
||||
.settings-form small { color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.unlock-panel { display: grid; gap: 8px; max-width: 560px; margin: 0 0 12px auto; padding: 12px 16px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--surface-1); }
|
||||
.unlock-panel label { display: grid; gap: 4px; font-weight: 600; }
|
||||
.unlock-panel small { color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.unlock-panel code { font-size: var(--fs-xs); }
|
||||
.unlock-error { color: var(--bad); font-size: var(--fs-md); }
|
||||
.unlock-actions { display: flex; gap: 8px; }
|
||||
.live-status { margin-left: 8px; padding: 1px 8px; border-radius: var(--radius-pill); font-size: var(--fs-xs); font-weight: 600; letter-spacing: 0; text-transform: none; }
|
||||
.live-status-live { color: var(--ok); background: rgba(34, 197, 94, .12); }
|
||||
.live-status-connecting { color: var(--text-2); background: rgba(95, 176, 236, .14); }
|
||||
.live-status-offline { color: var(--warn); background: rgba(251, 191, 36, .14); }
|
||||
.compact-hero { align-items: center; }
|
||||
.compact-hero h2 { margin: 3px 0; font-size: clamp(20px, 2vw, 28px); }
|
||||
.compact-hero .kicker { margin-bottom: 3px; }
|
||||
.compact-hero .muted { font-size: 12px; line-height: 1.4; }
|
||||
.compact-hero .muted { font-size: var(--fs-sm); line-height: 1.4; }
|
||||
.demo-mode .hero { margin-bottom: 10px; padding: 18px 22px; }
|
||||
.demo-mode .hero h2 { max-width: 650px; font-size: clamp(28px, 3vw, 39px); }
|
||||
.muted { max-width: 760px; margin-bottom: 0; color: #91a4bd; line-height: 1.55; }
|
||||
.muted.compact { margin-top: 10px; font-size: 13px; }
|
||||
.error-banner, .notice-banner { margin-bottom: 14px; padding: 11px 13px; border-radius: 11px; }
|
||||
.error-banner { border: 1px solid #7b3842; background: #35151c; color: #ffd7dc; }
|
||||
.notice-banner { display: flex; align-items: center; justify-content: space-between; gap: 12px; border: 1px solid #315d56; background: #102b28; color: #c8eee5; }
|
||||
.demo-banner, .demo-confirm { align-items: center; justify-content: space-between; gap: 18px; margin-bottom: 14px; padding: 14px 16px; border-radius: 14px; }
|
||||
.demo-banner { display: grid; grid-template-columns: minmax(0, 1fr) auto; border: 1px solid #755d2b; background: linear-gradient(110deg, #2a2515, #16251f); }
|
||||
.muted { max-width: 760px; margin-bottom: 0; color: var(--text-3); line-height: 1.55; }
|
||||
.muted.compact { margin-top: 10px; font-size: var(--fs-md); }
|
||||
.error-banner, .notice-banner { margin-bottom: 14px; padding: 11px 13px; border-radius: var(--radius-md); }
|
||||
.error-banner { border: 1px solid var(--bad-line); background: var(--bad-bg); color: var(--bad); }
|
||||
.notice-banner { display: flex; align-items: center; justify-content: space-between; gap: 12px; border: 1px solid var(--ok-line); background: var(--ok-bg); color: var(--ok); }
|
||||
.demo-banner, .demo-confirm { align-items: center; justify-content: space-between; gap: 18px; margin-bottom: 14px; padding: 14px 16px; border-radius: var(--radius-lg); }
|
||||
.demo-banner { display: grid; grid-template-columns: minmax(0, 1fr) auto; border: 1px solid var(--warn-line); background: linear-gradient(110deg, var(--warn-bg), var(--ok-bg)); }
|
||||
.demo-confirm { display: flex; }
|
||||
.demo-confirm { border: 1px solid #496d91; background: #0e2338; }
|
||||
.demo-banner strong, .demo-confirm strong { display: block; margin-top: 4px; color: #fff2c9; font-size: 16px; }
|
||||
.demo-confirm strong { color: #dcecff; }
|
||||
.demo-banner p, .demo-confirm p { margin: 4px 0 0; color: #b6c4ba; font-size: 13px; line-height: 1.45; }
|
||||
.demo-confirm p { color: #a9bdd2; }
|
||||
.demo-confirm { border: 1px solid var(--line-strong); background: var(--surface-2); }
|
||||
.demo-banner strong, .demo-confirm strong { display: block; margin-top: 4px; color: var(--warn); font-size: var(--fs-lg); }
|
||||
.demo-confirm strong { color: var(--text); }
|
||||
.demo-banner p, .demo-confirm p { margin: 4px 0 0; color: var(--text-2); font-size: var(--fs-md); line-height: 1.45; }
|
||||
.demo-confirm p { color: var(--text-2); }
|
||||
.demo-actions { display: flex; flex: 0 0 auto; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.demo-walkthrough { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding-top: 12px; border-top: 1px solid #66562d; }
|
||||
.demo-walkthrough { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; gap: 16px; padding-top: 12px; border-top: 1px solid var(--warn-line); }
|
||||
.demo-walkthrough-copy { min-width: 0; }
|
||||
.demo-walkthrough-copy strong { font-size: 14px; }
|
||||
.demo-walkthrough-copy strong { font-size: var(--fs-base); }
|
||||
.demo-walkthrough-copy p { max-width: 700px; }
|
||||
.demo-walkthrough-actions { display: flex; flex: 0 0 auto; gap: 8px; flex-wrap: wrap; }
|
||||
.health-summary { display: grid; grid-template-columns: repeat(4, minmax(64px, 1fr)); gap: 6px; min-width: 300px; }
|
||||
.health-summary div, .incident-metrics div { padding: 9px; border: 1px solid #233d5a; border-radius: 10px; background: #0a1828; }
|
||||
.health-summary strong, .incident-metrics strong { display: block; font-size: 20px; }
|
||||
.health-summary span, .incident-metrics span { color: #8198b3; font-size: 11px; text-transform: uppercase; letter-spacing: .08em; }
|
||||
.health-summary div, .incident-metrics div { padding: 9px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.health-summary strong, .incident-metrics strong { display: block; font-size: var(--fs-xl); }
|
||||
.health-summary span, .incident-metrics span { color: var(--text-3); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .08em; }
|
||||
|
||||
.panel-tabs { display: flex; gap: 7px; margin-bottom: 12px; overflow-x: auto; }
|
||||
.panel-tabs button { flex: 0 0 auto; padding: 8px 12px; border-color: #203a56; background: #091726; color: #90a5bf; }
|
||||
.panel-tabs button.active { border-color: #557da8; background: #142a43; color: #eef6ff; }
|
||||
.panel-tabs button { flex: 0 0 auto; padding: 8px 12px; border-color: var(--line); background: var(--surface-1); color: var(--text-3); }
|
||||
.panel-tabs button:hover:not(:disabled) { color: var(--text); }
|
||||
.panel-tabs button.active { border-color: var(--accent-line); background: var(--accent-soft); color: var(--text); font-weight: 600; }
|
||||
.workspace { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; align-items: start; }
|
||||
.topology-workspace:has(.topology-drawer) { grid-template-columns: minmax(0, 1fr) minmax(330px, 380px); }
|
||||
.demo-mode .canvas-card { min-height: 480px; height: min(620px, calc(100vh - 360px)); }
|
||||
.canvas-card { min-height: 500px; height: min(700px, calc(100vh - 370px)); overflow: hidden; border: 1px solid #203754; border-radius: 16px; background: #08131f; box-shadow: 0 26px 90px rgba(0,0,0,.28); }
|
||||
.empty-state { height: 100%; min-height: 620px; display: grid; place-content: center; gap: 8px; padding: 30px; text-align: center; color: #8fa4be; }
|
||||
.empty-state strong { color: #eaf3ff; font-size: 22px; }
|
||||
.canvas-card { min-height: 500px; height: min(700px, calc(100vh - 370px)); overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--bg); box-shadow: 0 26px 90px rgba(0,0,0,.28); }
|
||||
.empty-state { height: 100%; min-height: 620px; display: grid; place-content: center; gap: 8px; padding: 30px; text-align: center; color: var(--text-3); }
|
||||
.empty-state strong { color: var(--text); font-size: var(--fs-xl); }
|
||||
.side-panel { display: grid; min-width: 0; align-content: start; gap: 12px; height: min(700px, calc(100vh - 370px)); min-height: 500px; overflow-x: hidden; overflow-y: auto; padding-right: 2px; }
|
||||
.topology-drawer { position: sticky; top: 14px; border-left: 1px solid #203754; padding-left: 14px; }
|
||||
.panel-section { min-width: 0; padding: 19px; border: 1px solid #203754; border-radius: 18px; background: rgba(8, 20, 34, .95); box-shadow: 0 18px 50px rgba(0,0,0,.18); }
|
||||
.topology-drawer { position: sticky; top: 14px; border-left: 1px solid var(--line); padding-left: 14px; }
|
||||
.panel-section { min-width: 0; padding: 19px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: rgba(21, 26, 33, .95); box-shadow: 0 18px 50px rgba(0,0,0,.18); }
|
||||
.form-section { padding: 0; }
|
||||
.form-section summary { padding: 16px 19px; cursor: pointer; list-style: none; }
|
||||
.form-section summary::-webkit-details-marker { display: none; }
|
||||
.form-section summary::after { content: '+'; color: #7f99b7; font-size: 18px; }
|
||||
.form-section summary::after { content: '+'; color: var(--text-3); font-size: var(--fs-lg); }
|
||||
.form-section[open] summary::after { content: '−'; }
|
||||
.form-section .service-form { padding: 0 19px 19px; }
|
||||
.tall-panel { min-height: 520px; }
|
||||
.service-form { display: grid; gap: 13px; margin-top: 13px; }
|
||||
.field-row { display: grid; grid-template-columns: 1fr 105px; gap: 10px; }
|
||||
.semantic-fields { display: grid; gap: 9px; margin: 4px 0; padding: 10px; border: 1px solid #284563; border-radius: 10px; }
|
||||
.semantic-fields legend { padding: 0 5px; color: #89a8c9; font-size: 11px; text-transform: uppercase; letter-spacing: .08em; }
|
||||
.semantic-fields { display: grid; gap: 9px; margin: 4px 0; padding: 10px; border: 1px solid var(--line); border-radius: var(--radius-md); }
|
||||
.semantic-fields legend { padding: 0 5px; color: var(--text-3); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .08em; }
|
||||
.semantic-fields .field-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.semantic-fields .muted { align-self: end; font-size: 11px; }
|
||||
.dependency-fieldset { display: grid; gap: 7px; margin: 0; padding: 11px; border: 1px solid #263d57; border-radius: 11px; max-height: 150px; overflow-y: auto; }
|
||||
.dependency-fieldset legend { padding: 0 5px; color: #8197b2; font-size: 12px; }
|
||||
.semantic-fields .muted { align-self: end; font-size: var(--fs-xs); }
|
||||
.dependency-fieldset { display: grid; gap: 7px; margin: 0; padding: 11px; border: 1px solid var(--line); border-radius: var(--radius-md); max-height: 150px; overflow-y: auto; }
|
||||
.dependency-fieldset legend { padding: 0 5px; color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.check-row { display: flex; align-items: center; gap: 8px; }
|
||||
.check-row input { width: auto; margin: 0; }
|
||||
.inspector-section { min-height: 280px; }
|
||||
.observation-callout { border: 1px solid #31576c; background: #102433; color: #b7d9e8; }
|
||||
.root-cause-label { display: inline-block; margin-top: 2px; color: #ffd27c; font-size: 11px; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.inspector-callout { display: grid; gap: 5px; margin: 13px 0; padding: 11px 12px; border-radius: 10px; font-size: 12px; line-height: 1.4; }
|
||||
.inspector-callout strong { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; }
|
||||
.inspector-callout span, .inspector-callout small { color: #b7c8d9; }
|
||||
.root-cause-callout { border: 1px solid #80622f; background: #2a2517; color: #ffe7a2; }
|
||||
.impacted-callout { border: 1px solid #6a4f2a; background: #241f16; color: #f2c977; }
|
||||
.observation-callout { border: 1px solid var(--line-strong); background: var(--surface-2); color: var(--text-2); }
|
||||
.root-cause-label { display: inline-block; margin-top: 2px; color: var(--warn); font-size: var(--fs-xs); letter-spacing: .08em; text-transform: uppercase; }
|
||||
.inspector-callout { display: grid; gap: 5px; margin: 13px 0; padding: 11px 12px; border-radius: var(--radius-md); font-size: var(--fs-sm); line-height: 1.4; }
|
||||
.inspector-callout strong { font-size: var(--fs-sm); text-transform: uppercase; letter-spacing: .06em; }
|
||||
.inspector-callout span, .inspector-callout small { color: var(--text-2); }
|
||||
.root-cause-callout { border: 1px solid var(--warn-line); background: var(--warn-bg); color: var(--warn); }
|
||||
.impacted-callout { border: 1px solid var(--warn-line); background: var(--warn-bg); color: var(--warn); }
|
||||
.inspector dl { display: grid; gap: 8px; margin: 15px 0; }
|
||||
.inspector dl div { display: grid; grid-template-columns: 125px minmax(0, 1fr); gap: 9px; }
|
||||
dt { color: #7f94ae; font-size: 12px; }
|
||||
dd { margin: 0; overflow-wrap: anywhere; color: #dce8f7; font-size: 12px; }
|
||||
.probe-detail { padding: 10px; border-radius: 9px; background: #0a1625; color: #9db0c8; font-size: 12px; line-height: 1.45; }
|
||||
.health-pill { display: inline-flex; padding: 5px 9px; border-radius: 999px; border: 1px solid currentColor; font-size: 10px; text-transform: uppercase; letter-spacing: .08em; white-space: nowrap; }
|
||||
.status-healthy { color: #7ee2ac !important; }
|
||||
.status-degraded { color: #ffd27c !important; }
|
||||
.status-down { color: #ff929e !important; }
|
||||
.status-unknown { color: #9aabc0 !important; }
|
||||
.status-unmonitored { color: #87a9c4 !important; }
|
||||
.history-strip { display: flex; align-items: flex-end; gap: 4px; min-height: 24px; margin: 13px 0; padding: 7px 8px; border-radius: 9px; background: #08131f; overflow-x: auto; }
|
||||
.history-dot { flex: 0 0 8px; width: 8px; height: 18px; border-radius: 4px; background: currentColor; opacity: .85; }
|
||||
dt { color: var(--text-3); font-size: var(--fs-sm); }
|
||||
dd { margin: 0; overflow-wrap: anywhere; color: var(--text); font-size: var(--fs-sm); }
|
||||
.probe-detail { padding: 10px; border-radius: var(--radius-md); background: var(--surface-1); color: var(--text-2); font-size: var(--fs-sm); line-height: 1.45; }
|
||||
.health-pill { display: inline-flex; padding: 5px 9px; border-radius: var(--radius-pill); border: 1px solid currentColor; font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .08em; white-space: nowrap; }
|
||||
.status-healthy { color: var(--ok) !important; }
|
||||
.status-degraded { color: var(--warn) !important; }
|
||||
.status-down { color: var(--bad) !important; }
|
||||
.status-unknown { color: var(--text-3) !important; }
|
||||
.status-unmonitored { color: var(--text-3) !important; }
|
||||
.history-strip { display: flex; align-items: flex-end; gap: 4px; min-height: 24px; margin: 13px 0; padding: 7px 8px; border-radius: var(--radius-md); background: var(--bg); overflow-x: auto; }
|
||||
.history-dot { flex: 0 0 8px; width: 8px; height: 18px; border-radius: var(--radius-sm); background: currentColor; opacity: .85; }
|
||||
.incident-metrics { display: grid; grid-template-columns: repeat(2, 1fr); gap: 9px; margin: 15px 0; }
|
||||
.candidate-list, .docker-list { display: grid; gap: 9px; margin-top: 14px; }
|
||||
.candidate { width: 100%; display: grid; gap: 5px; text-align: left; background: #0a1727; }
|
||||
.candidate strong { font-size: 15px; }
|
||||
.candidate small, .docker-card small { color: #8196af; line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.candidate { width: 100%; display: grid; gap: 5px; text-align: left; background: var(--surface-1); }
|
||||
.candidate strong { font-size: var(--fs-base); }
|
||||
.candidate small, .docker-card small { color: var(--text-3); line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.config-label { display: grid; gap: 4px; margin: 14px 0; }
|
||||
.full-button { width: 100%; margin-top: 11px; }
|
||||
.docker-card { display: grid; gap: 7px; padding: 12px; border: 1px solid #243c57; border-radius: 12px; background: #0a1727; }
|
||||
.docker-card { display: grid; gap: 7px; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.docker-card > div { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
|
||||
.docker-card > div span { color: #85a0be; font-size: 11px; }
|
||||
.empty-inline { padding: 18px 0 8px; color: #8094ad; font-size: 13px; }
|
||||
.docker-card > div span { color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.empty-inline { padding: 18px 0 8px; color: var(--text-3); font-size: var(--fs-md); }
|
||||
|
||||
.react-flow__node { min-width: 165px; border: 1px solid #36587e !important; background: #10233a !important; color: #edf6ff !important; border-radius: 13px !important; padding: 0 !important; box-shadow: 0 10px 30px rgba(0,0,0,.25); font-size: 12px; }
|
||||
.react-flow__node { min-width: 165px; border: 1px solid var(--line-strong) !important; background: var(--surface-2) !important; color: var(--text) !important; border-radius: var(--radius-lg) !important; padding: 0 !important; box-shadow: 0 10px 30px rgba(0,0,0,.25); font-size: var(--fs-sm); }
|
||||
.react-flow__node.service-node { min-width: 198px; overflow: visible; }
|
||||
.react-flow__node.application-node { min-width: 226px; border-radius: 15px !important; }
|
||||
.application-node .service-node-body { min-height: 122px; background: linear-gradient(145deg, rgba(21, 51, 76, .88), rgba(12, 29, 47, .96)); }
|
||||
.scope-label { display: block; margin: 8px 0 4px; color: #91a8c2; font-size: 11px; }
|
||||
.node-kicker { color: #7fb6dd; font-size: 9px; letter-spacing: .1em; text-transform: uppercase; }
|
||||
.react-flow__node.service-node .react-flow__handle { width: 8px; height: 8px; border: 2px solid #9bb5d1; background: #173552; }
|
||||
.service-node-body { display: grid; gap: 4px; min-height: 108px; padding: 12px 14px; border-radius: 12px; }
|
||||
.service-node-body strong { overflow-wrap: anywhere; font-size: 14px; line-height: 1.15; }
|
||||
.service-node-body small { color: #91a8c2; font-size: 10px; }
|
||||
.react-flow__node.application-node { min-width: 226px; border-radius: var(--radius-lg) !important; }
|
||||
.application-node .service-node-body { min-height: 122px; background: linear-gradient(145deg, rgba(21, 26, 33, .88), rgba(21, 26, 33, .96)); }
|
||||
.scope-label { display: block; margin: 8px 0 4px; color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.node-kicker { color: var(--accent); font-size: var(--fs-xs); letter-spacing: .1em; text-transform: uppercase; }
|
||||
.react-flow__node.service-node .react-flow__handle { width: 8px; height: 8px; border: 2px solid var(--line-strong); background: var(--surface-3); }
|
||||
.service-node-body { display: grid; gap: 4px; min-height: 108px; padding: 12px 14px; border-radius: var(--radius-md); }
|
||||
.service-node-body strong { overflow-wrap: anywhere; font-size: var(--fs-base); line-height: 1.15; }
|
||||
.service-node-body small { color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.node-badges { min-height: 15px; }
|
||||
.node-badge { display: inline-flex; padding: 2px 5px; border-radius: 4px; font-size: 9px; font-weight: 700; letter-spacing: .08em; }
|
||||
.node-badge { display: inline-flex; padding: 2px 5px; border-radius: var(--radius-sm); font-size: var(--fs-xs); font-weight: 700; letter-spacing: .08em; }
|
||||
.app-micro-topology { display: flex; gap: 4px; margin: 6px 0 2px; }
|
||||
.app-micro-topology i { display: grid; width: 16px; height: 16px; place-items: center; border: 1px solid #416181; border-radius: 50%; color: #b7d9f4; background: #102842; font-size: 8px; font-style: normal; font-weight: 800; }
|
||||
.app-micro-topology i.role-database, .app-micro-topology i.role-cache, .app-micro-topology i.role-storage { border-radius: 4px; background: #19353c; }
|
||||
.app-micro-topology i.role-proxy, .app-micro-topology i.role-api { border-radius: 3px; background: #29395c; }
|
||||
.root-cause-badge { background: #825f25; color: #ffe8a3; }
|
||||
.impacted-badge { background: #68452a; color: #ffd69b; }
|
||||
.node-status { width: fit-content; font-size: 10px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.react-flow__node.service-node:has(.root-cause-badge) { border-color: #d39b38 !important; box-shadow: 0 0 0 2px rgba(211,155,56,.28), 0 12px 36px rgba(211,155,56,.2); }
|
||||
.react-flow__node.selected { outline: 2px solid #dcecff; outline-offset: 3px; }
|
||||
.react-flow__node.status-healthy { border-color: #3b8c67 !important; box-shadow: 0 10px 34px rgba(47,128,90,.12); }
|
||||
.react-flow__node.status-degraded { border-color: #9a7330 !important; box-shadow: 0 10px 34px rgba(154,115,48,.12); }
|
||||
.react-flow__node.status-down { border-color: #9b414d !important; box-shadow: 0 10px 34px rgba(155,65,77,.14); }
|
||||
.react-flow__node.status-unmonitored { border-color: #466a86 !important; box-shadow: none; }
|
||||
.react-flow__edge-path { stroke: #668ab3; stroke-width: 2; }
|
||||
.living-edge-path { fill: none; stroke: #668ab3; stroke-width: 2; transition: stroke .18s ease, stroke-width .18s ease, opacity .18s ease; }
|
||||
.living-edge-routes_to { stroke: #82a9cf; stroke-dasharray: 8 4; }
|
||||
.living-edge-review { stroke: #58718c; stroke-dasharray: 3 6; opacity: .68; }
|
||||
.living-edge-path.is-selected { stroke: #d5ebff; stroke-width: 3.2; }
|
||||
.living-edge-signal { fill: none; stroke: #bde6ff; stroke-width: 3.2; stroke-linecap: round; stroke-dasharray: 2 20; animation: servicemap-edge-signal 1.7s linear infinite; filter: drop-shadow(0 0 3px rgba(143, 211, 255, .8)); }
|
||||
.edge-down .living-edge-path { stroke: #b55967; }
|
||||
.edge-degraded .living-edge-path { stroke: #b08a45; }
|
||||
.edge-down .living-edge-signal, .edge-degraded .living-edge-signal { stroke: #ffd17b; }
|
||||
.app-micro-topology i { display: grid; width: 16px; height: 16px; place-items: center; border: 1px solid var(--line-strong); border-radius: 50%; color: var(--text-2); background: var(--surface-3); font-size: var(--fs-xs); font-style: normal; font-weight: 800; }
|
||||
.app-micro-topology i.role-database, .app-micro-topology i.role-cache, .app-micro-topology i.role-storage { border-radius: var(--radius-sm); background: var(--ok-bg); }
|
||||
.app-micro-topology i.role-proxy, .app-micro-topology i.role-api { border-radius: var(--radius-sm); background: var(--line-strong); }
|
||||
.root-cause-badge { background: var(--warn-line); color: var(--warn); }
|
||||
.impacted-badge { background: var(--warn-line); color: var(--warn); }
|
||||
.node-status { width: fit-content; font-size: var(--fs-xs); font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
|
||||
.react-flow__node.service-node:has(.root-cause-badge) { border-color: var(--warn-line) !important; box-shadow: 0 0 0 2px rgba(211,155,56,.28), 0 12px 36px rgba(211,155,56,.2); }
|
||||
.react-flow__node.selected { outline: 2px solid var(--accent); outline-offset: 3px; }
|
||||
/* Root-cause nodes are pre-selected by the graph; mark them as root cause, not as the operator's selection. */
|
||||
.react-flow__node.selected:has(.root-cause-badge) { outline-color: var(--warn); }
|
||||
.react-flow__node.status-healthy { border-color: var(--ok-line) !important; box-shadow: 0 10px 34px rgba(47,128,90,.12); }
|
||||
.react-flow__node.status-degraded { border-color: var(--warn-line) !important; box-shadow: 0 10px 34px rgba(154,115,48,.12); }
|
||||
.react-flow__node.status-down { border-color: var(--bad-line) !important; box-shadow: 0 10px 34px rgba(155,65,77,.14); }
|
||||
.react-flow__node.status-unmonitored { border-color: var(--line-strong) !important; box-shadow: none; }
|
||||
.react-flow__edge-path { stroke: var(--line-strong); stroke-width: 2; }
|
||||
.living-edge-path { fill: none; stroke: var(--line-strong); stroke-width: 2; transition: stroke .18s ease, stroke-width .18s ease, opacity .18s ease; }
|
||||
.living-edge-routes_to { stroke: var(--line-strong); stroke-dasharray: 8 4; }
|
||||
.living-edge-review { stroke: var(--line-strong); stroke-dasharray: 3 6; opacity: .68; }
|
||||
.living-edge-path.is-selected { stroke: var(--accent); stroke-width: 3.2; }
|
||||
.living-edge-signal { fill: none; stroke: var(--accent); stroke-width: 3.2; stroke-linecap: round; stroke-dasharray: 2 20; animation: servicemap-edge-signal 1.7s linear infinite; filter: drop-shadow(0 0 3px rgba(95, 176, 236, .8)); }
|
||||
.edge-down .living-edge-path { stroke: var(--bad-line); }
|
||||
.edge-degraded .living-edge-path { stroke: var(--warn-line); }
|
||||
.edge-down .living-edge-signal, .edge-degraded .living-edge-signal { stroke: var(--warn); }
|
||||
@keyframes servicemap-edge-signal { to { stroke-dashoffset: -44; } }
|
||||
@media (prefers-reduced-motion: reduce) { .living-edge-signal { animation: none; stroke-dasharray: none; opacity: .85; } }
|
||||
.react-flow__edge-marker { fill: #668ab3; }
|
||||
.react-flow__edge.edge-down .react-flow__edge-path { stroke: #b55967; }
|
||||
.react-flow__edge.edge-degraded .react-flow__edge-path { stroke: #b08a45; }
|
||||
.react-flow__edge.edge-down .react-flow__edge-marker { fill: #b55967; }
|
||||
.react-flow__edge.edge-degraded .react-flow__edge-marker { fill: #b08a45; }
|
||||
.react-flow__controls { border: 1px solid #274563; overflow: hidden; border-radius: 12px; }
|
||||
.react-flow__controls button { background: #10233a; color: #fff; border-bottom-color: #274563; }
|
||||
.react-flow__minimap { border: 1px solid #274563; border-radius: 12px; overflow: hidden; background: #08131f !important; }
|
||||
.react-flow__edge-marker { fill: var(--line-strong); }
|
||||
.react-flow__edge.edge-down .react-flow__edge-path { stroke: var(--bad-line); }
|
||||
.react-flow__edge.edge-degraded .react-flow__edge-path { stroke: var(--warn-line); }
|
||||
.react-flow__edge.edge-down .react-flow__edge-marker { fill: var(--bad-line); }
|
||||
.react-flow__edge.edge-degraded .react-flow__edge-marker { fill: var(--warn-line); }
|
||||
.react-flow__controls { border: 1px solid var(--line); overflow: hidden; border-radius: var(--radius-md); }
|
||||
.react-flow__controls { box-shadow: 0 8px 24px rgba(0, 0, 0, .35); }
|
||||
.react-flow__controls button { width: 30px; height: 30px; padding: 0; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: var(--surface-2); color: var(--text-2); }
|
||||
.react-flow__controls button:hover:not(:disabled) { border-color: var(--line); background: var(--surface-3); color: var(--text); }
|
||||
.react-flow__controls button svg { fill: currentColor; max-width: 13px; max-height: 13px; }
|
||||
.react-flow__attribution { background: transparent !important; opacity: .45; }
|
||||
.react-flow__attribution a { color: var(--text-3) !important; }
|
||||
.react-flow__minimap { border: 1px solid var(--line); border-radius: var(--radius-md); overflow: hidden; background: var(--bg) !important; }
|
||||
|
||||
/* v1.1 information architecture */
|
||||
.overview-grid, .incident-workspace, .services-workspace { display: grid; gap: 16px; }
|
||||
@@ -189,74 +273,74 @@ dd { margin: 0; overflow-wrap: anywhere; color: #dce8f7; font-size: 12px; }
|
||||
.overview-lead h2 { margin: 9px 0; font-size: clamp(28px, 3vw, 42px); }
|
||||
.overview-incident { min-height: 270px; }
|
||||
.summary-cards { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 9px; margin-top: 28px; }
|
||||
.summary-cards button { display: block; min-width: 0; padding: 14px; border: 1px solid #233d5a; border-radius: 14px; background: #0a1828; text-align: left; }
|
||||
.summary-cards strong { display: block; font-size: 26px; }
|
||||
.summary-cards span { color: #a9bdd4; font-size: 11px; text-transform: uppercase; letter-spacing: .08em; }
|
||||
.summary-cards button { display: block; min-width: 0; padding: 14px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--surface-1); text-align: left; }
|
||||
.summary-cards strong { display: block; font-size: var(--fs-2xl); }
|
||||
.summary-cards span { color: var(--text-2); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .08em; }
|
||||
.overview-root-list { max-height: 220px; overflow-y: auto; padding-right: 4px; }
|
||||
.coverage-overview { grid-column: span 2; }
|
||||
.coverage-overview h3 { margin-bottom: 0; }
|
||||
.coverage-breakdown { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 8px; margin: 14px 0; }
|
||||
.coverage-breakdown div { padding: 10px; border: 1px solid #233d5a; border-radius: 11px; background: #0a1828; }
|
||||
.coverage-breakdown div { padding: 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.coverage-breakdown strong, .coverage-breakdown span { display: block; }
|
||||
.coverage-breakdown strong { font-size: 20px; }
|
||||
.coverage-breakdown span { margin-top: 3px; color: #91a6bf; font-size: 10px; line-height: 1.25; text-transform: uppercase; letter-spacing: .06em; }
|
||||
.coverage-breakdown strong { font-size: var(--fs-xl); }
|
||||
.coverage-breakdown span { margin-top: 3px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.25; text-transform: uppercase; letter-spacing: .06em; }
|
||||
.event-panel { grid-column: 1 / -1; }
|
||||
.event-list { display: grid; gap: 2px; margin-top: 12px; }
|
||||
.event-row { display: flex; align-items: flex-start; gap: 11px; padding: 10px 0; border-bottom: 1px solid #172c43; }
|
||||
.event-dot { flex: 0 0 8px; width: 8px; height: 8px; margin-top: 5px; border-radius: 50%; background: #78a8d5; box-shadow: 0 0 0 4px rgba(120,168,213,.12); }
|
||||
.event-row { display: flex; align-items: flex-start; gap: 11px; padding: 10px 0; border-bottom: 1px solid var(--line); }
|
||||
.event-dot { flex: 0 0 8px; width: 8px; height: 8px; margin-top: 5px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 4px rgba(95, 176, 236, .12); }
|
||||
.event-row strong, .event-row small { display: block; }
|
||||
.event-row strong { font-size: 13px; }
|
||||
.event-row small { margin-top: 3px; color: #8095ae; font-size: 11px; }
|
||||
.event-row strong { font-size: var(--fs-md); }
|
||||
.event-row small { margin-top: 3px; color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.incident-workspace { grid-template-columns: minmax(0, 1.05fr) minmax(320px, .85fr); }
|
||||
.incident-list-panel, .incident-detail-panel { min-height: 560px; }
|
||||
.incident-card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: #8398b3; font-size: 11px; text-transform: uppercase; letter-spacing: .08em; }
|
||||
.incident-card-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--text-3); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .08em; }
|
||||
.incident-card.resolved { opacity: .72; }
|
||||
.review-filters { display: grid; grid-template-columns: minmax(170px, 1fr) repeat(2, minmax(130px, auto)); gap: 10px; margin-top: 16px; }
|
||||
.review-filters label { display: grid; gap: 5px; color: #afc3d9; font-size: 12px; }
|
||||
.review-filters label { display: grid; gap: 5px; color: var(--text-2); font-size: var(--fs-sm); }
|
||||
.review-filters input, .review-filters select { min-width: 0; width: 100%; margin: 0; }
|
||||
.incident-list-panel .review-filters { grid-template-columns: minmax(170px, 1fr) minmax(130px, 170px); }
|
||||
.timeline { display: grid; gap: 0; margin-top: 20px; }
|
||||
.timeline-row { display: grid; grid-template-columns: 17px minmax(0, 1fr); gap: 10px; min-height: 58px; }
|
||||
.timeline-line { position: relative; width: 9px; height: 9px; margin-top: 4px; border: 2px solid #78a8d5; border-radius: 50%; background: #0b1b2c; }
|
||||
.timeline-line::after { content: ''; position: absolute; top: 7px; left: 2px; width: 1px; height: 50px; background: #315271; }
|
||||
.timeline-line { position: relative; width: 9px; height: 9px; margin-top: 4px; border: 2px solid var(--accent); border-radius: 50%; background: var(--surface-1); }
|
||||
.timeline-line::after { content: ''; position: absolute; top: 7px; left: 2px; width: 1px; height: 50px; background: var(--line-strong); }
|
||||
.timeline-row:last-child .timeline-line::after { display: none; }
|
||||
.timeline-row strong, .timeline-row small { display: block; }
|
||||
.timeline-row strong { font-size: 13px; line-height: 1.35; }
|
||||
.timeline-row small { margin-top: 3px; color: #8298b2; font-size: 11px; }
|
||||
.timeline-row strong { font-size: var(--fs-md); line-height: 1.35; }
|
||||
.timeline-row small { margin-top: 3px; color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.services-workspace { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
||||
.services-workspace:has(.service-drawer) { grid-template-columns: minmax(0, 1fr) minmax(340px, 400px); }
|
||||
.service-drawer { position: sticky; top: 14px; display: grid; align-content: start; gap: 12px; max-height: calc(100vh - 42px); overflow-y: auto; padding: 0 2px 2px 14px; border-left: 1px solid #203754; }
|
||||
.service-drawer { position: sticky; top: 14px; display: grid; align-content: start; gap: 12px; max-height: calc(100vh - 42px); overflow-y: auto; padding: 0 2px 2px 14px; border-left: 1px solid var(--line); }
|
||||
.drawer-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 2px 0; }
|
||||
.table-panel { min-height: 630px; }
|
||||
.table-toolbar { display: grid; grid-template-columns: minmax(180px, 1.5fr) auto repeat(5, minmax(105px, 1fr)); gap: 9px; margin-bottom: 15px; }
|
||||
.search-field { min-width: 0; }
|
||||
.service-table { display: grid; gap: 1px; overflow-x: auto; }
|
||||
.service-table-head, .service-table-row { display: grid; grid-template-columns: minmax(180px, 1.25fr) minmax(115px, .8fr) minmax(110px, .65fr) minmax(130px, .9fr) minmax(100px, .7fr) minmax(75px, .45fr) minmax(75px, .45fr); gap: 12px; align-items: center; min-width: 920px; }
|
||||
.service-table-head { padding: 8px 12px; color: #7f96b2; font-size: 10px; text-transform: uppercase; letter-spacing: .1em; }
|
||||
.service-table-row { width: 100%; padding: 12px; border: 1px solid #1d3853; border-radius: 10px; background: #0a1727; color: #dbe9f8; text-align: left; }
|
||||
.service-table-row:hover { background: #10243a; }
|
||||
.service-table-row[aria-pressed="true"] { border-color: #78a8d5; background: #102943; box-shadow: inset 3px 0 #8dc5ee; }
|
||||
.service-table-head { padding: 8px 12px; color: var(--text-3); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .1em; }
|
||||
.service-table-row { width: 100%; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); color: var(--text); text-align: left; }
|
||||
.service-table-row:hover { background: var(--surface-2); }
|
||||
.service-table-row[aria-pressed="true"] { border-color: var(--accent); background: var(--surface-3); box-shadow: inset 3px 0 var(--accent); }
|
||||
.monitoring-cell { display: grid; gap: 2px; }
|
||||
.service-table-row span { min-width: 0; overflow-wrap: anywhere; font-size: 12px; }
|
||||
.service-table-row span { min-width: 0; overflow-wrap: anywhere; font-size: var(--fs-sm); }
|
||||
.service-table-row strong, .service-table-row small { display: block; }
|
||||
.service-table-row strong { font-size: 13px; }
|
||||
.service-table-row small { margin-top: 3px; color: #8197b1; font-size: 11px; }
|
||||
.service-table-row strong { font-size: var(--fs-md); }
|
||||
.service-table-row small { margin-top: 3px; color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.graph-tools { display: none; }
|
||||
.topology-command-bar { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; margin-bottom: 12px; padding: 9px 11px; border: 1px solid #203754; border-radius: 14px; background: rgba(8, 20, 34, .94); box-shadow: 0 16px 40px rgba(0,0,0,.14); }
|
||||
.topology-command-bar { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; margin-bottom: 12px; padding: 9px 11px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: rgba(21, 26, 33, .94); box-shadow: 0 16px 40px rgba(0,0,0,.14); }
|
||||
.topology-command-actions { display: flex; align-items: center; justify-content: flex-end; gap: 7px; flex-wrap: wrap; }
|
||||
.filter-chip { justify-self: start; padding: 4px 8px; border-color: #456b8d; border-radius: 999px; background: #102c43; color: #c5e2f7; font-size: 10px; }
|
||||
.topology-command-actions input { width: 175px; margin: 0; padding: 7px 9px; font-size: 12px; }
|
||||
.compact-button { padding: 7px 9px; border-radius: 9px; font-size: 11px; }
|
||||
.filter-chip { justify-self: start; padding: 4px 8px; border-color: var(--line-strong); border-radius: var(--radius-pill); background: var(--surface-3); color: var(--text); font-size: var(--fs-xs); }
|
||||
.topology-command-actions input { width: 175px; margin: 0; padding: 7px 9px; font-size: var(--fs-sm); }
|
||||
.compact-button { padding: 7px 9px; border-radius: var(--radius-md); font-size: var(--fs-xs); }
|
||||
.filter-popover { position: relative; }
|
||||
.filter-popover summary { cursor: pointer; list-style: none; padding: 7px 9px; border: 1px solid #355779; border-radius: 9px; background: #0b1a2b; color: #eef4ff; font-size: 11px; }
|
||||
.filter-popover summary { cursor: pointer; list-style: none; padding: 7px 9px; border: 1px solid var(--line-strong); border-radius: var(--radius-md); background: var(--surface-1); color: var(--text); font-size: var(--fs-xs); }
|
||||
.filter-popover summary::-webkit-details-marker { display: none; }
|
||||
.filter-popover > div { position: absolute; z-index: 12; right: 0; top: calc(100% + 7px); display: grid; grid-template-columns: repeat(2, minmax(145px, 1fr)); gap: 9px; width: 330px; padding: 12px; border: 1px solid #355779; border-radius: 12px; background: #0b1b2e; box-shadow: 0 20px 50px rgba(0,0,0,.42); }
|
||||
.filter-popover label { font-size: 11px; }
|
||||
.filter-popover select { padding: 7px 8px; font-size: 12px; }
|
||||
.filter-popover > div { position: absolute; z-index: 12; right: 0; top: calc(100% + 7px); display: grid; grid-template-columns: repeat(2, minmax(145px, 1fr)); gap: 9px; width: 330px; padding: 12px; border: 1px solid var(--line-strong); border-radius: var(--radius-md); background: var(--surface-1); box-shadow: 0 20px 50px rgba(0,0,0,.42); }
|
||||
.filter-popover label { font-size: var(--fs-xs); }
|
||||
.filter-popover select { padding: 7px 8px; font-size: var(--fs-sm); }
|
||||
.mode-tabs { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.mode-tabs button { padding: 7px 9px; font-size: 11px; }
|
||||
.mode-tabs button.active { border-color: #79a6d1; background: #193956; }
|
||||
.topology-breadcrumbs { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; color: #9fb4ca; font-size: 12px; }
|
||||
.mode-tabs button { padding: 7px 9px; font-size: var(--fs-xs); }
|
||||
.mode-tabs button.active { border-color: var(--accent); background: var(--surface-3); }
|
||||
.topology-breadcrumbs { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; color: var(--text-2); font-size: var(--fs-sm); }
|
||||
.domain-node .service-node-body { min-width: 205px; }
|
||||
.application-node .service-node-body { min-width: 225px; }
|
||||
.component-node .service-node-body { min-width: 198px; }
|
||||
@@ -265,70 +349,70 @@ dd { margin: 0; overflow-wrap: anywhere; color: #dce8f7; font-size: 12px; }
|
||||
.detail-grid { display: grid; gap: 8px; margin: 15px 0; }
|
||||
.detail-grid div { display: grid; grid-template-columns: 125px minmax(0, 1fr); gap: 9px; }
|
||||
.discovery-panel, .config-panel { max-width: 980px; min-height: 620px; }
|
||||
.suggestion { display: grid; gap: 4px; margin-top: 9px; padding: 10px; border: 1px solid #294563; border-radius: 9px; background: #0c1d30; }
|
||||
.suggestion small { color: #92a8c1; }
|
||||
.suggestion { display: grid; gap: 4px; margin-top: 9px; padding: 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-2); }
|
||||
.suggestion small { color: var(--text-3); }
|
||||
.suggestion button { margin-top: 4px; }
|
||||
.discovery-workspace { display: grid; gap: 16px; grid-template-columns: minmax(0, 1.05fr) minmax(340px, .95fr); align-items: start; }
|
||||
.discovery-workspace > .discovery-observations { grid-column: 1 / -1; }
|
||||
.discovery-panel, .suggestion-panel, .discovery-observations { min-height: 0; }
|
||||
.discovery-summary { display: grid; grid-template-columns: repeat(5, minmax(72px, 1fr)); gap: 8px; margin: 18px 0 12px; }
|
||||
.discovery-summary div { display: grid; gap: 4px; padding: 12px; border: 1px solid #233d5a; border-radius: 12px; background: #0a1828; }
|
||||
.discovery-summary strong { font-size: 21px; }
|
||||
.discovery-summary span { color: #8198b3; font-size: 10px; text-transform: uppercase; letter-spacing: .07em; }
|
||||
.discovery-callout, .notice-inline { display: grid; gap: 4px; margin: 13px 0; padding: 11px 12px; border: 1px solid #315c5e; border-radius: 10px; background: #0c2528; color: #bce8dd; font-size: 12px; line-height: 1.45; }
|
||||
.probe-safety-callout { display: grid; gap: 7px; margin: 13px 0; padding: 12px; border: 1px solid #496d91; border-radius: 10px; background: #0d2237; color: #d0e5fa; font-size: 12px; line-height: 1.45; }
|
||||
.probe-safety-callout span, .probe-safety-callout small { color: #9fb8d2; }
|
||||
.discovery-summary div { display: grid; gap: 4px; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.discovery-summary strong { font-size: var(--fs-xl); }
|
||||
.discovery-summary span { color: var(--text-3); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .07em; }
|
||||
.discovery-callout, .notice-inline { display: grid; gap: 4px; margin: 13px 0; padding: 11px 12px; border: 1px solid var(--ok-line); border-radius: var(--radius-md); background: var(--ok-bg); color: var(--ok); font-size: var(--fs-sm); line-height: 1.45; }
|
||||
.probe-safety-callout { display: grid; gap: 7px; margin: 13px 0; padding: 12px; border: 1px solid var(--line-strong); border-radius: var(--radius-md); background: var(--surface-2); color: var(--text); font-size: var(--fs-sm); line-height: 1.45; }
|
||||
.probe-safety-callout span, .probe-safety-callout small { color: var(--text-2); }
|
||||
.coverage-change-list { display: grid; gap: 6px; max-height: 260px; overflow-y: auto; }
|
||||
.coverage-change-list > div { display: grid; gap: 2px; padding: 8px 9px; border: 1px solid #294863; border-radius: 8px; background: #0a1b2b; }
|
||||
.coverage-change-list strong { font-size: 12px; }
|
||||
.coverage-change-list small { font-size: 11px; line-height: 1.35; }
|
||||
.discovery-callout span { color: #91bdb8; }
|
||||
.notice-inline { display: block; color: #b8d8f5; border-color: #315271; background: #0d2237; }
|
||||
.coverage-change-list > div { display: grid; gap: 2px; padding: 8px 9px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.coverage-change-list strong { font-size: var(--fs-sm); }
|
||||
.coverage-change-list small { font-size: var(--fs-xs); line-height: 1.35; }
|
||||
.discovery-callout span { color: var(--ok); }
|
||||
.notice-inline { display: block; color: var(--text); border-color: var(--line-strong); background: var(--surface-2); }
|
||||
.suggestion-list { display: grid; gap: 10px; margin-top: 14px; max-height: 720px; overflow-y: auto; padding-right: 2px; }
|
||||
.discovery-panel .field-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.review-confirm { margin-top: 14px; padding: 14px; border: 1px solid #b28a46; border-radius: 12px; background: #322714; }
|
||||
.review-confirm p { color: #e0d2b6; line-height: 1.5; }
|
||||
.review-confirm { margin-top: 14px; padding: 14px; border: 1px solid var(--warn-line); border-radius: var(--radius-md); background: var(--warn-bg); }
|
||||
.review-confirm p { color: var(--warn); line-height: 1.5; }
|
||||
.show-more { margin-top: 12px; }
|
||||
.suggestion-card { display: grid; gap: 7px; padding: 13px; border: 1px solid #2a4663; border-radius: 13px; background: #0a1727; }
|
||||
.suggestion-card { display: grid; gap: 7px; padding: 13px; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--surface-1); }
|
||||
.suggestion-card-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
|
||||
.suggestion-card-heading strong { display: block; margin-top: 4px; font-size: 14px; line-height: 1.3; }
|
||||
.suggestion-card > small { color: #8fa5be; }
|
||||
.suggestion-card-heading strong { display: block; margin-top: 4px; font-size: var(--fs-base); line-height: 1.3; }
|
||||
.suggestion-card > small { color: var(--text-3); }
|
||||
.evidence-list { display: grid; gap: 4px; margin-top: 6px; }
|
||||
.evidence-list strong { color: #9db4cf; font-size: 11px; text-transform: uppercase; letter-spacing: .07em; }
|
||||
.evidence-list small { display: block; color: #849bb6; line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.evidence-list strong { color: var(--text-2); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .07em; }
|
||||
.evidence-list small { display: block; color: var(--text-3); line-height: 1.4; overflow-wrap: anywhere; }
|
||||
.provider-statuses { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
|
||||
.provider-statuses small { border: 1px solid #294968; border-radius: 999px; padding: 3px 7px; text-transform: capitalize; }
|
||||
.provider-statuses small { border: 1px solid var(--line); border-radius: var(--radius-pill); padding: 3px 7px; }
|
||||
.change-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 9px; margin-top: 14px; align-items: start; }
|
||||
.snapshot-picker { display: grid; gap: 5px; max-width: 440px; margin: 14px 0; color: #afc3d9; font-size: 12px; }
|
||||
.change-card { padding: 12px; border: 1px solid #294563; border-radius: 10px; background: #0a1727; }
|
||||
.snapshot-picker { display: grid; gap: 5px; max-width: 440px; margin: 14px 0; color: var(--text-2); font-size: var(--fs-sm); }
|
||||
.change-card { padding: 12px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.change-card summary { display: grid; gap: 4px; cursor: pointer; }
|
||||
.change-card summary strong { color: #e3efff; }
|
||||
.change-card summary small { color: #9cb2cb; }
|
||||
.change-card summary strong { color: var(--text); }
|
||||
.change-card summary small { color: var(--text-2); }
|
||||
.change-fields { display: grid; gap: 6px; margin: 10px 0; }
|
||||
.change-fields div { display: grid; gap: 2px; padding: 7px; border: 1px solid #203b57; border-radius: 6px; }
|
||||
.change-fields strong { font-size: 11px; text-transform: capitalize; }
|
||||
.change-fields small { overflow-wrap: anywhere; color: #a8bed6; }
|
||||
.current-evidence-callout { border-color: #3b6d7b; background: #102b37; }
|
||||
.change-fields div { display: grid; gap: 2px; padding: 7px; border: 1px solid var(--line); border-radius: var(--radius-sm); }
|
||||
.change-fields strong { font-size: var(--fs-xs); text-transform: capitalize; }
|
||||
.change-fields small { overflow-wrap: anywhere; color: var(--text-2); }
|
||||
.current-evidence-callout { border-color: var(--ok-line); background: var(--surface-2); }
|
||||
.observation-list { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 6px; margin: 14px 0; }
|
||||
.observation-row { display: grid; grid-template-columns: minmax(0, 1.2fr) auto; gap: 3px 9px; padding: 9px 10px; border: 1px solid #203b57; border-radius: 9px; background: #0a1727; }
|
||||
.observation-row strong { overflow-wrap: anywhere; font-size: 12px; }
|
||||
.observation-row span, .observation-row small { color: #8ca3bd; font-size: 11px; }
|
||||
.observation-row { display: grid; grid-template-columns: minmax(0, 1.2fr) auto; gap: 3px 9px; padding: 9px 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-1); }
|
||||
.observation-row strong { overflow-wrap: anywhere; font-size: var(--fs-sm); }
|
||||
.observation-row span, .observation-row small { color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.observation-row small { grid-column: 1 / -1; }
|
||||
.candidate-details { margin-top: 14px; }
|
||||
.candidate-details summary { cursor: pointer; color: #a9bdd4; font-size: 12px; }
|
||||
.candidate-details summary { cursor: pointer; color: var(--text-2); font-size: var(--fs-sm); }
|
||||
.compact-list { max-height: 430px; overflow-y: auto; }
|
||||
.group-chips { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
.group-chips button { padding: 6px 8px; font-size: 11px; }
|
||||
.group-chips button.active { border-color: #79a6d1; background: #193956; }
|
||||
.edge-inspector { border-color: #46698b; }
|
||||
.group-chips button { padding: 6px 8px; font-size: var(--fs-xs); }
|
||||
.group-chips button.active { border-color: var(--accent); background: var(--surface-3); }
|
||||
.edge-inspector { border-color: var(--line-strong); }
|
||||
.edge-inspector .detail-grid { max-height: 280px; overflow-y: auto; }
|
||||
.flap-badge { margin-left: 4px; background: #3d3f74; color: #d9d8ff; }
|
||||
.status-recovering { color: #a9c5ff !important; }
|
||||
.status-maintenance { color: #b6a9dc !important; }
|
||||
.flap-badge { margin-left: 4px; background: var(--maint-line); color: var(--maint); }
|
||||
.status-recovering { color: var(--text-2) !important; }
|
||||
.status-maintenance { color: var(--maint) !important; }
|
||||
.react-flow__edge.edge-dimmed { opacity: .28; }
|
||||
.react-flow__edge.edge-down .react-flow__edge-path, .react-flow__edge.edge-degraded .react-flow__edge-path { stroke-dasharray: 7 5; }
|
||||
.react-flow__node.status-recovering { border-color: #687ab1 !important; }
|
||||
.react-flow__node.status-maintenance { border-color: #705d99 !important; }
|
||||
.react-flow__node.status-recovering { border-color: var(--line-strong) !important; }
|
||||
.react-flow__node.status-maintenance { border-color: var(--maint-line) !important; }
|
||||
.react-flow__node.service-node:has(.flap-badge) { border-style: dashed !important; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
@@ -369,8 +453,245 @@ dd { margin: 0; overflow-wrap: anywhere; color: #dce8f7; font-size: 12px; }
|
||||
.filter-popover > div { position: fixed; right: 12px; left: 12px; top: auto; width: auto; }
|
||||
.discovery-summary { grid-template-columns: repeat(2, 1fr); }
|
||||
.inspector-title { align-items: flex-start; }
|
||||
.panel-heading { flex-wrap: wrap; gap: 12px; }
|
||||
.panel-heading > label { flex: 1 1 100%; }
|
||||
.demo-banner { display: flex; align-items: flex-start; flex-direction: column; }
|
||||
.demo-confirm, .demo-walkthrough { align-items: flex-start; flex-direction: column; }
|
||||
.demo-actions { width: 100%; }
|
||||
.demo-actions button, .demo-walkthrough-actions button { flex: 1 1 auto; }
|
||||
}
|
||||
|
||||
/* Accessibility: a visible focus ring for keyboard users (WCAG 2.4.7, 1.4.11). */
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.react-flow__node:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; border-radius: var(--radius-lg); }
|
||||
main:focus { outline: none; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
|
||||
.skip-link { position: absolute; left: 12px; top: -60px; z-index: 50; padding: 10px 14px; border-radius: var(--radius-md); background: var(--surface-3); color: var(--text); }
|
||||
.skip-link:focus { top: 12px; }
|
||||
.flow-host { width: 100%; height: 100%; }
|
||||
.graph-list { height: 100%; overflow: auto; padding: 56px 16px 16px; }
|
||||
.graph-list ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
|
||||
.graph-list li { display: grid; gap: 4px; }
|
||||
.graph-list button { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; width: 100%; text-align: left; }
|
||||
.graph-list small { padding-left: 14px; color: var(--text-2); font-size: var(--fs-sm); }
|
||||
.graph-list-status { min-width: 128px; font-size: var(--fs-sm); font-weight: 700; }
|
||||
.graph-list .status-healthy .graph-list-status { color: var(--ok); }
|
||||
.graph-list .status-degraded .graph-list-status, .graph-list .status-recovering .graph-list-status { color: var(--warn); }
|
||||
.graph-list .status-down .graph-list-status { color: var(--bad); }
|
||||
.graph-list .status-unknown .graph-list-status, .graph-list .status-unmonitored .graph-list-status, .graph-list .status-maintenance .graph-list-status { color: var(--text-2); }
|
||||
.graph-list-flag { padding: 2px 8px; border: 1px solid currentColor; border-radius: var(--radius-pill); color: var(--warn); font-size: var(--fs-xs); }
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; scroll-behavior: auto !important; } }
|
||||
.confirm-dialog { width: min(520px, calc(100% - 32px)); padding: 20px 22px; border: 1px solid var(--line-strong); border-radius: var(--radius-lg); background: var(--surface-2); color: var(--text); box-shadow: 0 30px 90px rgba(0,0,0,.55); }
|
||||
.confirm-dialog::backdrop { background: rgba(21, 26, 33, .72); }
|
||||
.confirm-dialog h2 { margin: 0 0 8px; font-size: var(--fs-lg); }
|
||||
.confirm-dialog-body p { margin: 0 0 16px; color: var(--text-2); font-size: var(--fs-base); line-height: 1.5; }
|
||||
.confirm-dialog .button-row { justify-content: flex-end; }
|
||||
|
||||
/* Numbers line up in KPIs, tables and metrics. */
|
||||
.health-summary strong, .summary-cards strong, .metric strong, .service-table, .detail-grid dd, .history-strip, time { font-variant-numeric: tabular-nums; }
|
||||
/* Lucide icons sit on the text baseline; icon + label buttons get a fixed gap. */
|
||||
.status-icon { flex: none; vertical-align: -2px; }
|
||||
.health-pill .status-icon, .node-status .status-icon { margin-right: 3px; }
|
||||
button:has(> svg) { display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
button > svg { flex: none; opacity: .9; }
|
||||
.panel-tabs button > svg { opacity: .75; }
|
||||
.panel-tabs button.active > svg { opacity: 1; color: var(--accent); }
|
||||
|
||||
/* ── App shell ─────────────────────────────────────────────────────────
|
||||
One sticky header: brand, live status, KPI chips and actions on the
|
||||
first row, workspaces on the second. On phones the workspaces move to a
|
||||
bottom bar. */
|
||||
:root { --topbar-h: 98px; --page-w: min(1760px, calc(100% - 32px)); }
|
||||
.shell { width: 100%; margin: 0; padding: 0 0 32px; }
|
||||
.shell > :not(.topbar):not(.skip-link):not(dialog) { width: var(--page-w); margin-left: auto; margin-right: auto; }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: block; min-height: 0; margin-bottom: 14px; padding: 0; border-bottom: 1px solid var(--line); background: rgba(21, 26, 33, .94); backdrop-filter: blur(10px); }
|
||||
.topbar-inner { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "brand status actions" "nav nav nav"; align-items: center; column-gap: 16px; width: var(--page-w); margin: 0 auto; }
|
||||
.topbar .brand-lockup { grid-area: brand; gap: 10px; height: 54px; }
|
||||
.topbar .brand-lockup img { width: 28px; height: 28px; }
|
||||
.topbar .brand-lockup h1 { margin: 0; font-size: var(--fs-lg); font-weight: 700; letter-spacing: -.01em; }
|
||||
.topbar-status { grid-area: status; display: flex; align-items: center; justify-content: flex-end; gap: 10px; min-width: 0; }
|
||||
.topbar-status .live-status { margin: 0; }
|
||||
.kpi-chips { display: flex; gap: 6px; }
|
||||
.kpi-chip { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 1px solid var(--line); border-radius: var(--radius-pill); background: var(--surface-2); font-size: var(--fs-md); }
|
||||
.kpi-chip strong { color: var(--text); font-variant-numeric: tabular-nums; }
|
||||
.topbar .toolbar { grid-area: actions; gap: 6px; }
|
||||
.topbar .toolbar .primary { padding: 8px 14px; }
|
||||
.icon-button { width: 36px; height: 36px; padding: 0; }
|
||||
.topbar .panel-tabs { grid-area: nav; display: flex; gap: 2px; margin: 0 0 -1px; overflow-x: auto; scrollbar-width: none; }
|
||||
.topbar .panel-tabs::-webkit-scrollbar { display: none; }
|
||||
.topbar .panel-tabs button { padding: 9px 12px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: var(--text-3); font-size: var(--fs-md); }
|
||||
.topbar .panel-tabs button:hover:not(:disabled) { border-color: var(--line-strong); background: transparent; color: var(--text); }
|
||||
.topbar .panel-tabs button.active { border-color: var(--accent); background: transparent; color: var(--text); }
|
||||
.nav-more { display: none; }
|
||||
|
||||
.actions-menu { position: relative; }
|
||||
.actions-menu-panel { position: absolute; top: calc(100% + 6px); right: 0; z-index: 60; display: grid; gap: 2px; min-width: 210px; padding: 6px; border: 1px solid var(--line-strong); border-radius: var(--radius-md); background: var(--surface-2); box-shadow: 0 16px 40px rgba(0, 0, 0, .45); }
|
||||
.actions-menu-panel button { justify-content: flex-start; width: 100%; padding: 9px 10px; border-color: transparent; background: transparent; }
|
||||
.actions-menu-panel button:hover:not(:disabled) { border-color: transparent; background: var(--surface-3); }
|
||||
.actions-menu-footer { margin-top: 4px; padding: 6px 10px 2px; border-top: 1px solid var(--line); color: var(--text-3); font-size: var(--fs-xs); }
|
||||
|
||||
.unlock-popover { position: absolute; top: calc(100% + 6px); right: max(16px, calc((100% - 1760px) / 2)); z-index: 60; width: min(440px, calc(100vw - 32px)); margin: 0; background: var(--surface-2); border-color: var(--line-strong); box-shadow: 0 16px 40px rgba(0, 0, 0, .45); }
|
||||
|
||||
.status-line { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 14px; margin-bottom: 12px; padding: 8px 14px; border: 1px solid var(--bad-line); border-radius: var(--radius-md); background: var(--bad-bg); font-size: var(--fs-md); }
|
||||
.status-line strong { color: var(--bad); }
|
||||
.status-line span { color: var(--text-2); }
|
||||
.status-line .text-button { margin-left: auto; color: var(--text); font-size: var(--fs-md); text-decoration: underline; }
|
||||
.status-line-offline { border-color: var(--warn-line); background: var(--warn-bg); }
|
||||
.status-line-offline strong { color: var(--warn); }
|
||||
|
||||
/* ── Topology fills the viewport; the inspector is a drawer over it ── */
|
||||
.topology-workspace, .topology-workspace:has(.topology-drawer) { position: relative; display: block; }
|
||||
.canvas-card, .demo-mode .canvas-card { height: calc(100dvh - var(--topbar-h) - 100px); min-height: 460px; }
|
||||
.shell:has(.status-line) .canvas-card { height: calc(100dvh - var(--topbar-h) - 150px); }
|
||||
.topology-drawer { position: absolute; top: 10px; right: 10px; bottom: 10px; z-index: 6; display: block; width: min(400px, calc(100% - 20px)); height: auto; min-height: 0; max-height: none; padding: 16px; overflow-y: auto; border: 1px solid var(--line-strong); border-radius: var(--radius-lg); background: rgba(21, 26, 33, .97); box-shadow: -16px 0 48px rgba(0, 0, 0, .45); }
|
||||
.topology-drawer > .panel-section { padding: 0; border: 0; background: transparent; box-shadow: none; }
|
||||
.topology-drawer .inspector-section { min-height: 0; }
|
||||
.drawer-close { position: absolute; top: 10px; right: 10px; z-index: 1; }
|
||||
.topology-drawer .inspector-title { padding-right: 44px; }
|
||||
.topology-workspace:has(.topology-drawer) .canvas-toolbar { right: 420px; }
|
||||
|
||||
@media (max-width: 1120px) {
|
||||
.topology-workspace, .topology-workspace:has(.topology-drawer) { display: block; }
|
||||
.topology-drawer { position: absolute; display: block; height: auto; max-height: none; padding: 16px; border: 1px solid var(--line-strong); overflow-y: auto; }
|
||||
.topology-workspace:has(.topology-drawer) .canvas-toolbar { right: 10px; }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
:root { --topbar-h: 54px; --page-w: calc(100% - 24px); }
|
||||
.shell { padding-bottom: calc(76px + env(safe-area-inset-bottom)); }
|
||||
/* backdrop-filter would make the header the containing block of the fixed bottom bar. */
|
||||
.topbar { margin-bottom: 12px; background: var(--surface-1); backdrop-filter: none; }
|
||||
.topbar-inner { grid-template-areas: "brand status actions"; column-gap: 8px; }
|
||||
.topbar .brand-lockup { height: 54px; }
|
||||
.topbar .brand-lockup h1 { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
.topbar-status .live-status { display: none; }
|
||||
.kpi-chips { gap: 4px; }
|
||||
.kpi-chip { gap: 3px; padding: 3px 6px; font-size: var(--fs-sm); }
|
||||
.topbar .toolbar { flex-wrap: nowrap; width: auto; }
|
||||
.topbar .toolbar button { flex: none; }
|
||||
.topbar .toolbar .primary { width: 36px; height: 36px; padding: 0; }
|
||||
.toolbar-label { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
.topbar .panel-tabs { position: fixed; right: 0; bottom: 0; left: 0; z-index: 45; display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 2px; margin: 0; padding: 4px 6px calc(4px + env(safe-area-inset-bottom)); overflow: visible; border-top: 1px solid var(--line); background: rgba(21, 26, 33, .97); backdrop-filter: blur(10px); }
|
||||
.topbar .panel-tabs button { display: flex; flex-direction: column; gap: 3px; min-height: 52px; padding: 6px 2px; border: 0; border-radius: var(--radius-md); font-size: var(--fs-xs); }
|
||||
.topbar .panel-tabs button.active { background: var(--accent-soft); color: var(--text); }
|
||||
.topbar .panel-tabs .nav-secondary { display: none; }
|
||||
.topbar .panel-tabs .nav-more { display: flex; }
|
||||
.topbar .panel-tabs.nav-more-open .nav-secondary { display: flex; }
|
||||
.canvas-card, .demo-mode .canvas-card, .shell:has(.status-line) .canvas-card { height: calc(100dvh - var(--topbar-h) - 250px); min-height: 380px; }
|
||||
.topology-drawer { position: fixed; top: auto; right: 0; bottom: calc(64px + env(safe-area-inset-bottom)); left: 0; z-index: 44; width: auto; max-height: 55dvh; border-radius: var(--radius-lg) var(--radius-lg) 0 0; box-shadow: 0 -16px 48px rgba(0, 0, 0, .5); }
|
||||
.unlock-popover { right: 12px; }
|
||||
.status-line .text-button { margin-left: 0; }
|
||||
}
|
||||
|
||||
/* ── Graph: node cards ────────────────────────────────────────────────
|
||||
Name first, status as a coloured left edge plus icon and label, facts as
|
||||
chips, a single root-cause marker. */
|
||||
.react-flow__node.service-node { border-left-width: 4px !important; box-shadow: 0 8px 22px rgba(0, 0, 0, .3) !important; }
|
||||
.react-flow__node.status-healthy { border-left-color: var(--ok) !important; }
|
||||
.react-flow__node.status-degraded { border-left-color: var(--warn) !important; }
|
||||
.react-flow__node.status-down { border-left-color: var(--bad) !important; }
|
||||
.react-flow__node.status-recovering { border-left-color: var(--accent) !important; }
|
||||
.react-flow__node.status-maintenance { border-left-color: var(--maint) !important; }
|
||||
.react-flow__node.status-unknown, .react-flow__node.status-unmonitored { border-left-color: var(--unknown) !important; }
|
||||
.react-flow__node.domain-node { border-style: solid !important; }
|
||||
.react-flow__node.service-node:has(.root-cause-badge) { border-color: var(--warn-line) !important; box-shadow: 0 0 0 1px var(--warn-line), 0 10px 30px rgba(0, 0, 0, .35) !important; }
|
||||
.service-node-body, .domain-node .service-node-body, .application-node .service-node-body, .component-node .service-node-body { display: grid; align-content: start; gap: 6px; box-sizing: border-box; width: 236px; min-width: 0; min-height: 128px; padding: 11px 13px 12px; background: none; }
|
||||
.node-head { display: flex; align-items: center; gap: 6px; min-width: 0; color: var(--text-3); }
|
||||
.node-kind-icon { flex: none; }
|
||||
.node-head .node-kicker { overflow: hidden; color: var(--text-3); font-size: var(--fs-xs); font-weight: 500; letter-spacing: 0; text-overflow: ellipsis; text-transform: none; white-space: nowrap; }
|
||||
.service-node-body .node-name { display: -webkit-box; overflow: hidden; color: var(--text); font-size: var(--fs-lg); font-weight: 700; line-height: 1.2; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
||||
.node-state { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.service-node-body .node-status { display: inline-flex; align-items: center; gap: 4px; font-size: var(--fs-sm); font-weight: 600; letter-spacing: 0; text-transform: none; }
|
||||
.node-flag { display: inline-flex; align-items: center; gap: 4px; padding: 1px 7px; border: 1px solid var(--warn-line); border-radius: var(--radius-pill); background: var(--warn-bg); color: var(--warn); font-size: var(--fs-xs); font-weight: 600; letter-spacing: 0; }
|
||||
.node-flag.flap-badge { border-color: var(--line-strong); background: var(--surface-1); color: var(--text-2); }
|
||||
.node-chips { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.node-chip { padding: 1px 7px; border: 1px solid var(--line); border-radius: var(--radius-pill); background: var(--surface-1); color: var(--text-2); font-size: var(--fs-xs); line-height: 1.6; }
|
||||
.node-chip.criticality-critical { border-color: var(--bad-line); color: var(--text); }
|
||||
.node-chip-alert { border-color: var(--bad-line); background: var(--bad-bg); color: var(--bad); }
|
||||
.service-node-body .node-note { display: -webkit-box; overflow: hidden; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.35; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
||||
|
||||
/* ── Graph: edges ─────────────────────────────────────────────────────
|
||||
Calm by default; colour only on the incident path, the selection and the
|
||||
hovered node's relations. */
|
||||
.living-edge-path { stroke: #4a5664; stroke-width: 1.6; }
|
||||
.react-flow__edge.animated .living-edge-path { stroke-dasharray: none; animation: none; }
|
||||
.react-flow__edge.edge-down .living-edge-path, .react-flow__edge.edge-degraded .living-edge-path { stroke: #4a5664; stroke-dasharray: none; }
|
||||
.react-flow__edge.edge-down .living-edge-path.has-signal { stroke: var(--bad); stroke-width: 2.2; }
|
||||
.react-flow__edge.edge-degraded .living-edge-path.has-signal { stroke: var(--warn); stroke-width: 2.2; }
|
||||
.living-edge-path.has-signal { stroke: var(--accent); stroke-width: 2.2; }
|
||||
.living-edge-path.is-dimmed { opacity: .18; }
|
||||
.living-edge-signal { stroke-width: 2.4; }
|
||||
.react-flow__edge .react-flow__edge-marker, .react-flow__edge.edge-down .react-flow__edge-marker, .react-flow__edge.edge-degraded .react-flow__edge-marker { fill: #4a5664; }
|
||||
.react-flow__arrowhead polyline { stroke: #4a5664 !important; fill: #4a5664 !important; }
|
||||
|
||||
/* ── Panels: headings ──────────────────────────────────────────────── */
|
||||
h2 { max-width: none; margin-bottom: 8px; font-size: var(--fs-xl); line-height: 1.25; letter-spacing: -.01em; }
|
||||
h3 { font-size: var(--fs-lg); letter-spacing: -.01em; }
|
||||
.overview-lead h2, .demo-mode .hero h2 { font-size: var(--fs-2xl); line-height: 1.15; }
|
||||
.compact-hero h2 { font-size: var(--fs-xl); }
|
||||
.settings-panel h2:not(:first-of-type) { margin-top: 24px; padding-top: 20px; border-top: 1px solid var(--line); }
|
||||
.locked-note { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
|
||||
.locked-note p { margin: 0; }
|
||||
|
||||
/* ── Services: one filter row and a compact table ──────────────────── */
|
||||
.table-toolbar { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 10px; }
|
||||
.table-toolbar > label { flex: 0 1 150px; min-width: 120px; color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.table-toolbar > .search-field { flex: 1 1 240px; }
|
||||
.table-toolbar > .checkbox-field { flex: none; min-width: 0; align-self: center; margin-top: 18px; white-space: nowrap; }
|
||||
.table-toolbar > .checkbox-field input { width: 16px; height: 16px; margin: 0; }
|
||||
.table-toolbar input, .table-toolbar select { margin-top: 4px; padding: 8px 10px; }
|
||||
.table-toolbar .toolbar-end { margin-left: auto; padding: 9px 14px; }
|
||||
.table-panel { min-height: 0; }
|
||||
.service-table { gap: 0; border: 1px solid var(--line); border-radius: var(--radius-md); overflow: clip; }
|
||||
.service-table > .service-row-wrap { padding-left: 12px; border-bottom: 1px solid var(--line); }
|
||||
.service-table > .service-row-wrap:last-of-type { border-bottom: 0; }
|
||||
.service-table > .service-row-wrap:first-child { position: sticky; top: var(--topbar-h); z-index: 2; background: var(--surface-2); }
|
||||
.service-table-head { padding: 9px 12px; }
|
||||
.service-table-row { padding: 9px 12px; border: 0; border-radius: 0; background: transparent; }
|
||||
.service-table-row:hover:not(:disabled) { border: 0; background: var(--surface-2); }
|
||||
.service-row-wrap:has(.service-table-row[aria-pressed="true"]) { background: var(--accent-soft); box-shadow: inset 3px 0 var(--accent); }
|
||||
.service-table-row[aria-pressed="true"] { border: 0; background: transparent; box-shadow: none; }
|
||||
.service-table.no-metrics .service-table-head, .service-table.no-metrics .service-table-row { grid-template-columns: minmax(180px, 1.3fr) minmax(115px, .8fr) minmax(110px, .7fr) minmax(130px, .9fr) minmax(110px, .7fr); }
|
||||
.service-table.no-metrics .service-table-head > :nth-child(n + 6), .service-table.no-metrics .service-table-row > :nth-child(n + 6) { display: none; }
|
||||
.service-table-row .status-icon { margin-right: 4px; }
|
||||
|
||||
/* ── Activity: per day, readable rows ──────────────────────────────── */
|
||||
.activity-days { display: grid; gap: 18px; margin-top: 8px; }
|
||||
.activity-day h3 { position: sticky; top: var(--topbar-h); z-index: 1; margin: 0 0 6px; padding: 6px 0; background: var(--surface-1); color: var(--text-2); font-size: var(--fs-md); font-weight: 600; letter-spacing: 0; }
|
||||
.activity-list { margin: 0; gap: 0; border: 1px solid var(--line); border-radius: var(--radius-md); overflow: hidden; }
|
||||
.activity-list li.activity-row { grid-template-columns: 52px 24px minmax(0, 1fr) auto; gap: 10px; padding: 9px 12px; border: 0; border-bottom: 1px solid var(--line); border-radius: 0; background: transparent; }
|
||||
.activity-list li.activity-row:last-child { border-bottom: 0; }
|
||||
.activity-row time { color: var(--text-3); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
|
||||
.activity-icon { display: grid; width: 24px; height: 24px; place-items: center; border-radius: 50%; background: var(--surface-3); color: var(--text-2); }
|
||||
.tone-ok .activity-icon { background: var(--ok-bg); color: var(--ok); }
|
||||
.tone-warn .activity-icon { background: var(--warn-bg); color: var(--warn); }
|
||||
.tone-bad .activity-icon { background: var(--bad-bg); color: var(--bad); }
|
||||
.tone-maint .activity-icon { background: var(--maint-bg); color: var(--maint); }
|
||||
.tone-accent .activity-icon { background: var(--accent-soft); color: var(--accent); }
|
||||
.activity-text { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; min-width: 0; }
|
||||
.activity-text strong { font-size: var(--fs-md); }
|
||||
.activity-message { color: var(--text-3); font-size: var(--fs-sm); }
|
||||
.activity-count { padding: 0 7px; border-radius: var(--radius-pill); background: var(--surface-3); color: var(--text-2); font-size: var(--fs-xs); font-variant-numeric: tabular-nums; }
|
||||
.activity-services { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 4px; max-width: 46%; }
|
||||
.activity-more { align-self: center; color: var(--text-3); font-size: var(--fs-xs); }
|
||||
.activity-services .compact-button { padding: 3px 8px; white-space: nowrap; }
|
||||
.activity-list li.activity-row { align-items: center; }
|
||||
@media (max-width: 760px) {
|
||||
.activity-list li.activity-row { grid-template-columns: 44px 24px minmax(0, 1fr); }
|
||||
.activity-services { grid-column: 3; justify-content: flex-start; max-width: none; }
|
||||
}
|
||||
|
||||
/* ── Loading skeletons in the final layout ─────────────────────────── */
|
||||
.graph-skeleton { display: grid; grid-template-columns: repeat(4, 200px); gap: 28px 64px; place-content: center; height: 100%; padding: 32px; }
|
||||
.skeleton-card, .skeleton-row { display: block; border-radius: var(--radius-md); background: linear-gradient(90deg, var(--surface-2) 0%, var(--surface-3) 50%, var(--surface-2) 100%); background-size: 200% 100%; animation: servicemap-shimmer 1.4s ease-in-out infinite; }
|
||||
.skeleton-card { height: 112px; border-left: 4px solid var(--line-strong); }
|
||||
.skeleton-card:nth-child(2n) { transform: translateY(40px); }
|
||||
.table-skeleton { display: grid; gap: 1px; }
|
||||
.skeleton-row { height: 46px; border-radius: 0; }
|
||||
@keyframes servicemap-shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }
|
||||
@media (max-width: 760px) { .graph-skeleton { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; padding: 16px; } }
|
||||
|
||||
/* Freshness next to the live status; amber once live updates stop. */
|
||||
.freshness { color: var(--text-3); font-size: var(--fs-sm); font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.freshness.is-stale { color: var(--warn); }
|
||||
@media (max-width: 760px) { .freshness { display: none; } }
|
||||
@@ -0,0 +1,56 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import type { Edge, Node } from "@xyflow/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { GraphListView, nodeAriaLabel } from "./GraphListView";
|
||||
import type { ServiceNodeData } from "./ServiceNode";
|
||||
|
||||
const data = (name: string, status: ServiceNodeData["status"], extra: Partial<ServiceNodeData> = {}): ServiceNodeData => ({
|
||||
name,
|
||||
status,
|
||||
kind: "http",
|
||||
latency: null,
|
||||
dependencyCount: 0,
|
||||
rootCause: false,
|
||||
impacted: false,
|
||||
group: null,
|
||||
criticality: "medium",
|
||||
flapping: false,
|
||||
category: "service",
|
||||
...extra,
|
||||
});
|
||||
|
||||
const nodes: Node[] = [
|
||||
{ id: "db", position: { x: 0, y: 0 }, data: data("PostgreSQL", "down", { rootCause: true }) },
|
||||
{ id: "api", position: { x: 0, y: 0 }, data: data("API", "degraded", { impacted: true, latency: 812.4 }) },
|
||||
];
|
||||
const edges: Edge[] = [{ id: "db-api", source: "db", target: "api" }];
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("graph text alternative", () => {
|
||||
it("names every node with its status and dependencies", () => {
|
||||
render(<GraphListView nodes={nodes} edges={edges} onOpen={() => undefined} />);
|
||||
const region = screen.getByRole("region", { name: "Topologie als lijst" });
|
||||
const items = region.querySelectorAll("li");
|
||||
expect([...items].map((item) => item.querySelector("strong")?.textContent)).toEqual(["API", "PostgreSQL"]);
|
||||
expect(screen.getByText("Hangt af van PostgreSQL")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: /Uitgevallen PostgreSQL Hoofdoorzaak/ })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("opens a node with the keyboard", async () => {
|
||||
const onOpen = vi.fn();
|
||||
render(<GraphListView nodes={nodes} edges={edges} onOpen={onOpen} />);
|
||||
const user = userEvent.setup();
|
||||
await user.tab();
|
||||
await user.keyboard("{Enter}");
|
||||
expect(onOpen).toHaveBeenCalledWith(nodes[1]);
|
||||
});
|
||||
|
||||
it("gives canvas nodes a spoken label", () => {
|
||||
expect(nodeAriaLabel(nodes[0].data as ServiceNodeData)).toBe("Service PostgreSQL, Uitgevallen, waarschijnlijke hoofdoorzaak");
|
||||
expect(nodeAriaLabel(nodes[1].data as ServiceNodeData)).toBe("Service API, Verminderd, geraakt, 812 ms");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Edge, Node } from "@xyflow/react";
|
||||
|
||||
import { StatusIcon } from "../components/StatusIcon";
|
||||
import { statusLabel, type ServiceNodeData } from "./ServiceNode";
|
||||
|
||||
/** Spoken name for a graph node: what it is and how it is doing. */
|
||||
export function nodeAriaLabel(data: ServiceNodeData): string {
|
||||
const kind =
|
||||
data.nodeKind === "domain" ? "Domein" : data.nodeKind === "application" ? "Applicatie" : "Service";
|
||||
const parts = [`${kind} ${data.name}`, statusLabel(data.status)];
|
||||
if (data.rootCause) parts.push("waarschijnlijke hoofdoorzaak");
|
||||
else if (data.impacted) parts.push("geraakt");
|
||||
if (data.latency != null) parts.push(`${Math.round(data.latency)} ms`);
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
type Props = {
|
||||
nodes: Node[];
|
||||
edges: Edge[];
|
||||
onOpen: (node: Node) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Text alternative for the topology canvas (WCAG 1.1.1): every node with its
|
||||
* status and what it depends on, operable with the keyboard alone.
|
||||
*/
|
||||
export function GraphListView({ nodes, edges, onOpen }: Props) {
|
||||
const names = new Map(nodes.map((node) => [node.id, (node.data as ServiceNodeData).name]));
|
||||
// Edges point from a dependency to the service that uses it.
|
||||
const dependsOn = new Map<string, string[]>();
|
||||
for (const edge of edges) {
|
||||
const name = names.get(edge.source);
|
||||
if (!name) continue;
|
||||
dependsOn.set(edge.target, [...(dependsOn.get(edge.target) ?? []), name]);
|
||||
}
|
||||
const sorted = [...nodes].sort((a, b) =>
|
||||
(a.data as ServiceNodeData).name.localeCompare((b.data as ServiceNodeData).name),
|
||||
);
|
||||
return (
|
||||
<div className="graph-list" role="region" aria-label="Topologie als lijst">
|
||||
<ul>
|
||||
{sorted.map((node) => {
|
||||
const data = node.data as ServiceNodeData;
|
||||
const deps = dependsOn.get(node.id) ?? [];
|
||||
return (
|
||||
<li key={node.id} className={`status-${data.status}`}>
|
||||
<button className="ghost" onClick={() => onOpen(node)}>
|
||||
<span className="graph-list-status">
|
||||
<StatusIcon status={data.status} /> {statusLabel(data.status)}
|
||||
</span>
|
||||
<strong>{data.name}</strong>
|
||||
{data.rootCause && <span className="graph-list-flag">Hoofdoorzaak</span>}
|
||||
{!data.rootCause && data.impacted && <span className="graph-list-flag">Geraakt</span>}
|
||||
</button>
|
||||
{deps.length > 0 && <small>Hangt af van {deps.join(", ")}</small>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
|
||||
|
||||
import { Box, Boxes, Crosshair, Layers } from "lucide-react";
|
||||
|
||||
import { StatusIcon } from "../components/StatusIcon";
|
||||
import { criticalityText, statusText } from "../labels";
|
||||
|
||||
import type {
|
||||
ComponentRole,
|
||||
Criticality,
|
||||
@@ -33,63 +38,60 @@ export type ServiceNodeData = {
|
||||
|
||||
export type ServiceNode = Node<ServiceNodeData, "service">;
|
||||
|
||||
const statusLabel = (status: HealthStatus) =>
|
||||
status === "unmonitored"
|
||||
? "Not monitored"
|
||||
: status[0].toUpperCase() + status.slice(1);
|
||||
const statusIcon = (status: HealthStatus) =>
|
||||
({
|
||||
healthy: "✓",
|
||||
degraded: "△",
|
||||
down: "!",
|
||||
recovering: "↻",
|
||||
maintenance: "Ⅱ",
|
||||
unknown: "?",
|
||||
unmonitored: "○",
|
||||
})[status];
|
||||
export const statusLabel = (status: HealthStatus) => statusText(status);
|
||||
/** Splits "2/4 resolved · 2 unresolved · 1 incident" into separate chips. */
|
||||
function factChips(text: string | undefined): string[] {
|
||||
return (text ?? "").split(" · ").map((part) => part.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export function ServiceNodeView({ data }: NodeProps<ServiceNode>) {
|
||||
const targetLabel =
|
||||
data.nodeKind === "domain"
|
||||
? `${data.memberIds?.length ?? 0} components`
|
||||
: data.applicationNode
|
||||
? `${data.monitoredComponents ?? 0} resolved · ${data.unmonitoredComponents ?? 0} unresolved`
|
||||
: data.latency != null
|
||||
? `${data.latency} ms · ${data.kind.toUpperCase()}`
|
||||
: data.kind.toUpperCase();
|
||||
const kind = data.nodeKind ?? (data.applicationNode ? "application" : "component");
|
||||
const KindIcon = kind === "domain" ? Layers : kind === "application" ? Boxes : Box;
|
||||
const memberCount = data.memberIds?.length ?? 0;
|
||||
const kicker =
|
||||
kind === "domain"
|
||||
? `Domein · ${memberCount} ${memberCount === 1 ? "component" : "componenten"}`
|
||||
: kind === "application"
|
||||
? `Applicatie · ${memberCount} ${memberCount === 1 ? "component" : "componenten"}`
|
||||
: `${data.role ?? data.category.replace("_", " ")} · ${data.kind.toUpperCase()}`;
|
||||
const chips =
|
||||
kind === "domain"
|
||||
? factChips(data.explanation)
|
||||
: kind === "application"
|
||||
? [`${data.monitoredComponents ?? 0} opgelost`, `${data.unmonitoredComponents ?? 0} onopgelost`]
|
||||
: [
|
||||
...(data.latency != null ? [`${data.latency} ms`] : []),
|
||||
`${data.dependencyCount} ${data.dependencyCount === 1 ? "afhankelijkheid" : "afhankelijkheden"}`,
|
||||
];
|
||||
const note = kind === "domain" ? null : data.explanation;
|
||||
return (
|
||||
<>
|
||||
<Handle type="target" position={Position.Left} />
|
||||
<div
|
||||
className={`service-node-body status-${data.status}`}
|
||||
aria-label={`${data.name}, ${statusLabel(data.status)}${data.rootCause ? ", likely root cause" : ""}`}
|
||||
className={`service-node-body node-${kind}`}
|
||||
aria-label={`${data.name}, ${statusLabel(data.status)}${data.rootCause ? ", waarschijnlijke hoofdoorzaak" : ""}`}
|
||||
>
|
||||
<div className="node-badges">
|
||||
{data.rootCause && (
|
||||
<span className="node-badge root-cause-badge">ROOT CAUSE</span>
|
||||
)}
|
||||
{!data.rootCause && data.impacted && (
|
||||
<span className="node-badge impacted-badge">IMPACTED</span>
|
||||
)}
|
||||
{data.flapping && (
|
||||
<span className="node-badge flap-badge">FLAPPING</span>
|
||||
)}
|
||||
<div className="node-head">
|
||||
<KindIcon className="node-kind-icon" size={13} aria-hidden="true" />
|
||||
<span className="node-kicker">{kicker}</span>
|
||||
</div>
|
||||
{data.nodeKind === "domain" && (
|
||||
<span className="node-kicker">
|
||||
DOMAIN · {data.memberIds?.length ?? 0} components
|
||||
<strong className="node-name">{data.name}</strong>
|
||||
<div className="node-state">
|
||||
<span className={`node-status status-${data.status}`}>
|
||||
<StatusIcon status={data.status} />
|
||||
{statusLabel(data.status)}
|
||||
</span>
|
||||
{data.rootCause && (
|
||||
<span className="node-flag root-cause-badge">
|
||||
<Crosshair size={12} aria-hidden="true" />
|
||||
Hoofdoorzaak
|
||||
</span>
|
||||
)}
|
||||
{data.applicationNode && (
|
||||
<span className="node-kicker">
|
||||
APPLICATION · {data.memberIds?.length ?? 0} components
|
||||
</span>
|
||||
)}
|
||||
{data.applicationNode && data.roles?.length ? (
|
||||
<span
|
||||
className="app-micro-topology"
|
||||
aria-label={`Component roles: ${data.roles.join(", ")}`}
|
||||
>
|
||||
{!data.rootCause && data.impacted && <span className="node-flag impacted-badge">Geraakt</span>}
|
||||
{data.flapping && <span className="node-flag flap-badge">Wisselvallig</span>}
|
||||
</div>
|
||||
{kind === "application" && data.roles?.length ? (
|
||||
<span className="app-micro-topology" aria-label={`Componentrollen: ${data.roles.join(", ")}`}>
|
||||
{data.roles.slice(0, 5).map((role) => (
|
||||
<i key={role} className={`role-${role}`}>
|
||||
{role.slice(0, 1).toUpperCase()}
|
||||
@@ -97,19 +99,15 @@ export function ServiceNodeView({ data }: NodeProps<ServiceNode>) {
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
{data.nodeKind === "component" && (
|
||||
<span className="node-kicker">{data.role ?? data.category}</span>
|
||||
)}
|
||||
<strong>{data.name}</strong>
|
||||
<span className={`node-status status-${data.status}`}>
|
||||
<i aria-hidden="true">{statusIcon(data.status)}</i>{" "}
|
||||
{statusLabel(data.status)}
|
||||
<div className="node-chips">
|
||||
<span className={`node-chip criticality-${data.criticality}`}>{criticalityText(data.criticality)}</span>
|
||||
{chips.map((chip) => (
|
||||
<span key={chip} className={`node-chip${/incident/.test(chip) ? " node-chip-alert" : ""}`}>
|
||||
{chip}
|
||||
</span>
|
||||
<small>{targetLabel} · {data.criticality}</small>
|
||||
<small>
|
||||
{data.explanation ??
|
||||
`${data.category.replace("_", " ")} · ${data.dependencyCount} ${data.dependencyCount === 1 ? "dependency" : "dependencies"}`}
|
||||
</small>
|
||||
))}
|
||||
</div>
|
||||
{note && <small className="node-note">{note}</small>}
|
||||
</div>
|
||||
<Handle type="source" position={Position.Right} />
|
||||
</>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
|
||||
import type { Criticality, HealthStatus, MonitoringState } from "../api";
|
||||
import { MONITORING_LABELS, criticalityText, lifecycleText, modeText, statusText } from "../labels";
|
||||
import {
|
||||
domainLocation,
|
||||
isTopologyRoot,
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
} from "../topologyNavigation";
|
||||
|
||||
export type TopologyMode = "landscape" | "dependencies" | "impact";
|
||||
export type FilterStatus = "all" | "unresolved" | HealthStatus;
|
||||
export type FilterStatus = "all" | "unresolved" | "problems" | HealthStatus;
|
||||
export type MonitoringFilter = "all" | MonitoringState;
|
||||
|
||||
type TopologyCommandBarProps = {
|
||||
@@ -99,18 +100,18 @@ export function TopologyCommandBar({
|
||||
lifecycleFilter,
|
||||
].filter((value) => value !== "all").length;
|
||||
return (
|
||||
<section className="topology-command-bar" aria-label="Topology commands">
|
||||
<div className="topology-breadcrumbs" aria-label="Topology hierarchy">
|
||||
<section className="topology-command-bar" aria-label="Topologieopdrachten">
|
||||
<div className="topology-breadcrumbs" aria-label="Topologiehiërarchie">
|
||||
{!isTopologyRoot(location) && (
|
||||
<button
|
||||
className="ghost compact-button"
|
||||
onClick={() => setLocation((current) => topologyUp(current))}
|
||||
>
|
||||
← Back
|
||||
← Terug
|
||||
</button>
|
||||
)}
|
||||
<button className="text-button" onClick={() => setLocation(topologyRoot())}>
|
||||
Infrastructure
|
||||
Infrastructuur
|
||||
</button>
|
||||
{selectedDomain && (
|
||||
<>
|
||||
@@ -144,20 +145,22 @@ export function TopologyCommandBar({
|
||||
>
|
||||
{candidate === "impact"
|
||||
? "Impact"
|
||||
: candidate[0].toUpperCase() + candidate.slice(1)}
|
||||
: modeText(candidate)}
|
||||
</button>
|
||||
))}
|
||||
<input
|
||||
aria-label="Search topology"
|
||||
aria-label="Topologie doorzoeken"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder="Search topology"
|
||||
placeholder="Topologie doorzoeken"
|
||||
/>
|
||||
<button
|
||||
className={statusFilter === "down" || statusFilter === "degraded" ? "compact-button" : "ghost compact-button"}
|
||||
onClick={() => setStatusFilter(statusFilter === "all" ? "down" : "all")}
|
||||
className={statusFilter === "problems" ? "compact-button" : "ghost compact-button"}
|
||||
aria-pressed={statusFilter === "problems"}
|
||||
title="Uitgevallen, verminderd en herstellend"
|
||||
onClick={() => setStatusFilter(statusFilter === "problems" ? "all" : "problems")}
|
||||
>
|
||||
Problems only
|
||||
Alleen problemen
|
||||
</button>
|
||||
<details
|
||||
className="filter-popover"
|
||||
@@ -166,18 +169,18 @@ export function TopologyCommandBar({
|
||||
>
|
||||
<summary>Filters{activeFilterCount ? ` (${activeFilterCount})` : ""}</summary>
|
||||
<div>
|
||||
<label>Status<select aria-label="Filter topology by status" value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as FilterStatus)}><option value="all">All status</option><option value="unresolved">Unresolved health</option>{(["healthy", "degraded", "down", "recovering", "unmonitored", "unknown", "maintenance"] as HealthStatus[]).map((item) => <option key={item} value={item}>{item === "unmonitored" ? "Not monitored" : item}</option>)}</select></label>
|
||||
<label>Monitoring<select aria-label="Filter topology by monitoring source" value={monitoringFilter} onChange={(event) => setMonitoringFilter(event.target.value as MonitoringFilter)}><option value="all">Any source</option>{(["active_probe", "docker_health", "appops_observation", "observed", "unmonitored"] as MonitoringState[]).map((item) => <option key={item} value={item}>{item.replaceAll("_", " ")}</option>)}</select></label>
|
||||
<label>Domain<select aria-label="Filter topology by domain" value={domainFilter} onChange={(event) => setDomainFilter(event.target.value)}><option value="all">All domains</option>{domains.map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Application<select aria-label="Filter topology by application" value={applicationFilter} onChange={(event) => setApplicationFilter(event.target.value)}><option value="all">All applications</option>{applications.map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Environment<select aria-label="Filter topology by environment" value={environmentFilter} onChange={(event) => setEnvironmentFilter(event.target.value)}><option value="all">All environments</option>{environments.map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Criticality<select aria-label="Filter topology by criticality" value={criticalityFilter} onChange={(event) => setCriticalityFilter(event.target.value)}><option value="all">All criticality</option>{(["low", "medium", "high", "critical"] as Criticality[]).map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Lifecycle<select aria-label="Filter topology by lifecycle" value={lifecycleFilter} onChange={(event) => setLifecycleFilter(event.target.value)}><option value="all">All lifecycle</option>{["active", "missing", "stale", "retired", "ignored"].map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Status<select aria-label="Topologie filteren op status" value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as FilterStatus)}><option value="all">Alle statussen</option><option value="problems">Problemen (uitgevallen, verminderd, herstellend)</option><option value="unresolved">Onopgeloste gezondheid</option>{(["healthy", "degraded", "down", "recovering", "unmonitored", "unknown", "maintenance"] as HealthStatus[]).map((item) => <option key={item} value={item}>{statusText(item)}</option>)}</select></label>
|
||||
<label>Bewaking<select aria-label="Topologie filteren op bewakingsbron" value={monitoringFilter} onChange={(event) => setMonitoringFilter(event.target.value as MonitoringFilter)}><option value="all">Elke bron</option>{(["active_probe", "docker_health", "appops_observation", "observed", "unmonitored"] as MonitoringState[]).map((item) => <option key={item} value={item}>{MONITORING_LABELS[item] ?? item.replaceAll("_", " ")}</option>)}</select></label>
|
||||
<label>Domein<select aria-label="Topologie filteren op domein" value={domainFilter} onChange={(event) => setDomainFilter(event.target.value)}><option value="all">Alle domeinen</option>{domains.map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Applicatie<select aria-label="Topologie filteren op applicatie" value={applicationFilter} onChange={(event) => setApplicationFilter(event.target.value)}><option value="all">Alle applicaties</option>{applications.map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Omgeving<select aria-label="Topologie filteren op omgeving" value={environmentFilter} onChange={(event) => setEnvironmentFilter(event.target.value)}><option value="all">Alle omgevingen</option>{environments.map((item) => <option key={item}>{item}</option>)}</select></label>
|
||||
<label>Kritiek<select aria-label="Topologie filteren op kritiek" value={criticalityFilter} onChange={(event) => setCriticalityFilter(event.target.value)}><option value="all">Alle kritiekniveaus</option>{(["low", "medium", "high", "critical"] as Criticality[]).map((item) => <option key={item} value={item}>{criticalityText(item)}</option>)}</select></label>
|
||||
<label>Levenscyclus<select aria-label="Topologie filteren op levenscyclus" value={lifecycleFilter} onChange={(event) => setLifecycleFilter(event.target.value)}><option value="all">Alle levenscycli</option>{["active", "missing", "stale", "retired", "ignored"].map((item) => <option key={item} value={item}>{lifecycleText(item)}</option>)}</select></label>
|
||||
</div>
|
||||
</details>
|
||||
<button className="ghost compact-button" onClick={onFit}>Fit</button>
|
||||
<button className="ghost compact-button" onClick={onArrange}>Arrange</button>
|
||||
<button className="ghost compact-button" onClick={onToggleInspector}>{inspectorOpen ? "Hide details" : "Details"}</button>
|
||||
<button className="ghost compact-button" onClick={onFit}>Passend</button>
|
||||
<button className="ghost compact-button" onClick={onArrange}>Schikken</button>
|
||||
<button className="ghost compact-button" onClick={onToggleInspector}>{inspectorOpen ? "Details verbergen" : "Details"}</button>
|
||||
</div>
|
||||
{activeFilters
|
||||
.filter((item) => item.value !== "all")
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { HealthStatus, SemanticTopology } from "../api";
|
||||
import { matchesStatusFilter, semanticTopologyGraph } from "./semanticGraph";
|
||||
|
||||
function component(id: string, application: string, status: HealthStatus, dependencies: string[] = []) {
|
||||
return {
|
||||
service_id: id,
|
||||
name: id.toUpperCase(),
|
||||
kind: "http" as const,
|
||||
application_id: application,
|
||||
domain_id: "platform",
|
||||
role: "api" as const,
|
||||
direct_status: status,
|
||||
effective_status: status,
|
||||
unknown_reason: null,
|
||||
runtime_state: "running",
|
||||
runtime_health: status,
|
||||
monitoring_state: "active_probe" as const,
|
||||
latest_latency_ms: null,
|
||||
dependency_ids: dependencies,
|
||||
dependent_ids: [],
|
||||
root_cause: false,
|
||||
affected: false,
|
||||
};
|
||||
}
|
||||
|
||||
function topology(): SemanticTopology {
|
||||
return {
|
||||
generated_at: "2026-11-17T12:00:00Z",
|
||||
domains: [],
|
||||
applications: [],
|
||||
components: [
|
||||
component("api", "shop", "healthy", ["db"]),
|
||||
component("db", "shop", "degraded"),
|
||||
component("worker", "shop", "down", ["db"]),
|
||||
component("cache", "shop", "recovering"),
|
||||
],
|
||||
relations: [],
|
||||
monitoring_coverage: {},
|
||||
} as unknown as SemanticTopology;
|
||||
}
|
||||
|
||||
describe("semantic topology filters and facts", () => {
|
||||
it("'problems' covers down, degraded and recovering", () => {
|
||||
expect(["down", "degraded", "recovering"].every((status) => matchesStatusFilter(status, "problems"))).toBe(true);
|
||||
expect(matchesStatusFilter("healthy", "problems")).toBe(false);
|
||||
const graph = semanticTopologyGraph(topology(), "components", "shop", false, "", "problems");
|
||||
expect(graph.nodes.map((node) => node.id).sort()).toEqual(["cache", "db", "worker"]);
|
||||
});
|
||||
|
||||
it("applies per-service attribute filters and real criticality/flapping", () => {
|
||||
const graph = semanticTopologyGraph(topology(), "components", "shop", false, "", "all", {
|
||||
serviceFacts: (id) => (id === "db" ? { criticality: "critical", flapping: true } : { criticality: "low", flapping: false }),
|
||||
serviceFilter: (id) => id !== "cache",
|
||||
});
|
||||
expect(graph.nodes.map((node) => node.id).sort()).toEqual(["api", "db", "worker"]);
|
||||
const db = graph.nodes.find((node) => node.id === "db");
|
||||
expect(db?.data.criticality).toBe("critical");
|
||||
expect(db?.data.flapping).toBe(true);
|
||||
expect(graph.nodes.find((node) => node.id === "api")?.data.criticality).toBe("low");
|
||||
});
|
||||
|
||||
it("draws relations dependency -> dependent and counts nothing hidden at component level", () => {
|
||||
const graph = semanticTopologyGraph(topology(), "components", "shop", false, "", "all");
|
||||
expect(graph.edges.map((edge) => `${edge.source}->${edge.target}`).sort()).toEqual(["db->api", "db->worker"]);
|
||||
expect(graph.hiddenEdgeCount).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,42 @@
|
||||
import { MarkerType, type Edge } from "@xyflow/react";
|
||||
|
||||
import type { HealthStatus, SemanticTopology } from "../api";
|
||||
import type { Criticality, HealthStatus, SemanticTopology } from "../api";
|
||||
import type { ServiceNode } from "./ServiceNode";
|
||||
|
||||
export type SemanticView = "domains" | "applications" | "components";
|
||||
export type SemanticFilterStatus = "all" | "unresolved" | HealthStatus;
|
||||
export type SemanticFilterStatus = "all" | "unresolved" | "problems" | HealthStatus;
|
||||
|
||||
/** Statuses that "Problems only" shows: anything needing attention. */
|
||||
export const PROBLEM_STATUSES: ReadonlySet<string> = new Set(["down", "degraded", "recovering"]);
|
||||
|
||||
export function matchesStatusFilter(status: string, filter: SemanticFilterStatus): boolean {
|
||||
if (filter === "all") return true;
|
||||
if (filter === "unresolved") return status === "unknown" || status === "unmonitored";
|
||||
if (filter === "problems") return PROBLEM_STATUSES.has(status);
|
||||
return status === filter;
|
||||
}
|
||||
|
||||
const CRITICALITY_RANK: Record<Criticality, number> = { low: 0, medium: 1, high: 2, critical: 3 };
|
||||
|
||||
export type ServiceFacts = { criticality: Criticality; flapping: boolean };
|
||||
|
||||
export type SemanticGraphOptions = {
|
||||
/** Per-service facts the semantic projection does not carry. */
|
||||
serviceFacts?: (serviceId: string) => ServiceFacts | undefined;
|
||||
/**
|
||||
* Extra filters (domain, application, environment, criticality, lifecycle,
|
||||
* monitoring, group) evaluated per service. A domain or application node is
|
||||
* shown when at least one of its components matches.
|
||||
*/
|
||||
serviceFilter?: (serviceId: string) => boolean;
|
||||
};
|
||||
|
||||
export type SemanticGraph = {
|
||||
nodes: ServiceNode[];
|
||||
edges: Edge[];
|
||||
/** Relations not drawn because of the per-level cap or the weight rule. */
|
||||
hiddenEdgeCount: number;
|
||||
};
|
||||
|
||||
/** Projects canonical services and relationships into the active semantic level. */
|
||||
export function semanticTopologyGraph(
|
||||
@@ -14,7 +46,21 @@ export function semanticTopologyGraph(
|
||||
incidentOnly: boolean,
|
||||
search: string,
|
||||
statusFilter: SemanticFilterStatus,
|
||||
): { nodes: ServiceNode[]; edges: Edge[] } {
|
||||
options: SemanticGraphOptions = {},
|
||||
): SemanticGraph {
|
||||
const facts = (ids: string[]): ServiceFacts => {
|
||||
let criticality: Criticality = "low";
|
||||
let flapping = false;
|
||||
let known = false;
|
||||
for (const id of ids) {
|
||||
const item = options.serviceFacts?.(id);
|
||||
if (!item) continue;
|
||||
known = true;
|
||||
if (CRITICALITY_RANK[item.criticality] > CRITICALITY_RANK[criticality]) criticality = item.criticality;
|
||||
flapping ||= item.flapping;
|
||||
}
|
||||
return known ? { criticality, flapping } : { criticality: "medium", flapping: false };
|
||||
};
|
||||
const applicationById = new Map(
|
||||
topology.applications.map((item) => [item.id, item]),
|
||||
);
|
||||
@@ -51,14 +97,13 @@ export function semanticTopologyGraph(
|
||||
rootCause: domain.root_cause,
|
||||
impacted: domain.affected,
|
||||
group: domain.name,
|
||||
criticality: "medium",
|
||||
flapping: false,
|
||||
...facts(domain.application_ids.flatMap((id) => applicationById.get(id)?.component_ids ?? [])),
|
||||
category: "domain",
|
||||
memberIds: domain.application_ids.flatMap(
|
||||
(id) => applicationById.get(id)?.component_ids ?? [],
|
||||
),
|
||||
nodeKind: "domain",
|
||||
explanation: `${domain.resolved_application_count}/${domain.application_count} resolved · ${domain.unresolved_application_count} unresolved${domain.incident_count ? ` · ${domain.incident_count} incident` : ""}`,
|
||||
explanation: `${domain.resolved_application_count}/${domain.application_count} opgelost · ${domain.unresolved_application_count} onopgelost${domain.incident_count ? ` · ${domain.incident_count} incident` : ""}`,
|
||||
},
|
||||
className: `service-node domain-node status-${domain.status}`,
|
||||
}))
|
||||
@@ -77,8 +122,7 @@ export function semanticTopologyGraph(
|
||||
rootCause: app.root_cause,
|
||||
impacted: app.affected,
|
||||
group: domainById.get(app.domain_id)?.name ?? null,
|
||||
criticality: "medium",
|
||||
flapping: false,
|
||||
...facts(app.component_ids),
|
||||
category: "application",
|
||||
application: app.name,
|
||||
applicationNode: true,
|
||||
@@ -106,20 +150,21 @@ export function semanticTopologyGraph(
|
||||
impacted: component.affected,
|
||||
group:
|
||||
applicationById.get(component.application_id)?.name ?? null,
|
||||
criticality: "medium",
|
||||
flapping: false,
|
||||
...facts([component.service_id]),
|
||||
category: component.role,
|
||||
nodeKind: "component",
|
||||
role: component.role,
|
||||
explanation: component.unknown_reason
|
||||
? `${component.unknown_reason.replaceAll("_", " ")} · ${component.dependent_ids.length} dependents`
|
||||
: `${component.monitoring_state.replace("_", " ")} · ${component.dependent_ids.length} dependents`,
|
||||
? `${component.unknown_reason.replaceAll("_", " ")} · ${component.dependent_ids.length} afhankelijken`
|
||||
: `${component.monitoring_state.replace("_", " ")} · ${component.dependent_ids.length} afhankelijken`,
|
||||
},
|
||||
className: `service-node component-node status-${component.effective_status}`,
|
||||
}));
|
||||
const normalizedSearch = search.trim().toLocaleLowerCase();
|
||||
const serviceFilter = options.serviceFilter;
|
||||
const visibleNodes = nodes.filter((node) => {
|
||||
const descendants = node.data.memberIds ?? [node.id];
|
||||
if (serviceFilter && !descendants.some((serviceId) => serviceFilter(serviceId))) return false;
|
||||
const descendantMatches = descendants.some((serviceId) =>
|
||||
componentById
|
||||
.get(serviceId)
|
||||
@@ -132,10 +177,7 @@ export function semanticTopologyGraph(
|
||||
.toLocaleLowerCase()
|
||||
.includes(normalizedSearch) ||
|
||||
descendantMatches) &&
|
||||
(statusFilter === "all" ||
|
||||
(statusFilter === "unresolved"
|
||||
? ["unknown", "unmonitored"].includes(node.data.status)
|
||||
: node.data.status === statusFilter))
|
||||
matchesStatusFilter(node.data.status, statusFilter)
|
||||
);
|
||||
});
|
||||
const nodeIds = new Set(visibleNodes.map((node) => node.id));
|
||||
@@ -244,6 +286,7 @@ export function semanticTopologyGraph(
|
||||
);
|
||||
return {
|
||||
nodes: visibleNodes,
|
||||
hiddenEdgeCount: projectedEdges.length - visibleEdges.length,
|
||||
edges: visibleEdges.map((edge) => ({
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Edge, Node } from "@xyflow/react";
|
||||
|
||||
import { arrangeTopology, clearTopologyLayoutCache, topologyStructureKey } from "./topologyLayout";
|
||||
|
||||
const node = (id: string): Node => ({ id, position: { x: 0, y: 0 }, data: {} });
|
||||
|
||||
describe("topology layout", () => {
|
||||
it("lays out in-thread without Worker support and reuses cached results", async () => {
|
||||
clearTopologyLayoutCache();
|
||||
const nodes = [node("a"), node("b")];
|
||||
const edges: Edge[] = [{ id: "a-b", source: "a", target: "b" }];
|
||||
const first = await arrangeTopology(nodes, edges);
|
||||
expect(Object.keys(first.positions).sort()).toEqual(["a", "b"]);
|
||||
expect(await arrangeTopology(nodes, edges)).toBe(first);
|
||||
});
|
||||
|
||||
it("keeps the layout cache bounded", async () => {
|
||||
clearTopologyLayoutCache();
|
||||
const firstNodes = [node("n0")];
|
||||
const first = await arrangeTopology(firstNodes, []);
|
||||
for (let index = 1; index <= 40; index += 1) {
|
||||
await arrangeTopology([node(`n${index}`)], []);
|
||||
}
|
||||
// The oldest entry was evicted, so a fresh object is computed.
|
||||
expect(await arrangeTopology(firstNodes, [])).not.toBe(first);
|
||||
expect(topologyStructureKey(firstNodes, [])).toBe("n0|");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import type ElkConstructor from "elkjs/lib/elk.bundled.js";
|
||||
import type ElkApi from "elkjs/lib/elk-api.js";
|
||||
import type { Edge, Node } from "@xyflow/react";
|
||||
|
||||
type ElkInstance = InstanceType<typeof ElkConstructor>;
|
||||
type ElkInstance = InstanceType<typeof ElkApi>;
|
||||
|
||||
export type TopologyRoute = { x: number; y: number }[];
|
||||
export type TopologyLayout = {
|
||||
@@ -14,13 +14,42 @@ type ElkRoutedEdge = {
|
||||
sections?: { startPoint?: ElkPoint; bendPoints?: ElkPoint[]; endPoint?: ElkPoint }[];
|
||||
};
|
||||
|
||||
let elk: ElkInstance | null = null;
|
||||
/** Must match the node card size in styles.css (.service-node-body). */
|
||||
export const NODE_WIDTH = 236;
|
||||
export const NODE_HEIGHT = 128;
|
||||
|
||||
let elk: Promise<ElkInstance> | null = null;
|
||||
/** Bounded LRU: every distinct filter/scope combination used to stay forever. */
|
||||
const CACHE_LIMIT = 30;
|
||||
const cache = new Map<string, TopologyLayout>();
|
||||
|
||||
async function layoutEngine(): Promise<ElkInstance> {
|
||||
if (elk) return elk;
|
||||
const { default: ElkConstructor } = await import("elkjs/lib/elk.bundled.js");
|
||||
elk = new ElkConstructor();
|
||||
function remember(key: string, layout: TopologyLayout): void {
|
||||
cache.delete(key);
|
||||
cache.set(key, layout);
|
||||
while (cache.size > CACHE_LIMIT) {
|
||||
const oldest = cache.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
cache.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ELK runs in a Web Worker so a large layout never blocks the main thread
|
||||
* (drag, scroll and SSE updates stay responsive). Environments without
|
||||
* Worker support (unit tests) fall back to the in-thread bundle.
|
||||
*/
|
||||
function layoutEngine(): Promise<ElkInstance> {
|
||||
elk ??= (async () => {
|
||||
if (typeof Worker !== "undefined") {
|
||||
const [{ default: Elk }, { default: workerUrl }] = await Promise.all([
|
||||
import("elkjs/lib/elk-api.js"),
|
||||
import("elkjs/lib/elk-worker.min.js?url"),
|
||||
]);
|
||||
return new Elk({ workerUrl });
|
||||
}
|
||||
const { default: Bundled } = await import("elkjs/lib/elk.bundled.js");
|
||||
return new Bundled() as unknown as ElkInstance;
|
||||
})();
|
||||
return elk;
|
||||
}
|
||||
|
||||
@@ -41,7 +70,10 @@ export async function arrangeTopology(
|
||||
): Promise<TopologyLayout> {
|
||||
const key = topologyStructureKey(nodes, edges);
|
||||
const cached = cache.get(key);
|
||||
if (cached) return cached;
|
||||
if (cached) {
|
||||
remember(key, cached);
|
||||
return cached;
|
||||
}
|
||||
const layout = await (await layoutEngine()).layout({
|
||||
id: "servicemap-topology",
|
||||
layoutOptions: {
|
||||
@@ -51,10 +83,15 @@ export async function arrangeTopology(
|
||||
"elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX",
|
||||
"elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
|
||||
"elk.spacing.nodeNode": "44",
|
||||
"elk.layered.spacing.nodeNodeBetweenLayers": "92",
|
||||
"elk.layered.spacing.nodeNodeBetweenLayers": "110",
|
||||
// Keep parallel orthogonal routes apart instead of stacking them into one "comb".
|
||||
"elk.spacing.edgeEdge": "16",
|
||||
"elk.layered.spacing.edgeEdgeBetweenLayers": "16",
|
||||
"elk.layered.spacing.edgeNodeBetweenLayers": "28",
|
||||
"elk.layered.mergeEdges": "false",
|
||||
"elk.padding": "[top=42,left=42,bottom=42,right=42]",
|
||||
},
|
||||
children: nodes.map((node) => ({ id: node.id, width: 230, height: 132 })),
|
||||
children: nodes.map((node) => ({ id: node.id, width: NODE_WIDTH, height: NODE_HEIGHT })),
|
||||
edges: edges.map((edge) => ({
|
||||
id: edge.id,
|
||||
sources: [edge.source],
|
||||
@@ -79,7 +116,7 @@ export async function arrangeTopology(
|
||||
]),
|
||||
);
|
||||
const result = { positions, routes };
|
||||
cache.set(key, result);
|
||||
remember(key, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "servicemap-workspace",
|
||||
"version": "1.6.2",
|
||||
"version": "1.6.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "servicemap-workspace",
|
||||
"version": "1.6.2"
|
||||
"version": "1.6.3"
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "servicemap-workspace",
|
||||
"private": true,
|
||||
"version": "1.6.2",
|
||||
"version": "1.6.3",
|
||||
"scripts": {
|
||||
"install:frontend": "npm --prefix frontend ci --no-audit --no-fund",
|
||||
"lint": "npm run install:frontend && npm --prefix frontend run lint",
|
||||
|
||||
@@ -23,5 +23,7 @@
|
||||
<Config Name="Probe interval" Target="SERVICEMAP_PROBE_INTERVAL" Default="60" Mode="" Description="Default scheduled-probe interval in seconds; set 0 to disable." Type="Variable" Display="always" Required="true" Mask="false">60</Config>
|
||||
<Config Name="Docker host" Target="SERVICEMAP_DOCKER_HOST" Default="unix:///var/run/docker.sock" Mode="" Description="Read-only local Docker socket." Type="Variable" Display="advanced" Required="true" Mask="false">unix:///var/run/docker.sock</Config>
|
||||
<Config Name="AppOps URL" Target="SERVICEMAP_APPOPS_URL" Default="http://[IP]:[PORT:1216]" Mode="" Description="Optional read-only AppOps enrichment endpoint." Type="Variable" Display="advanced" Required="false" Mask="false">http://[IP]:[PORT:1216]</Config>
|
||||
<Config Name="Edit protection" Target="SERVICEMAP_AUTH_MODE" Default="token" Mode="" Description="token: reads stay open, changes need the admin token from /data/admin-token (generated on first start). disabled: no authentication." Type="Variable" Display="always" Required="true" Mask="false">token</Config>
|
||||
<Config Name="Allowed hosts" Target="SERVICEMAP_ALLOWED_HOSTS" Default="" Mode="" Description="Optional comma-separated host names that may reach ServiceMap (DNS-rebinding guard). Empty accepts any host." Type="Variable" Display="advanced" Required="false" Mask="false" />
|
||||
<Config Name="Probe host" Target="SERVICEMAP_PROBE_HOST" Default="" Mode="" Description="Optional host address reachable from the container for explicitly published Docker probes." Type="Variable" Display="advanced" Required="false" Mask="false" />
|
||||
</Container>
|
||||
Reference in new issue
Block a user