Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29d3c91f5a | ||
|
|
5a11a3b602 | ||
|
|
ca66b9a7b1 | ||
|
|
b420b28ea8 | ||
|
|
d3c8eee393 | ||
|
|
c8deabd4d9 | ||
|
|
c1a70b025c | ||
|
|
37888af374 | ||
|
|
1569100721 | ||
|
|
d9fcc75792 | ||
|
|
a2699a3ec3 | ||
|
|
3bdaf28737 | ||
|
|
168cbe98f8 | ||
|
|
9f2e78c6c4 | ||
|
|
9ce3b868bb | ||
|
|
a7355ffdc8 | ||
|
|
ce786b716b | ||
|
|
c28f9e186b | ||
|
|
4480e8b509 | ||
|
|
aa1c9b5d2b | ||
|
|
b2b9fd2a02 | ||
|
|
8d839ed5ad | ||
|
|
b079cf9267 | ||
|
|
2157ae2d42 | ||
|
|
13d09dc830 |
No files matched your search
+5
-19
@@ -1,23 +1,9 @@
|
||||
[advisories]
|
||||
ignore = [
|
||||
# hickory-proto 0.25.x pulled in transitively via mongodb → hickory-resolver.
|
||||
# MongoDB 3.x has not yet released with hickory-resolver 0.26.x, so we cannot
|
||||
# upgrade past this without a mongodb release. Both are DNS-layer DoS vectors
|
||||
# requiring a MITM/controlled DNS server against MongoDB's hostname resolution —
|
||||
# not a realistic attack surface here. Revisit when mongodb bumps hickory.
|
||||
# hickory-proto, pulled in transitively via mongodb → hickory-resolver
|
||||
# (0.26.3 since mongodb 3.10, which fixed RUSTSEC-2026-0119). The NSEC3 loop
|
||||
# is in DNSSEC validation, which the driver does not use, and needs a
|
||||
# MITM/controlled DNS server against MongoDB's hostname resolution — not a
|
||||
# realistic attack surface here. Revisit when hickory ships a fix.
|
||||
"RUSTSEC-2026-0118", # NSEC3 loop, no fix available upstream
|
||||
"RUSTSEC-2026-0119", # O(n²) name compression, fixed in hickory-proto >=0.26.1
|
||||
|
||||
# rmcp 0.16.0 — DNS rebinding in Streamable HTTP server transport (missing
|
||||
# Host header validation). Patched in rmcp >= 1.4.0, which is a major API
|
||||
# version jump from our pin; rmcp shipped 0.x → 1.x → 2.x in three months
|
||||
# and the migration touches every tool handler + the auth middleware we
|
||||
# just landed in #92. Threat model in our deployment: the MCP server is
|
||||
# exposed at a public hostname (comp-mcp-dev.breakpilot.com) behind orca's
|
||||
# TLS-terminating ingress with per-tenant bearer auth — the attack model
|
||||
# (browser DNS-rebinding into localhost MCP server) doesn't directly apply.
|
||||
# Defense-in-depth Host-header check is still a worthwhile follow-up.
|
||||
# FOLLOW-UP: bump rmcp to 2.x in a dedicated PR (M7.3 follow-up, sized
|
||||
# multi-hour due to API surface change).
|
||||
"RUSTSEC-2026-0189",
|
||||
]
|
||||
@@ -146,6 +146,11 @@ DASHBOARD_SESSION_KEY=
|
||||
|
||||
# MCP Server
|
||||
MCP_ENDPOINT_URL=http://localhost:8090
|
||||
# The hostnames (or host:port) clients reach the MCP server at, comma-separated:
|
||||
# the public hostname behind the ingress and the in-network name the dashboard
|
||||
# uses. Requests with another Host header are refused (DNS rebinding
|
||||
# protection). Unset, the Host header is not checked and a warning is logged.
|
||||
# MCP_ALLOWED_HOSTS=pruefwerk-stage.breakpilot.com,compliance-mcp:8090
|
||||
# Absolute health URL for the default MCP server card. Set it where an ingress
|
||||
# routes /mcp/* to a server that serves /health at its own root (staging:
|
||||
# https://pruefwerk-stage.breakpilot.com/mcp/health). Derived from
|
||||
|
||||
+18
-2
@@ -138,6 +138,8 @@ jobs:
|
||||
run: cargo clippy -p werkbank-exec --all-targets -- -D warnings
|
||||
- name: Clippy (control-map)
|
||||
run: cargo clippy -p control-map --all-targets -- -D warnings
|
||||
- name: Clippy (graph)
|
||||
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
|
||||
|
||||
# Security audit
|
||||
- name: Security Audit
|
||||
@@ -146,14 +148,21 @@ jobs:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# Tests (reuses compilation artifacts from clippy)
|
||||
- name: Tests (core + agent + werkbank-exec + control-map)
|
||||
run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib
|
||||
- name: Tests (core + agent + graph + werkbank-exec + control-map)
|
||||
run: cargo test -p compliance-core -p compliance-agent -p compliance-graph -p werkbank-exec -p control-map --lib
|
||||
# compliance-core's integration tests need no services.
|
||||
- name: Tests (core integration)
|
||||
run: cargo test -p compliance-core --tests
|
||||
# The dashboard crate compiles as the library and as its test harness at
|
||||
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
|
||||
# and get OOM-killed (signal 9). One at a time for these two steps.
|
||||
- name: Tests (dashboard server)
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
run: cargo test -p compliance-dashboard --features server --no-default-features
|
||||
- name: Tests (dashboard web)
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "1"
|
||||
run: cargo test -p compliance-dashboard --features web --no-default-features
|
||||
|
||||
- name: Show sccache stats
|
||||
@@ -374,9 +383,16 @@ jobs:
|
||||
apk add --no-cache git curl openssl
|
||||
git init && git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
|
||||
git fetch --depth=1 origin "${GITHUB_SHA}" && git checkout FETCH_HEAD
|
||||
# service.version in telemetry: the latest release tag without its v,
|
||||
# as for the agent. No tag → empty, and the crate version is used.
|
||||
git fetch --quiet --unshallow --tags origin || true
|
||||
TAG=$(git describe --tags --abbrev=0 --match 'v[0-9]*' 2>/dev/null || true)
|
||||
PRUEFWERK_VERSION="${TAG#v}"
|
||||
echo "version: ${PRUEFWERK_VERSION:-crate}"
|
||||
IMAGE=repo.breakpilot.com/pruefwerk/compliance-dashboard
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
DOCKER_BUILDKIT=1 docker build --pull --secret id=git_token,env=PLATFORM_CI_TOKEN \
|
||||
--build-arg PRUEFWERK_VERSION="${PRUEFWERK_VERSION}" \
|
||||
-f Dockerfile.dashboard -t "$IMAGE:latest" -t "$IMAGE:${GITHUB_SHA}" .
|
||||
docker push "$IMAGE:latest" && docker push "$IMAGE:${GITHUB_SHA}"
|
||||
{ command -v cosign >/dev/null 2>&1 || curl -sSfLo /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64 || wget -qO /usr/local/bin/cosign https://github.com/sigstore/cosign/releases/download/v2.4.3/cosign-linux-amd64; } || echo "::warning::cosign fetch failed"
|
||||
|
||||
@@ -51,30 +51,6 @@ jobs:
|
||||
env:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
MONGO_INITDB_ROOT_PASSWORD: example
|
||||
# The image main deployed. Dev mode (no Keycloak): the harness talks to
|
||||
# the unauthenticated dev tenant; source_only matches staging.
|
||||
agent:
|
||||
image: repo.breakpilot.com/pruefwerk/compliance-agent:latest
|
||||
credentials:
|
||||
username: ${{ secrets.REGISTRY_USERNAME }}
|
||||
password: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
env:
|
||||
APP_ENV: dev
|
||||
MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin
|
||||
MONGODB_DATABASE: nightly
|
||||
PW_FEATURES: source_only
|
||||
# No chat model: LLM triage, code review and the control judge are
|
||||
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
|
||||
# output never gates the run, and with the model on, ~600 calls of
|
||||
# 11 s on average (p99 147 s) on the gateway prod also uses kept
|
||||
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
|
||||
# Embeddings stay on: the gateway's embedding model.
|
||||
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
|
||||
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
|
||||
LITELLM_EMBED_MODEL: bge-multilingual-gemma2
|
||||
# Optional. The CODESYS CVE match queries NVD, which rate-limits
|
||||
# unauthenticated clients; a key keeps those CVEs from going missing.
|
||||
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
@@ -149,10 +125,59 @@ jobs:
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# The image main deployed, started here rather than as a service:
|
||||
# act_runner 0.6.1 hands a service's registry credentials to the job
|
||||
# container's own pull (map order decides which service wins), so the
|
||||
# Harbor login reached docker.io about every other night. mongo, the
|
||||
# only service left, has no credentials. The agent shares this
|
||||
# container's network: it reaches mongo by name and listens on
|
||||
# localhost here. The login lands in this container's ~/.docker, which
|
||||
# goes with it.
|
||||
# Dev mode (no Keycloak): the harness talks to the unauthenticated dev
|
||||
# tenant; source_only matches staging.
|
||||
- name: Start the agent
|
||||
run: |
|
||||
curl -fsSL -o /tmp/docker.tgz \
|
||||
https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
|
||||
echo "4f798b3ee1e0140eab5bf30b0edc4e84f4cdb53255a429dc3bbae9524845d640 /tmp/docker.tgz" \
|
||||
| sha256sum -c -
|
||||
tar xzf /tmp/docker.tgz --strip-components=1 -C /usr/local/bin docker/docker
|
||||
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
|
||||
# -e NAME without a value passes this step's variable, so no secret
|
||||
# appears on the command line. The container runs on the runner's
|
||||
# daemon, outside the job's own limits, so it has its own; the label
|
||||
# finds one a cancelled job left behind.
|
||||
docker run -d --pull always --name "nightly-agent-${GITHUB_RUN_ID}" \
|
||||
--label pruefwerk-nightly --memory 4g --cpus 2 \
|
||||
--network "container:$(hostname)" \
|
||||
-e APP_ENV=dev \
|
||||
-e MONGODB_URI=mongodb://root:example@mongo:27017/?authSource=admin \
|
||||
-e MONGODB_DATABASE=nightly \
|
||||
-e PW_FEATURES=source_only \
|
||||
-e LITELLM_URL -e LITELLM_API_KEY \
|
||||
-e LITELLM_EMBED_MODEL=bge-multilingual-gemma2 \
|
||||
-e NVD_API_KEY \
|
||||
repo.breakpilot.com/pruefwerk/compliance-agent:latest
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
|
||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
# No chat model: LLM triage, code review and the control judge are
|
||||
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
|
||||
# output never gates the run, and with the model on, ~600 calls of
|
||||
# 11 s on average (p99 147 s) on the gateway prod also uses kept
|
||||
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
|
||||
# Embeddings stay on: the gateway's embedding model.
|
||||
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
|
||||
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
|
||||
# Optional. The CODESYS CVE match queries NVD, which rate-limits
|
||||
# unauthenticated clients; a key keeps those CVEs from going missing.
|
||||
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
|
||||
|
||||
- name: Wait for the agent
|
||||
run: |
|
||||
for i in $(seq 1 90); do
|
||||
curl -fsS http://agent:3001/api/v1/health && exit 0
|
||||
curl -fsS http://localhost:3001/api/v1/health && exit 0
|
||||
sleep 2
|
||||
done
|
||||
echo "agent did not become healthy" >&2
|
||||
@@ -163,13 +188,20 @@ jobs:
|
||||
- name: Scan the corpus and compare with the baselines
|
||||
run: cargo test -p compliance-agent --test nightly -- --nocapture
|
||||
env:
|
||||
NIGHTLY_AGENT_URL: http://agent:3001
|
||||
NIGHTLY_AGENT_URL: http://localhost:3001
|
||||
NIGHTLY_CODESYS_SAMPLE: /tmp/csv-blackbox.projectarchive
|
||||
NIGHTLY_ZEPHYR_EXAMPLE: /tmp/zephyr-example.zip
|
||||
NIGHTLY_IOS_SAMPLE: /tmp/ios-sample.zip
|
||||
NIGHTLY_ANDROID_SAMPLE: /tmp/android-sample.zip
|
||||
NIGHTLY_BLESS: ${{ inputs.bless && '1' || '0' }}
|
||||
|
||||
# The agent is not a service, so the runner does not remove it.
|
||||
- name: Stop the agent
|
||||
if: always()
|
||||
run: docker rm -f "nightly-agent-${GITHUB_RUN_ID}" || true
|
||||
env:
|
||||
RUSTC_WRAPPER: ""
|
||||
|
||||
# upload-artifact is a Node action and the Rust image has no node.
|
||||
- name: Install node for the artifact upload
|
||||
if: always()
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Made-up secrets in Prüfwerk's own tests, found by the secret scanner in the
|
||||
# git history (commit:file:rule:line, as gitleaks fingerprints them). Neither is
|
||||
# a real credential; the history keeps them, so they are listed here.
|
||||
#
|
||||
# A Firebase-shaped key in the test that the real scanner still finds Firebase
|
||||
# keys (compliance-agent/src/pipeline/gitleaks.rs).
|
||||
6c9756bebf599eb16112d693c769cd752292d6a9:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
|
||||
d42b429273668bd285440596fd78e564d34b01ef:compliance-agent/src/pipeline/gitleaks.rs:gcp-api-key:278
|
||||
# The throwaway MongoDB root password of a CI test container.
|
||||
3ef5c28a97f169ed03009f70a9a20a7c9095f0b2:.gitea/workflows/ci.yml:generic-password:170
|
||||
5424074d26552882c6529c2dd9d309b9cc37376a:.gitea/workflows/ci.yml:generic-password:72
|
||||
Generated
+261
-79
@@ -526,6 +526,16 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono-tz"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
|
||||
dependencies = [
|
||||
"chrono",
|
||||
"phf 0.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ciborium"
|
||||
version = "0.2.2"
|
||||
@@ -596,6 +606,7 @@ dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"chrono-tz",
|
||||
"compliance-core",
|
||||
"compliance-dast",
|
||||
"compliance-graph",
|
||||
@@ -651,6 +662,7 @@ dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bson",
|
||||
"chrono",
|
||||
"encoding_rs",
|
||||
"hex",
|
||||
"jsonschema",
|
||||
"jsonwebtoken",
|
||||
@@ -743,13 +755,17 @@ dependencies = [
|
||||
"petgraph",
|
||||
"serde",
|
||||
"tantivy",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tree-sitter",
|
||||
"tree-sitter-c",
|
||||
"tree-sitter-c-sharp",
|
||||
"tree-sitter-javascript",
|
||||
"tree-sitter-python",
|
||||
"tree-sitter-rust",
|
||||
"tree-sitter-typescript",
|
||||
"tree-sitter-vb-dotnet",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1114,7 +1130,7 @@ dependencies = [
|
||||
"cssparser-macros",
|
||||
"dtoa-short",
|
||||
"itoa",
|
||||
"phf",
|
||||
"phf 0.13.1",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -1166,6 +1182,16 @@ dependencies = [
|
||||
"darling_macro 0.23.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"darling_macro 0.24.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.21.3"
|
||||
@@ -1193,6 +1219,19 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.21.3"
|
||||
@@ -1215,6 +1254,17 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.24.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
|
||||
dependencies = [
|
||||
"darling_core 0.24.1",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dashmap"
|
||||
version = "6.1.0"
|
||||
@@ -1368,7 +1418,7 @@ dependencies = [
|
||||
"dioxus-cli-config 0.7.3",
|
||||
"http",
|
||||
"infer",
|
||||
"jni",
|
||||
"jni 0.21.1",
|
||||
"js-sys",
|
||||
"ndk",
|
||||
"ndk-context",
|
||||
@@ -2037,18 +2087,6 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enum-as-inner"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "enumset"
|
||||
version = "1.1.10"
|
||||
@@ -2647,23 +2685,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hickory-proto"
|
||||
version = "0.25.2"
|
||||
name = "hickory-net"
|
||||
version = "0.26.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502"
|
||||
checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"cfg-if",
|
||||
"data-encoding",
|
||||
"enum-as-inner",
|
||||
"futures-channel",
|
||||
"futures-io",
|
||||
"futures-util",
|
||||
"hickory-proto",
|
||||
"idna",
|
||||
"ipnet",
|
||||
"once_cell",
|
||||
"rand 0.9.2",
|
||||
"ring",
|
||||
"jni 0.22.4",
|
||||
"rand 0.10.3",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tokio",
|
||||
@@ -2672,21 +2709,46 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hickory-resolver"
|
||||
version = "0.25.2"
|
||||
name = "hickory-proto"
|
||||
version = "0.26.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a"
|
||||
checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d"
|
||||
dependencies = [
|
||||
"data-encoding",
|
||||
"idna",
|
||||
"ipnet",
|
||||
"jni 0.22.4",
|
||||
"once_cell",
|
||||
"prefix-trie",
|
||||
"rand 0.10.3",
|
||||
"ring",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hickory-resolver"
|
||||
version = "0.26.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
"hickory-net",
|
||||
"hickory-proto",
|
||||
"ipconfig",
|
||||
"ipnet",
|
||||
"jni 0.22.4",
|
||||
"moka",
|
||||
"ndk-context",
|
||||
"once_cell",
|
||||
"parking_lot",
|
||||
"rand 0.9.2",
|
||||
"rand 0.10.3",
|
||||
"resolv-conf",
|
||||
"smallvec",
|
||||
"system-configuration",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -3070,6 +3132,9 @@ name = "ipnet"
|
||||
version = "2.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iri-string"
|
||||
@@ -3105,19 +3170,68 @@ dependencies = [
|
||||
"cesu8",
|
||||
"cfg-if",
|
||||
"combine",
|
||||
"jni-sys",
|
||||
"jni-sys 0.3.0",
|
||||
"log",
|
||||
"thiserror 1.0.69",
|
||||
"walkdir",
|
||||
"windows-sys 0.45.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jni"
|
||||
version = "0.22.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"combine",
|
||||
"jni-macros",
|
||||
"jni-sys 0.4.1",
|
||||
"log",
|
||||
"simd_cesu8",
|
||||
"thiserror 2.0.18",
|
||||
"walkdir",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jni-macros"
|
||||
version = "0.22.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"simd_cesu8",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jni-sys"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
|
||||
|
||||
[[package]]
|
||||
name = "jni-sys"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
|
||||
dependencies = [
|
||||
"jni-sys-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jni-sys-macros"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.34"
|
||||
@@ -3486,12 +3600,12 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "md-5"
|
||||
version = "0.10.6"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"digest 0.10.7",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3589,9 +3703,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mongocrypt"
|
||||
version = "0.3.2"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8da0cd419a51a5fb44819e290fbdb0665a54f21dead8923446a799c7f4d26ad9"
|
||||
checksum = "8426a875ded61430d4a811dbfda7633b6b8af0225c547fc6c28b8b0aa7d79a13"
|
||||
dependencies = [
|
||||
"bson",
|
||||
"mongocrypt-sys",
|
||||
@@ -3601,43 +3715,42 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mongocrypt-sys"
|
||||
version = "0.1.5+1.15.1"
|
||||
version = "0.1.6+1.18.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224484c5d09285a7b8cb0a0c117e847ebd14cb6e4470ecf68cdb89c503b0edb9"
|
||||
checksum = "851fac73f7fe22f6a3ab87f720ce509cae7c9fd08e7dd27866cc232dee07ccf4"
|
||||
|
||||
[[package]]
|
||||
name = "mongodb"
|
||||
version = "3.6.0"
|
||||
version = "3.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ef2c933617431ad0246fb5b43c425ebdae18c7f7259c87de0726d93b0e7e91b"
|
||||
checksum = "6466d4601ff396952e1895d88083d1ab03930b812277180eb8258bbe1a10bb0f"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bitflags",
|
||||
"bson",
|
||||
"derive-where",
|
||||
"derive_more",
|
||||
"futures-core",
|
||||
"futures-io",
|
||||
"futures-util",
|
||||
"hex",
|
||||
"hickory-net",
|
||||
"hickory-proto",
|
||||
"hickory-resolver",
|
||||
"hmac 0.12.1",
|
||||
"hmac 0.13.0",
|
||||
"macro_magic",
|
||||
"md-5",
|
||||
"mongocrypt",
|
||||
"mongodb-internal-macros",
|
||||
"pbkdf2 0.12.2",
|
||||
"pbkdf2",
|
||||
"percent-encoding",
|
||||
"rand 0.9.2",
|
||||
"rustc_version_runtime",
|
||||
"rustls",
|
||||
"rustversion",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_with",
|
||||
"sha1 0.10.6",
|
||||
"sha2 0.10.9",
|
||||
"sha1 0.11.0",
|
||||
"sha2 0.11.1",
|
||||
"socket2 0.6.2",
|
||||
"stringprep",
|
||||
"strsim",
|
||||
@@ -3653,9 +3766,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mongodb-internal-macros"
|
||||
version = "3.6.0"
|
||||
version = "3.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5758dc828eb2d02ec30563cba365609d56ddd833190b192beaee2b475a7bb3"
|
||||
checksum = "995f1171fab2a793f15afd0e9ba1d84116a9411ff8e3467fe9c167462435033d"
|
||||
dependencies = [
|
||||
"macro_magic",
|
||||
"proc-macro2",
|
||||
@@ -3710,7 +3823,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"jni-sys",
|
||||
"jni-sys 0.3.0",
|
||||
"log",
|
||||
"ndk-sys",
|
||||
"num_enum",
|
||||
@@ -3730,7 +3843,7 @@ version = "0.6.0+11769913"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
|
||||
dependencies = [
|
||||
"jni-sys",
|
||||
"jni-sys 0.3.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3960,15 +4073,14 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||
|
||||
[[package]]
|
||||
name = "openssl"
|
||||
version = "0.10.75"
|
||||
version = "0.10.82"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08838db121398ad17ab8531ce9de97b244589089e290a384c900cb9ff7434328"
|
||||
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cfg-if",
|
||||
"foreign-types",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"openssl-macros",
|
||||
"openssl-sys",
|
||||
]
|
||||
@@ -3998,9 +4110,9 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
|
||||
|
||||
[[package]]
|
||||
name = "openssl-sys"
|
||||
version = "0.9.111"
|
||||
version = "0.9.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82cab2d520aa75e3c58898289429321eb788c3106963d0dc886ec7a5f4adc321"
|
||||
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -4152,15 +4264,6 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"
|
||||
|
||||
[[package]]
|
||||
name = "pbkdf2"
|
||||
version = "0.12.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pbkdf2"
|
||||
version = "0.13.0"
|
||||
@@ -4197,6 +4300,15 @@ dependencies = [
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
|
||||
dependencies = [
|
||||
"phf_shared 0.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf"
|
||||
version = "0.13.1"
|
||||
@@ -4204,7 +4316,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
|
||||
dependencies = [
|
||||
"phf_macros",
|
||||
"phf_shared",
|
||||
"phf_shared 0.13.1",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -4215,7 +4327,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
|
||||
dependencies = [
|
||||
"phf_generator",
|
||||
"phf_shared",
|
||||
"phf_shared 0.13.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4225,7 +4337,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
|
||||
dependencies = [
|
||||
"fastrand",
|
||||
"phf_shared",
|
||||
"phf_shared 0.13.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4235,12 +4347,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
|
||||
dependencies = [
|
||||
"phf_generator",
|
||||
"phf_shared",
|
||||
"phf_shared 0.13.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
|
||||
dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phf_shared"
|
||||
version = "0.13.1"
|
||||
@@ -4342,6 +4463,17 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
|
||||
|
||||
[[package]]
|
||||
name = "prefix-trie"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7"
|
||||
dependencies = [
|
||||
"either",
|
||||
"ipnet",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prettyplease"
|
||||
version = "0.2.37"
|
||||
@@ -4767,18 +4899,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "0.16.0"
|
||||
version = "3.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4c9c94680f75470ee8083a0667988b5d7b5beb70b9f998a8e51de7c682ce60"
|
||||
checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"base64 0.23.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"futures",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"indexmap",
|
||||
"libc",
|
||||
"pastey",
|
||||
"pin-project-lite",
|
||||
"rand 0.10.3",
|
||||
@@ -4786,6 +4920,7 @@ dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.1",
|
||||
"sse-stream",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
@@ -4798,15 +4933,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcp-macros"
|
||||
version = "0.16.0"
|
||||
version = "3.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90c23c8f26cae4da838fbc3eadfaecf2d549d97c04b558e7bd90526a9c28b42a"
|
||||
checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029"
|
||||
dependencies = [
|
||||
"darling 0.23.0",
|
||||
"darling 0.24.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_json",
|
||||
"syn 2.0.117",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5028,7 +5163,7 @@ dependencies = [
|
||||
"derive_more",
|
||||
"log",
|
||||
"new_debug_unreachable",
|
||||
"phf",
|
||||
"phf 0.13.1",
|
||||
"phf_codegen",
|
||||
"precomputed-hash",
|
||||
"rustc-hash 2.1.1",
|
||||
@@ -5302,6 +5437,22 @@ version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
|
||||
|
||||
[[package]]
|
||||
name = "simd_cesu8"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"
|
||||
dependencies = [
|
||||
"rustc_version",
|
||||
"simdutf8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simdutf8"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
|
||||
|
||||
[[package]]
|
||||
name = "simple_asn1"
|
||||
version = "0.6.4"
|
||||
@@ -5429,9 +5580,9 @@ checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
|
||||
|
||||
[[package]]
|
||||
name = "sse-stream"
|
||||
version = "0.2.1"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb4dc4d33c68ec1f27d386b5610a351922656e1fdf5c05bbaad930cd1519479a"
|
||||
checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-util",
|
||||
@@ -5460,7 +5611,7 @@ checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
|
||||
dependencies = [
|
||||
"new_debug_unreachable",
|
||||
"parking_lot",
|
||||
"phf_shared",
|
||||
"phf_shared 0.13.1",
|
||||
"precomputed-hash",
|
||||
]
|
||||
|
||||
@@ -5471,7 +5622,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
|
||||
dependencies = [
|
||||
"phf_generator",
|
||||
"phf_shared",
|
||||
"phf_shared 0.13.1",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
]
|
||||
@@ -6345,17 +6496,38 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter"
|
||||
version = "0.24.7"
|
||||
version = "0.25.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a5387dffa7ffc7d2dae12b50c6f7aab8ff79d6210147c6613561fc3d474c6f75"
|
||||
checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"regex",
|
||||
"regex-syntax",
|
||||
"serde_json",
|
||||
"streaming-iterator",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-c"
|
||||
version = "0.23.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "afd2b1bf1585dc2ef6d69e87d01db8adb059006649dd5f96f31aa789ee6e9c71"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-c-sharp"
|
||||
version = "0.23.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67f06accca7b45351758663b8215089e643d53bd9a660ce0349314263737fcb0"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-javascript"
|
||||
version = "0.23.1"
|
||||
@@ -6402,6 +6574,16 @@ dependencies = [
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tree-sitter-vb-dotnet"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "180e4a199378505f9305c3d01d6ece8a8d34035f310de1c727693f8a2296025e"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"tree-sitter-language",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "try-lock"
|
||||
version = "0.2.5"
|
||||
@@ -6879,7 +7061,7 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "57a9779e9f04d2ac1ce317aee707aa2f6b773afba7b931222bff6983843b1576"
|
||||
dependencies = [
|
||||
"phf",
|
||||
"phf 0.13.1",
|
||||
"phf_codegen",
|
||||
"string_cache",
|
||||
"string_cache_codegen",
|
||||
@@ -7595,7 +7777,7 @@ dependencies = [
|
||||
"lzma-rust2",
|
||||
"memchr",
|
||||
"nix",
|
||||
"pbkdf2 0.13.0",
|
||||
"pbkdf2",
|
||||
"ppmd-rust",
|
||||
"sha1 0.11.0",
|
||||
"time",
|
||||
|
||||
@@ -28,6 +28,8 @@ chrono = { version = "0.4", features = ["serde"] }
|
||||
mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] }
|
||||
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false }
|
||||
thiserror = "2"
|
||||
# Source files in UTF-16 or Windows-1252 (code graph, PLC, .NET).
|
||||
encoding_rs = "0.8"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
uuid = { version = "1", features = ["v4", "v5", "serde"] }
|
||||
|
||||
@@ -5,6 +5,9 @@ RUN cargo install dioxus-cli --version 0.7.3 --locked
|
||||
# Legal pages linked from the sidebar; the defaults are breakpilot.com's.
|
||||
ARG IMPRINT_URL=https://breakpilot.com/impressum
|
||||
ARG PRIVACY_URL=https://breakpilot.com/datenschutz
|
||||
# The release telemetry reports as service.version (CI passes the latest
|
||||
# release tag); empty falls back to the crate version.
|
||||
ARG PRUEFWERK_VERSION=
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
@@ -33,6 +33,8 @@ tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
# Calendar days and months of metering in Europe/Berlin (t72).
|
||||
chrono-tz = "0.10"
|
||||
mongodb = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
+238
-29
@@ -10,9 +10,15 @@ use crate::database::DatabasePool;
|
||||
use crate::llm::LlmClient;
|
||||
use crate::pipeline::orchestrator::PipelineOrchestrator;
|
||||
use crate::registry::RegistryClient;
|
||||
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
|
||||
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
|
||||
use crate::secrets::SecretBox;
|
||||
|
||||
/// A target whose billing changed, with its new billing (t72).
|
||||
pub type BillingChange = (
|
||||
mongodb::bson::oid::ObjectId,
|
||||
compliance_core::models::TargetBilling,
|
||||
);
|
||||
|
||||
/// Default maximum concurrent pentest sessions.
|
||||
const DEFAULT_MAX_CONCURRENT_SESSIONS: usize = 5;
|
||||
|
||||
@@ -133,6 +139,19 @@ impl ComplianceAgent {
|
||||
metric: &str,
|
||||
key: String,
|
||||
properties: serde_json::Value,
|
||||
) {
|
||||
self.emit_usage_quantity(tenant_id, metric, key, 1.0, properties);
|
||||
}
|
||||
|
||||
/// [`Self::emit_usage`] with a `quantity` other than one, such as the
|
||||
/// month's peak of extra targets (t72).
|
||||
pub fn emit_usage_quantity(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
metric: &str,
|
||||
key: String,
|
||||
quantity: f64,
|
||||
properties: serde_json::Value,
|
||||
) {
|
||||
let Some(registry) = self.registry.clone() else {
|
||||
return;
|
||||
@@ -142,7 +161,7 @@ impl ComplianceAgent {
|
||||
tenant_id: tenant_id.to_string(),
|
||||
product: registry.product().to_string(),
|
||||
metric: metric.to_string(),
|
||||
quantity: 1.0,
|
||||
quantity,
|
||||
occurred_at: chrono::Utc::now().to_rfc3339(),
|
||||
properties: Some(properties),
|
||||
};
|
||||
@@ -153,12 +172,106 @@ impl ComplianceAgent {
|
||||
});
|
||||
}
|
||||
|
||||
/// Store which of the tenant's targets are the plan's included ones and
|
||||
/// which are extra (t72), from the plan's `included_targets`. Without a
|
||||
/// registry every target is included. Best-effort: when the plan cannot
|
||||
/// be read or the targets not updated, the stored split stays.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The targets whose billing changed, with their new billing.
|
||||
pub async fn refresh_billing(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
db: &crate::database::Database,
|
||||
) -> Vec<BillingChange> {
|
||||
match self.plan(tenant_id).await {
|
||||
Some(plan) => {
|
||||
self.assign_billing(tenant_id, db, plan.included_targets)
|
||||
.await
|
||||
}
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tenant's plan for metering (t72), from its entitlement; without
|
||||
/// a registry, no limits at all. `None` when the registry did not
|
||||
/// answer: then the stored billing stays, and counted Prüfungen are
|
||||
/// neither checked nor charged.
|
||||
pub async fn plan(&self, tenant_id: &str) -> Option<crate::metering::Plan> {
|
||||
let Some(registry) = &self.registry else {
|
||||
return Some(crate::metering::Plan::default());
|
||||
};
|
||||
match registry.check_entitlement(tenant_id, None, None).await {
|
||||
Ok(check) => Some(crate::metering::Plan {
|
||||
included_targets: check.included_targets(),
|
||||
limits: check.plan_limits(),
|
||||
}),
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "plan not read, metering waits: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Store the billing of the tenant's targets for a plan that includes
|
||||
/// `included` targets; best-effort.
|
||||
async fn assign_billing(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
db: &crate::database::Database,
|
||||
included: Option<u32>,
|
||||
) -> Vec<BillingChange> {
|
||||
let changes = match crate::metering::assign_billing(db, included).await {
|
||||
Ok(changes) => {
|
||||
if !changes.is_empty() {
|
||||
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
|
||||
}
|
||||
changes
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(tenant_id, "target billing not updated: {e}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
self.report_extra_peak(tenant_id, db).await;
|
||||
changes
|
||||
}
|
||||
|
||||
/// Send the month's peak of extra targets as `target.extra` when it
|
||||
/// rose, and once a day besides (t72). The key carries the peak, so the
|
||||
/// registry keeps every rise and drops the daily re-send as a duplicate;
|
||||
/// billing takes the highest quantity per tenant-month. Count only: no
|
||||
/// target names leave Prüfwerk. Best-effort.
|
||||
async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) {
|
||||
let now = chrono::Utc::now();
|
||||
match crate::metering::record_extra_peak(db, now).await {
|
||||
Ok(Some(peak)) => {
|
||||
let (month, _) = crate::metering::berlin_period(now);
|
||||
self.emit_usage_quantity(
|
||||
tenant_id,
|
||||
"target.extra",
|
||||
format!("target-extra:{tenant_id}:{month}:{peak}"),
|
||||
f64::from(peak),
|
||||
serde_json::json!({ "month": month }),
|
||||
);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
|
||||
/// run at once, and a request for a target that is already being scanned is
|
||||
/// coalesced — it becomes the one pending follow-up that this task runs next,
|
||||
/// or it is dropped if a follow-up is already pending. A scheduled scan
|
||||
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
|
||||
/// (click, webhook, scheduler, demo seed) comes through here.
|
||||
/// run at once, a person's before scheduled and webhook ones, and a request
|
||||
/// for a target that is already queued or being scanned is coalesced — it
|
||||
/// becomes the one pending follow-up that this task runs next, it takes over
|
||||
/// a queued scan that was not a person's, or it is dropped as covered. A
|
||||
/// scheduled scan first waits a random [`crate::scan_gate::start_delay`].
|
||||
/// Every trigger (click, webhook, scheduler, demo seed) comes through here.
|
||||
///
|
||||
/// Each request is recorded at once as a `queued` run, which shows that it
|
||||
/// waits for a slot (t84); a request that will not run has its queued run
|
||||
/// removed again.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -180,15 +293,22 @@ impl ComplianceAgent {
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
}
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
let run_id = queue_run(&db, target_id, &trigger).await;
|
||||
let key = ScanGate::key(tenant_id, target_id);
|
||||
match self.scan_gate.admit(&key, trigger.clone()) {
|
||||
match self
|
||||
.scan_gate
|
||||
.admit(&key, Job::new(trigger, run_id.clone()))
|
||||
{
|
||||
Admission::Run => {}
|
||||
Admission::Coalesced => {
|
||||
Admission::Coalesced { replaced } => {
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
took_over = replaced.is_some(),
|
||||
"scan already running; follow-up queued"
|
||||
);
|
||||
discard_queued_run(&db, replaced.as_deref()).await;
|
||||
return Ok(());
|
||||
}
|
||||
Admission::Dropped => {
|
||||
@@ -197,57 +317,83 @@ impl ComplianceAgent {
|
||||
target_id,
|
||||
"scan and follow-up already queued; dropped"
|
||||
);
|
||||
discard_queued_run(&db, run_id.as_deref()).await;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
// Released on panic or cancellation; a normal finish disarms it.
|
||||
let held = HeldTarget::new(&self.scan_gate, key.clone());
|
||||
let mut trigger = trigger;
|
||||
let result = loop {
|
||||
let outcome = {
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
self.run_one_target_scan(tenant_id, target_id, trigger.clone())
|
||||
.await
|
||||
};
|
||||
// The scan to run is the one current when the slot is granted: a
|
||||
// person's request may have taken it over while it waited.
|
||||
let (slot, job) = self
|
||||
.scan_gate
|
||||
.start(&key)
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await;
|
||||
drop(slot);
|
||||
if let Err(e) = &outcome {
|
||||
tracing::error!(tenant_id, target_id, "scan failed: {e}");
|
||||
fail_queued_run(&db, job.run_id.as_deref(), e).await;
|
||||
}
|
||||
match self.scan_gate.finish(&key) {
|
||||
Some(next) => trigger = next,
|
||||
None => break outcome,
|
||||
if !self.scan_gate.finish(&key) {
|
||||
break outcome;
|
||||
}
|
||||
};
|
||||
held.disarm();
|
||||
result
|
||||
}
|
||||
|
||||
/// One scan of a target, with no gating: the pipeline plus its usage event.
|
||||
/// One scan of a target, with no gating: the pipeline plus its usage event,
|
||||
/// recorded on the run that waited for it and charged as `job` says.
|
||||
async fn run_one_target_scan(
|
||||
&self,
|
||||
tenant_id: &str,
|
||||
target_id: &str,
|
||||
trigger: compliance_core::models::ScanTrigger,
|
||||
job: &Job,
|
||||
) -> Result<(), crate::error::AgentError> {
|
||||
let trigger = job.trigger.clone();
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
// Whether this target is included or extra decides whether its scan
|
||||
// counts, and the plan's limits whether a counted one may run (t72).
|
||||
let plan = self.plan(tenant_id).await;
|
||||
if let Some(plan) = &plan {
|
||||
self.assign_billing(tenant_id, &db, plan.included_targets)
|
||||
.await;
|
||||
}
|
||||
let orchestrator =
|
||||
PipelineOrchestrator::new(self.config.clone(), tenant_id, db.clone(), self.llm.clone())
|
||||
.with_nuget_license_cache(self.nuget_license_cache.clone())
|
||||
.with_exploit_cache(self.exploit_cache.clone())
|
||||
.with_advisory_index(self.advisory_index.clone());
|
||||
.with_advisory_index(self.advisory_index.clone())
|
||||
.with_plan_limits(plan.map(|p| p.limits))
|
||||
.with_charged_as(job.charged_as.clone());
|
||||
let started = chrono::Utc::now();
|
||||
let scanned = orchestrator.run_target(target_id, trigger.clone()).await?;
|
||||
let outcome = orchestrator
|
||||
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
|
||||
.await?;
|
||||
// Support's scans are ours, not the customer's usage; a scheduled scan
|
||||
// skipped because nothing changed scanned nothing (#465).
|
||||
if scanned && trigger != compliance_core::models::ScanTrigger::Support {
|
||||
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
|
||||
self.emit_usage(
|
||||
tenant_id,
|
||||
"scan.completed",
|
||||
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
|
||||
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
|
||||
serde_json::json!({
|
||||
"target_id": target_id,
|
||||
"trigger": format!("{trigger:?}"),
|
||||
"attribution": outcome.attribution,
|
||||
"counted": outcome.chargeable,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(day) = &outcome.booked_prueftag {
|
||||
self.emit_usage(
|
||||
tenant_id,
|
||||
"prueftag.booked",
|
||||
format!("prueftag:{tenant_id}:{target_id}:{day}"),
|
||||
serde_json::json!({ "target_id": target_id, "day": day }),
|
||||
);
|
||||
}
|
||||
self.notify_new_findings(tenant_id, target_id, &db, started);
|
||||
@@ -295,7 +441,7 @@ impl ComplianceAgent {
|
||||
// slot too. Each PR is distinct work, so it is not coalesced.
|
||||
let _slot = self
|
||||
.scan_gate
|
||||
.slot()
|
||||
.slot(Priority::Background)
|
||||
.await
|
||||
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
|
||||
let db = self.db_pool.for_tenant_id(tenant_id).await?;
|
||||
@@ -371,6 +517,69 @@ impl ComplianceAgent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a scan request for `target_id` as a run waiting for a slot (t84),
|
||||
/// so it shows at once. Returns its id, or `None` when it could not be
|
||||
/// written: the scan then runs on a run of its own when it starts.
|
||||
async fn queue_run(
|
||||
db: &crate::database::Database,
|
||||
target_id: &str,
|
||||
trigger: &compliance_core::models::ScanTrigger,
|
||||
) -> Option<String> {
|
||||
let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone());
|
||||
match db.scan_runs().insert_one(&run).await {
|
||||
Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()),
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, "queued scan run not recorded: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the queued run `run_id` of a request that will not run, because
|
||||
/// another queued scan covers it or took it over. A run that has started
|
||||
/// meanwhile is kept.
|
||||
async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) {
|
||||
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
|
||||
return;
|
||||
};
|
||||
if let Err(e) = db
|
||||
.scan_runs()
|
||||
.delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" })
|
||||
.await
|
||||
{
|
||||
tracing::warn!(run_id = %oid, "queued scan run not removed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the queued run `run_id` as failed when its scan ended with `error`
|
||||
/// before it started (an unknown target, an unreachable database), so it does
|
||||
/// not stay queued. A run the scan started records its own outcome.
|
||||
async fn fail_queued_run(
|
||||
db: &crate::database::Database,
|
||||
run_id: Option<&str>,
|
||||
error: &crate::error::AgentError,
|
||||
) {
|
||||
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
|
||||
return;
|
||||
};
|
||||
let (code, message) = error.run_failure();
|
||||
if let Err(e) = db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
mongodb::bson::doc! { "_id": oid, "status": "queued" },
|
||||
mongodb::bson::doc! { "$set": {
|
||||
"status": "failed",
|
||||
"error_message": message,
|
||||
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
|
||||
"completed_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(run_id = %oid, "queued scan run not closed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Findings of `target_id` first stored since `since`, by severity; `None`
|
||||
/// when there are none.
|
||||
async fn new_findings_summary(
|
||||
|
||||
@@ -79,9 +79,14 @@ async fn load_inputs(
|
||||
.map_err(load_err)?,
|
||||
)
|
||||
.await,
|
||||
// A run still waiting for a slot has examined nothing yet (t84).
|
||||
last_run: db
|
||||
.scan_runs()
|
||||
.find_one(by_target)
|
||||
.find_one({
|
||||
let mut started = by_target;
|
||||
started.insert("status", doc! { "$ne": "queued" });
|
||||
started
|
||||
})
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(load_err)?,
|
||||
|
||||
@@ -6,7 +6,9 @@ use axum::Json;
|
||||
use mongodb::bson::doc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::models::graph::{CodeEdge, CodeNode, GraphBuildRun, ImpactAnalysis};
|
||||
use compliance_core::models::graph::{
|
||||
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
|
||||
};
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
@@ -188,6 +190,60 @@ pub async fn get_nodes(
|
||||
}))
|
||||
}
|
||||
|
||||
/// What the target page shows of a code graph.
|
||||
#[derive(Serialize)]
|
||||
pub struct GraphSummary {
|
||||
/// Declarations: functions, methods, types, PLC blocks (nodes that are
|
||||
/// not files).
|
||||
pub units: u32,
|
||||
pub entry_points: u32,
|
||||
/// Language codes, sorted (`c`, `csharp`, `structured_text`, …).
|
||||
pub languages: Vec<String>,
|
||||
/// Source files left out because they could not be read as text; 0 when
|
||||
/// none were, or the build did not count them.
|
||||
pub unreadable_files: u32,
|
||||
}
|
||||
|
||||
impl GraphSummary {
|
||||
/// The summary of a completed build; `None` for one still running, a
|
||||
/// failed one, or one stored before its files and entry points were
|
||||
/// counted.
|
||||
fn of(build: GraphBuildRun) -> Option<Self> {
|
||||
if build.status != GraphBuildStatus::Completed {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
units: build.node_count.saturating_sub(build.file_count?),
|
||||
entry_points: build.entry_point_count?,
|
||||
languages: build.languages_parsed,
|
||||
// Not `?`: a build from before this count still shows its card.
|
||||
unreadable_files: build.unreadable_file_count.unwrap_or(0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/summary — The latest build's counts, without
|
||||
/// loading any node: `data` is `null` when there is none to show.
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_summary(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(repo_id): Path<String>,
|
||||
) -> Result<Json<ApiResponse<Option<GraphSummary>>>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let build = db
|
||||
.graph_builds()
|
||||
.find_one(doc! { "repo_id": &repo_id })
|
||||
.sort(doc! { "started_at": -1 })
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(Json(ApiResponse {
|
||||
data: build.and_then(GraphSummary::of),
|
||||
total: None,
|
||||
page: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// GET /api/v1/graph/:repo_id/communities — List detected communities
|
||||
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
|
||||
pub async fn get_communities(
|
||||
@@ -355,7 +411,9 @@ pub async fn get_file_content(
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
|
||||
let content =
|
||||
compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
|
||||
|
||||
// Cap at 10,000 lines
|
||||
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
|
||||
@@ -434,10 +492,17 @@ pub async fn trigger_build(
|
||||
}
|
||||
};
|
||||
|
||||
// A PLC target's graph is its POUs, as the scan builds it.
|
||||
let plc_files = crate::pipeline::plan::build_scan_plan(&repo)
|
||||
.has(compliance_core::models::ScanType::PlcControlLogic)
|
||||
.then(|| crate::pipeline::plc::read_tree(&repo_path));
|
||||
let source = match &plc_files {
|
||||
Some(files) => crate::pipeline::graph_build::GraphSource::Plc(files),
|
||||
None => crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
|
||||
};
|
||||
let graph_build_id = uuid::Uuid::new_v4().to_string();
|
||||
let engine = compliance_graph::GraphEngine::new(50_000);
|
||||
|
||||
match engine.build_graph(&repo_path, &repo_id, &graph_build_id) {
|
||||
match crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) {
|
||||
Ok((code_graph, build_run)) => {
|
||||
let store = compliance_graph::graph::persistence::GraphStore::new(db.inner());
|
||||
let _ = store.delete_repo_graph(&repo_id).await;
|
||||
@@ -460,3 +525,48 @@ pub async fn trigger_build(
|
||||
serde_json::json!({ "status": "graph_build_triggered" }),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn completed(nodes: u32, files: Option<u32>, entry_points: Option<u32>) -> GraphBuildRun {
|
||||
let mut build = GraphBuildRun::new("t".to_string());
|
||||
build.status = GraphBuildStatus::Completed;
|
||||
build.node_count = nodes;
|
||||
build.file_count = files;
|
||||
build.entry_point_count = entry_points;
|
||||
build.languages_parsed = vec!["c".to_string()];
|
||||
build
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completed_build_counts_its_declarations() {
|
||||
let summary = GraphSummary::of(completed(120, Some(20), Some(7))).expect("shown");
|
||||
assert_eq!((summary.units, summary.entry_points), (100, 7));
|
||||
assert_eq!(summary.languages, ["c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_failed_and_uncounted_builds_show_nothing() {
|
||||
let mut running = completed(10, Some(2), Some(1));
|
||||
running.status = GraphBuildStatus::Running;
|
||||
assert!(GraphSummary::of(running).is_none());
|
||||
let mut failed = completed(10, Some(2), Some(1));
|
||||
failed.status = GraphBuildStatus::Failed;
|
||||
assert!(GraphSummary::of(failed).is_none());
|
||||
assert!(GraphSummary::of(completed(10, None, None)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_files_are_shown_and_an_uncounted_build_has_none() {
|
||||
let mut build = completed(10, Some(2), Some(1));
|
||||
build.unreadable_file_count = Some(3);
|
||||
assert_eq!(GraphSummary::of(build).expect("shown").unreadable_files, 3);
|
||||
let uncounted = completed(10, Some(2), Some(1));
|
||||
assert_eq!(
|
||||
GraphSummary::of(uncounted).expect("shown").unreadable_files,
|
||||
0
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! The tenant's metering this month, for the dashboard's usage view (t72).
|
||||
|
||||
use axum::extract::Extension;
|
||||
use axum::http::StatusCode;
|
||||
use axum::Json;
|
||||
use serde::Serialize;
|
||||
|
||||
use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use super::dto::{tenant_db, AgentExt};
|
||||
use crate::metering::{month_summary, MonthSummary};
|
||||
|
||||
/// The usage view: what was used this month, and what the plan allows.
|
||||
#[derive(Debug, Serialize)]
|
||||
struct UsageView {
|
||||
/// What was used.
|
||||
#[serde(flatten)]
|
||||
used: MonthSummary,
|
||||
/// Whether the plan could be read; without it the limits are unknown,
|
||||
/// not unlimited.
|
||||
plan_known: bool,
|
||||
/// The plan's included targets; `None` is unlimited.
|
||||
included_targets: Option<u32>,
|
||||
/// The monthly quota; `None` is unlimited.
|
||||
monthly_pruefungen: Option<u32>,
|
||||
/// The customer's Prüftag cap; `None` is no cap.
|
||||
prueftag_cap: Option<u32>,
|
||||
}
|
||||
|
||||
/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra
|
||||
/// targets this month (Europe/Berlin), with the plan's limits.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `500` when the counters cannot be read.
|
||||
pub async fn get_usage(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
let used = month_summary(&db, chrono::Utc::now()).await.map_err(|e| {
|
||||
tracing::error!(tenant_id = %tenant.0.tenant_id, "usage not read: {e}");
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
let plan = agent.plan(&tenant.0.tenant_id).await;
|
||||
let view = UsageView {
|
||||
used,
|
||||
plan_known: plan.is_some(),
|
||||
included_targets: plan.and_then(|p| p.included_targets),
|
||||
monthly_pruefungen: plan.and_then(|p| p.limits.monthly_pruefungen),
|
||||
prueftag_cap: plan.and_then(|p| p.limits.prueftag_cap),
|
||||
};
|
||||
Ok(Json(serde_json::json!({ "data": view })))
|
||||
}
|
||||
@@ -14,6 +14,7 @@ pub mod licenses;
|
||||
pub mod manual_findings;
|
||||
pub mod mcp_servers;
|
||||
pub mod mcp_tokens;
|
||||
pub mod metering;
|
||||
pub mod notifications;
|
||||
pub mod onboarding;
|
||||
pub mod oscal;
|
||||
|
||||
@@ -114,7 +114,7 @@ pub async fn list_targets(
|
||||
// `join!` borrows its futures' arguments, so the collections need names.
|
||||
let (runs, findings) = (db.scan_runs(), db.findings());
|
||||
let (mut last_scans, counts) = tokio::join!(
|
||||
latest_scan_runs(&runs, ids.clone()),
|
||||
latest_scan_runs(&runs, ids.clone(), true),
|
||||
findings_counts(&findings, ids),
|
||||
);
|
||||
let data = targets
|
||||
@@ -179,10 +179,13 @@ impl TargetFilter {
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest scan run of each target in `target_ids`, in one query.
|
||||
/// The newest scan run of each target in `target_ids`, in one query; with
|
||||
/// `with_queued`, also a run still waiting for a slot (t84), which the
|
||||
/// dashboard shows but which has scanned nothing yet.
|
||||
pub(crate) async fn latest_scan_runs(
|
||||
runs: &mongodb::Collection<ScanRun>,
|
||||
target_ids: Vec<String>,
|
||||
with_queued: bool,
|
||||
) -> HashMap<String, ScanRun> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
@@ -190,8 +193,12 @@ pub(crate) async fn latest_scan_runs(
|
||||
return HashMap::new();
|
||||
}
|
||||
// Runs store their target's id as `repo_id`.
|
||||
let mut matching = doc! { "repo_id": { "$in": target_ids } };
|
||||
if !with_queued {
|
||||
matching.insert("status", doc! { "$ne": "queued" });
|
||||
}
|
||||
let pipeline = vec![
|
||||
doc! { "$match": { "repo_id": { "$in": target_ids } } },
|
||||
doc! { "$match": matching },
|
||||
doc! { "$sort": { "started_at": -1 } },
|
||||
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
|
||||
];
|
||||
@@ -999,6 +1006,100 @@ pub async fn detect_target(
|
||||
}))
|
||||
}
|
||||
|
||||
/// Why a scan is asked for (`POST /api/v1/targets/{id}/scan?reason=…`).
|
||||
#[derive(Debug, Default, serde::Deserialize)]
|
||||
pub struct ScanReason {
|
||||
/// `new_content` after the customer created the target or uploaded
|
||||
/// files (t72): it runs only when something changed, as a change-driven
|
||||
/// Prüfung. Absent: the customer asks for a Prüfung, which always runs
|
||||
/// and counts.
|
||||
#[serde(default)]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// The trigger of a scan the customer (`staff: false`) or support asked
|
||||
/// for, for `reason`. Support's scans are never the customer's usage.
|
||||
fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::models::ScanTrigger {
|
||||
use compliance_core::models::ScanTrigger;
|
||||
if staff {
|
||||
ScanTrigger::Support
|
||||
} else if reason == Some("new_content") {
|
||||
ScanTrigger::NewContent
|
||||
} else {
|
||||
ScanTrigger::Manual
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap
|
||||
/// the extra target `{id}` with.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SwapRequest {
|
||||
/// The id of the included target that becomes extra.
|
||||
pub with: String,
|
||||
}
|
||||
|
||||
/// The JSON `error` of a refused swap, for the dashboard to word.
|
||||
fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static str {
|
||||
use compliance_core::models::SwapRefusal;
|
||||
match refusal {
|
||||
SwapRefusal::Unlimited => "swap_unlimited",
|
||||
SwapRefusal::NotExtra => "swap_not_extra",
|
||||
SwapRefusal::NotIncluded => "swap_not_included",
|
||||
SwapRefusal::Locked => "swap_locked",
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/billing/swap — swap the extra target `{id}`
|
||||
/// with the included target `with` (t72): `{id}` becomes included and stays
|
||||
/// so until the end of the calendar month, `with` becomes extra at once.
|
||||
/// The number of extra targets, and so the extra-target line, is the same.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `404` for a target that is not an active one of the tenant, `409` with
|
||||
/// the reason when the swap is not allowed, `503` when the plan cannot be
|
||||
/// read.
|
||||
pub async fn swap_target_billing(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Json(req): Json<SwapRequest>,
|
||||
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
|
||||
let refuse =
|
||||
|status: StatusCode, error: &str| (status, Json(serde_json::json!({ "error": error })));
|
||||
let incoming = parse_oid(&id).map_err(|s| refuse(s, "invalid_id"))?;
|
||||
let outgoing = parse_oid(&req.with).map_err(|s| refuse(s, "invalid_id"))?;
|
||||
let db = tenant_db(&agent, &tenant)
|
||||
.await
|
||||
.map_err(|s| refuse(s, "database_unavailable"))?;
|
||||
let tenant_id = tenant.0.tenant_id.as_str();
|
||||
let plan = agent
|
||||
.plan(tenant_id)
|
||||
.await
|
||||
.ok_or_else(|| refuse(StatusCode::SERVICE_UNAVAILABLE, "plan_unavailable"))?;
|
||||
let outcome = crate::metering::swap(
|
||||
&db,
|
||||
incoming,
|
||||
outgoing,
|
||||
plan.included_targets.is_some(),
|
||||
chrono::Utc::now(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(tenant_id, "swap failed: {e}");
|
||||
refuse(StatusCode::INTERNAL_SERVER_ERROR, "swap_failed")
|
||||
})?;
|
||||
match outcome {
|
||||
None => Err(refuse(StatusCode::NOT_FOUND, "target_not_found")),
|
||||
Some(Err(refusal)) => Err(refuse(StatusCode::CONFLICT, swap_refusal_code(refusal))),
|
||||
Some(Ok(())) => {
|
||||
agent.refresh_billing(tenant_id, &db).await;
|
||||
tracing::info!(tenant_id, incoming = %id, outgoing = %req.with, "targets swapped");
|
||||
Ok(Json(serde_json::json!({ "data": { "swapped": true } })))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
|
||||
///
|
||||
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
|
||||
@@ -1008,6 +1109,7 @@ pub async fn trigger_target_scan(
|
||||
Extension(agent): AgentExt,
|
||||
tenant: TenantCtx,
|
||||
Path(id): Path<String>,
|
||||
Query(reason): Query<ScanReason>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let oid = parse_oid(&id)?;
|
||||
let db = tenant_db(&agent, &tenant).await?;
|
||||
@@ -1024,12 +1126,7 @@ pub async fn trigger_target_scan(
|
||||
|
||||
let agent_clone = (*agent).clone();
|
||||
let tenant_id = tenant.0.tenant_id.clone();
|
||||
// A scan support starts is not the customer's usage.
|
||||
let trigger = if tenant.0.staff.is_some() {
|
||||
compliance_core::models::ScanTrigger::Support
|
||||
} else {
|
||||
compliance_core::models::ScanTrigger::Manual
|
||||
};
|
||||
let trigger = requested_trigger(tenant.0.staff.is_some(), reason.reason.as_deref());
|
||||
tokio::spawn(async move {
|
||||
// Always the unified target pipeline — this endpoint is about an
|
||||
// onboarded target by construction, independent of the global
|
||||
@@ -1045,6 +1142,22 @@ pub async fn trigger_target_scan(
|
||||
mod filter_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_scan_asked_for_new_content_is_change_driven() {
|
||||
use compliance_core::models::ScanTrigger;
|
||||
assert_eq!(requested_trigger(false, None), ScanTrigger::Manual);
|
||||
assert_eq!(
|
||||
requested_trigger(false, Some("new_content")),
|
||||
ScanTrigger::NewContent
|
||||
);
|
||||
assert_eq!(requested_trigger(false, Some("other")), ScanTrigger::Manual);
|
||||
assert_eq!(
|
||||
requested_trigger(true, Some("new_content")),
|
||||
ScanTrigger::Support,
|
||||
"support's scans are never the customer's usage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_filter_matches_its_targets() {
|
||||
let filter = TargetFilter {
|
||||
|
||||
@@ -18,6 +18,8 @@ use mongodb::bson::{doc, Document};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use compliance_core::auth::{validate_service_token, JwksState};
|
||||
// Re-exported: the VEX, evidence and change-detection code import them from here.
|
||||
pub use compliance_core::build_info::{BUILD_COMMIT, BUILD_VERSION};
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
|
||||
@@ -432,23 +434,6 @@ pub async fn usage(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The build version: `PRUEFWERK_VERSION` at compile time (CI: the latest
|
||||
/// release tag without its `v`), else the crate version.
|
||||
pub const BUILD_VERSION: &str =
|
||||
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
|
||||
|
||||
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI:
|
||||
/// the full SHA), else "unknown". The portal's version line shows 8 characters.
|
||||
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
|
||||
|
||||
/// A Docker build arg left empty is an empty env var, not an unset one.
|
||||
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
|
||||
match value {
|
||||
Some(v) if !v.is_empty() => v,
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /api/v1/platform/version` — contract handshake (§4.1 /version).
|
||||
pub async fn version(State(st): State<PlatformState>) -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({
|
||||
@@ -575,7 +560,7 @@ pub async fn list_targets(
|
||||
.collect();
|
||||
let runs = db.scan_runs();
|
||||
let (mut last_scans, open, vulns) = tokio::join!(
|
||||
super::onboarding::latest_scan_runs(&runs, ids.clone()),
|
||||
super::onboarding::latest_scan_runs(&runs, ids.clone(), false),
|
||||
open_findings_counts(&db, ids.clone()),
|
||||
open_vulnerabilities_counts(&db, ids),
|
||||
);
|
||||
@@ -807,20 +792,6 @@ pub async fn delete_git_source(
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod build_info_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unset_or_empty_build_value_falls_back() {
|
||||
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
|
||||
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
|
||||
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
|
||||
assert!(!BUILD_VERSION.is_empty());
|
||||
assert!(!BUILD_COMMIT.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod target_count_tests {
|
||||
use super::*;
|
||||
|
||||
@@ -15,6 +15,7 @@ pub fn build_router() -> Router {
|
||||
.route("/api/v1/stats/overview", get(handlers::stats_overview))
|
||||
// The tenant's projects (owned by the registry), for assigning targets.
|
||||
.route("/api/v1/projects", get(handlers::projects::list_projects))
|
||||
.route("/api/v1/metering/usage", get(handlers::metering::get_usage))
|
||||
// Whether the caller may use Prüfwerk at all: answered by the
|
||||
// authentication and entitlement layers in front of it (a blocked
|
||||
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
|
||||
@@ -84,6 +85,10 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/targets/{id}/scan",
|
||||
post(handlers::onboarding::trigger_target_scan),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/billing/swap",
|
||||
post(handlers::onboarding::swap_target_billing),
|
||||
)
|
||||
.route("/api/v1/findings", get(handlers::list_findings))
|
||||
.route(
|
||||
"/api/v1/findings/variants",
|
||||
@@ -194,6 +199,10 @@ pub fn build_router() -> Router {
|
||||
"/api/v1/graph/{repo_id}/nodes",
|
||||
get(handlers::graph::get_nodes),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/summary",
|
||||
get(handlers::graph::get_summary),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/graph/{repo_id}/communities",
|
||||
get(handlers::graph::get_communities),
|
||||
|
||||
@@ -215,7 +215,7 @@ pub async fn grounded_surface_findings(
|
||||
|
||||
/// Read a window of lines around `line` (1-based) from `repo_path/file`.
|
||||
fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option<CandidateRegion> {
|
||||
let content = std::fs::read_to_string(repo_path.join(file)).ok()?;
|
||||
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
if lines.is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -116,8 +116,8 @@ pub const SURFACES: &[Surface] = &[
|
||||
|
||||
/// Source file extensions worth reading (skip binaries/assets/lockfiles).
|
||||
const CODE_EXTS: &[&str] = &[
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "kt", "c", "h", "cc",
|
||||
"cpp", "hpp",
|
||||
"py", "js", "ts", "tsx", "jsx", "go", "java", "rb", "php", "rs", "cs", "vb", "kt", "c", "h",
|
||||
"cc", "cpp", "hpp",
|
||||
];
|
||||
/// Directories never worth walking.
|
||||
const SKIP_DIRS: &[&str] = &[
|
||||
@@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
|
||||
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
|
||||
continue;
|
||||
}
|
||||
let Ok(content) = std::fs::read_to_string(path) else {
|
||||
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
|
||||
let Ok(content) = compliance_core::encoding::read_source(path) else {
|
||||
continue;
|
||||
};
|
||||
let rel = path
|
||||
@@ -286,6 +287,24 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_1252_file_is_read() {
|
||||
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// "Prüfung" as Windows-1252 writes it: 0xFC for "ü".
|
||||
let path = dir.join("app/Auth.cs");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&path,
|
||||
b"// Pr\xFCfung\nbool Login(string u, string p) { }\n",
|
||||
)
|
||||
.unwrap();
|
||||
let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(regions.len(), 1);
|
||||
assert!(regions[0].content.contains("Prüfung"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn firmware_update_code_is_read_but_not_the_vendor_hal() {
|
||||
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
|
||||
|
||||
@@ -42,6 +42,11 @@ pub enum AgentError {
|
||||
#[error("the archive password set on the target does not open it")]
|
||||
ArchivePasswordWrong,
|
||||
|
||||
/// A counted Prüfung the plan does not allow now (t72): not an error of
|
||||
/// the scan, which ends without scanning.
|
||||
#[error("not run: {0:?}")]
|
||||
NotAdmitted(compliance_core::models::Refusal),
|
||||
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
@@ -73,6 +78,7 @@ impl AgentError {
|
||||
| Self::Config(_)
|
||||
| Self::Secret(_)
|
||||
| Self::Exec(_)
|
||||
| Self::NotAdmitted(_)
|
||||
| Self::Other(_) => (
|
||||
RunErrorCode::Internal,
|
||||
"the scan stopped because of an internal error",
|
||||
|
||||
@@ -17,6 +17,7 @@ pub mod ingest;
|
||||
pub mod license_conclusions;
|
||||
pub mod lifecycle;
|
||||
pub mod llm;
|
||||
pub mod metering;
|
||||
pub mod pentest;
|
||||
pub mod pipeline;
|
||||
pub mod rag;
|
||||
|
||||
@@ -43,14 +43,15 @@ struct OrphanRule {
|
||||
}
|
||||
|
||||
/// Code scans are what customers see, so they get their own `interrupted`
|
||||
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
|
||||
/// status, also those still waiting for a slot: the queue lives in the agent's
|
||||
/// memory and is gone after a restart (t84). The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
|
||||
/// pentest are off in production, and graph and embedding builds are steps of
|
||||
/// a scan. A paused pentest session can only be resumed through in-memory
|
||||
/// state, so after a restart it is as dead as a running one.
|
||||
const ORPHAN_RULES: [OrphanRule; 5] = [
|
||||
OrphanRule {
|
||||
collection: "scan_runs",
|
||||
open: &["running"],
|
||||
open: &["queued", "running"],
|
||||
closed_as: "interrupted",
|
||||
},
|
||||
OrphanRule {
|
||||
@@ -218,12 +219,16 @@ async fn targets_to_resume(
|
||||
.await?;
|
||||
let mut out = Vec::new();
|
||||
for id in ids.iter().filter_map(|v| v.as_str()) {
|
||||
// Only scans that had started count: one interrupted while it still
|
||||
// waited for a slot cannot be what stopped the agent. It never got a
|
||||
// start time of its own, so it still starts when it was requested.
|
||||
let interruptions = db
|
||||
.scan_runs()
|
||||
.count_documents(doc! {
|
||||
"repo_id": id,
|
||||
"status": "interrupted",
|
||||
"completed_at": { "$gte": window },
|
||||
"$expr": { "$ne": ["$started_at", "$queued_at"] },
|
||||
})
|
||||
.await?;
|
||||
if interruptions > MAX_RECENT_INTERRUPTIONS {
|
||||
@@ -243,12 +248,25 @@ async fn targets_to_resume(
|
||||
.await?;
|
||||
if active > 0 {
|
||||
// Resumed as it was started: a scan a person started runs even when
|
||||
// nothing changed since the last completed one (#465).
|
||||
let trigger = db
|
||||
// nothing changed since the last completed one (#465). Of a running
|
||||
// scan and its queued follow-up, a person's wins.
|
||||
let triggers = db
|
||||
.scan_runs()
|
||||
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
|
||||
.await?
|
||||
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
|
||||
.distinct(
|
||||
"trigger",
|
||||
doc! { "repo_id": id, "status": "interrupted", "completed_at": closed },
|
||||
)
|
||||
.await?;
|
||||
let triggers: Vec<ScanTrigger> = triggers
|
||||
.into_iter()
|
||||
.filter_map(|t| mongodb::bson::from_bson(t).ok())
|
||||
.collect();
|
||||
let trigger = triggers
|
||||
.iter()
|
||||
.find(|t| t.started_by_person())
|
||||
.or_else(|| triggers.first())
|
||||
.cloned()
|
||||
.unwrap_or(ScanTrigger::Scheduled);
|
||||
out.push((id.to_string(), trigger));
|
||||
}
|
||||
}
|
||||
@@ -365,10 +383,11 @@ mod tests {
|
||||
let archived = insert(archived_target).await;
|
||||
let earlier_only = insert(target("earlier-only")).await;
|
||||
|
||||
// Arrange: runs left open, plus one interrupted an hour ago.
|
||||
// The scan to resume was started by a person.
|
||||
// Arrange: runs left open, plus one interrupted an hour ago. The
|
||||
// target to resume has a scheduled scan running and a person's
|
||||
// follow-up queued (t84): one interruption, resumed as the person's.
|
||||
for (id, trigger) in [
|
||||
(&resumes, ScanTrigger::Manual),
|
||||
(&resumes, ScanTrigger::Scheduled),
|
||||
(&looping, ScanTrigger::Scheduled),
|
||||
(&archived, ScanTrigger::Scheduled),
|
||||
] {
|
||||
@@ -377,6 +396,10 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
db.scan_runs()
|
||||
.insert_one(ScanRun::queued(resumes.clone(), ScanTrigger::Manual))
|
||||
.await
|
||||
.unwrap();
|
||||
for id in [&looping, &earlier_only] {
|
||||
let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled);
|
||||
run.status = compliance_core::models::ScanRunStatus::Interrupted;
|
||||
@@ -423,6 +446,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_code_scans_are_closed_at_startup_too() {
|
||||
let scan_rule = ORPHAN_RULES
|
||||
.iter()
|
||||
.find(|r| r.collection == "scan_runs")
|
||||
.expect("scan_runs rule");
|
||||
assert!(scan_rule.open.contains(&"queued"));
|
||||
assert!(scan_rule.open.contains(&"running"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_scans_are_interrupted_not_failed() {
|
||||
let scan_rule = ORPHAN_RULES
|
||||
|
||||
@@ -861,7 +861,7 @@ fn read_surrounding_context(finding: &Finding) -> Option<String> {
|
||||
let line = finding.line_number? as usize;
|
||||
|
||||
// Try to read the file — this works because the repo is cloned locally
|
||||
let content = std::fs::read_to_string(file_path).ok()?;
|
||||
let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?;
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
|
||||
let start = line.saturating_sub(25);
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
//! Metering of a tenant's Prüfungen (t72).
|
||||
//!
|
||||
//! **Included and extra targets.** The oldest active targets are included,
|
||||
//! up to the plan's `included_targets`; every other active target is extra.
|
||||
//! The split is stored on each target ([`OnboardedTarget::billing`]) and
|
||||
//! brought up to date before each scan and when a target is created, so
|
||||
//! archiving an included target moves the oldest extra one up.
|
||||
//!
|
||||
//! **Counters.** A counted Prüfung is checked against the plan when it
|
||||
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
|
||||
//! when it completes ([`charge`]): to the month's quota, else to the
|
||||
//! target's Prüftag for the day, booking one if none is. Months and days
|
||||
//! are calendar ones in Europe/Berlin. A run that fails because of us is
|
||||
//! never charged, so nothing is refunded.
|
||||
//!
|
||||
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::{doc, oid::ObjectId, Document};
|
||||
|
||||
use compliance_core::models::{
|
||||
check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits,
|
||||
RunCharge, SwapRefusal, TargetBilling,
|
||||
};
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// Store the billing of the tenant's active targets for a plan that
|
||||
/// includes `included` targets.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - The tenant's database.
|
||||
/// * `included` - How many targets the plan includes; `None` is unlimited.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The targets whose billing changed, with their new billing.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the targets cannot be read or updated.
|
||||
pub async fn assign_billing(
|
||||
db: &Database,
|
||||
included: Option<u32>,
|
||||
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
|
||||
// Only the fields the split needs: a whole target holds its artifacts,
|
||||
// and older documents may lack fields the model requires.
|
||||
let docs: Vec<Document> = db
|
||||
.raw_collection("onboarded_targets")
|
||||
.find(doc! { "archived_at": null })
|
||||
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1, "included_choice": 1 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let targets: Vec<BillableTarget<ObjectId>> = docs.iter().filter_map(billable).collect();
|
||||
let changes = split_included(&targets, included);
|
||||
for wanted in [TargetBilling::Included, TargetBilling::Extra] {
|
||||
let ids: Vec<ObjectId> = changes
|
||||
.iter()
|
||||
.filter(|(_, billing)| *billing == wanted)
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value =
|
||||
mongodb::bson::to_bson(&wanted).map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
db.onboarded_targets()
|
||||
.update_many(
|
||||
doc! { "_id": { "$in": ids } },
|
||||
doc! { "$set": { "billing": value } },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(changes)
|
||||
}
|
||||
|
||||
/// A stored target as the split sees it; `None` without an id. A target
|
||||
/// without a creation time counts as the oldest, one without a billing as
|
||||
/// included (stored before metering).
|
||||
fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
|
||||
Some(BillableTarget {
|
||||
id: target.get_object_id("_id").ok()?,
|
||||
created_at: target
|
||||
.get_datetime("created_at")
|
||||
.map_or(DateTime::<Utc>::MIN_UTC, |at| at.to_chrono()),
|
||||
billing: target
|
||||
.get("billing")
|
||||
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
|
||||
.unwrap_or_default(),
|
||||
choice: target
|
||||
.get("included_choice")
|
||||
.and_then(|c| mongodb::bson::from_bson(c.clone()).ok()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The first instant after the calendar month (Europe/Berlin) of `at`: until
|
||||
/// then a target swapped in at `at` stays included.
|
||||
pub fn end_of_berlin_month(at: DateTime<Utc>) -> DateTime<Utc> {
|
||||
use chrono::{Datelike, TimeZone};
|
||||
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
|
||||
let (year, month) = if local.month() == 12 {
|
||||
(local.year() + 1, 1)
|
||||
} else {
|
||||
(local.year(), local.month() + 1)
|
||||
};
|
||||
// Midnight is never skipped or repeated in Berlin (DST changes at 2–3 h).
|
||||
chrono_tz::Europe::Berlin
|
||||
.with_ymd_and_hms(year, month, 1, 0, 0, 0)
|
||||
.earliest()
|
||||
.map_or(at, |next| next.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
/// Swap the extra target `incoming` with the included target `outgoing`
|
||||
/// (t72): the one swapped in stays included until the end of the calendar
|
||||
/// month, the other becomes extra. It records the customer's choice; the
|
||||
/// next [`assign_billing`] (which the caller runs) moves the billing.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `limited` - Whether the plan limits the included targets.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `None` when either target is not an active one of the tenant; else
|
||||
/// whether the swap was made, or why not.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the targets cannot be read or updated.
|
||||
pub async fn swap(
|
||||
db: &Database,
|
||||
incoming: ObjectId,
|
||||
outgoing: ObjectId,
|
||||
limited: bool,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<Option<Result<(), SwapRefusal>>, AgentError> {
|
||||
let targets = db.onboarded_targets();
|
||||
let active = |id: ObjectId| doc! { "_id": id, "archived_at": null };
|
||||
let (Some(swapped_in), Some(swapped_out)) = (
|
||||
targets.find_one(active(incoming)).await?,
|
||||
targets.find_one(active(outgoing)).await?,
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let locked = swapped_out.included_until.is_some_and(|until| until > at);
|
||||
if let Err(refusal) = check_swap(limited, swapped_in.billing, swapped_out.billing, locked) {
|
||||
return Ok(Some(Err(refusal)));
|
||||
}
|
||||
let to_bson = |v: IncludedChoice| {
|
||||
mongodb::bson::to_bson(&v).map_err(|e| AgentError::Other(e.to_string()))
|
||||
};
|
||||
targets
|
||||
.update_one(
|
||||
doc! { "_id": incoming },
|
||||
doc! { "$set": {
|
||||
"included_choice": to_bson(IncludedChoice::Included)?,
|
||||
"included_until": mongodb::bson::DateTime::from_chrono(end_of_berlin_month(at)),
|
||||
} },
|
||||
)
|
||||
.await?;
|
||||
targets
|
||||
.update_one(
|
||||
doc! { "_id": outgoing },
|
||||
doc! {
|
||||
"$set": { "included_choice": to_bson(IncludedChoice::Extra)? },
|
||||
"$unset": { "included_until": "" },
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(Some(Ok(())))
|
||||
}
|
||||
|
||||
/// The tenant's plan as metering reads it from the registry.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Plan {
|
||||
/// How many targets the plan includes; `None` is unlimited.
|
||||
pub included_targets: Option<u32>,
|
||||
/// The quota and the customer's Prüftag cap.
|
||||
pub limits: PlanLimits,
|
||||
}
|
||||
|
||||
/// The tenant's counted Prüfungen and booked Prüftage per month.
|
||||
const MONTHS: &str = "metering_months";
|
||||
/// Each target's Prüftag per day, once the quota was used up.
|
||||
const DAYS: &str = "metering_days";
|
||||
|
||||
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
|
||||
/// `YYYY-MM-DD`: the periods the contract counts in.
|
||||
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
|
||||
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
|
||||
(
|
||||
local.format("%Y-%m").to_string(),
|
||||
local.format("%Y-%m-%d").to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The id of a target's counter for one day.
|
||||
fn day_id(target_id: &str, day: &str) -> String {
|
||||
format!("{target_id}:{day}")
|
||||
}
|
||||
|
||||
/// A stored counter as a `u32`; missing or negative reads as 0.
|
||||
fn count(document: Option<&Document>, field: &str) -> u32 {
|
||||
document
|
||||
.and_then(|d| d.get(field))
|
||||
.and_then(mongodb::bson::Bson::as_i64)
|
||||
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// What the tenant used this month and `target_id` today, at `at`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the counters cannot be read.
|
||||
pub async fn usage(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<(MonthUsage, DayUsage), AgentError> {
|
||||
let (month, day) = berlin_period(at);
|
||||
let month_doc = db
|
||||
.raw_collection(MONTHS)
|
||||
.find_one(doc! { "_id": &month })
|
||||
.await?;
|
||||
let day_doc = db
|
||||
.raw_collection(DAYS)
|
||||
.find_one(doc! { "_id": day_id(target_id, &day) })
|
||||
.await?;
|
||||
Ok((
|
||||
MonthUsage {
|
||||
pruefungen: count(month_doc.as_ref(), "pruefungen"),
|
||||
prueftage: count(month_doc.as_ref(), "prueftage"),
|
||||
},
|
||||
DayUsage {
|
||||
prueftag_booked: day_doc
|
||||
.as_ref()
|
||||
.and_then(|d| d.get_bool("prueftag_booked").ok())
|
||||
.unwrap_or(false),
|
||||
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// What [`charge`] charged a completed Prüfung to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Charged {
|
||||
/// The quota or the target's Prüftag.
|
||||
pub charge: RunCharge,
|
||||
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
|
||||
/// goes to the registry as `prueftag.booked`.
|
||||
pub booked_prueftag: Option<String>,
|
||||
}
|
||||
|
||||
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
|
||||
/// month's quota while it lasts, else to the target's Prüftag that day,
|
||||
/// booking it if none is. The start of the run checked the limits, so this
|
||||
/// never refuses; scans of several targets finishing at once can take the
|
||||
/// quota or a Prüftag over by the ones that raced.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the counters cannot be written.
|
||||
pub async fn charge(
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
limits: PlanLimits,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<Charged, AgentError> {
|
||||
let (month, day) = berlin_period(at);
|
||||
let months = db.raw_collection(MONTHS);
|
||||
months
|
||||
.update_one(
|
||||
doc! { "_id": &month },
|
||||
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
|
||||
)
|
||||
.upsert(true)
|
||||
.await?;
|
||||
let quota_filter = match limits.monthly_pruefungen {
|
||||
// `$not $gte` also matches a month document without the counter.
|
||||
Some(quota) => doc! {
|
||||
"_id": &month,
|
||||
"pruefungen": { "$not": { "$gte": i64::from(quota) } },
|
||||
},
|
||||
None => doc! { "_id": &month },
|
||||
};
|
||||
let in_quota = months
|
||||
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
|
||||
.await?;
|
||||
if in_quota.matched_count == 1 {
|
||||
return Ok(Charged {
|
||||
charge: RunCharge::Quota,
|
||||
booked_prueftag: None,
|
||||
});
|
||||
}
|
||||
|
||||
let days = db.raw_collection(DAYS);
|
||||
let id = day_id(target_id, &day);
|
||||
days.update_one(
|
||||
doc! { "_id": &id },
|
||||
doc! { "$setOnInsert": {
|
||||
"target_id": target_id,
|
||||
"day": &day,
|
||||
"month": &month,
|
||||
"prueftag_booked": false,
|
||||
"prueftag_pruefungen": 0_i64,
|
||||
} },
|
||||
)
|
||||
.upsert(true)
|
||||
.await?;
|
||||
let booked = days
|
||||
.update_one(
|
||||
doc! { "_id": &id, "prueftag_booked": false },
|
||||
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
|
||||
)
|
||||
.await?;
|
||||
if booked.matched_count == 1 {
|
||||
months
|
||||
.update_one(
|
||||
doc! { "_id": &month },
|
||||
doc! { "$inc": { "prueftage": 1_i64 } },
|
||||
)
|
||||
.await?;
|
||||
return Ok(Charged {
|
||||
charge: RunCharge::Prueftag,
|
||||
booked_prueftag: Some(day),
|
||||
});
|
||||
}
|
||||
days.update_one(
|
||||
doc! { "_id": &id },
|
||||
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
|
||||
)
|
||||
.await?;
|
||||
Ok(Charged {
|
||||
charge: RunCharge::Prueftag,
|
||||
booked_prueftag: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Record how many of the tenant's active targets are extra at `at`, as
|
||||
/// the month's peak (t72): the 5,99 € line bills the highest number of
|
||||
/// extra targets at once in the calendar month (Europe/Berlin).
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The month's peak when it goes to the registry as `target.extra`: when it
|
||||
/// rose, and once a day besides (a re-send the registry drops as a
|
||||
/// duplicate of its key). `None` otherwise, and while no target was extra.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the targets or the month's counters cannot be read
|
||||
/// or written.
|
||||
pub async fn record_extra_peak(
|
||||
db: &Database,
|
||||
at: DateTime<Utc>,
|
||||
) -> Result<Option<u32>, AgentError> {
|
||||
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let now = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! { "archived_at": null, "billing": extra })
|
||||
.await?;
|
||||
let now = u32::try_from(now).unwrap_or(u32::MAX);
|
||||
let (month, day) = berlin_period(at);
|
||||
let months = db.raw_collection(MONTHS);
|
||||
// The document before the update: the peak and the day it was last sent.
|
||||
let before = months
|
||||
.find_one_and_update(
|
||||
doc! { "_id": &month },
|
||||
doc! {
|
||||
"$max": { "extra_peak": i64::from(now) },
|
||||
"$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 },
|
||||
},
|
||||
)
|
||||
.upsert(true)
|
||||
.await?;
|
||||
let previous = count(before.as_ref(), "extra_peak");
|
||||
let sent_on = before
|
||||
.as_ref()
|
||||
.and_then(|d| d.get_str("extra_sent_on").ok());
|
||||
let peak = previous.max(now);
|
||||
if peak == 0 || (peak == previous && sent_on == Some(day.as_str())) {
|
||||
return Ok(None);
|
||||
}
|
||||
months
|
||||
.update_one(
|
||||
doc! { "_id": &month },
|
||||
doc! { "$set": { "extra_sent_on": &day } },
|
||||
)
|
||||
.await?;
|
||||
Ok(Some(peak))
|
||||
}
|
||||
|
||||
/// The tenant's metering this month, for the dashboard (t72).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
|
||||
pub struct MonthSummary {
|
||||
/// The calendar month in Europe/Berlin, `YYYY-MM`.
|
||||
pub month: String,
|
||||
/// Counted Prüfungen charged to the quota.
|
||||
pub pruefungen: u32,
|
||||
/// Prüftage booked.
|
||||
pub prueftage: u32,
|
||||
/// Active targets that are extra now.
|
||||
pub extra_targets: u32,
|
||||
/// The highest number of extra targets at once this month, which the
|
||||
/// extra-target line bills.
|
||||
pub extra_peak: u32,
|
||||
}
|
||||
|
||||
/// What the tenant used in the month of `at`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the counters or the targets cannot be read.
|
||||
pub async fn month_summary(db: &Database, at: DateTime<Utc>) -> Result<MonthSummary, AgentError> {
|
||||
let (month, _) = berlin_period(at);
|
||||
let stored = db
|
||||
.raw_collection(MONTHS)
|
||||
.find_one(doc! { "_id": &month })
|
||||
.await?;
|
||||
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let extra_targets = db
|
||||
.onboarded_targets()
|
||||
.count_documents(doc! { "archived_at": null, "billing": extra })
|
||||
.await?;
|
||||
let extra_targets = u32::try_from(extra_targets).unwrap_or(u32::MAX);
|
||||
Ok(MonthSummary {
|
||||
month,
|
||||
pruefungen: count(stored.as_ref(), "pruefungen"),
|
||||
prueftage: count(stored.as_ref(), "prueftage"),
|
||||
extra_targets,
|
||||
// The peak is recorded when the billing is refreshed; until then
|
||||
// it is at least what is extra now.
|
||||
extra_peak: count(stored.as_ref(), "extra_peak").max(extra_targets),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
|
||||
#[test]
|
||||
fn a_swap_holds_until_the_berlin_month_ends() {
|
||||
let at = |y, m, d, h| {
|
||||
Utc.with_ymd_and_hms(y, m, d, h, 0, 0)
|
||||
.single()
|
||||
.expect("valid")
|
||||
};
|
||||
// 1 Dec 00:00 in Berlin (CET) is 30 Nov 23:00 UTC.
|
||||
assert_eq!(
|
||||
end_of_berlin_month(at(2026, 11, 6, 9)),
|
||||
at(2026, 11, 30, 23)
|
||||
);
|
||||
// December rolls into January of the next year.
|
||||
assert_eq!(
|
||||
end_of_berlin_month(at(2026, 12, 15, 9)),
|
||||
at(2026, 12, 31, 23)
|
||||
);
|
||||
// 1 Aug 00:00 in Berlin (CEST) is 31 Jul 22:00 UTC.
|
||||
assert_eq!(
|
||||
end_of_berlin_month(at(2026, 7, 31, 21)),
|
||||
at(2026, 7, 31, 22)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn periods_are_calendar_ones_in_berlin() {
|
||||
let at = |y, m, d, h, min| {
|
||||
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
|
||||
.single()
|
||||
.expect("valid")
|
||||
};
|
||||
|
||||
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
|
||||
assert_eq!(
|
||||
berlin_period(at(2026, 10, 31, 23, 30)),
|
||||
("2026-11".to_string(), "2026-11-01".to_string())
|
||||
);
|
||||
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
|
||||
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
|
||||
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_counter_reads_as_zero_when_missing() {
|
||||
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
|
||||
assert_eq!(count(Some(&stored), "pruefungen"), 7);
|
||||
assert_eq!(count(Some(&stored), "small"), 3);
|
||||
assert_eq!(count(Some(&stored), "negative"), 0);
|
||||
assert_eq!(count(Some(&stored), "absent"), 0);
|
||||
assert_eq!(count(None, "pruefungen"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
|
||||
// Arrange
|
||||
let id = ObjectId::new();
|
||||
let at = mongodb::bson::DateTime::from_millis(1_700_000_000_000);
|
||||
let extra = doc! { "_id": id, "created_at": at, "billing": "extra" };
|
||||
let old = doc! { "_id": id };
|
||||
|
||||
// Act
|
||||
let extra = billable(&extra);
|
||||
let old = billable(&old);
|
||||
|
||||
// Assert
|
||||
assert_eq!(
|
||||
extra,
|
||||
Some(BillableTarget {
|
||||
id,
|
||||
created_at: at.to_chrono(),
|
||||
billing: TargetBilling::Extra,
|
||||
choice: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
old,
|
||||
Some(BillableTarget {
|
||||
id,
|
||||
created_at: DateTime::<Utc>::MIN_UTC,
|
||||
billing: TargetBilling::Included,
|
||||
choice: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(billable(&doc! { "name": "no id" }), None);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,22 @@ pub fn uploads_allow_git_skip(target: &OnboardedTarget) -> bool {
|
||||
upload_skip_enabled() && uploads_match(target)
|
||||
}
|
||||
|
||||
/// Whether a file uploaded to `target` changed since its last completed
|
||||
/// scan: it has uploads, and they are not the ones that scan read. For
|
||||
/// metering (t72), independent of [`upload_skip_enabled`].
|
||||
pub fn uploads_changed(target: &OnboardedTarget) -> bool {
|
||||
target.artifacts.iter().any(is_upload) && !uploads_match(target)
|
||||
}
|
||||
|
||||
/// Whether the customer changed what `target`, which has no git repository,
|
||||
/// gives a scan to read since its last completed one: it was never scanned,
|
||||
/// its uploads changed, or it has a live URL (the service changes on its
|
||||
/// own). A scheduled scan that runs without such a change is our own rescan
|
||||
/// (t72).
|
||||
pub fn content_changed(target: &OnboardedTarget) -> bool {
|
||||
target.live_url().is_some() || target.last_scan.is_none() || uploads_changed(target)
|
||||
}
|
||||
|
||||
/// Whether the uploads of `target` are the ones its last completed scan read.
|
||||
fn uploads_match(target: &OnboardedTarget) -> bool {
|
||||
target
|
||||
@@ -219,4 +235,31 @@ mod tests {
|
||||
let unhashed = target(vec![upload("a", None)]);
|
||||
assert_eq!(upload_inputs(&unhashed), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_change_the_customer_made_is_a_content_change() {
|
||||
// Arrange: a target scanned once, by an older build.
|
||||
let mut t = target(vec![upload("a", Some("h1"))]);
|
||||
assert!(content_changed(&t), "never scanned");
|
||||
t.last_scan = Some(LastScan {
|
||||
build: "0.0.1+old".into(),
|
||||
inputs: upload_inputs(&t),
|
||||
});
|
||||
|
||||
// Act / Assert: a new build alone is no change of the customer's.
|
||||
assert!(!content_changed(&t));
|
||||
assert!(!uploads_changed(&t));
|
||||
|
||||
t.artifacts[0].content_hash = Some("h2".into());
|
||||
assert!(content_changed(&t), "another upload");
|
||||
assert!(uploads_changed(&t));
|
||||
|
||||
let mut live = target(vec![Artifact::live_url("https://pump.example.com")]);
|
||||
live.last_scan = Some(LastScan {
|
||||
build: build_id(),
|
||||
inputs: None,
|
||||
});
|
||||
assert!(content_changed(&live), "a live service changes on its own");
|
||||
assert!(!uploads_changed(&live), "nothing uploaded");
|
||||
}
|
||||
}
|
||||
@@ -145,33 +145,15 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String {
|
||||
}
|
||||
|
||||
/// The text of a file that may start with a byte-order mark (Visual Studio
|
||||
/// writes UTF-8 with BOM, older tools UTF-16). `None` for a file too large or
|
||||
/// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by
|
||||
/// [`compliance_core::encoding::read_source`]. `None` for a file too large or
|
||||
/// unreadable.
|
||||
pub(crate) fn read_text(path: &Path) -> Option<String> {
|
||||
let meta = std::fs::metadata(path).ok()?;
|
||||
if meta.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
let utf16 = |bytes: &[u8], le: bool| {
|
||||
let units: Vec<u16> = bytes
|
||||
.chunks_exact(2)
|
||||
.map(|c| {
|
||||
if le {
|
||||
u16::from_le_bytes([c[0], c[1]])
|
||||
} else {
|
||||
u16::from_be_bytes([c[0], c[1]])
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
String::from_utf16(&units).ok()
|
||||
};
|
||||
match bytes.as_slice() {
|
||||
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8(rest.to_vec()).ok(),
|
||||
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
|
||||
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
|
||||
_ => String::from_utf8(bytes).ok(),
|
||||
}
|
||||
compliance_core::encoding::read_source(path).ok()
|
||||
}
|
||||
|
||||
/// Parse XML the way project and configuration files need: a DTD is allowed
|
||||
|
||||
@@ -147,7 +147,8 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
|
||||
}) {
|
||||
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
|
||||
let Some(text) = small
|
||||
.then(|| std::fs::read_to_string(entry.path()).ok())
|
||||
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
|
||||
.then(|| compliance_core::encoding::read_source(entry.path()).ok())
|
||||
.flatten()
|
||||
else {
|
||||
continue;
|
||||
|
||||
@@ -782,12 +782,24 @@ impl RunFindings {
|
||||
Ok(closed)
|
||||
}
|
||||
|
||||
/// Close the undecided findings of `scanner` on target `target_id` whose
|
||||
/// file lies in the excluded paths or the test data this run left out
|
||||
/// Close the undecided findings on target `target_id` whose file lies in
|
||||
/// the excluded paths or the test data this run left out
|
||||
/// ([`Self::with_excluded`], [`Self::with_test_data`]), each with its
|
||||
/// reason. For a stage that stores its findings without this object (the
|
||||
/// PLC analysis), so nothing it no longer sees is closed as fixed; only
|
||||
/// what was left out.
|
||||
/// reason. Nothing is closed as fixed; only what was left out.
|
||||
///
|
||||
/// [`Self::resolve_missing`] only closes what a scanner that completed no
|
||||
/// longer reports. A scanner that did not run cannot close its findings in
|
||||
/// a left-out path, although nothing can see them any more: cppcheck runs
|
||||
/// only on a tree with C, so once a fixture held the tree's only C, its
|
||||
/// findings would stay open for good. This closes them, whichever scanner
|
||||
/// stored them. A finding this run reported again is kept.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `db` - the tenant database
|
||||
/// * `target_id` - the scanned target (`Finding::repo_id`)
|
||||
/// * `scanner` - only this scanner's findings (a stage that stores its
|
||||
/// findings without this object, the PLC analysis), or `None` for all
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
@@ -800,20 +812,23 @@ impl RunFindings {
|
||||
&mut self,
|
||||
db: &Database,
|
||||
target_id: &str,
|
||||
scanner: &str,
|
||||
scanner: Option<&str>,
|
||||
) -> Result<u32, AgentError> {
|
||||
if self.excluded.is_empty() && self.test_data.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut filter = doc! {
|
||||
"repo_id": target_id,
|
||||
"status": { "$in": UNDECIDED.to_vec() },
|
||||
};
|
||||
if let Some(scanner) = scanner {
|
||||
filter.insert("scanner", scanner);
|
||||
}
|
||||
let rows: Vec<Document> = db
|
||||
.findings()
|
||||
.clone_with_type::<Document>()
|
||||
.find(doc! {
|
||||
"repo_id": target_id,
|
||||
"scanner": scanner,
|
||||
"status": { "$in": UNDECIDED.to_vec() },
|
||||
})
|
||||
.projection(doc! { "file_path": 1 })
|
||||
.find(filter)
|
||||
.projection(doc! { "fingerprint": 1, "file_path": 1 })
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
@@ -822,6 +837,14 @@ impl RunFindings {
|
||||
let (Ok(id), Ok(file)) = (row.get_object_id("_id"), row.get_str("file_path")) else {
|
||||
continue;
|
||||
};
|
||||
// Something in this run still reports it, so it is not left out:
|
||||
// closing it would only see it reopened by the next run.
|
||||
let reported = row
|
||||
.get_str("fingerprint")
|
||||
.is_ok_and(|fp| self.inserted.contains_key(fp) || self.earlier.contains(fp));
|
||||
if reported {
|
||||
continue;
|
||||
}
|
||||
if crate::pipeline::vendor::in_vendor_dir(file, &self.excluded) {
|
||||
excluded.push(id);
|
||||
} else if crate::pipeline::vendor::in_vendor_dir(file, &self.test_data) {
|
||||
@@ -950,7 +973,8 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
|
||||
continue;
|
||||
};
|
||||
let lines = files.entry(path.clone()).or_insert_with(|| {
|
||||
std::fs::read_to_string(tree.join(&path))
|
||||
// Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252.
|
||||
compliance_core::encoding::read_source(&tree.join(&path))
|
||||
.ok()
|
||||
.map(|text| text.lines().map(normalised).collect())
|
||||
});
|
||||
@@ -1226,6 +1250,26 @@ mod tests {
|
||||
assert!(missing[0].legacy_fingerprints.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_1252_file_is_keyed_by_content_as_its_utf8_version_is() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// "größe" as Windows-1252 writes it (0xF6 0xDF), then the same file
|
||||
// saved again as UTF-8.
|
||||
std::fs::write(dir.join("a.c"), b"int x;\nint gr\xF6\xDFe = read();\n").unwrap();
|
||||
let ansi = keyed(&dir, vec![at("a.c", 2)]);
|
||||
std::fs::write(dir.join("a.c"), "int x;\nint größe = read();\n").unwrap();
|
||||
let utf8 = keyed(&dir, vec![at("a.c", 2)]);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
// Keyed by content, with the line-based key kept to adopt the row
|
||||
// stored under it while the file could not be read.
|
||||
let line_key = crate::pipeline::dedup::compute_fingerprint(&["repo-1", "rule", "a.c", "2"]);
|
||||
assert_eq!(ansi[0].legacy_fingerprints, std::slice::from_ref(&line_key));
|
||||
assert_ne!(ansi[0].fingerprint, line_key);
|
||||
// Re-saving the file in another encoding keeps the key.
|
||||
assert_eq!(ansi[0].fingerprint, utf8[0].fingerprint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scanners_own_content_and_groups_are_respected() {
|
||||
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
|
||||
|
||||
@@ -495,7 +495,18 @@ impl GitOps {
|
||||
_ => "",
|
||||
};
|
||||
|
||||
let content = std::str::from_utf8(line.content()).unwrap_or("");
|
||||
// A diff line is UTF-8 or, from an older tool, Windows-1252
|
||||
// (single-byte, so a line decodes on its own). UTF-16 files are
|
||||
// binary to git and have no lines here.
|
||||
let bytes = line.content();
|
||||
let decoded;
|
||||
let content = match std::str::from_utf8(bytes) {
|
||||
Ok(text) => text,
|
||||
Err(_) => {
|
||||
decoded = compliance_core::encoding::decode(bytes.to_vec()).unwrap_or_default();
|
||||
decoded.as_str()
|
||||
}
|
||||
};
|
||||
diff_file.hunks.push_str(prefix);
|
||||
diff_file.hunks.push_str(content);
|
||||
|
||||
@@ -919,4 +930,38 @@ mod tests {
|
||||
.expect_err("private origin must be refused");
|
||||
assert!(err.to_string().contains("10.0.0.5"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_1252_line_shows_in_the_diff() {
|
||||
// Arrange: a file committed, then a line with "für" as Windows-1252
|
||||
// writes it (0xFC) added in a second commit.
|
||||
let dir = source_repo();
|
||||
let repo = git2::Repository::open(&dir).unwrap();
|
||||
let old = repo.head().unwrap().peel_to_commit().unwrap();
|
||||
std::fs::write(
|
||||
dir.join("README.md"),
|
||||
b"pump controller\n// f\xFCr Halle 2\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut index = repo.index().unwrap();
|
||||
index.add_path(Path::new("README.md")).unwrap();
|
||||
index.write().unwrap();
|
||||
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
|
||||
let sig = git2::Signature::now("t", "t@example.com").unwrap();
|
||||
let new = repo
|
||||
.commit(Some("HEAD"), &sig, &sig, "note", &tree, &[&old])
|
||||
.unwrap();
|
||||
|
||||
// Act
|
||||
let diff = GitOps::get_diff_content(&dir, &old.id().to_string(), &new.to_string()).unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
|
||||
// Assert: the added line is there, decoded.
|
||||
assert_eq!(diff.len(), 1);
|
||||
assert!(
|
||||
diff[0].hunks.contains("+// für Halle 2"),
|
||||
"{}",
|
||||
diff[0].hunks
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,71 @@
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::GraphBuildRun;
|
||||
use compliance_core::models::Finding;
|
||||
use compliance_graph::graph::engine::CodeGraph;
|
||||
|
||||
use super::orchestrator::{GraphContext, PipelineOrchestrator};
|
||||
use super::plc::PlcFile;
|
||||
use crate::error::AgentError;
|
||||
|
||||
/// The most nodes a graph build parses.
|
||||
const GRAPH_MAX_NODES: u32 = 50_000;
|
||||
|
||||
/// What a code graph is built from.
|
||||
pub(crate) enum GraphSource<'a> {
|
||||
/// The source files of a checked-out tree, by the graph crate's parsers.
|
||||
Tree(&'a Path),
|
||||
/// The POUs of a PLC target, read from every one of its PLC source trees.
|
||||
Plc(&'a [PlcFile]),
|
||||
}
|
||||
|
||||
/// Build a code graph and detect its communities.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the graph engine's error when a tree can't be read or the graph
|
||||
/// can't be assembled.
|
||||
pub(crate) fn build_graph(
|
||||
source: GraphSource<'_>,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
|
||||
let engine = compliance_graph::GraphEngine::new(GRAPH_MAX_NODES);
|
||||
match source {
|
||||
GraphSource::Tree(path) => engine.build_graph(path, repo_id, graph_build_id),
|
||||
GraphSource::Plc(files) => engine.assemble(
|
||||
super::plc::graph::parse_output(files, repo_id, graph_build_id),
|
||||
repo_id,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
impl PipelineOrchestrator {
|
||||
/// Build the code knowledge graph for a repo and compute impact analyses
|
||||
/// Build the code knowledge graph for a repo, store it in place of the
|
||||
/// previous one and compute the impact of each finding.
|
||||
pub(super) async fn build_code_graph(
|
||||
&self,
|
||||
repo_path: &std::path::Path,
|
||||
source: GraphSource<'_>,
|
||||
repo_id: &str,
|
||||
findings: &[Finding],
|
||||
) -> Result<GraphContext, AgentError> {
|
||||
let graph_build_id = uuid::Uuid::new_v4().to_string();
|
||||
let engine = compliance_graph::GraphEngine::new(50_000);
|
||||
let built = build_graph(source, repo_id, &graph_build_id)
|
||||
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
|
||||
self.store_code_graph(built, repo_id, &graph_build_id, findings)
|
||||
.await
|
||||
}
|
||||
|
||||
let (mut code_graph, build_run) =
|
||||
engine
|
||||
.build_graph(repo_path, repo_id, &graph_build_id)
|
||||
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
|
||||
|
||||
// Apply community detection
|
||||
compliance_graph::graph::community::apply_communities(&mut code_graph);
|
||||
|
||||
// Store graph in MongoDB
|
||||
/// Replace the repo's stored graph with `built`, and store the impact of
|
||||
/// each finding that has a file.
|
||||
async fn store_code_graph(
|
||||
&self,
|
||||
(code_graph, build_run): (CodeGraph, GraphBuildRun),
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
findings: &[Finding],
|
||||
) -> Result<GraphContext, AgentError> {
|
||||
let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner());
|
||||
store
|
||||
.delete_repo_graph(repo_id)
|
||||
@@ -42,7 +85,7 @@ impl PipelineOrchestrator {
|
||||
let impact = analyzer.analyze(
|
||||
repo_id,
|
||||
&finding.fingerprint,
|
||||
&graph_build_id,
|
||||
graph_build_id,
|
||||
file_path,
|
||||
finding.line_number,
|
||||
);
|
||||
|
||||
@@ -23,7 +23,7 @@ pub mod git;
|
||||
pub mod git_retry;
|
||||
pub mod git_submodules;
|
||||
pub mod gitleaks;
|
||||
mod graph_build;
|
||||
pub(crate) mod graph_build;
|
||||
pub mod grouping;
|
||||
pub mod ios_config;
|
||||
mod issue_catchup;
|
||||
|
||||
@@ -37,6 +37,20 @@ pub struct GraphContext {
|
||||
pub impacts: Vec<compliance_core::models::graph::ImpactAnalysis>,
|
||||
}
|
||||
|
||||
/// How a scan of an onboarded target went, for its usage events (t72).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TargetScanOutcome {
|
||||
/// `false` when it was skipped because nothing changed (#465), or the
|
||||
/// plan did not allow it now.
|
||||
pub scanned: bool,
|
||||
/// Why it ran; `None` when it was skipped.
|
||||
pub attribution: Option<ScanAttribution>,
|
||||
/// Whether it counts toward the customer's usage.
|
||||
pub chargeable: bool,
|
||||
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this scan booked.
|
||||
pub booked_prueftag: Option<String>,
|
||||
}
|
||||
|
||||
/// What a scan left out of its working copy before the first stage, as
|
||||
/// paths relative to the tree.
|
||||
#[derive(Debug, Default)]
|
||||
@@ -65,6 +79,13 @@ pub struct PipelineOrchestrator {
|
||||
pub(super) exploit_cache: Option<Arc<dyn ExploitCache>>,
|
||||
/// The vendor CSAF advisories (#515); none in tests.
|
||||
pub(super) advisory_index: Option<Arc<dyn crate::pipeline::csaf_match::AdvisoryIndex>>,
|
||||
/// The tenant's plan limits for metering (t72); `None` when not known,
|
||||
/// and then counted Prüfungen are neither checked nor charged.
|
||||
pub(super) plan_limits: Option<PlanLimits>,
|
||||
/// Set when this person's scan took over a waiting scheduled, webhook or
|
||||
/// new-content scan (t84): the trigger it is charged as. Change detection
|
||||
/// then decides whether it counts, as for that scan.
|
||||
pub(super) charged_as: Option<ScanTrigger>,
|
||||
}
|
||||
|
||||
impl PipelineOrchestrator {
|
||||
@@ -81,9 +102,24 @@ impl PipelineOrchestrator {
|
||||
nuget_license_cache: None,
|
||||
exploit_cache: None,
|
||||
advisory_index: None,
|
||||
plan_limits: None,
|
||||
charged_as: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge this run as a scan started by `trigger` would be, when a
|
||||
/// person's request took that waiting scan over (t84).
|
||||
pub(crate) fn with_charged_as(mut self, trigger: Option<ScanTrigger>) -> Self {
|
||||
self.charged_as = trigger;
|
||||
self
|
||||
}
|
||||
|
||||
/// Check and charge counted Prüfungen against `limits` (t72).
|
||||
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
|
||||
self.plan_limits = limits;
|
||||
self
|
||||
}
|
||||
|
||||
/// Cache the NuGet licenses looked up on nuget.org in `cache` (#467).
|
||||
pub(crate) fn with_nuget_license_cache(mut self, cache: Arc<dyn LicenseCache>) -> Self {
|
||||
self.nuget_license_cache = Some(cache);
|
||||
@@ -174,25 +210,45 @@ impl PipelineOrchestrator {
|
||||
// new to find; one a person started always runs (after a changed
|
||||
// setting it can find something else), a new Prüfwerk build scans
|
||||
// once (#465), and so does a file uploaded to the target since.
|
||||
if !trigger.started_by_person()
|
||||
&& repo.uploads_allow_skip
|
||||
&& repo.last_scanned_build.as_deref()
|
||||
== Some(crate::pipeline::change::build_id().as_str())
|
||||
&& !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?
|
||||
{
|
||||
tracing::info!("[{repo_id}] No new commits, skipping scan");
|
||||
self.skip_stage(
|
||||
if !trigger.started_by_person() {
|
||||
let new_commits =
|
||||
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
|
||||
if !new_commits
|
||||
&& repo.uploads_allow_skip
|
||||
&& repo.last_scanned_build.as_deref()
|
||||
== Some(crate::pipeline::change::build_id().as_str())
|
||||
{
|
||||
tracing::info!("[{repo_id}] No new commits, skipping scan");
|
||||
self.skip_stage(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
"change_detection",
|
||||
SkipCode::NoNewCommits,
|
||||
"no new commits since the last scan",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
// Findings deferred by the catch-up's cap still get their issues.
|
||||
self.catch_up_unchanged(repo, &repo_id).await;
|
||||
return Ok(0);
|
||||
}
|
||||
self.attribute_run(
|
||||
scan_run_id,
|
||||
SkippedStage::new(
|
||||
"change_detection",
|
||||
SkipCode::NoNewCommits,
|
||||
"no new commits since the last scan",
|
||||
),
|
||||
&repo_id,
|
||||
ScanAttribution::detected(trigger, new_commits || repo.changed_besides_commits),
|
||||
repo.billing,
|
||||
)
|
||||
.await;
|
||||
// Findings deferred by the catch-up's cap still get their issues.
|
||||
self.catch_up_unchanged(repo, &repo_id).await;
|
||||
return Ok(0);
|
||||
.await?;
|
||||
} else if let Some(original) = &self.charged_as {
|
||||
let new_commits =
|
||||
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
|
||||
self.charge_as_taken_over(
|
||||
scan_run_id,
|
||||
&repo_id,
|
||||
ScanAttribution::detected(original, new_commits || repo.changed_besides_commits),
|
||||
repo.billing,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
// Submodules are part of what the product ships (a HAL, an RTOS).
|
||||
@@ -255,6 +311,14 @@ impl PipelineOrchestrator {
|
||||
tokio::task::spawn_blocking(move || crate::pipeline::variants::app_variants(&tree))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
// Left out of the tree, but a scanner that walks the git history
|
||||
// (gitleaks) still sees what was committed there.
|
||||
let left_out_dirs: Vec<String> = left_out
|
||||
.excluded
|
||||
.iter()
|
||||
.chain(&left_out.test_data)
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut run_findings = crate::pipeline::finding_store::RunFindings::new(scan_run_id)
|
||||
.with_variants(variants)
|
||||
.with_tree(repo_path.clone())
|
||||
@@ -293,12 +357,14 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
}
|
||||
// The same vendor code is left out of every code scanner's findings:
|
||||
// the pattern, secret and lint scanners walk the whole tree.
|
||||
// the pattern, secret and lint scanners walk the whole tree. So are the
|
||||
// left-out paths, for the secret scanner, which reads the history.
|
||||
let outside_vendor = |findings: &mut Vec<Finding>| {
|
||||
findings.retain(|f| {
|
||||
!f.file_path
|
||||
.as_deref()
|
||||
.is_some_and(|p| crate::pipeline::vendor::in_vendor_dir(p, &vendor))
|
||||
!f.file_path.as_deref().is_some_and(|p| {
|
||||
crate::pipeline::vendor::in_vendor_dir(p, &vendor)
|
||||
|| crate::pipeline::vendor::in_vendor_dir(p, &left_out_dirs)
|
||||
})
|
||||
})
|
||||
};
|
||||
match SemgrepScanner::new(vendor.clone())
|
||||
@@ -894,8 +960,12 @@ impl PipelineOrchestrator {
|
||||
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
|
||||
.await;
|
||||
let graph_context = match async {
|
||||
self.build_code_graph(&repo_path, &repo_id, &all_findings)
|
||||
.await
|
||||
self.build_code_graph(
|
||||
crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
|
||||
&repo_id,
|
||||
&all_findings,
|
||||
)
|
||||
.await
|
||||
}
|
||||
.instrument(tracing::info_span!("stage_graph_building"))
|
||||
.await
|
||||
@@ -997,6 +1067,11 @@ impl PipelineOrchestrator {
|
||||
run_findings
|
||||
.resolve_missing(&self.db, &repo_id, &vendor)
|
||||
.await?;
|
||||
// And what an earlier scan stored in a left-out path, also of a scanner
|
||||
// that did not run this time.
|
||||
run_findings
|
||||
.resolve_left_out(&self.db, &repo_id, None)
|
||||
.await?;
|
||||
// Their issues follow: closed with a comment, or reopened.
|
||||
crate::pipeline::issue_sync::IssueSync {
|
||||
db: self.db.clone(),
|
||||
@@ -1106,12 +1181,15 @@ impl PipelineOrchestrator {
|
||||
/// `OnboardedTarget`. Mirrors [`Self::run`] but sources the target from
|
||||
/// `onboarded_targets` and dispatches by the scan plan.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %target_id, trigger = ?trigger))]
|
||||
/// Run one scan of the target `target_id`.
|
||||
/// Run one scan of the target `target_id`, recorded on the run `queued`
|
||||
/// that waited for this scan's slot (t84), or on a new run when there is
|
||||
/// none.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Whether it scanned: `false` when it was skipped because nothing changed
|
||||
/// since the last completed scan (a scheduled or webhook scan, #465).
|
||||
/// Whether it scanned (`false` when it was skipped because nothing changed
|
||||
/// since the last completed scan, a scheduled or webhook scan, #465), and
|
||||
/// how it is metered (t72).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -1120,7 +1198,8 @@ impl PipelineOrchestrator {
|
||||
&self,
|
||||
target_id: &str,
|
||||
trigger: ScanTrigger,
|
||||
) -> Result<bool, AgentError> {
|
||||
queued: Option<&str>,
|
||||
) -> Result<TargetScanOutcome, AgentError> {
|
||||
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?;
|
||||
let target = self
|
||||
@@ -1130,17 +1209,35 @@ impl PipelineOrchestrator {
|
||||
.await?
|
||||
.ok_or_else(|| AgentError::Other(format!("Onboarded target {target_id} not found")))?;
|
||||
|
||||
let scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
|
||||
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
|
||||
let scan_run_id = insert
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.map(|id| id.to_hex())
|
||||
.unwrap_or_default();
|
||||
let mut scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
|
||||
// A scan a person started is attributed from the start; change
|
||||
// detection attributes the others (t72).
|
||||
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
|
||||
scan_run.attribution = Some(attribution);
|
||||
// One that took over a waiting scan counts only as that scan
|
||||
// would have; change detection decides below (t84).
|
||||
scan_run.chargeable =
|
||||
self.charged_as.is_none() && attribution.chargeable(target.billing);
|
||||
}
|
||||
scan_run.charged_as = self.charged_as.clone();
|
||||
let run_oid = self.start_run(&scan_run, queued).await?;
|
||||
let scan_run_id = run_oid.to_hex();
|
||||
let run_id = mongodb::bson::Bson::ObjectId(run_oid);
|
||||
|
||||
let result = self
|
||||
.run_target_pipeline(&target, &scan_run_id, &trigger)
|
||||
.await;
|
||||
// A counted Prüfung a person started is checked against the plan
|
||||
// before anything runs (t72).
|
||||
let admitted = if scan_run.chargeable {
|
||||
self.admit_run(&scan_run_id, target_id).await
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
let result = match admitted {
|
||||
Ok(()) => {
|
||||
self.run_target_pipeline(&target, &scan_run_id, &trigger)
|
||||
.await
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
match &result {
|
||||
Ok(count) => {
|
||||
let mut completed = doc! {
|
||||
@@ -1159,10 +1256,7 @@ impl PipelineOrchestrator {
|
||||
}
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "$set": completed },
|
||||
)
|
||||
.update_one(doc! { "_id": &run_id }, doc! { "$set": completed })
|
||||
.await?;
|
||||
// Refresh the target's cached findings count. The shared pipeline
|
||||
// (Stage 7) increments `repositories`, which the unified path does
|
||||
@@ -1191,13 +1285,30 @@ impl PipelineOrchestrator {
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
// The plan does not allow it now: the run ends without scanning,
|
||||
// and the target keeps what its last scan read, so the change is
|
||||
// scanned once it may be.
|
||||
Err(AgentError::NotAdmitted(refusal)) => {
|
||||
tracing::info!(target_id, ?refusal, "counted Prüfung not run");
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &run_id },
|
||||
doc! { "$set": {
|
||||
"status": "completed",
|
||||
"current_phase": "completed",
|
||||
"completed_at": mongodb::bson::DateTime::now(),
|
||||
} },
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(target_id, error = %e, "Unified scan pipeline failed");
|
||||
let (code, message) = e.run_failure();
|
||||
self.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": &insert.inserted_id },
|
||||
doc! { "_id": &run_id },
|
||||
doc! { "$set": {
|
||||
"status": "failed",
|
||||
"error_message": message,
|
||||
@@ -1208,16 +1319,258 @@ impl PipelineOrchestrator {
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
result?;
|
||||
let skipped = self
|
||||
let refused = matches!(result, Err(AgentError::NotAdmitted(_)));
|
||||
let invalid_input = matches!(
|
||||
result,
|
||||
Err(AgentError::ArchivePasswordRequired | AgentError::ArchivePasswordWrong)
|
||||
);
|
||||
// Read back without hiding the scan's own error behind a failed read.
|
||||
let run = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.count_documents(doc! {
|
||||
"_id": &insert.inserted_id,
|
||||
"skipped_stages.stage": "change_detection",
|
||||
})
|
||||
.await?;
|
||||
Ok(skipped == 0)
|
||||
.find_one(doc! { "_id": &run_id })
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
let unchanged = run.as_ref().is_some_and(|r| {
|
||||
r.skipped_stages
|
||||
.iter()
|
||||
.any(|s| s.stage == "change_detection")
|
||||
});
|
||||
let chargeable = run.as_ref().is_some_and(|r| r.chargeable);
|
||||
let attribution = run.and_then(|r| r.attribution);
|
||||
// A counted Prüfung is charged when it completed, or when it failed on
|
||||
// the customer's input; a failure of ours never is (t72).
|
||||
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
|
||||
self.charge_run(&run_id, target_id).await
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !refused {
|
||||
result?;
|
||||
}
|
||||
Ok(TargetScanOutcome {
|
||||
scanned: !refused && !unchanged,
|
||||
attribution,
|
||||
chargeable,
|
||||
booked_prueftag: charged.and_then(|c| c.booked_prueftag),
|
||||
})
|
||||
}
|
||||
|
||||
/// Record that `run` starts now: on the run `queued` that waited for the
|
||||
/// slot, which moves from `queued` to `running`, or as a new run when
|
||||
/// there is none or it is gone. Returns the run's id.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The run could not be written.
|
||||
async fn start_run(
|
||||
&self,
|
||||
run: &ScanRun,
|
||||
queued: Option<&str>,
|
||||
) -> Result<mongodb::bson::oid::ObjectId, AgentError> {
|
||||
if let Some(oid) = queued.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) {
|
||||
let mut started = doc! {
|
||||
"status": "running",
|
||||
"trigger": mongodb::bson::to_bson(&run.trigger)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?,
|
||||
"started_at": mongodb::bson::DateTime::from_chrono(run.started_at),
|
||||
"chargeable": run.chargeable,
|
||||
};
|
||||
if let Some(charged_as) = &run.charged_as {
|
||||
started.insert(
|
||||
"charged_as",
|
||||
mongodb::bson::to_bson(charged_as)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
if let Some(attribution) = run.attribution {
|
||||
started.insert(
|
||||
"attribution",
|
||||
mongodb::bson::to_bson(&attribution)
|
||||
.map_err(|e| AgentError::Other(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
let updated = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": oid, "status": "queued" },
|
||||
doc! { "$set": started },
|
||||
)
|
||||
.await?;
|
||||
if updated.matched_count == 1 {
|
||||
return Ok(oid);
|
||||
}
|
||||
}
|
||||
let insert = self.db.scan_runs().insert_one(run).await?;
|
||||
insert
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.ok_or_else(|| AgentError::Other("the scan run got no id".into()))
|
||||
}
|
||||
|
||||
/// Check a counted Prüfung against the plan before it scans (t72):
|
||||
/// the quota, today's Prüftag on the target, the customer's cap. It runs
|
||||
/// when the plan's limits or the usage are not known.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`AgentError::NotAdmitted`] when the plan does not allow it now; why
|
||||
/// is recorded on the run.
|
||||
async fn admit_run(&self, scan_run_id: &str, target_id: &str) -> Result<(), AgentError> {
|
||||
let Some(limits) = self.plan_limits else {
|
||||
return Ok(());
|
||||
};
|
||||
let (month, day) =
|
||||
match crate::metering::usage(&self.db, target_id, chrono::Utc::now()).await {
|
||||
Ok(usage) => usage,
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, "usage not read, the Prüfung runs: {e}");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let Admission::Refused(refusal) = admit(limits, month, day) else {
|
||||
return Ok(());
|
||||
};
|
||||
let (code, reason) = match refusal {
|
||||
Refusal::DailyLimit => (
|
||||
SkipCode::PrueftagLimitReached,
|
||||
"the quota is used up and today's Prüftag on the target has had its Prüfungen",
|
||||
),
|
||||
Refusal::PrueftagCap => (
|
||||
SkipCode::PrueftagCapReached,
|
||||
"the quota is used up and the customer's Prüftag limit is reached",
|
||||
),
|
||||
};
|
||||
self.skip_stage(scan_run_id, SkippedStage::new("metering", code, reason))
|
||||
.await;
|
||||
Err(AgentError::NotAdmitted(refusal))
|
||||
}
|
||||
|
||||
/// Charge the completed, counted run `run_id` on `target_id` and record
|
||||
/// what it was charged to (t72). Nothing is charged when the plan's
|
||||
/// limits are not known. Best-effort: a counter that cannot be written is
|
||||
/// logged.
|
||||
async fn charge_run(
|
||||
&self,
|
||||
run_id: &mongodb::bson::Bson,
|
||||
target_id: &str,
|
||||
) -> Option<crate::metering::Charged> {
|
||||
let limits = self.plan_limits?;
|
||||
match crate::metering::charge(&self.db, target_id, limits, chrono::Utc::now()).await {
|
||||
Ok(charged) => {
|
||||
if let Ok(value) = mongodb::bson::to_bson(&charged.charge) {
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": run_id.clone() },
|
||||
doc! { "$set": { "charge": value } },
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(target_id, "charge not recorded on the run: {e}");
|
||||
}
|
||||
}
|
||||
Some(charged)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(target_id, "Prüfung not charged: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record why the run `scan_run_id` on `target_id` runs and whether it
|
||||
/// counts, on a target billed as `billing`, and check a counted one
|
||||
/// against the plan (t72). A run with several code artifacts is
|
||||
/// attributed once per artifact; a change found in any of them wins over
|
||||
/// our rescan. The record is best-effort, like [`Self::skip_stage`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
|
||||
/// Prüfung now.
|
||||
async fn attribute_run(
|
||||
&self,
|
||||
scan_run_id: &str,
|
||||
target_id: &str,
|
||||
attribution: ScanAttribution,
|
||||
billing: TargetBilling,
|
||||
) -> Result<(), AgentError> {
|
||||
let chargeable = attribution.chargeable(billing);
|
||||
self.record_attribution(scan_run_id, attribution, chargeable)
|
||||
.await;
|
||||
if chargeable {
|
||||
self.admit_run(scan_run_id, target_id).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Count the run `scan_run_id`, a person's request that took over a
|
||||
/// waiting scan, only when `detected` (that scan's attribution from change
|
||||
/// detection) counts on a target billed as `billing`, and then check it
|
||||
/// against the plan (t84). The run keeps the person's attribution, so its
|
||||
/// history shows that a person asked. Several code artifacts: a change in
|
||||
/// any of them counts it, as in [`Self::attribute_run`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
|
||||
/// Prüfung now.
|
||||
async fn charge_as_taken_over(
|
||||
&self,
|
||||
scan_run_id: &str,
|
||||
target_id: &str,
|
||||
detected: ScanAttribution,
|
||||
billing: TargetBilling,
|
||||
) -> Result<(), AgentError> {
|
||||
if !detected.chargeable(billing) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) {
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(doc! { "_id": oid }, doc! { "$set": { "chargeable": true } })
|
||||
.await
|
||||
{
|
||||
tracing::warn!(scan_run_id, "scan run not marked as counted: {e}");
|
||||
}
|
||||
}
|
||||
self.admit_run(scan_run_id, target_id).await
|
||||
}
|
||||
|
||||
/// Store `attribution` and `chargeable` on the run, unless it already
|
||||
/// reads as a change.
|
||||
async fn record_attribution(
|
||||
&self,
|
||||
scan_run_id: &str,
|
||||
attribution: ScanAttribution,
|
||||
chargeable: bool,
|
||||
) {
|
||||
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else {
|
||||
return;
|
||||
};
|
||||
let Ok(value) = mongodb::bson::to_bson(&attribution) else {
|
||||
return;
|
||||
};
|
||||
let change = mongodb::bson::to_bson(&ScanAttribution::Change).unwrap_or_default();
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.scan_runs()
|
||||
.update_one(
|
||||
doc! { "_id": oid, "attribution": { "$ne": change } },
|
||||
doc! { "$set": {
|
||||
"attribution": value,
|
||||
"chargeable": chargeable,
|
||||
} },
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(scan_run_id, "scan run not attributed: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the applicable scans for a target. For a code target this reuses the
|
||||
@@ -1262,6 +1615,27 @@ impl PipelineOrchestrator {
|
||||
.await;
|
||||
return Ok(0);
|
||||
}
|
||||
// A git target is attributed where its commits are compared.
|
||||
if !has_git {
|
||||
let changed = crate::pipeline::change::content_changed(target);
|
||||
if !trigger.started_by_person() {
|
||||
self.attribute_run(
|
||||
scan_run_id,
|
||||
&target_id,
|
||||
ScanAttribution::detected(trigger, changed),
|
||||
target.billing,
|
||||
)
|
||||
.await?;
|
||||
} else if let Some(original) = &self.charged_as {
|
||||
self.charge_as_taken_over(
|
||||
scan_run_id,
|
||||
&target_id,
|
||||
ScanAttribution::detected(original, changed),
|
||||
target.billing,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let plan = build_scan_plan(target);
|
||||
// An attached artifact nothing analyses is recorded, never passed over:
|
||||
// a completed run must not read as "we looked and found nothing".
|
||||
@@ -1471,6 +1845,8 @@ impl PipelineOrchestrator {
|
||||
// Each source's findings next to the tree they were found in: the
|
||||
// control mapping below reads the flagged regions from it.
|
||||
let mut analysed = Vec::with_capacity(sources.len());
|
||||
// Every tree's POUs, for the code graph.
|
||||
let mut plc_files = Vec::new();
|
||||
let mut all_sbom: Vec<SbomEntry> = Vec::new();
|
||||
let mut sbom_seen = std::collections::BTreeSet::new();
|
||||
// CODESYS projects in their native format: their control logic is not
|
||||
@@ -1489,10 +1865,12 @@ impl PipelineOrchestrator {
|
||||
left_out.excluded.extend(pruned.excluded);
|
||||
left_out.test_data.extend(pruned.test_data);
|
||||
native.extend(crate::pipeline::plc::native_projects(&path));
|
||||
let files = crate::pipeline::plc::read_tree(&path);
|
||||
analysed.push((
|
||||
path.clone(),
|
||||
crate::pipeline::plc::analyze_tree(&path, target_id),
|
||||
crate::pipeline::plc::findings(&files, target_id),
|
||||
));
|
||||
plc_files.extend(files);
|
||||
// Control-application SBOM: CODESYS libraries + runtime from a
|
||||
// `.projectarchive` (uploaded, or committed in the working tree).
|
||||
let archive = a
|
||||
@@ -1554,6 +1932,21 @@ impl PipelineOrchestrator {
|
||||
"PLC control-logic analysis complete"
|
||||
);
|
||||
|
||||
// The POUs and how they use each other, as for a code scan; a stale
|
||||
// graph is replaced even when no POU was read.
|
||||
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
|
||||
.await;
|
||||
if let Err(e) = self
|
||||
.build_code_graph(
|
||||
crate::pipeline::graph_build::GraphSource::Plc(&plc_files),
|
||||
target_id,
|
||||
&all_findings,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(target_id, error = %e, "PLC graph building failed");
|
||||
}
|
||||
|
||||
let mut new_count = 0u32;
|
||||
let mut refreshed_count = 0u32;
|
||||
for mut finding in all_findings {
|
||||
@@ -1594,7 +1987,7 @@ impl PipelineOrchestrator {
|
||||
.with_excluded(left_out.excluded)
|
||||
.with_test_data(left_out.test_data);
|
||||
let closed = left_out_run
|
||||
.resolve_left_out(&self.db, target_id, "plc-control-logic")
|
||||
.resolve_left_out(&self.db, target_id, Some("plc-control-logic"))
|
||||
.await?;
|
||||
if closed > 0 {
|
||||
tracing::info!(target_id, closed, "PLC findings in left-out paths resolved");
|
||||
@@ -3006,6 +3399,7 @@ fn planned_phases(
|
||||
if config.breakpilot.semantic_mapping {
|
||||
phases.push(ScanPhase::SemanticControlMapping);
|
||||
}
|
||||
phases.push(ScanPhase::GraphBuilding);
|
||||
if config.plc_runtime.enabled && target.live_url().is_none() {
|
||||
phases.push(ScanPhase::PlcProvision);
|
||||
}
|
||||
@@ -3159,7 +3553,11 @@ mod tests {
|
||||
|
||||
assert_eq!(
|
||||
planned_phases(&target, &plan, &config),
|
||||
[ScanPhase::Classification, ScanPhase::PlcAnalysis]
|
||||
[
|
||||
ScanPhase::Classification,
|
||||
ScanPhase::PlcAnalysis,
|
||||
ScanPhase::GraphBuilding
|
||||
]
|
||||
);
|
||||
|
||||
// The LLM control mapping is a phase of its own, so a long one shows.
|
||||
@@ -3169,7 +3567,8 @@ mod tests {
|
||||
[
|
||||
ScanPhase::Classification,
|
||||
ScanPhase::PlcAnalysis,
|
||||
ScanPhase::SemanticControlMapping
|
||||
ScanPhase::SemanticControlMapping,
|
||||
ScanPhase::GraphBuilding
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -186,9 +186,17 @@ fn scan_with_patterns(
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
let content = match std::fs::read_to_string(path) {
|
||||
Ok(c) => c,
|
||||
Err(_) => continue, // skip binary files
|
||||
// Only files a pattern looks at are read at all.
|
||||
if !patterns.iter().any(|p| p.file_extensions.contains(&ext)) {
|
||||
continue;
|
||||
}
|
||||
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
|
||||
let content = match compliance_core::encoding::read_source(path) {
|
||||
Ok(text) => text,
|
||||
Err(error) => {
|
||||
tracing::debug!(file = %path.display(), %error, "pattern scan: file not readable");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let relative_path = path
|
||||
@@ -386,8 +394,12 @@ mod tests {
|
||||
fn oauth_token_url_matches() {
|
||||
let scanner = OAuthPatternScanner::new();
|
||||
let pattern = &scanner.patterns[3]; // oauth-token-url
|
||||
assert!(pattern.pattern.is_match("access_token = build_url(query)"));
|
||||
assert!(pattern.pattern.is_match("bearer = url.param"));
|
||||
// Split, so this file's own line does not match the rule it tests
|
||||
// when Prüfwerk scans its own repository.
|
||||
assert!(pattern
|
||||
.pattern
|
||||
.is_match(concat!("access_", "token = build_url(query)")));
|
||||
assert!(pattern.pattern.is_match(concat!("bear", "er = url.param")));
|
||||
}
|
||||
|
||||
// --- Pattern rule file extension filtering ---
|
||||
@@ -413,4 +425,30 @@ mod tests {
|
||||
assert!(!pattern.file_extensions.contains(&"rs".to_string()));
|
||||
assert!(!pattern.file_extensions.contains(&"py".to_string()));
|
||||
}
|
||||
|
||||
// --- file decoding ---
|
||||
|
||||
#[test]
|
||||
fn a_windows_1252_file_is_scanned_not_skipped() {
|
||||
// Arrange: a C# file written by an older tool, "Größe" as 0xF6 0xDF.
|
||||
let dir = std::env::temp_dir().join(format!("cs-pat-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Log.cs"), b"// Gr\xF6\xDFe\nLog(email);\n").unwrap();
|
||||
let rule = PatternRule {
|
||||
id: "pii".into(),
|
||||
title: "t".into(),
|
||||
description: "d".into(),
|
||||
pattern: compile_regex(r"Log\(email\)"),
|
||||
severity: Severity::Medium,
|
||||
file_extensions: vec!["cs".into()],
|
||||
};
|
||||
|
||||
// Act
|
||||
let findings = scan_with_patterns(&dir, "repo", &[rule], ScanType::Gdpr, "t").unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// Assert: found on its line.
|
||||
assert_eq!(findings.len(), 1);
|
||||
assert_eq!(findings[0].line_number, Some(2));
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,96 @@ pub struct Pou {
|
||||
pub vars: Vec<VarDecl>,
|
||||
/// The statement body.
|
||||
pub body: Vec<Stmt>,
|
||||
/// 1-based line where the POU header appears (in the source that was parsed).
|
||||
/// 1-based line where the POU header appears. For a PLCopen POU it is
|
||||
/// the `<pou>` element's line in the XML; its statements keep the lines
|
||||
/// of the Structured Text reconstructed from it.
|
||||
pub line: u32,
|
||||
/// 1-based line of its `END_*` keyword (the last line when it is
|
||||
/// missing); for a PLCopen POU, the `</pou>` line.
|
||||
pub end_line: u32,
|
||||
}
|
||||
|
||||
impl Pou {
|
||||
/// Call `visit` with the callee and line of every call in the body, bare
|
||||
/// (`TON1(IN := x);`) or inside an expression (`LIMIT(0, x, 10)`), in
|
||||
/// source order.
|
||||
pub fn for_each_call(&self, mut visit: impl FnMut(&str, u32)) {
|
||||
for stmt in &self.body {
|
||||
stmt.for_each_call(&mut visit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stmt {
|
||||
/// See [`Pou::for_each_call`]. `visit` is `&mut dyn` so the recursion
|
||||
/// through nested blocks doesn't instantiate a new closure type per level.
|
||||
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
|
||||
let block = |body: &[Stmt], visit: &mut dyn FnMut(&str, u32)| {
|
||||
for stmt in body {
|
||||
stmt.for_each_call(visit);
|
||||
}
|
||||
};
|
||||
match self {
|
||||
Stmt::Assign { target, value, .. } => {
|
||||
target.for_each_call(visit);
|
||||
value.for_each_call(visit);
|
||||
}
|
||||
Stmt::If {
|
||||
branches,
|
||||
else_body,
|
||||
..
|
||||
} => {
|
||||
for (cond, body) in branches {
|
||||
cond.for_each_call(visit);
|
||||
block(body, visit);
|
||||
}
|
||||
if let Some(body) = else_body {
|
||||
block(body, visit);
|
||||
}
|
||||
}
|
||||
Stmt::Case {
|
||||
selector,
|
||||
arms,
|
||||
else_body,
|
||||
..
|
||||
} => {
|
||||
selector.for_each_call(visit);
|
||||
for (labels, body) in arms {
|
||||
for label in labels {
|
||||
label.for_each_call(visit);
|
||||
}
|
||||
block(body, visit);
|
||||
}
|
||||
if let Some(body) = else_body {
|
||||
block(body, visit);
|
||||
}
|
||||
}
|
||||
Stmt::For {
|
||||
from, to, by, body, ..
|
||||
} => {
|
||||
from.for_each_call(visit);
|
||||
to.for_each_call(visit);
|
||||
if let Some(by) = by {
|
||||
by.for_each_call(visit);
|
||||
}
|
||||
block(body, visit);
|
||||
}
|
||||
Stmt::While { cond, body, .. }
|
||||
| Stmt::Repeat {
|
||||
body, until: cond, ..
|
||||
} => {
|
||||
cond.for_each_call(visit);
|
||||
block(body, visit);
|
||||
}
|
||||
Stmt::Call { callee, args, line } => {
|
||||
visit(callee, *line);
|
||||
for arg in args {
|
||||
arg.value.for_each_call(visit);
|
||||
}
|
||||
}
|
||||
Stmt::Return { .. } | Stmt::Exit { .. } | Stmt::Jump { .. } | Stmt::Label { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -191,6 +279,35 @@ impl Expr {
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`Pou::for_each_call`].
|
||||
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
|
||||
match self {
|
||||
Expr::Int(..)
|
||||
| Expr::Real(..)
|
||||
| Expr::Bool(..)
|
||||
| Expr::Str(..)
|
||||
| Expr::Time(..)
|
||||
| Expr::Ident(..) => {}
|
||||
Expr::Index { base, index, .. } => {
|
||||
base.for_each_call(visit);
|
||||
index.for_each_call(visit);
|
||||
}
|
||||
Expr::Member { base, .. } | Expr::Unary { expr: base, .. } => {
|
||||
base.for_each_call(visit);
|
||||
}
|
||||
Expr::Binary { lhs, rhs, .. } => {
|
||||
lhs.for_each_call(visit);
|
||||
rhs.for_each_call(visit);
|
||||
}
|
||||
Expr::Call { callee, args, line } => {
|
||||
visit(callee, *line);
|
||||
for arg in args {
|
||||
arg.value.for_each_call(visit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// If this expression is a plain identifier, its name.
|
||||
pub fn as_ident(&self) -> Option<&str> {
|
||||
match self {
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
//! The POUs of a PLC project as code-graph nodes and edges, for
|
||||
//! [`compliance_graph::GraphEngine::assemble`].
|
||||
//!
|
||||
//! - A `PROGRAM` is a module and an entry point: the PLC's tasks run it.
|
||||
//! - A `FUNCTION_BLOCK` is a class, since each instance keeps its own state.
|
||||
//! - A `FUNCTION` is a function.
|
||||
//!
|
||||
//! A variable whose type is a function block is a dependency on it (a type
|
||||
//! reference). A call through an instance (`Pump1(Start := x)`) is a call to
|
||||
//! its type. Standard blocks such as `TON` or `CTU` have no node, so their
|
||||
//! edges stay unresolved and the engine drops them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
|
||||
use compliance_core::traits::graph_builder::ParseOutput;
|
||||
use compliance_graph::parsers::FileGraph;
|
||||
|
||||
use super::ast::{Pou, PouKind};
|
||||
use super::PlcFile;
|
||||
|
||||
/// The nodes and edges of every POU in `files`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `files` - the PLC source files read from one or more trees
|
||||
/// * `repo_id`, `graph_build_id` - stamped on every node and edge
|
||||
pub(crate) fn parse_output(files: &[PlcFile], repo_id: &str, graph_build_id: &str) -> ParseOutput {
|
||||
let mut output = ParseOutput::default();
|
||||
for file in files {
|
||||
let language = if file.plcopen {
|
||||
"plcopen"
|
||||
} else {
|
||||
"structured_text"
|
||||
};
|
||||
let mut graph = FileGraph::new(
|
||||
Path::new(&file.rel),
|
||||
file.line_count,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
language,
|
||||
);
|
||||
for pou in &file.pous {
|
||||
add_pou(&mut graph, pou);
|
||||
}
|
||||
let part = graph.finish();
|
||||
output.nodes.extend(part.nodes);
|
||||
output.edges.extend(part.edges);
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Add `pou`'s node, its type references and its calls.
|
||||
fn add_pou(graph: &mut FileGraph<'_>, pou: &Pou) {
|
||||
let qualified = graph.top_level(&pou.name);
|
||||
let kind = match pou.kind {
|
||||
PouKind::Program => CodeNodeKind::Module,
|
||||
PouKind::FunctionBlock => CodeNodeKind::Class,
|
||||
PouKind::Function => CodeNodeKind::Function,
|
||||
};
|
||||
graph.node_at(
|
||||
qualified.clone(),
|
||||
pou.name.clone(),
|
||||
kind,
|
||||
(pou.line, pou.end_line),
|
||||
pou.kind == PouKind::Program,
|
||||
);
|
||||
|
||||
// IEC 61131-3 identifiers are case-insensitive, so the instances are
|
||||
// looked up by their lowercased name.
|
||||
let mut instances: HashMap<String, &str> = HashMap::with_capacity(pou.vars.len());
|
||||
for var in &pou.vars {
|
||||
if !is_identifier(&var.type_name) {
|
||||
continue; // ARRAY[..] OF, POINTER TO, STRING(80): not a block type
|
||||
}
|
||||
graph.edge_at(&qualified, &var.type_name, CodeEdgeKind::TypeRef, var.line);
|
||||
instances.insert(var.name.to_ascii_lowercase(), var.type_name.as_str());
|
||||
}
|
||||
|
||||
pou.for_each_call(|callee, line| {
|
||||
let target = instances
|
||||
.get(&callee.to_ascii_lowercase())
|
||||
.copied()
|
||||
.unwrap_or(callee);
|
||||
graph.edge_at(&qualified, target, CodeEdgeKind::Calls, line);
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a declared type is a plain name (`FB_Pump`, `TON`, `INT`).
|
||||
fn is_identifier(type_name: &str) -> bool {
|
||||
!type_name.is_empty()
|
||||
&& type_name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pipeline::plc::{parser, plcopen};
|
||||
|
||||
fn st_file(rel: &str, source: &str) -> PlcFile {
|
||||
PlcFile {
|
||||
rel: rel.to_string(),
|
||||
plcopen: false,
|
||||
line_count: source.lines().count() as u32,
|
||||
pous: parser::parse(source),
|
||||
}
|
||||
}
|
||||
|
||||
const LINE: &str = "\
|
||||
FUNCTION_BLOCK FB_Pump
|
||||
VAR_INPUT
|
||||
Start : BOOL;
|
||||
END_VAR
|
||||
VAR
|
||||
Delay : TON;
|
||||
END_VAR
|
||||
Delay(IN := Start, PT := T#2s);
|
||||
END_FUNCTION_BLOCK
|
||||
|
||||
FUNCTION Clamp : INT
|
||||
VAR_INPUT
|
||||
x : INT;
|
||||
END_VAR
|
||||
Clamp := LIMIT(0, x, 100);
|
||||
END_FUNCTION
|
||||
|
||||
PROGRAM Main
|
||||
VAR
|
||||
pump1 : FB_Pump;
|
||||
level : INT;
|
||||
END_VAR
|
||||
PUMP1(Start := TRUE);
|
||||
IF Clamp(level) > 50 THEN
|
||||
level := 0;
|
||||
END_IF;
|
||||
END_PROGRAM
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn pous_become_nodes_and_programs_entry_points() {
|
||||
let output = parse_output(&[st_file("src/line.st", LINE)], "r", "b");
|
||||
|
||||
let node = |name: &str| {
|
||||
output
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.name == name)
|
||||
.unwrap_or_else(|| panic!("no node {name}"))
|
||||
};
|
||||
assert_eq!(node("line.st").kind, CodeNodeKind::File);
|
||||
let pump = node("FB_Pump");
|
||||
assert_eq!(pump.kind, CodeNodeKind::Class);
|
||||
assert_eq!(pump.qualified_name, "src/line.st::FB_Pump");
|
||||
assert_eq!((pump.start_line, pump.end_line), (1, 9));
|
||||
assert!(!pump.is_entry_point);
|
||||
assert_eq!(node("Clamp").kind, CodeNodeKind::Function);
|
||||
let main = node("Main");
|
||||
assert_eq!(main.kind, CodeNodeKind::Module);
|
||||
assert_eq!((main.start_line, main.end_line), (18, 27));
|
||||
assert!(main.is_entry_point);
|
||||
assert!(output.nodes.iter().all(|n| n.language == "structured_text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_lead_to_their_type_and_calls_to_the_callee() {
|
||||
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
|
||||
let edges: Vec<(&str, CodeEdgeKind)> = output
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| e.source == "line.st::Main")
|
||||
.map(|e| (e.target.as_str(), e.kind.clone()))
|
||||
.collect();
|
||||
|
||||
// The instance declaration and the call through it (in another case)
|
||||
// lead to FB_Pump; the function is called by name.
|
||||
let to = |target: &str, kind: CodeEdgeKind| {
|
||||
edges
|
||||
.iter()
|
||||
.filter(|(t, k)| *t == target && *k == kind)
|
||||
.count()
|
||||
};
|
||||
assert_eq!(to("FB_Pump", CodeEdgeKind::TypeRef), 1);
|
||||
assert_eq!(to("FB_Pump", CodeEdgeKind::Calls), 1);
|
||||
assert_eq!(to("Clamp", CodeEdgeKind::Calls), 1);
|
||||
// A standard block keeps its own name and resolves to nothing.
|
||||
assert!(output
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.source == "line.st::FB_Pump" && e.target == "TON"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plcopen_pous_span_their_xml_element() {
|
||||
let xml = r#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<project>
|
||||
<types>
|
||||
<pous>
|
||||
<pou name="Main" pouType="program">
|
||||
<interface>
|
||||
<localVars>
|
||||
<variable name="pump1"><type><derived name="FB_Pump"/></type></variable>
|
||||
</localVars>
|
||||
</interface>
|
||||
<body>
|
||||
<ST><xhtml xmlns="http://www.w3.org/1999/xhtml">pump1(Start := TRUE);</xhtml></ST>
|
||||
</body>
|
||||
</pou>
|
||||
</pous>
|
||||
</types>
|
||||
</project>
|
||||
"#;
|
||||
let file = PlcFile {
|
||||
rel: "export.xml".to_string(),
|
||||
plcopen: true,
|
||||
line_count: xml.lines().count() as u32,
|
||||
pous: plcopen::parse_plcopen(xml),
|
||||
};
|
||||
let output = parse_output(&[file], "r", "b");
|
||||
|
||||
let main = output
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|n| n.name == "Main")
|
||||
.expect("Main is a node");
|
||||
assert_eq!((main.start_line, main.end_line), (5, 14));
|
||||
assert_eq!(main.language, "plcopen");
|
||||
assert!(output
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.target == "FB_Pump" && e.kind == CodeEdgeKind::Calls));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_engine_links_instances_and_drops_standard_blocks() {
|
||||
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
|
||||
let (graph, run) = compliance_graph::GraphEngine::new(1_000)
|
||||
.assemble(output, "r")
|
||||
.expect("assembles");
|
||||
|
||||
let linked = |source: &str, target: &str| {
|
||||
graph
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.source == source && e.target == target)
|
||||
};
|
||||
assert!(linked("line.st::Main", "line.st::FB_Pump"));
|
||||
assert!(linked("line.st::Main", "line.st::Clamp"));
|
||||
assert!(!graph.edges.iter().any(|e| e.target == "TON"));
|
||||
assert_eq!(run.languages_parsed, ["structured_text"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pou_of_the_demo_project_is_a_node() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/plc-demo");
|
||||
let mut files = crate::pipeline::plc::read_tree(&root);
|
||||
files.sort_by(|a, b| a.rel.cmp(&b.rel));
|
||||
let output = parse_output(&files, "r", "b");
|
||||
|
||||
let mut pous: Vec<(&str, bool)> = output
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|n| n.kind != CodeNodeKind::File)
|
||||
.map(|n| (n.name.as_str(), n.is_entry_point))
|
||||
.collect();
|
||||
pous.sort();
|
||||
assert_eq!(
|
||||
pous,
|
||||
[
|
||||
("ConveyorCtrl", true),
|
||||
("PumpFbdCtrl", false),
|
||||
("PumpStationCtrl", false),
|
||||
("TrafficLight", true),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
output
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|n| n.kind == CodeNodeKind::File)
|
||||
.count(),
|
||||
4
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_plain_type_names_are_references() {
|
||||
assert!(is_identifier("FB_Pump"));
|
||||
assert!(!is_identifier("ARRAY[0..9] OF INT"));
|
||||
assert!(!is_identifier("STRING(80)"));
|
||||
assert!(!is_identifier(""));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
//! scan says so instead of finding nothing in silence (#165).
|
||||
|
||||
pub mod ast;
|
||||
pub(crate) mod graph;
|
||||
pub mod lexer;
|
||||
pub mod parser;
|
||||
pub mod plcopen;
|
||||
@@ -45,9 +46,26 @@ impl Scanner for PlcControlLogicScanner {
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk a PLC project tree and produce findings.
|
||||
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
let mut findings = Vec::new();
|
||||
/// A PLC source file and the POUs read from it.
|
||||
pub(crate) struct PlcFile {
|
||||
/// The path relative to the tree it was found in.
|
||||
pub(crate) rel: String,
|
||||
/// Whether it is a PLCopen XML export rather than Structured Text.
|
||||
pub(crate) plcopen: bool,
|
||||
/// Its number of lines.
|
||||
pub(crate) line_count: u32,
|
||||
pub(crate) pous: Vec<ast::Pou>,
|
||||
}
|
||||
|
||||
/// Read every PLC source file under `root` (Structured Text, and PLCopen XML
|
||||
/// exports) into its POUs. Files with no POU are left out.
|
||||
///
|
||||
/// Each file is decoded by [`compliance_core::encoding::read_source`]:
|
||||
/// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not
|
||||
/// readable as text are logged as one warning per tree.
|
||||
pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
|
||||
let mut files = Vec::new();
|
||||
let mut unreadable: u32 = 0;
|
||||
for entry in walkdir::WalkDir::new(root)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
@@ -66,8 +84,17 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
if !is_st && !is_xml {
|
||||
continue;
|
||||
}
|
||||
let Ok(content) = std::fs::read_to_string(path) else {
|
||||
continue;
|
||||
let content = match compliance_core::encoding::read_source(path) {
|
||||
Ok(text) => text,
|
||||
Err(error) => {
|
||||
// A binary `.project` is CODESYS's native format, which
|
||||
// [`native_projects`] reports; anything else is a loss.
|
||||
if ext != "project" {
|
||||
tracing::debug!(file = %path.display(), %error, "PLC source file not readable");
|
||||
unreadable += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// A `.project` is read only as a PLCopen export; CODESYS's native one
|
||||
// is binary ([`native_projects`] reports it).
|
||||
@@ -82,16 +109,41 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
if pous.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rel = path
|
||||
.strip_prefix(root)
|
||||
.unwrap_or(path)
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
for pou in &pous {
|
||||
files.push(PlcFile {
|
||||
rel: path
|
||||
.strip_prefix(root)
|
||||
.unwrap_or(path)
|
||||
.to_string_lossy()
|
||||
.to_string(),
|
||||
plcopen: is_xml,
|
||||
line_count: content.lines().count() as u32,
|
||||
pous,
|
||||
});
|
||||
}
|
||||
// One line per tree; the paths are logged at debug level only.
|
||||
if unreadable > 0 {
|
||||
tracing::warn!(
|
||||
unreadable_files = unreadable,
|
||||
"PLC source files left out: not readable as text"
|
||||
);
|
||||
}
|
||||
files
|
||||
}
|
||||
|
||||
/// Run the control-logic rules over the POUs of `files`.
|
||||
pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
|
||||
let mut findings = Vec::new();
|
||||
for file in files {
|
||||
for pou in &file.pous {
|
||||
for hit in rules::analyze(pou) {
|
||||
let line_s = hit.line.to_string();
|
||||
let fingerprint =
|
||||
dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]);
|
||||
let fingerprint = dedup::compute_fingerprint(&[
|
||||
repo_id,
|
||||
&file.rel,
|
||||
hit.rule_id,
|
||||
&pou.name,
|
||||
&line_s,
|
||||
]);
|
||||
let mut f = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
@@ -101,7 +153,7 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
hit.description,
|
||||
hit.severity,
|
||||
);
|
||||
f.file_path = Some(rel.clone());
|
||||
f.file_path = Some(file.rel.clone());
|
||||
f.line_number = Some(hit.line);
|
||||
f.rule_id = Some(hit.rule_id.to_string());
|
||||
f.cwe = hit.cwe.map(String::from);
|
||||
@@ -113,6 +165,11 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
findings
|
||||
}
|
||||
|
||||
/// Walk a PLC project tree and produce findings.
|
||||
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
findings(&read_tree(root), repo_id)
|
||||
}
|
||||
|
||||
/// Whether `content` starts as an XML document (after a byte-order mark and
|
||||
/// white space).
|
||||
fn looks_like_xml(content: &str) -> bool {
|
||||
@@ -152,10 +209,9 @@ pub fn native_projects(root: &Path) -> Vec<String> {
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
let native = match ext.as_str() {
|
||||
"project" => !std::fs::read(path)
|
||||
.ok()
|
||||
.and_then(|bytes| String::from_utf8(bytes).ok())
|
||||
.is_some_and(|text| looks_like_xml(&text)),
|
||||
// Decoded as [`read_tree`] reads it: a UTF-16 export is no native one.
|
||||
"project" => !compliance_core::encoding::read_source(path)
|
||||
.is_ok_and(|text| looks_like_xml(&text)),
|
||||
"projectarchive" => sbom::check_archive(path).is_ok(),
|
||||
_ => false,
|
||||
};
|
||||
@@ -349,4 +405,41 @@ mod tests {
|
||||
// The binary project yields no POUs and no error.
|
||||
assert!(analyze_tree(&root.0, "t").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_1252_and_utf16_sources_are_read() {
|
||||
// Arrange: Structured Text as older CODESYS saves it (Windows-1252:
|
||||
// "Größe" is F6 DF, "€" is 80), and a PLCopen export in UTF-16 LE.
|
||||
let root =
|
||||
Scratch(std::env::temp_dir().join(format!("cs-plc-enc-{}", uuid::Uuid::new_v4())));
|
||||
std::fs::create_dir_all(&root.0).expect("mkdir");
|
||||
std::fs::write(
|
||||
root.0.join("legacy.st"),
|
||||
b"PROGRAM Legacy\nVAR\n s : STRING := 'Gr\xF6\xDFe in \x80';\nEND_VAR\n\
|
||||
s := 'x'; (* Gr\xF6\xDFe *)\nEND_PROGRAM\n",
|
||||
)
|
||||
.expect("write st");
|
||||
let xml = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\
|
||||
<project xmlns=\"http://www.plcopen.org/xml/tc6_0201\"><types><pous>\
|
||||
<pou name=\"Wide\" pouType=\"program\"><interface><localVars>\
|
||||
<variable name=\"Größe\"><type><INT/></type></variable></localVars></interface>\
|
||||
<body><ST><xhtml xmlns=\"http://www.w3.org/1999/xhtml\">x := 1;</xhtml></ST></body>\
|
||||
</pou></pous></types></project>";
|
||||
let utf16: Vec<u8> = [0xFF, 0xFE]
|
||||
.into_iter()
|
||||
.chain(xml.encode_utf16().flat_map(u16::to_le_bytes))
|
||||
.collect();
|
||||
std::fs::write(root.0.join("wide.xml"), utf16).expect("write xml");
|
||||
|
||||
// Act
|
||||
let files = read_tree(&root.0);
|
||||
|
||||
// Assert
|
||||
let mut pous: Vec<&str> = files
|
||||
.iter()
|
||||
.flat_map(|f| f.pous.iter().map(|p| p.name.as_str()))
|
||||
.collect();
|
||||
pous.sort_unstable();
|
||||
assert_eq!(pous, ["Legacy", "Wide"]);
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,7 @@ impl Parser {
|
||||
body.push(s);
|
||||
}
|
||||
}
|
||||
let end_line = self.line();
|
||||
self.eat_kw(end);
|
||||
|
||||
Some(Pou {
|
||||
@@ -127,6 +128,7 @@ impl Parser {
|
||||
vars,
|
||||
body,
|
||||
line,
|
||||
end_line,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,16 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
|
||||
_ => "PROGRAM",
|
||||
};
|
||||
let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n");
|
||||
pous.extend(parser::parse(&synthetic));
|
||||
// Statement lines stay those of the synthetic source (the findings'
|
||||
// lines and fingerprints use them); the POU itself spans its
|
||||
// `<pou>` element in the XML, which is what the code graph shows.
|
||||
let start = doc.text_pos_at(pou.range().start).row;
|
||||
let end = doc.text_pos_at(pou.range().end).row;
|
||||
pous.extend(parser::parse(&synthetic).into_iter().map(|mut parsed| {
|
||||
parsed.line = start;
|
||||
parsed.end_line = end;
|
||||
parsed
|
||||
}));
|
||||
}
|
||||
pous
|
||||
}
|
||||
|
||||
@@ -45,6 +45,11 @@ pub struct RepoView {
|
||||
/// Whether the target's uploaded files let a scheduled scan without new
|
||||
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
|
||||
pub uploads_allow_skip: bool,
|
||||
/// Whether the customer changed something besides the commits since the
|
||||
/// last completed scan: an uploaded file, or a live URL to probe (t72).
|
||||
pub changed_besides_commits: bool,
|
||||
/// How the target is billed, for whether its scan counts (t72).
|
||||
pub billing: compliance_core::models::TargetBilling,
|
||||
/// Whether the tree is read as Yocto layers (its recipe inventory): it
|
||||
/// was classified as one, or the target is a Yocto target. Set by the
|
||||
/// caller after classification; `false` from [`Self::from_target`].
|
||||
@@ -84,6 +89,9 @@ impl RepoView {
|
||||
findings_count: target.findings_count,
|
||||
managed: target.source_repo.is_some(),
|
||||
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
|
||||
changed_besides_commits: target.live_url().is_some()
|
||||
|| crate::pipeline::change::uploads_changed(target),
|
||||
billing: target.billing,
|
||||
yocto_layers: false,
|
||||
exclude_paths: target.scan_config.exclude_paths.clone(),
|
||||
build_outputs: Vec::new(),
|
||||
|
||||
@@ -19,9 +19,10 @@ pub fn relative_path(root: &Path, path: &str) -> String {
|
||||
rel.to_string_lossy().replace('\\', "/")
|
||||
}
|
||||
|
||||
/// The whole text of `root/rel`. `None` when the file is unreadable or the
|
||||
/// path would leave `root`: scanner output is not trusted to stay inside the
|
||||
/// tree.
|
||||
/// The whole text of `root/rel`, decoded by
|
||||
/// [`compliance_core::encoding::read_source`]. `None` when the file is
|
||||
/// unreadable or the path would leave `root`: scanner output is not trusted
|
||||
/// to stay inside the tree.
|
||||
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
|
||||
let rel_path = Path::new(rel);
|
||||
if rel_path.is_absolute()
|
||||
@@ -31,7 +32,8 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
std::fs::read_to_string(root.join(rel_path)).ok()
|
||||
// UTF-16 with a BOM and Windows-1252 too, as the code graph reads them.
|
||||
compliance_core::encoding::read_source(&root.join(rel_path)).ok()
|
||||
}
|
||||
|
||||
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
|
||||
|
||||
@@ -13,11 +13,19 @@
|
||||
//! working copy is a git clone, restored on every fetch, or an unpacked
|
||||
//! upload, unpacked again on every scan, so nothing is lost.
|
||||
//!
|
||||
//! Matching is by directory name only, and narrow: `tests/` and `spec/`
|
||||
//! hold test code that can leak a real secret, and `examples/` or `demo/` are
|
||||
//! often the product's own code, so neither is matched.
|
||||
//! Matching is by directory name, and narrow: `tests/` and `spec/` hold test
|
||||
//! code that can leak a real secret, and `examples/` or `demo/` are often the
|
||||
//! product's own code, so neither is matched.
|
||||
//!
|
||||
//! One more kind is found by its content: a Semgrep rule pack. Semgrep's own
|
||||
//! test convention puts each rule `X.yaml` next to the sample it is tested
|
||||
//! on, `X.py` or `X.cs`, and the samples hold the flaws the rules must find.
|
||||
//! A directory with such a pair is test data with everything below it (a
|
||||
//! vendored pack's manifests too), unless it is the tree itself.
|
||||
|
||||
use std::path::Path;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Directory names that hold test data by convention, compared
|
||||
/// case-insensitively: `fixtures` (Rails, pytest, Jest's `__fixtures__`),
|
||||
@@ -32,8 +40,13 @@ const TEST_DATA_DIR_NAMES: &[&str] = &[
|
||||
"test_fixtures",
|
||||
];
|
||||
|
||||
/// A rule file larger than this is not read: Semgrep rule files are a few
|
||||
/// kilobytes, and a large YAML file is data, not a rule pack.
|
||||
const MAX_RULE_FILE_BYTES: u64 = 1024 * 1024;
|
||||
|
||||
/// The top-most test-data directories under `root`, relative to it with `/`
|
||||
/// separators, sorted. A directory inside one that already matched is not
|
||||
/// separators, sorted: those named like test data, and Semgrep rule packs
|
||||
/// with their samples. A directory inside one that already matched is not
|
||||
/// listed again, `root` itself is never listed, and a symbolic link is never
|
||||
/// followed or listed.
|
||||
///
|
||||
@@ -47,6 +60,9 @@ const TEST_DATA_DIR_NAMES: &[&str] = &[
|
||||
/// "pkg/parser/testdata"]`.
|
||||
pub fn test_data_dirs(root: &Path) -> Vec<String> {
|
||||
let mut found = Vec::new();
|
||||
// YAML files outside the test data found so far: rule pack candidates,
|
||||
// checked once the walk is done.
|
||||
let mut yaml_files = Vec::new();
|
||||
let mut walker = walkdir::WalkDir::new(root).min_depth(1).into_iter();
|
||||
while let Some(entry) = walker.next() {
|
||||
let Ok(entry) = entry else {
|
||||
@@ -54,6 +70,12 @@ pub fn test_data_dirs(root: &Path) -> Vec<String> {
|
||||
};
|
||||
// `file_type()` does not follow links: a link to a directory is a
|
||||
// link here, never a directory.
|
||||
if entry.file_type().is_file() {
|
||||
if is_yaml(entry.path()) {
|
||||
yaml_files.push(entry.into_path());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !entry.file_type().is_dir() {
|
||||
continue;
|
||||
}
|
||||
@@ -69,8 +91,97 @@ pub fn test_data_dirs(root: &Path) -> Vec<String> {
|
||||
walker.skip_current_dir();
|
||||
}
|
||||
}
|
||||
found.sort();
|
||||
found
|
||||
found.extend(rule_pack_dirs(root, &yaml_files));
|
||||
top_most(found)
|
||||
}
|
||||
|
||||
/// The directories, relative to `root`, of the `yaml_files` that are Semgrep
|
||||
/// rules with a sample of the same name next to them. Each directory is read
|
||||
/// once, and a rule file only when such a sample exists.
|
||||
fn rule_pack_dirs(root: &Path, yaml_files: &[PathBuf]) -> Vec<String> {
|
||||
// Per directory: the names (without extension) of its files that are not
|
||||
// YAML, the possible samples.
|
||||
let mut samples: HashMap<&Path, HashSet<OsString>> = HashMap::new();
|
||||
let mut packs: HashSet<&Path> = HashSet::new();
|
||||
for rule in yaml_files {
|
||||
let (Some(dir), Some(stem)) = (rule.parent(), rule.file_stem()) else {
|
||||
continue;
|
||||
};
|
||||
if dir == root || packs.contains(dir) {
|
||||
continue;
|
||||
}
|
||||
let names = samples.entry(dir).or_insert_with(|| sample_stems(dir));
|
||||
if names.contains(stem) && is_semgrep_rule_file(rule) {
|
||||
packs.insert(dir);
|
||||
}
|
||||
}
|
||||
packs
|
||||
.into_iter()
|
||||
.filter_map(|dir| dir.strip_prefix(root).ok())
|
||||
.map(|rel| rel.to_string_lossy().replace('\\', "/"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The names without extension of the regular files in `dir` that are not
|
||||
/// YAML.
|
||||
fn sample_stems(dir: &Path) -> HashSet<OsString> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return HashSet::new();
|
||||
};
|
||||
entries
|
||||
.flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
|
||||
.map(|e| e.path())
|
||||
.filter(|p| !is_yaml(p))
|
||||
.filter_map(|p| p.file_stem().map(OsString::from))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `path` ends in `.yaml` or `.yml`.
|
||||
fn is_yaml(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
|
||||
}
|
||||
|
||||
/// Whether the file at `path` is a Semgrep rule file: a `rules` list with at
|
||||
/// least one rule naming its `id`, `languages` and `message`, which Semgrep
|
||||
/// requires of every rule.
|
||||
fn is_semgrep_rule_file(path: &Path) -> bool {
|
||||
if !std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_RULE_FILE_BYTES) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(docs) = yaml_rust2::YamlLoader::load_from_str(&text) else {
|
||||
return false;
|
||||
};
|
||||
docs.first()
|
||||
.and_then(|doc| doc["rules"].as_vec())
|
||||
.is_some_and(|rules| {
|
||||
rules.iter().any(|rule| {
|
||||
rule["id"].as_str().is_some()
|
||||
&& !rule["languages"].is_badvalue()
|
||||
&& !rule["message"].is_badvalue()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `dirs` sorted, without those inside another one listed.
|
||||
fn top_most(mut dirs: Vec<String>) -> Vec<String> {
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
let mut kept: Vec<String> = Vec::with_capacity(dirs.len());
|
||||
for dir in dirs {
|
||||
let inside = kept.iter().any(|outer| {
|
||||
dir.strip_prefix(outer.as_str())
|
||||
.is_some_and(|rest| rest.starts_with('/'))
|
||||
});
|
||||
if !inside {
|
||||
kept.push(dir);
|
||||
}
|
||||
}
|
||||
kept
|
||||
}
|
||||
|
||||
/// Remove the `paths` (the [`test_data_dirs`], or the directories and files
|
||||
@@ -228,6 +339,70 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// A Semgrep rule file with one rule.
|
||||
const RULE: &str = "rules:\n - id: no-exec\n languages: [python]\n \
|
||||
message: exec runs code\n severity: ERROR\n pattern: exec(...)\n";
|
||||
|
||||
fn write_text(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_semgrep_rule_pack_with_its_samples_is_test_data() {
|
||||
let (_base, root) = tree();
|
||||
// A pack: a rule and its sample, with a vendored pack below it.
|
||||
write_text(&root, "agent/rules/cra.yaml", RULE);
|
||||
write(&root, "agent/rules/cra.py");
|
||||
write(&root, "agent/rules/vendor/gitlab/java/pom.xml");
|
||||
write_text(
|
||||
&root,
|
||||
"agent/rules/vendor/gitlab/java/inject/ognl.yml",
|
||||
RULE,
|
||||
);
|
||||
write(&root, "agent/rules/vendor/gitlab/java/inject/ognl.java");
|
||||
// Not packs: a configuration next to the code it configures, a rule
|
||||
// without a sample, and a rule pack that is the tree itself.
|
||||
write_text(&root, "app/settings.yaml", "debug: true\n");
|
||||
write(&root, "app/settings.py");
|
||||
write_text(&root, "ci/.semgrep.yml", RULE);
|
||||
write(&root, "ci/build.sh");
|
||||
write_text(&root, "local.yaml", RULE);
|
||||
write(&root, "local.py");
|
||||
|
||||
let dirs = test_data_dirs(&root);
|
||||
|
||||
assert!(dirs.contains(&"agent/rules".to_string()));
|
||||
assert!(
|
||||
!dirs.iter().any(|d| d.starts_with("agent/rules/")),
|
||||
"a pack inside the pack is not listed again: {dirs:?}"
|
||||
);
|
||||
for not_test_data in ["app", "ci", ""] {
|
||||
assert!(
|
||||
!dirs.contains(¬_test_data.to_string()),
|
||||
"{not_test_data}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_or_unreadable_yaml_file_is_not_a_rule_file() {
|
||||
let base = Scratch::new();
|
||||
write_text(base.path(), "big.yaml", &"x: 1\n".repeat(300_000));
|
||||
write_text(base.path(), "broken.yaml", "rules: [\n");
|
||||
write_text(base.path(), "rule.yaml", RULE);
|
||||
assert!(!is_semgrep_rule_file(&base.path().join("big.yaml")));
|
||||
assert!(!is_semgrep_rule_file(&base.path().join("broken.yaml")));
|
||||
assert!(is_semgrep_rule_file(&base.path().join("rule.yaml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_top_most_directories_are_kept() {
|
||||
let dirs = ["a/b", "a", "a-x", "a/b/c", "b"].map(String::from).to_vec();
|
||||
assert_eq!(top_most(dirs), ["a", "a-x", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tree_itself_is_never_test_data() {
|
||||
let base = Scratch::new();
|
||||
|
||||
@@ -63,6 +63,30 @@ impl EntitlementCheck {
|
||||
pub fn member_blocked(&self) -> bool {
|
||||
!self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED)
|
||||
}
|
||||
|
||||
/// How many targets the tenant's plan includes (t72):
|
||||
/// `limits.included_targets`. `None` when the plan sets no limit (no
|
||||
/// limits, the key missing or null), so every target is included.
|
||||
pub fn included_targets(&self) -> Option<u32> {
|
||||
self.limit("included_targets")
|
||||
}
|
||||
|
||||
/// The plan's monthly quota and the customer's Prüftag cap (t72), from
|
||||
/// `limits.monthly_pruefungen` and `limits.prueftag_cap`; a missing or
|
||||
/// null key is no limit.
|
||||
pub fn plan_limits(&self) -> compliance_core::models::PlanLimits {
|
||||
compliance_core::models::PlanLimits {
|
||||
monthly_pruefungen: self.limit("monthly_pruefungen"),
|
||||
prueftag_cap: self.limit("prueftag_cap"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole-number limit `key`; `None` when absent or null.
|
||||
fn limit(&self, key: &str) -> Option<u32> {
|
||||
let n = self.limits.as_ref()?.get(key)?.as_u64()?;
|
||||
// A count beyond u32 is no limit in practice.
|
||||
Some(u32::try_from(n).unwrap_or(u32::MAX))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -634,6 +658,46 @@ pub fn scheduler_runs_for(status: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_plan_sets_how_many_targets_are_included() {
|
||||
let check = |limits: serde_json::Value| -> EntitlementCheck {
|
||||
serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits }))
|
||||
.expect("an entitlement answer")
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
check(serde_json::json!({ "included_targets": 5 })).included_targets(),
|
||||
Some(5)
|
||||
);
|
||||
assert_eq!(
|
||||
check(serde_json::json!({ "included_targets": null })).included_targets(),
|
||||
None
|
||||
);
|
||||
assert_eq!(check(serde_json::json!({})).included_targets(), None);
|
||||
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_plan_sets_the_quota_and_the_cap() {
|
||||
let check: EntitlementCheck = serde_json::from_value(serde_json::json!({
|
||||
"allowed": true,
|
||||
"limits": { "included_targets": 5, "monthly_pruefungen": 100, "prueftag_cap": 0 },
|
||||
}))
|
||||
.expect("an entitlement answer");
|
||||
assert_eq!(
|
||||
check.plan_limits(),
|
||||
compliance_core::models::PlanLimits {
|
||||
monthly_pruefungen: Some(100),
|
||||
prueftag_cap: Some(0),
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
EntitlementCheck::default().plan_limits(),
|
||||
compliance_core::models::PlanLimits::default(),
|
||||
"Enterprise: no limits"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ladder_filter() {
|
||||
for s in ["active", "trial", "demo", "warning", ""] {
|
||||
|
||||
@@ -1,74 +1,170 @@
|
||||
//! How many scans run at once, and what happens to a scan requested while the
|
||||
//! same target is already being scanned.
|
||||
//! How many scans run at once, in which order they get a slot, and what
|
||||
//! happens to a scan requested while the same target is already queued or
|
||||
//! being scanned.
|
||||
//!
|
||||
//! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes,
|
||||
//! a scheduler tick and a few clicks could start any number of scans side by
|
||||
//! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two
|
||||
//! scans of the same target shared one checkout directory and corrupted each
|
||||
//! other. Two rules now apply to every trigger (click, webhook, scheduler):
|
||||
//! other. These rules now apply to every trigger (click, webhook, scheduler):
|
||||
//!
|
||||
//! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait
|
||||
//! for a slot.
|
||||
//! * **Per target — coalesce:** one scan runs and at most one more is pending.
|
||||
//! A request that arrives while one is pending is dropped, because the pending
|
||||
//! scan will pick up the latest code anyway. Ten pushes during a long scan
|
||||
//! therefore cost two scans, not ten. Dropped requests are never billed: only
|
||||
//! a scan that actually ran emits usage.
|
||||
//! * **Order:** a scan a person started ([`Priority::Person`]) gets a free slot
|
||||
//! before scheduled, webhook and new-content scans ([`Priority::Background`]);
|
||||
//! within a class the first to ask is the first served. So that a stream of
|
||||
//! clicks never starves the scheduler, a waiting background scan gets the
|
||||
//! slot after [`PERSON_GRANTS_IN_A_ROW`] person scans in a row (t84).
|
||||
//! * **Per target — coalesce:** one scan of a target waits or runs, and while
|
||||
//! it runs at most one more is pending. A request while the scan still waits
|
||||
//! for its slot is covered by it (it reads the latest code once it starts);
|
||||
//! a request while one is pending is covered by that one. Ten pushes during
|
||||
//! a long scan therefore cost two scans, not ten. A person's request takes
|
||||
//! over a waiting or pending scan that was not a person's, so it runs at
|
||||
//! person priority and always scans. Requests that do not run are never
|
||||
//! billed: only a scan that actually ran emits usage.
|
||||
//!
|
||||
//! Each admitted request carries the id of the run recorded for it while it
|
||||
//! waits (status `queued`); the gate tells the caller which of those runs will
|
||||
//! not happen, so no queued run is left behind.
|
||||
//!
|
||||
//! A scheduled scan also starts after a random delay of up to
|
||||
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
|
||||
//! all on one git host) do not start in the same second.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use dashmap::mapref::entry::Entry;
|
||||
use dashmap::DashMap;
|
||||
use rand::Rng;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use compliance_core::models::ScanTrigger;
|
||||
|
||||
/// The longest a scheduled scan waits before it starts.
|
||||
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
|
||||
|
||||
/// How many slots in a row go to person-started scans while a background scan
|
||||
/// waits; the next one goes to the background scan.
|
||||
pub const PERSON_GRANTS_IN_A_ROW: u32 = 3;
|
||||
|
||||
/// How long a scan with `trigger` waits before it starts: a random delay of
|
||||
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
|
||||
/// webhook or a person started.
|
||||
pub fn start_delay(trigger: &ScanTrigger) -> Duration {
|
||||
match trigger {
|
||||
ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER),
|
||||
ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO,
|
||||
ScanTrigger::Webhook
|
||||
| ScanTrigger::Manual
|
||||
| ScanTrigger::Support
|
||||
| ScanTrigger::NewContent => Duration::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which queue a scan waits in for a slot.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Priority {
|
||||
/// Started by a person (the customer or support): served first.
|
||||
Person,
|
||||
/// Scheduled, webhook and new-content scans, and PR reviews.
|
||||
Background,
|
||||
}
|
||||
|
||||
impl Priority {
|
||||
/// The queue a scan with `trigger` waits in.
|
||||
pub fn of(trigger: &ScanTrigger) -> Self {
|
||||
if trigger.started_by_person() {
|
||||
Self::Person
|
||||
} else {
|
||||
Self::Background
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One scan to run: what started it and the run recorded for it while it
|
||||
/// waits (`None` when that record could not be written).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Job {
|
||||
pub trigger: ScanTrigger,
|
||||
pub run_id: Option<String>,
|
||||
/// Set when a person's request took over a waiting scan that was not a
|
||||
/// person's: that scan's trigger, which the run is charged as (t84).
|
||||
pub charged_as: Option<ScanTrigger>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// A scan started by `trigger`, recorded as the run `run_id`.
|
||||
pub fn new(trigger: ScanTrigger, run_id: Option<String>) -> Self {
|
||||
Self {
|
||||
trigger,
|
||||
run_id,
|
||||
charged_as: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(&self) -> Priority {
|
||||
Priority::of(&self.trigger)
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to a scan request.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
/// Nothing was running for this target: the caller runs the scan now.
|
||||
/// Nothing was queued or running for this target: the caller now holds
|
||||
/// it and runs its scans through [`ScanGate::start`].
|
||||
Run,
|
||||
/// A scan is running; this request becomes the single pending follow-up,
|
||||
/// run by the task that holds the target once it finishes.
|
||||
Coalesced,
|
||||
/// A scan is running and a follow-up is already pending: nothing to do.
|
||||
/// The request will run: as the target's pending follow-up, or in place
|
||||
/// of the target's waiting scan. `replaced` is the run of the request it
|
||||
/// took over, which will not happen.
|
||||
Coalesced { replaced: Option<String> },
|
||||
/// A scan already queued for this target covers the request: its own run
|
||||
/// will not happen.
|
||||
Dropped,
|
||||
}
|
||||
|
||||
/// The scan queue is gone, or the target is no longer held.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum GateError {
|
||||
#[error("the scan queue was closed")]
|
||||
Closed,
|
||||
#[error("the target is not held")]
|
||||
NotHeld,
|
||||
}
|
||||
|
||||
/// Global scan slots plus the per-target coalescing state.
|
||||
#[derive(Debug)]
|
||||
pub struct ScanGate {
|
||||
slots: Arc<Semaphore>,
|
||||
/// Present while a scan of the key is running; the value is the pending
|
||||
/// follow-up's trigger, if one was requested meanwhile.
|
||||
running: DashMap<String, Option<ScanTrigger>>,
|
||||
slots: Arc<Slots>,
|
||||
/// Present while a scan of the key waits or runs.
|
||||
targets: DashMap<String, Held>,
|
||||
}
|
||||
|
||||
/// The scans of one target that are queued or running.
|
||||
#[derive(Debug)]
|
||||
struct Held {
|
||||
/// The scan that waits for a slot or runs now.
|
||||
current: Job,
|
||||
/// Whether `current` has its slot.
|
||||
running: bool,
|
||||
/// The follow-up requested while `current` runs.
|
||||
pending: Option<Job>,
|
||||
}
|
||||
|
||||
impl ScanGate {
|
||||
/// A gate allowing `concurrency` scans at once (at least one).
|
||||
pub fn new(concurrency: usize) -> Self {
|
||||
Self {
|
||||
slots: Arc::new(Semaphore::new(concurrency.max(1))),
|
||||
running: DashMap::new(),
|
||||
slots: Arc::new(Slots {
|
||||
queue: Mutex::new(Queue {
|
||||
free: concurrency.max(1),
|
||||
person: VecDeque::new(),
|
||||
background: VecDeque::new(),
|
||||
person_grants: 0,
|
||||
}),
|
||||
}),
|
||||
targets: DashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,60 +176,253 @@ impl ScanGate {
|
||||
|
||||
/// Decide what to do with a scan request for `key`. Atomic per key, so two
|
||||
/// simultaneous requests can never both be told to [`Admission::Run`].
|
||||
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
|
||||
match self.running.entry(key.to_string()) {
|
||||
pub fn admit(&self, key: &str, job: Job) -> Admission {
|
||||
// Lock order: a target's entry, then the slot queue (in `promote`).
|
||||
// `start` keeps the same order and `Permit::drop` takes only the queue.
|
||||
match self.targets.entry(key.to_string()) {
|
||||
Entry::Vacant(v) => {
|
||||
v.insert(None);
|
||||
v.insert(Held {
|
||||
current: job,
|
||||
running: false,
|
||||
pending: None,
|
||||
});
|
||||
Admission::Run
|
||||
}
|
||||
Entry::Occupied(mut o) if o.get().is_none() => {
|
||||
o.insert(Some(trigger));
|
||||
Admission::Coalesced
|
||||
Entry::Occupied(mut o) => {
|
||||
let held = o.get_mut();
|
||||
let person = job.trigger.started_by_person();
|
||||
// A person's request takes over a queued scan that is not a
|
||||
// person's: that one might skip as unchanged (#465), theirs
|
||||
// always scans, e.g. right after they uploaded new files.
|
||||
let takes_over = |queued: &Job| person && !queued.trigger.started_by_person();
|
||||
if !held.running {
|
||||
// The waiting scan reads the latest code once it starts,
|
||||
// so it covers the request, or the person's takes its
|
||||
// place, at person priority. It would have run anyway,
|
||||
// so it is charged as the scan it replaces.
|
||||
if !takes_over(&held.current) {
|
||||
return Admission::Dropped;
|
||||
}
|
||||
let job = Job {
|
||||
charged_as: Some(held.current.trigger.clone()),
|
||||
..job
|
||||
};
|
||||
let replaced = std::mem::replace(&mut held.current, job).run_id;
|
||||
self.slots.promote(key);
|
||||
return Admission::Coalesced { replaced };
|
||||
}
|
||||
match held.pending.as_ref().map(takes_over) {
|
||||
None => {
|
||||
held.pending = Some(job);
|
||||
Admission::Coalesced { replaced: None }
|
||||
}
|
||||
Some(true) => {
|
||||
let replaced = held.pending.replace(job).and_then(|p| p.run_id);
|
||||
Admission::Coalesced { replaced }
|
||||
}
|
||||
Some(false) => Admission::Dropped,
|
||||
}
|
||||
}
|
||||
// A person's request takes over a pending scheduled or webhook
|
||||
// follow-up: that one may skip as unchanged (#465), theirs always
|
||||
// scans, e.g. right after they uploaded new files.
|
||||
Entry::Occupied(mut o)
|
||||
if trigger.started_by_person()
|
||||
&& o.get().as_ref().is_some_and(|p| !p.started_by_person()) =>
|
||||
{
|
||||
o.insert(Some(trigger));
|
||||
Admission::Coalesced
|
||||
}
|
||||
Entry::Occupied(_) => Admission::Dropped,
|
||||
}
|
||||
}
|
||||
|
||||
/// Called by the task holding `key` after each scan. Returns the pending
|
||||
/// follow-up to run next (the target stays held), or `None` once there is
|
||||
/// nothing left, releasing the target.
|
||||
pub fn finish(&self, key: &str) -> Option<ScanTrigger> {
|
||||
match self.running.entry(key.to_string()) {
|
||||
Entry::Occupied(mut o) => match o.get_mut().take() {
|
||||
Some(next) => Some(next),
|
||||
None => {
|
||||
o.remove();
|
||||
None
|
||||
/// Wait for a slot for the held target `key`'s next scan, in the queue of
|
||||
/// its priority, and return the slot with the scan to run. The scan is the
|
||||
/// one current when the slot is granted: a person's request may have taken
|
||||
/// it over meanwhile.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// [`GateError::NotHeld`] if `key` was released meanwhile, and
|
||||
/// [`GateError::Closed`] if the queue is gone, which this gate never does.
|
||||
pub async fn start(&self, key: &str) -> Result<(Permit, Job), GateError> {
|
||||
let waiting = {
|
||||
let held = self.targets.get(key).ok_or(GateError::NotHeld)?;
|
||||
self.slots.enqueue(Some(key), held.current.priority())
|
||||
// The entry's guard is dropped here, before waiting.
|
||||
};
|
||||
let permit = waiting.wait().await?;
|
||||
let mut held = self.targets.get_mut(key).ok_or(GateError::NotHeld)?;
|
||||
held.running = true;
|
||||
Ok((permit, held.current.clone()))
|
||||
}
|
||||
|
||||
/// Called by the task holding `key` after each scan. Returns whether a
|
||||
/// follow-up is pending, to run next through [`Self::start`] (the target
|
||||
/// stays held), or `false` once there is nothing left, releasing it.
|
||||
pub fn finish(&self, key: &str) -> bool {
|
||||
match self.targets.entry(key.to_string()) {
|
||||
Entry::Occupied(mut o) => {
|
||||
let held = o.get_mut();
|
||||
match held.pending.take() {
|
||||
Some(next) => {
|
||||
held.current = next;
|
||||
held.running = false;
|
||||
true
|
||||
}
|
||||
None => {
|
||||
o.remove();
|
||||
false
|
||||
}
|
||||
}
|
||||
},
|
||||
Entry::Vacant(_) => None,
|
||||
}
|
||||
Entry::Vacant(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Release `key` unconditionally, dropping any pending follow-up. Used when
|
||||
/// the holding task dies, so the target does not stay "running" forever.
|
||||
pub fn release(&self, key: &str) {
|
||||
self.running.remove(key);
|
||||
self.targets.remove(key);
|
||||
}
|
||||
|
||||
/// Wait for one of the global scan slots. The slot is freed when the
|
||||
/// returned permit is dropped.
|
||||
/// Wait for a slot for work that is not a target's scan (a PR review).
|
||||
/// The slot is freed when the returned permit is dropped.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Only if the semaphore was closed, which this gate never does.
|
||||
pub async fn slot(&self) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
|
||||
self.slots.clone().acquire_owned().await
|
||||
/// Only if the queue is gone, which this gate never does.
|
||||
pub async fn slot(&self, priority: Priority) -> Result<Permit, GateError> {
|
||||
self.slots.enqueue(None, priority).wait().await
|
||||
}
|
||||
}
|
||||
|
||||
/// The slots and the two queues waiting for them.
|
||||
#[derive(Debug)]
|
||||
struct Slots {
|
||||
queue: Mutex<Queue>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Queue {
|
||||
/// Slots nobody holds. Only above zero while nobody waits.
|
||||
free: usize,
|
||||
person: VecDeque<Waiter>,
|
||||
background: VecDeque<Waiter>,
|
||||
/// Person scans granted in a row while a background scan waited.
|
||||
person_grants: u32,
|
||||
}
|
||||
|
||||
/// One request waiting for a slot; the slot is handed over through `grant`.
|
||||
#[derive(Debug)]
|
||||
struct Waiter {
|
||||
/// The target it is for, so a person's request can move it forward.
|
||||
key: Option<String>,
|
||||
grant: oneshot::Sender<Permit>,
|
||||
}
|
||||
|
||||
/// A request in a queue, or a slot already granted.
|
||||
enum Waiting {
|
||||
Granted(Permit),
|
||||
Queued(oneshot::Receiver<Permit>),
|
||||
}
|
||||
|
||||
impl Waiting {
|
||||
async fn wait(self) -> Result<Permit, GateError> {
|
||||
match self {
|
||||
Self::Granted(permit) => Ok(permit),
|
||||
// The sender only goes away unsent with the gate itself.
|
||||
Self::Queued(grant) => grant.await.map_err(|_| GateError::Closed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Slots {
|
||||
/// The queue, also after a thread panicked while holding it: every change
|
||||
/// to it is a single push or pop, so it is never left half-changed.
|
||||
fn lock(&self) -> MutexGuard<'_, Queue> {
|
||||
self.queue.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Take a free slot, or join the queue of `priority`.
|
||||
fn enqueue(self: &Arc<Self>, key: Option<&str>, priority: Priority) -> Waiting {
|
||||
let mut queue = self.lock();
|
||||
if queue.free > 0 {
|
||||
queue.free -= 1;
|
||||
return Waiting::Granted(Permit::new(self));
|
||||
}
|
||||
let (grant, granted) = oneshot::channel();
|
||||
let waiter = Waiter {
|
||||
key: key.map(str::to_string),
|
||||
grant,
|
||||
};
|
||||
match priority {
|
||||
Priority::Person => queue.person.push_back(waiter),
|
||||
Priority::Background => queue.background.push_back(waiter),
|
||||
}
|
||||
Waiting::Queued(granted)
|
||||
}
|
||||
|
||||
/// Move the background request for `key`, if one waits, to the back of
|
||||
/// the person queue.
|
||||
fn promote(&self, key: &str) {
|
||||
let mut queue = self.lock();
|
||||
let found = queue
|
||||
.background
|
||||
.iter()
|
||||
.position(|w| w.key.as_deref() == Some(key));
|
||||
if let Some(waiter) = found.and_then(|i| queue.background.remove(i)) {
|
||||
queue.person.push_back(waiter);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a freed slot to the next request, or keep it free.
|
||||
fn release(self: &Arc<Self>) {
|
||||
let mut queue = self.lock();
|
||||
while let Some(waiter) = queue.next() {
|
||||
match waiter.grant.send(Permit::new(self)) {
|
||||
Ok(()) => return,
|
||||
// The request was given up (its task ended): the permit comes
|
||||
// back unused, and the slot goes to the next one.
|
||||
Err(mut unused) => unused.slots = None,
|
||||
}
|
||||
}
|
||||
queue.free += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
/// The next request to serve: person scans first, except that a waiting
|
||||
/// background scan gets the slot after [`PERSON_GRANTS_IN_A_ROW`] person
|
||||
/// scans in a row.
|
||||
fn next(&mut self) -> Option<Waiter> {
|
||||
let background_due = self.person.is_empty() || self.person_grants >= PERSON_GRANTS_IN_A_ROW;
|
||||
if background_due {
|
||||
if let Some(waiter) = self.background.pop_front() {
|
||||
self.person_grants = 0;
|
||||
return Some(waiter);
|
||||
}
|
||||
}
|
||||
let waiter = self.person.pop_front()?;
|
||||
self.person_grants = if self.background.is_empty() {
|
||||
0
|
||||
} else {
|
||||
self.person_grants + 1
|
||||
};
|
||||
Some(waiter)
|
||||
}
|
||||
}
|
||||
|
||||
/// One scan slot; freed, and handed to the next request, when dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct Permit {
|
||||
/// `None` once the permit was given back unused.
|
||||
slots: Option<Arc<Slots>>,
|
||||
}
|
||||
|
||||
impl Permit {
|
||||
fn new(slots: &Arc<Slots>) -> Self {
|
||||
Self {
|
||||
slots: Some(Arc::clone(slots)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Permit {
|
||||
fn drop(&mut self) {
|
||||
if let Some(slots) = self.slots.take() {
|
||||
slots.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,10 +461,20 @@ impl Drop for HeldTarget<'_> {
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
|
||||
use super::{
|
||||
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
|
||||
SCHEDULED_SCAN_JITTER,
|
||||
};
|
||||
use compliance_core::models::ScanTrigger;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
type Log = Arc<Mutex<Vec<(String, ScanTrigger)>>>;
|
||||
|
||||
fn job(trigger: ScanTrigger, run: &str) -> Job {
|
||||
Job::new(trigger, Some(run.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scheduled_scan_waits_within_the_jitter() {
|
||||
let delays: Vec<Duration> = (0..1000)
|
||||
@@ -187,63 +486,175 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webhook_manual_and_support_scans_start_at_once() {
|
||||
fn webhook_manual_support_and_new_content_scans_start_at_once() {
|
||||
for trigger in [
|
||||
ScanTrigger::Webhook,
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Support,
|
||||
ScanTrigger::NewContent,
|
||||
] {
|
||||
assert_eq!(start_delay(&trigger), Duration::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
fn only_a_persons_scan_has_person_priority() {
|
||||
assert_eq!(Priority::of(&ScanTrigger::Manual), Priority::Person);
|
||||
assert_eq!(Priority::of(&ScanTrigger::Support), Priority::Person);
|
||||
for trigger in [
|
||||
ScanTrigger::Scheduled,
|
||||
ScanTrigger::Webhook,
|
||||
ScanTrigger::NewContent,
|
||||
] {
|
||||
assert_eq!(Priority::of(&trigger), Priority::Background);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_burst_coalesces_into_one_run_and_one_follow_up() {
|
||||
let gate = ScanGate::new(2);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
|
||||
for _ in 0..8 {
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let (_slot, running) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(running, job(ScanTrigger::Manual, "r1"));
|
||||
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
for i in 0..8 {
|
||||
let run = format!("drop{i}");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, &run)),
|
||||
Admission::Dropped
|
||||
);
|
||||
}
|
||||
// The holder runs the one follow-up, then releases the target.
|
||||
assert!(gate.finish(&key).is_some());
|
||||
assert!(gate.finish(&key).is_none());
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert!(gate.finish(&key));
|
||||
let (_next, follow_up) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(follow_up, job(ScanTrigger::Webhook, "r2"));
|
||||
assert!(!gate.finish(&key));
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
|
||||
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, ScanTrigger::Scheduled),
|
||||
Admission::Coalesced
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
// Not started yet, so it will read the push's code anyway.
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
|
||||
Admission::Dropped
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_waiting_scan_taken_over_is_charged_as_the_scan_it_replaces() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("r1".into())
|
||||
}
|
||||
);
|
||||
let (_slot, run) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(run.trigger, ScanTrigger::Manual);
|
||||
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_follow_up_after_a_running_scan_is_charged_as_theirs() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let (running, _) = gate.start(&key).await.unwrap();
|
||||
// Pending behind the running scan, replacing a scheduled follow-up.
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("r2".into())
|
||||
}
|
||||
);
|
||||
drop(running);
|
||||
assert!(gate.finish(&key));
|
||||
let (_slot, follow_up) = gate.start(&key).await.unwrap();
|
||||
assert_eq!(follow_up, job(ScanTrigger::Manual, "r3"));
|
||||
assert_eq!(follow_up.charged_as, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let _slot = gate.start(&key).await.unwrap();
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
|
||||
// Clicked after uploading new files: the follow-up scans in full.
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced);
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped);
|
||||
// Clicked after uploading new files: the follow-up scans in full, and
|
||||
// the scheduled follow-up's queued run will not happen.
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("r2".into())
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r4")),
|
||||
Admission::Dropped
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Support, "r5")),
|
||||
Admission::Dropped
|
||||
);
|
||||
|
||||
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
|
||||
assert!(gate.finish(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn targets_and_tenants_are_independent() {
|
||||
let gate = ScanGate::new(2);
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
|
||||
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
|
||||
Admission::Run
|
||||
);
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
|
||||
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
|
||||
Admission::Run
|
||||
);
|
||||
// Same target id in another tenant is another target.
|
||||
assert_eq!(
|
||||
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
|
||||
gate.admit(
|
||||
&ScanGate::key("globex", "t1"),
|
||||
job(ScanTrigger::Manual, "c")
|
||||
),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
@@ -252,34 +663,228 @@ mod tests {
|
||||
fn a_dead_holder_does_not_leave_the_target_locked() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
{
|
||||
// The holding task ends without calling finish (panic / shutdown).
|
||||
let _held = HeldTarget::new(&gate, key.clone());
|
||||
}
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
|
||||
Admission::Run
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disarmed_holder_leaves_the_state_to_finish() {
|
||||
#[tokio::test]
|
||||
async fn a_disarmed_holder_leaves_the_state_to_finish() {
|
||||
let gate = ScanGate::new(1);
|
||||
let key = ScanGate::key("acme", "t1");
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
|
||||
Admission::Run
|
||||
);
|
||||
let _slot = gate.start(&key).await.unwrap();
|
||||
HeldTarget::new(&gate, key.clone()).disarm();
|
||||
// Still held: disarm does not release, finish does.
|
||||
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
}
|
||||
|
||||
/// What `ComplianceAgent::run_target_scan` does once admitted: take a
|
||||
/// slot, scan (here: log), and run the pending follow-up, if any.
|
||||
async fn hold_and_scan(gate: Arc<ScanGate>, key: String, log: Log) {
|
||||
loop {
|
||||
{
|
||||
let (_slot, job) = gate.start(&key).await.unwrap();
|
||||
log.lock().unwrap().push((key.clone(), job.trigger));
|
||||
}
|
||||
if !gate.finish(&key) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Admit `trigger` for each of `targets` of tenant `acme`, each with a
|
||||
/// task that scans it, queued in that order behind a slot held elsewhere.
|
||||
async fn queue_targets(
|
||||
gate: &Arc<ScanGate>,
|
||||
targets: &[&str],
|
||||
trigger: ScanTrigger,
|
||||
log: &Log,
|
||||
) -> Vec<tokio::task::JoinHandle<()>> {
|
||||
let mut tasks = Vec::new();
|
||||
for target in targets {
|
||||
let key = ScanGate::key("acme", target);
|
||||
assert_eq!(
|
||||
gate.admit(&key, job(trigger.clone(), target)),
|
||||
Admission::Run
|
||||
);
|
||||
tasks.push(tokio::spawn(hold_and_scan(gate.clone(), key, log.clone())));
|
||||
// Let it queue for the slot before the next one does.
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
tasks
|
||||
}
|
||||
|
||||
fn triggers(log: &Log) -> Vec<ScanTrigger> {
|
||||
log.lock().unwrap().iter().map(|(_, t)| t.clone()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_scan_gets_the_next_slot_before_scheduled_scans() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
// Another tenant's scan has the only slot.
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
let mut tasks = queue_targets(&gate, &["t1", "t2"], ScanTrigger::Scheduled, &log).await;
|
||||
tasks.extend(queue_targets(&gate, &["t3"], ScanTrigger::Manual, &log).await);
|
||||
|
||||
drop(busy);
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
triggers(&log),
|
||||
[
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Scheduled,
|
||||
ScanTrigger::Scheduled
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_request_takes_over_a_scheduled_scan_still_waiting() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
// Another tenant's scan has the only slot.
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
// A scheduler tick admits three targets; all wait for the slot.
|
||||
let tasks = queue_targets(&gate, &["t1", "t2", "t3"], ScanTrigger::Scheduled, &log).await;
|
||||
|
||||
// A person asks for t3 while its scheduled scan still waits, last.
|
||||
let t3 = ScanGate::key("acme", "t3");
|
||||
assert_eq!(
|
||||
gate.admit(&t3, job(ScanTrigger::Manual, "click")),
|
||||
Admission::Coalesced {
|
||||
replaced: Some("t3".into())
|
||||
}
|
||||
);
|
||||
|
||||
drop(busy);
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
// Their scan runs first, once, in place of the scheduled one, and
|
||||
// is charged as the scheduled one (asserted on the job below).
|
||||
let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone();
|
||||
assert_eq!(
|
||||
order,
|
||||
[
|
||||
(t3, ScanTrigger::Manual),
|
||||
(ScanGate::key("acme", "t1"), ScanTrigger::Scheduled),
|
||||
(ScanGate::key("acme", "t2"), ScanTrigger::Scheduled),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_persons_follow_up_waits_only_for_the_running_scan() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
let t1 = ScanGate::key("acme", "t1");
|
||||
assert_eq!(
|
||||
gate.admit(&t1, job(ScanTrigger::Scheduled, "t1")),
|
||||
Admission::Run
|
||||
);
|
||||
// t1's scheduled scan runs; two more targets queue behind it.
|
||||
let (running, _) = gate.start(&t1).await.unwrap();
|
||||
let tasks = queue_targets(&gate, &["t2", "t3"], ScanTrigger::Scheduled, &log).await;
|
||||
|
||||
assert_eq!(
|
||||
gate.admit(&t1, job(ScanTrigger::Manual, "click")),
|
||||
Admission::Coalesced { replaced: None }
|
||||
);
|
||||
// t1's scan ends; its follow-up queues as a person's.
|
||||
assert!(gate.finish(&t1));
|
||||
let follow_up = tokio::spawn(hold_and_scan(gate.clone(), t1.clone(), log.clone()));
|
||||
tokio::task::yield_now().await;
|
||||
drop(running);
|
||||
follow_up.await.unwrap();
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
triggers(&log),
|
||||
[
|
||||
ScanTrigger::Manual,
|
||||
ScanTrigger::Scheduled,
|
||||
ScanTrigger::Scheduled
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stream_of_clicks_does_not_starve_scheduled_scans() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let log = Log::default();
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
let mut tasks = queue_targets(&gate, &["s1"], ScanTrigger::Scheduled, &log).await;
|
||||
let clicks: Vec<String> = (0..10).map(|i| format!("p{i}")).collect();
|
||||
let clicks: Vec<&str> = clicks.iter().map(String::as_str).collect();
|
||||
tasks.extend(queue_targets(&gate, &clicks, ScanTrigger::Manual, &log).await);
|
||||
|
||||
drop(busy);
|
||||
for task in tasks {
|
||||
task.await.unwrap();
|
||||
}
|
||||
let scheduled_at = triggers(&log)
|
||||
.iter()
|
||||
.position(|t| *t == ScanTrigger::Scheduled)
|
||||
.unwrap();
|
||||
assert_eq!(scheduled_at, PERSON_GRANTS_IN_A_ROW as usize);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_given_up_request_passes_its_slot_on() {
|
||||
let gate = Arc::new(ScanGate::new(1));
|
||||
let busy = gate.slot(Priority::Background).await.unwrap();
|
||||
// A request that waits and is then given up (its task ends).
|
||||
let gone = tokio::spawn({
|
||||
let gate = gate.clone();
|
||||
async move { gate.slot(Priority::Person).await.map(drop) }
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
gone.abort();
|
||||
let _ = gone.await;
|
||||
|
||||
drop(busy);
|
||||
let next = tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Background));
|
||||
assert!(
|
||||
next.await.is_ok(),
|
||||
"the slot is not lost to the given-up request"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slots_bound_how_many_scans_run_at_once() {
|
||||
let gate = ScanGate::new(2);
|
||||
let a = gate.slot().await.unwrap();
|
||||
let _b = gate.slot().await.unwrap();
|
||||
let a = gate.slot(Priority::Background).await.unwrap();
|
||||
let _b = gate.slot(Priority::Background).await.unwrap();
|
||||
// A third slot is not available until one is freed.
|
||||
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
|
||||
let third =
|
||||
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
|
||||
assert!(third.is_err(), "a third concurrent scan must wait");
|
||||
drop(a);
|
||||
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
|
||||
let third =
|
||||
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
|
||||
assert!(third.is_ok(), "a freed slot is reused");
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,15 @@ pub async fn create_target(
|
||||
) -> Result<OnboardedTarget, AgentError> {
|
||||
let res = db.onboarded_targets().insert_one(&target).await?;
|
||||
target.id = res.inserted_id.as_object_id();
|
||||
// A target beyond the plan's included ones is extra from the start (t72).
|
||||
if let Some((_, billing)) = agent
|
||||
.refresh_billing(tenant_id, db)
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|(id, _)| Some(*id) == target.id)
|
||||
{
|
||||
target.billing = billing;
|
||||
}
|
||||
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
agent.emit_usage(
|
||||
tenant_id,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! The month's peak of extra targets goes to the registry when it rises and
|
||||
//! once a day besides; a new month starts again (t72). Runs against a live
|
||||
//! Mongo (`TEST_MONGODB_URI`) and skips cleanly without one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use chrono::{Duration, TimeZone, Utc};
|
||||
use compliance_agent::database::DatabasePool;
|
||||
use compliance_agent::metering::{assign_billing, charge, record_extra_peak};
|
||||
use compliance_core::models::{OnboardedTarget, PlanLimits, RunCharge, TargetType};
|
||||
use mongodb::bson::doc;
|
||||
|
||||
const TENANT: &str = "extra-peak";
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_peak_is_sent_when_it_rises_and_once_a_day() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"extrapeak_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP extra_peak: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
// Arrange: three targets on a plan that includes one, on 6 Nov.
|
||||
let mut ids = Vec::new();
|
||||
for days in [3, 2, 1] {
|
||||
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
|
||||
target.created_at = Utc::now() - Duration::days(days);
|
||||
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
|
||||
ids.push(res.inserted_id.as_object_id().unwrap());
|
||||
}
|
||||
assign_billing(&db, Some(1)).await.unwrap();
|
||||
let nov6 = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
|
||||
|
||||
// Act / Assert: two extra targets, sent once that day.
|
||||
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), Some(2));
|
||||
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None);
|
||||
|
||||
// One extra target is archived: the month's peak stays two.
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": ids[2] },
|
||||
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assign_billing(&db, Some(1)).await.unwrap();
|
||||
assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None);
|
||||
assert_eq!(
|
||||
record_extra_peak(&db, nov6 + Duration::days(1))
|
||||
.await
|
||||
.unwrap(),
|
||||
Some(2),
|
||||
"re-sent once the next day"
|
||||
);
|
||||
|
||||
// A new month starts from the targets extra now.
|
||||
let dec1 = Utc.with_ymd_and_hms(2026, 12, 1, 9, 0, 0).single().unwrap();
|
||||
assert_eq!(record_extra_peak(&db, dec1).await.unwrap(), Some(1));
|
||||
|
||||
// The month document the peak created still counts the quota.
|
||||
let plan = PlanLimits {
|
||||
monthly_pruefungen: Some(1),
|
||||
prueftag_cap: None,
|
||||
};
|
||||
assert_eq!(
|
||||
charge(&db, "t", plan, dec1).await.unwrap().charge,
|
||||
RunCharge::Quota
|
||||
);
|
||||
assert_eq!(
|
||||
charge(&db, "t", plan, dec1).await.unwrap().charge,
|
||||
RunCharge::Prueftag
|
||||
);
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Counted Prüfungen go to the month's quota first; once it is used up, the
|
||||
//! first one on a target that day books a Prüftag that allows six (t72).
|
||||
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
|
||||
//! one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use chrono::{TimeZone, Utc};
|
||||
use compliance_agent::database::DatabasePool;
|
||||
use compliance_agent::metering::{charge, month_summary, usage};
|
||||
use compliance_core::models::{
|
||||
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
|
||||
};
|
||||
|
||||
const TENANT: &str = "metering-counters";
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_quota_then_a_prueftag_of_six_then_nothing() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"metering_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP metering_counters: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
// Arrange: a quota of two and a cap of one Prüftag, on 6 Nov in Berlin.
|
||||
let plan = PlanLimits {
|
||||
monthly_pruefungen: Some(2),
|
||||
prueftag_cap: Some(1),
|
||||
};
|
||||
let at = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap();
|
||||
let admitted = |target: &'static str| {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
let (month, day) = usage(&db, target, at).await.unwrap();
|
||||
admit(plan, month, day)
|
||||
}
|
||||
};
|
||||
|
||||
// Act / Assert: the quota first.
|
||||
for _ in 0..2 {
|
||||
assert_eq!(admitted("a").await, Admission::Quota);
|
||||
let charged = charge(&db, "a", plan, at).await.unwrap();
|
||||
assert_eq!(charged.charge, RunCharge::Quota);
|
||||
assert_eq!(charged.booked_prueftag, None);
|
||||
}
|
||||
|
||||
// The quota is used up: the next one books target a's Prüftag.
|
||||
assert_eq!(admitted("a").await, Admission::BookPrueftag);
|
||||
let booked = charge(&db, "a", plan, at).await.unwrap();
|
||||
assert_eq!(booked.charge, RunCharge::Prueftag);
|
||||
assert_eq!(booked.booked_prueftag.as_deref(), Some("2026-11-06"));
|
||||
|
||||
// It allows six in all; the seventh that day does not run.
|
||||
for _ in 1..PRUEFUNGEN_PER_PRUEFTAG {
|
||||
assert_eq!(admitted("a").await, Admission::Prueftag);
|
||||
let charged = charge(&db, "a", plan, at).await.unwrap();
|
||||
assert_eq!(charged.booked_prueftag, None, "no second booking");
|
||||
}
|
||||
assert_eq!(admitted("a").await, Admission::Refused(Refusal::DailyLimit));
|
||||
|
||||
// Another target would need a second Prüftag, over the cap of one.
|
||||
assert_eq!(
|
||||
admitted("b").await,
|
||||
Admission::Refused(Refusal::PrueftagCap)
|
||||
);
|
||||
|
||||
// The next calendar day in Berlin is a new day for target a.
|
||||
let tomorrow = Utc
|
||||
.with_ymd_and_hms(2026, 11, 6, 23, 30, 0)
|
||||
.single()
|
||||
.unwrap();
|
||||
let (month, day) = usage(&db, "a", tomorrow).await.unwrap();
|
||||
assert!(!day.prueftag_booked, "7 Nov in Berlin");
|
||||
assert_eq!(month.prueftage, 1);
|
||||
assert_eq!(month.pruefungen, 2);
|
||||
|
||||
// The usage view reads the same month.
|
||||
let summary = month_summary(&db, at).await.unwrap();
|
||||
assert_eq!(summary.month, "2026-11");
|
||||
assert_eq!((summary.pruefungen, summary.prueftage), (2, 1));
|
||||
assert_eq!((summary.extra_targets, summary.extra_peak), (0, 0));
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -196,7 +196,7 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
|
||||
.with_excluded(vec!["legacy".to_string()])
|
||||
.with_test_data(vec!["fixtures".to_string()]);
|
||||
let closed = run
|
||||
.resolve_left_out(&db, TARGET, "plc-control-logic")
|
||||
.resolve_left_out(&db, TARGET, Some("plc-control-logic"))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -228,3 +228,66 @@ async fn only_what_was_left_out_is_closed_for_a_stage_without_a_seen_set() {
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn left_out_findings_close_whichever_scanner_stored_them() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"leftoutall_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP resolve_findings: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
|
||||
// Arrange: an earlier scan stored findings of scanners that do not run
|
||||
// now (no C, no BitBake left in the tree), one in the test data that this
|
||||
// run still reports, and one outside the left-out paths.
|
||||
db.findings()
|
||||
.insert_many([
|
||||
finding("fp-cppcheck", "cppcheck", "fixtures/firmware/sensors.c"),
|
||||
finding("fp-recipe", "yocto-config", "legacy/image.bb"),
|
||||
finding("fp-reported", "gitleaks", "fixtures/app/.env.local"),
|
||||
finding("fp-kept", "cppcheck", "src/main.c"),
|
||||
])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Act: only gitleaks completes, and it reports fp-reported again.
|
||||
let mut run = RunFindings::new("run-all")
|
||||
.with_excluded(vec!["legacy".to_string()])
|
||||
.with_test_data(vec!["fixtures".to_string()]);
|
||||
run.completed("gitleaks");
|
||||
let mut seen = vec![finding(
|
||||
"fp-reported",
|
||||
"gitleaks",
|
||||
"fixtures/app/.env.local",
|
||||
)];
|
||||
run.write_back(&db, &mut seen).await.unwrap();
|
||||
run.resolve_missing(&db, TARGET, &[]).await.unwrap();
|
||||
let closed = run.resolve_left_out(&db, TARGET, None).await.unwrap();
|
||||
|
||||
// Assert: the left-out findings close with their reason, although their
|
||||
// scanner did not run; one this run reported, and one outside, stay.
|
||||
assert_eq!(closed, 2);
|
||||
let cppcheck = row(&db, "fp-cppcheck").await;
|
||||
assert_eq!(cppcheck.status, FindingStatus::Resolved);
|
||||
assert_eq!(
|
||||
last_scan_change(&cppcheck),
|
||||
Some(ScanChangeKind::NowTestData)
|
||||
);
|
||||
let recipe = row(&db, "fp-recipe").await;
|
||||
assert_eq!(recipe.status, FindingStatus::Resolved);
|
||||
assert_eq!(last_scan_change(&recipe), Some(ScanChangeKind::NowExcluded));
|
||||
assert_eq!(
|
||||
row(&db, "fp-reported").await.status,
|
||||
FindingStatus::Open,
|
||||
"a finding this run reported is not closed"
|
||||
);
|
||||
assert_eq!(row(&db, "fp-kept").await.status, FindingStatus::Open);
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! A scan request shows at once as a run waiting for a slot (t84): the run is
|
||||
//! recorded `queued` before the scan gets one of the agent's slots, a person's
|
||||
//! request takes over a waiting webhook scan without leaving its queued run
|
||||
//! behind, a request covered by the waiting scan leaves none, and the run
|
||||
//! leaves `queued` once its scan had its turn. Runs against a live Mongo
|
||||
//! (`TEST_MONGODB_URI`) and skips cleanly without one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use mongodb::bson::doc;
|
||||
|
||||
use compliance_agent::agent::ComplianceAgent;
|
||||
use compliance_agent::database::Database;
|
||||
use compliance_agent::scan_gate::Priority;
|
||||
use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger};
|
||||
|
||||
use common::dev_config;
|
||||
|
||||
const TENANT: &str = "scanqueue";
|
||||
|
||||
async fn runs(db: &Database, target_id: &str) -> Vec<ScanRun> {
|
||||
db.scan_runs()
|
||||
.find(doc! { "repo_id": target_id })
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Wait until the runs of `target_id` satisfy `done`, and return them.
|
||||
async fn until(db: &Database, target_id: &str, done: impl Fn(&[ScanRun]) -> bool) -> Vec<ScanRun> {
|
||||
for _ in 0..200 {
|
||||
let found = runs(db, target_id).await;
|
||||
if done(&found) {
|
||||
return found;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
panic!(
|
||||
"runs never reached the expected state: {:?}",
|
||||
runs(db, target_id).await
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_request_shows_as_queued_until_its_scan_has_a_slot() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
|
||||
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
|
||||
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
let mut config = dev_config(uri, db_name);
|
||||
config.scan_concurrency = 1;
|
||||
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
|
||||
// No such target, so its scan ends at once when it gets the slot.
|
||||
let target = mongodb::bson::oid::ObjectId::new().to_hex();
|
||||
|
||||
// Arrange: another scan has the only slot.
|
||||
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
|
||||
|
||||
// Act 1: a push asks for a scan; it waits, recorded as queued.
|
||||
let holder = tokio::spawn({
|
||||
let (agent, target) = (agent.clone(), target.clone());
|
||||
async move {
|
||||
agent
|
||||
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let queued = until(&db, &target, |r| r.len() == 1).await;
|
||||
assert_eq!(queued[0].status, ScanRunStatus::Queued);
|
||||
assert_eq!(queued[0].trigger, ScanTrigger::Webhook);
|
||||
assert!(queued[0].queued_at.is_some());
|
||||
|
||||
// Act 2: a person asks while it waits: theirs takes its place, and only
|
||||
// their queued run is left. Another push is covered and leaves none.
|
||||
agent
|
||||
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
|
||||
.await
|
||||
.unwrap();
|
||||
agent
|
||||
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
|
||||
.await
|
||||
.unwrap();
|
||||
let waiting = runs(&db, &target).await;
|
||||
assert_eq!(waiting.len(), 1, "one queued run: {waiting:?}");
|
||||
assert_eq!(waiting[0].status, ScanRunStatus::Queued);
|
||||
assert_eq!(waiting[0].trigger, ScanTrigger::Manual);
|
||||
|
||||
// Act 3: the slot frees; the person's scan has its turn.
|
||||
drop(busy);
|
||||
assert!(holder.await.unwrap().is_err(), "the unknown target fails");
|
||||
|
||||
// Assert: the same run, no longer queued.
|
||||
let done = runs(&db, &target).await;
|
||||
assert_eq!(done.len(), 1);
|
||||
assert_eq!(done[0].id, waiting[0].id);
|
||||
assert_eq!(done[0].status, ScanRunStatus::Failed);
|
||||
assert!(done[0].completed_at.is_some());
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_scan_runs_on_the_run_that_waited() {
|
||||
use compliance_core::models::{OnboardedTarget, TargetType};
|
||||
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
|
||||
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
|
||||
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
let mut config = dev_config(uri, db_name);
|
||||
config.scan_concurrency = 1;
|
||||
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
|
||||
// A target with nothing attached yet: its scan has nothing to read.
|
||||
let target = db
|
||||
.onboarded_targets()
|
||||
.insert_one(OnboardedTarget::new(
|
||||
"empty".into(),
|
||||
TargetType::BackendService,
|
||||
))
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap()
|
||||
.to_hex();
|
||||
|
||||
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
|
||||
let holder = tokio::spawn({
|
||||
let (agent, target) = (agent.clone(), target.clone());
|
||||
async move {
|
||||
agent
|
||||
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
|
||||
.await
|
||||
}
|
||||
});
|
||||
let queued = until(&db, &target, |r| r.len() == 1).await;
|
||||
assert_eq!(queued[0].status, ScanRunStatus::Queued);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
|
||||
drop(busy);
|
||||
holder.await.unwrap().ok();
|
||||
|
||||
// The scan used the queued run: one run, started after it was requested.
|
||||
let done = runs(&db, &target).await;
|
||||
assert_eq!(done.len(), 1, "{done:?}");
|
||||
assert_eq!(done[0].id, queued[0].id);
|
||||
assert_ne!(done[0].status, ScanRunStatus::Queued);
|
||||
assert!(done[0].started_at > done[0].queued_at.unwrap());
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
/// The run of `target`'s scan by `trigger`, started while another scan has the
|
||||
/// only slot; with `takes_over`, a webhook scan waits first and the person's
|
||||
/// request takes it over.
|
||||
async fn scan_with_slot_busy(
|
||||
agent: &Arc<ComplianceAgent>,
|
||||
db: &Database,
|
||||
target: &str,
|
||||
takes_over: bool,
|
||||
) -> ScanRun {
|
||||
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
|
||||
let first = if takes_over {
|
||||
ScanTrigger::Webhook
|
||||
} else {
|
||||
ScanTrigger::Manual
|
||||
};
|
||||
let holder = tokio::spawn({
|
||||
let (agent, target) = (agent.clone(), target.to_string());
|
||||
async move { agent.run_target_scan(TENANT, &target, first).await }
|
||||
});
|
||||
until(db, target, |r| r.len() == 1).await;
|
||||
if takes_over {
|
||||
agent
|
||||
.run_target_scan(TENANT, target, ScanTrigger::Manual)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
drop(busy);
|
||||
holder.await.unwrap().ok();
|
||||
let mut done = runs(db, target).await;
|
||||
assert_eq!(done.len(), 1, "{done:?}");
|
||||
done.remove(0)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_taken_over_scan_is_charged_as_the_scan_it_replaces() {
|
||||
use compliance_core::models::{OnboardedTarget, ScanAttribution, TargetType};
|
||||
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
|
||||
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
|
||||
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
let mut config = dev_config(uri, db_name);
|
||||
config.scan_concurrency = 1;
|
||||
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
|
||||
let new_target = || {
|
||||
let db = db.clone();
|
||||
async move {
|
||||
let target = OnboardedTarget::new("t".into(), TargetType::BackendService);
|
||||
db.onboarded_targets()
|
||||
.insert_one(target)
|
||||
.await
|
||||
.unwrap()
|
||||
.inserted_id
|
||||
.as_object_id()
|
||||
.unwrap()
|
||||
.to_hex()
|
||||
}
|
||||
};
|
||||
|
||||
// A person's request that took over a waiting webhook scan of an
|
||||
// included target: their priority and attribution, but not counted, as
|
||||
// the webhook scan would not have been.
|
||||
let included = new_target().await;
|
||||
let run = scan_with_slot_busy(&agent, &db, &included, true).await;
|
||||
assert_eq!(run.trigger, ScanTrigger::Manual);
|
||||
assert_eq!(run.attribution, Some(ScanAttribution::Request));
|
||||
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
|
||||
assert!(!run.chargeable, "it would have run anyway: {run:?}");
|
||||
|
||||
// A person's own scan, not taking any over, counts as their request.
|
||||
let asked = new_target().await;
|
||||
let run = scan_with_slot_busy(&agent, &db, &asked, false).await;
|
||||
assert_eq!(run.attribution, Some(ScanAttribution::Request));
|
||||
assert_eq!(run.charged_as, None);
|
||||
assert!(run.chargeable);
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! The oldest active targets are the plan's included ones; the rest are
|
||||
//! extra, and an extra one moves up when an included one is archived (t72).
|
||||
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
|
||||
//! one.
|
||||
|
||||
#![allow(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
use chrono::{Duration, Utc};
|
||||
use compliance_agent::database::{Database, DatabasePool};
|
||||
use compliance_agent::metering::assign_billing;
|
||||
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
|
||||
use mongodb::bson::{doc, oid::ObjectId};
|
||||
|
||||
const TENANT: &str = "target-billing";
|
||||
|
||||
async fn billing(db: &Database, id: ObjectId) -> TargetBilling {
|
||||
db.onboarded_targets()
|
||||
.find_one(doc! { "_id": id })
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.billing
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() {
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!(
|
||||
"billing_{}",
|
||||
&uuid::Uuid::new_v4().simple().to_string()[..10]
|
||||
);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP target_billing: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
|
||||
// Arrange: three targets, created a day apart.
|
||||
let mut ids = Vec::new();
|
||||
for days in [3, 2, 1] {
|
||||
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
|
||||
target.created_at = Utc::now() - Duration::days(days);
|
||||
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
|
||||
ids.push(res.inserted_id.as_object_id().unwrap());
|
||||
}
|
||||
let (oldest, middle, newest) = (ids[0], ids[1], ids[2]);
|
||||
|
||||
// Act: a plan with two included targets.
|
||||
let changes = assign_billing(&db, Some(2)).await.unwrap();
|
||||
|
||||
// Assert: only the newest is extra, and it is the one change.
|
||||
assert_eq!(changes, vec![(newest, TargetBilling::Extra)]);
|
||||
assert_eq!(billing(&db, oldest).await, TargetBilling::Included);
|
||||
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
|
||||
assert_eq!(billing(&db, newest).await, TargetBilling::Extra);
|
||||
assert!(
|
||||
assign_billing(&db, Some(2)).await.unwrap().is_empty(),
|
||||
"nothing changes a second time"
|
||||
);
|
||||
|
||||
// Act: the oldest is archived.
|
||||
db.onboarded_targets()
|
||||
.update_one(
|
||||
doc! { "_id": oldest },
|
||||
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assign_billing(&db, Some(2)).await.unwrap();
|
||||
|
||||
// Assert: the extra one moved up.
|
||||
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
|
||||
|
||||
// Act / Assert: a plan without a limit includes every target.
|
||||
assign_billing(&db, Some(0)).await.unwrap();
|
||||
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
|
||||
assign_billing(&db, None).await.unwrap();
|
||||
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_swap_moves_both_and_holds_the_one_swapped_in_until_month_end() {
|
||||
use compliance_agent::metering::swap;
|
||||
use compliance_core::models::SwapRefusal;
|
||||
|
||||
let uri = std::env::var("TEST_MONGODB_URI")
|
||||
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
|
||||
let prefix = format!("swap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
|
||||
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
|
||||
eprintln!("SKIP target_billing swap: no MongoDB reachable at {uri}");
|
||||
return;
|
||||
};
|
||||
let db = pool.for_tenant_id(TENANT).await.unwrap();
|
||||
// Arrange: three targets on a plan with two included: the newest is extra.
|
||||
let mut ids = Vec::new();
|
||||
for days in [3, 2, 1] {
|
||||
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
|
||||
target.created_at = Utc::now() - Duration::days(days);
|
||||
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
|
||||
ids.push(res.inserted_id.as_object_id().unwrap());
|
||||
}
|
||||
let (oldest, middle, newest) = (ids[0], ids[1], ids[2]);
|
||||
assign_billing(&db, Some(2)).await.unwrap();
|
||||
let nov6 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 6, 9, 0, 0)
|
||||
.single()
|
||||
.unwrap();
|
||||
|
||||
// Act: swap the newest in for the oldest.
|
||||
let swapped = swap(&db, newest, oldest, true, nov6).await.unwrap();
|
||||
assign_billing(&db, Some(2)).await.unwrap();
|
||||
|
||||
// Assert: they changed places; the count of extra targets is the same.
|
||||
assert_eq!(swapped, Some(Ok(())));
|
||||
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
|
||||
assert_eq!(billing(&db, oldest).await, TargetBilling::Extra);
|
||||
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
|
||||
|
||||
// The one swapped in stays included this month; another may go out.
|
||||
assert_eq!(
|
||||
swap(&db, oldest, newest, true, nov6).await.unwrap(),
|
||||
Some(Err(SwapRefusal::Locked))
|
||||
);
|
||||
assert_eq!(
|
||||
swap(&db, oldest, middle, true, nov6).await.unwrap(),
|
||||
Some(Ok(()))
|
||||
);
|
||||
assign_billing(&db, Some(2)).await.unwrap();
|
||||
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
|
||||
|
||||
// From December, the target swapped in on 6 Nov may go out again.
|
||||
let dec1 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 12, 1, 9, 0, 0)
|
||||
.single()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
swap(&db, middle, newest, true, dec1).await.unwrap(),
|
||||
Some(Ok(()))
|
||||
);
|
||||
assert_eq!(
|
||||
swap(&db, middle, ObjectId::new(), true, dec1)
|
||||
.await
|
||||
.unwrap(),
|
||||
None,
|
||||
"an unknown target"
|
||||
);
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
}
|
||||
@@ -45,6 +45,8 @@ serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
|
||||
encoding_rs = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//! The release a binary was built as, read at compile time.
|
||||
//!
|
||||
//! CI passes the latest release tag (without its `v`) as `PRUEFWERK_VERSION`
|
||||
//! and the commit as `PRUEFWERK_COMMIT` to the image build. The crate version
|
||||
//! is only the fallback for a local build: it is not bumped per release, so
|
||||
//! anything that names the running version (the agent's `/version` handshake,
|
||||
//! telemetry's `service.version`, evidence tooling) uses these constants.
|
||||
|
||||
/// The build version: `PRUEFWERK_VERSION` at compile time, else the crate
|
||||
/// version.
|
||||
pub const BUILD_VERSION: &str =
|
||||
non_empty_or(option_env!("PRUEFWERK_VERSION"), env!("CARGO_PKG_VERSION"));
|
||||
|
||||
/// The commit the build is from: `PRUEFWERK_COMMIT` at compile time (CI: the
|
||||
/// full SHA), else "unknown". The portal's version line shows 8 characters.
|
||||
pub const BUILD_COMMIT: &str = non_empty_or(option_env!("PRUEFWERK_COMMIT"), "unknown");
|
||||
|
||||
/// A Docker build arg left empty is an empty env var, not an unset one.
|
||||
const fn non_empty_or(value: Option<&'static str>, fallback: &'static str) -> &'static str {
|
||||
match value {
|
||||
Some(v) if !v.is_empty() => v,
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_unset_or_empty_build_value_falls_back() {
|
||||
assert_eq!(non_empty_or(None, "0.4.4"), "0.4.4");
|
||||
assert_eq!(non_empty_or(Some(""), "unknown"), "unknown");
|
||||
assert_eq!(non_empty_or(Some("0.4.5"), "0.4.4"), "0.4.5");
|
||||
assert!(!BUILD_VERSION.is_empty());
|
||||
assert!(!BUILD_COMMIT.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! Source files as text, whatever encoding the tool that wrote them chose.
|
||||
//!
|
||||
//! Visual Studio writes UTF-8 with a byte-order mark (BOM) or UTF-16, older
|
||||
//! .NET and PLC tools write Windows-1252. `std::fs::read_to_string` accepts
|
||||
//! only UTF-8 (and keeps a UTF-8 BOM as a leading `U+FEFF`), so every reader
|
||||
//! of source files decodes through [`read_source`] instead:
|
||||
//!
|
||||
//! 1. a BOM (UTF-8 `EF BB BF`, UTF-16 LE `FF FE`, UTF-16 BE `FE FF`) names the
|
||||
//! encoding; the BOM itself is dropped;
|
||||
//! 2. without one, the bytes are UTF-8 if they are valid UTF-8;
|
||||
//! 3. otherwise they are Windows-1252, unless they contain a NUL byte: no
|
||||
//! 1252 text does, but binaries and UTF-16 without a BOM do.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use encoding_rs::{Encoding, UTF_8, WINDOWS_1252};
|
||||
|
||||
/// Why a file could not be read as text.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SourceTextError {
|
||||
/// The file could not be read at all (missing, no permission, ...).
|
||||
#[error("cannot read the file: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
/// The file's BOM names an encoding its bytes don't follow, e.g. UTF-16
|
||||
/// with an odd byte count or an unpaired surrogate.
|
||||
#[error("the file is not valid {0} although its byte-order mark says so")]
|
||||
Malformed(&'static str),
|
||||
/// The file has no BOM, is not UTF-8 and contains a NUL byte: a binary
|
||||
/// file, or UTF-16 we can't tell the byte order of.
|
||||
#[error("the file is binary or of an unknown encoding")]
|
||||
Binary,
|
||||
}
|
||||
|
||||
/// Read the file at `path` as text, decoded as the module docs describe.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `path` - the file to read
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The file's text, without a byte-order mark.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`SourceTextError::Io`] when the file can't be read, and the
|
||||
/// errors of [`decode`] when its bytes aren't text.
|
||||
pub fn read_source(path: &Path) -> Result<String, SourceTextError> {
|
||||
decode(std::fs::read(path)?)
|
||||
}
|
||||
|
||||
/// Decode a source file's bytes, as the module docs describe.
|
||||
///
|
||||
/// Takes the bytes by value so that the common case, UTF-8 without a BOM,
|
||||
/// becomes the `String` without copying: a Rust `String` is a UTF-8 byte
|
||||
/// buffer, so `String::from_utf8` only validates and reuses the `Vec`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `bytes` - the whole file
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The text, without a byte-order mark.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`SourceTextError::Malformed`] when a BOM names an encoding the
|
||||
/// bytes don't follow, and [`SourceTextError::Binary`] for non-UTF-8 bytes
|
||||
/// that contain a NUL.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::encoding::decode;
|
||||
///
|
||||
/// // "€" is 0x80 in Windows-1252.
|
||||
/// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €"));
|
||||
/// ```
|
||||
pub fn decode(mut bytes: Vec<u8>) -> Result<String, SourceTextError> {
|
||||
if let Some((encoding, bom_len)) = Encoding::for_bom(&bytes) {
|
||||
if encoding == UTF_8 {
|
||||
// Drop the BOM in place, then validate without another copy.
|
||||
bytes.drain(..bom_len);
|
||||
return String::from_utf8(bytes).map_err(|_| SourceTextError::Malformed("UTF-8"));
|
||||
}
|
||||
// UTF-16 LE or BE: `None` on an odd byte count or unpaired surrogate.
|
||||
return encoding
|
||||
.decode_without_bom_handling_and_without_replacement(&bytes[bom_len..])
|
||||
.map(|text| text.into_owned())
|
||||
.ok_or(SourceTextError::Malformed(encoding.name()));
|
||||
}
|
||||
match String::from_utf8(bytes) {
|
||||
Ok(text) => Ok(text),
|
||||
Err(not_utf8) => {
|
||||
// Hand the buffer back; `from_utf8` gave up ownership on failure.
|
||||
let bytes = not_utf8.into_bytes();
|
||||
if bytes.contains(&0) {
|
||||
return Err(SourceTextError::Binary);
|
||||
}
|
||||
// Windows-1252 maps every byte, so this decoding can't fail.
|
||||
let (text, _had_errors) = WINDOWS_1252.decode_without_bom_handling(&bytes);
|
||||
Ok(text.into_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `text` as UTF-16 with its BOM, in the byte order asked for.
|
||||
fn utf16(text: &str, little_endian: bool) -> Vec<u8> {
|
||||
let bom: [u8; 2] = if little_endian {
|
||||
[0xFF, 0xFE]
|
||||
} else {
|
||||
[0xFE, 0xFF]
|
||||
};
|
||||
let units = text.encode_utf16().flat_map(|unit| {
|
||||
if little_endian {
|
||||
unit.to_le_bytes()
|
||||
} else {
|
||||
unit.to_be_bytes()
|
||||
}
|
||||
});
|
||||
bom.into_iter().chain(units).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf8_without_a_bom_is_kept_as_it_is() {
|
||||
let text = decode("int größe = 1; // €".as_bytes().to_vec());
|
||||
assert_eq!(text.ok().as_deref(), Some("int größe = 1; // €"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_utf8_bom_is_dropped() {
|
||||
let mut bytes = vec![0xEF, 0xBB, 0xBF];
|
||||
bytes.extend_from_slice(b"class A {}");
|
||||
assert_eq!(decode(bytes).ok().as_deref(), Some("class A {}"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_with_a_bom_is_decoded_in_both_byte_orders() {
|
||||
for little_endian in [true, false] {
|
||||
let text = decode(utf16("class Größe {}", little_endian));
|
||||
assert_eq!(text.ok().as_deref(), Some("class Größe {}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_1252_is_the_fallback() {
|
||||
// "Größe" and "€" as Windows-1252 writes them: 0xF6 0xDF and 0x80.
|
||||
let text = decode(b"// Gr\xF6\xDFe in \x80".to_vec());
|
||||
assert_eq!(text.ok().as_deref(), Some("// Größe in €"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_utf16_and_binaries_are_not_text() {
|
||||
// An odd byte count after a UTF-16 LE BOM.
|
||||
assert!(matches!(
|
||||
decode(vec![0xFF, 0xFE, 0x41]),
|
||||
Err(SourceTextError::Malformed("UTF-16LE"))
|
||||
));
|
||||
// An unpaired high surrogate (D800) in UTF-16 BE.
|
||||
assert!(matches!(
|
||||
decode(vec![0xFE, 0xFF, 0xD8, 0x00, 0x00, 0x41]),
|
||||
Err(SourceTextError::Malformed("UTF-16BE"))
|
||||
));
|
||||
// Invalid UTF-8 after a UTF-8 BOM.
|
||||
assert!(matches!(
|
||||
decode(vec![0xEF, 0xBB, 0xBF, 0xFF]),
|
||||
Err(SourceTextError::Malformed("UTF-8"))
|
||||
));
|
||||
// Not UTF-8 and a NUL: a binary.
|
||||
assert!(matches!(
|
||||
decode(vec![0x7F, b'E', b'L', b'F', 0x00, 0xFF]),
|
||||
Err(SourceTextError::Binary)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_an_io_error() {
|
||||
let missing = std::env::temp_dir().join("compliance-core-no-such-file.cs");
|
||||
assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_))));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
pub mod build_info;
|
||||
pub mod config;
|
||||
pub mod control_check;
|
||||
pub mod csaf_docs;
|
||||
pub mod csaf_ingest;
|
||||
pub mod db;
|
||||
pub mod encoding;
|
||||
pub mod enisa_docs;
|
||||
pub mod error;
|
||||
pub mod exec_policy;
|
||||
|
||||
@@ -121,6 +121,20 @@ pub struct GraphBuildRun {
|
||||
pub edge_count: u32,
|
||||
pub community_count: u32,
|
||||
pub languages_parsed: Vec<String>,
|
||||
/// Nodes that are files; the other nodes are the declarations in them.
|
||||
/// `None` on a build stored before it was counted.
|
||||
#[serde(default)]
|
||||
pub file_count: Option<u32>,
|
||||
/// Nodes that are entry points (`main`, request handlers, interrupt
|
||||
/// handlers, PLC programs). `None` on a build stored before it was counted.
|
||||
#[serde(default)]
|
||||
pub entry_point_count: Option<u32>,
|
||||
/// Source files left out because they could not be read as text (not
|
||||
/// UTF-8, UTF-16 with a byte-order mark or Windows-1252, or an I/O
|
||||
/// error). `None` on a build stored before it was counted, and on a PLC
|
||||
/// build, whose files are read by the PLC stage.
|
||||
#[serde(default)]
|
||||
pub unreadable_file_count: Option<u32>,
|
||||
pub error_message: Option<String>,
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub started_at: DateTime<Utc>,
|
||||
@@ -139,6 +153,9 @@ impl GraphBuildRun {
|
||||
edge_count: 0,
|
||||
community_count: 0,
|
||||
languages_parsed: Vec::new(),
|
||||
file_count: None,
|
||||
entry_point_count: None,
|
||||
unreadable_file_count: None,
|
||||
error_message: None,
|
||||
started_at: Utc::now(),
|
||||
completed_at: None,
|
||||
@@ -187,3 +204,25 @@ impl ImpactAnalysis {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_build_stored_before_the_counts_still_reads() {
|
||||
// Arrange: a stored build as t82 and earlier wrote it.
|
||||
let mut stored = bson::to_document(&GraphBuildRun::new("r".to_string())).expect("bson");
|
||||
for field in ["file_count", "entry_point_count", "unreadable_file_count"] {
|
||||
stored.remove(field);
|
||||
}
|
||||
|
||||
// Act
|
||||
let build: GraphBuildRun = bson::from_document(stored).expect("old build reads");
|
||||
|
||||
// Assert
|
||||
assert_eq!(build.file_count, None);
|
||||
assert_eq!(build.unreadable_file_count, None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
//! Metering (t72): whether a target is one of the plan's included targets,
|
||||
//! why a scan ran, and whether that scan counts toward the customer's usage.
|
||||
//!
|
||||
//! The contract (Leistungsbeschreibung Prüfwerk §2 Abs. 4–5, §7): change-driven
|
||||
//! scans of an included target are not counted; Prüfungen the customer
|
||||
//! requests are, and so is every scan of an extra target. Our own rescans and
|
||||
//! support's scans never are.
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::repository::ScanTrigger;
|
||||
|
||||
/// Whether a target is one of the plan's included targets or an extra one
|
||||
/// (billed per month on top).
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TargetBilling {
|
||||
/// One of the plan's included targets. Targets stored before metering
|
||||
/// existed read as included.
|
||||
#[default]
|
||||
Included,
|
||||
/// A target beyond the plan's included ones.
|
||||
Extra,
|
||||
}
|
||||
|
||||
/// Why a scan ran, as far as metering is concerned.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScanAttribution {
|
||||
/// Started because something changed: new commits, other uploaded
|
||||
/// files, or a live URL (scanned on every schedule).
|
||||
Change,
|
||||
/// The customer asked for it (dashboard or API).
|
||||
Request,
|
||||
/// Our own: a scheduled scan where nothing the customer changed, only
|
||||
/// the Prüfwerk build. Never counted.
|
||||
Rescan,
|
||||
/// Started by Breakpilot support in the customer's tenant. Never counted.
|
||||
Support,
|
||||
}
|
||||
|
||||
impl ScanAttribution {
|
||||
/// The attribution a scan started by a person has from the start, before
|
||||
/// any change detection; `None` for a scheduled or webhook scan, which
|
||||
/// change detection attributes.
|
||||
pub fn of_person(trigger: &ScanTrigger) -> Option<Self> {
|
||||
match trigger {
|
||||
ScanTrigger::Manual => Some(Self::Request),
|
||||
ScanTrigger::Support => Some(Self::Support),
|
||||
ScanTrigger::Scheduled | ScanTrigger::Webhook | ScanTrigger::NewContent => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The attribution of a scan that runs, from its trigger and whether
|
||||
/// change detection found a change the customer made.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `trigger` - What started the scan.
|
||||
/// * `content_changed` - New commits, other uploaded files, or a live
|
||||
/// URL. Ignored for a scan a person started.
|
||||
pub fn detected(trigger: &ScanTrigger, content_changed: bool) -> Self {
|
||||
match Self::of_person(trigger) {
|
||||
Some(person) => person,
|
||||
None if content_changed => Self::Change,
|
||||
None => Self::Rescan,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a scan with this attribution, on a target billed as
|
||||
/// `billing`, counts toward the customer's usage once it completes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::models::{ScanAttribution, TargetBilling};
|
||||
///
|
||||
/// assert!(!ScanAttribution::Change.chargeable(TargetBilling::Included));
|
||||
/// assert!(ScanAttribution::Change.chargeable(TargetBilling::Extra));
|
||||
/// assert!(ScanAttribution::Request.chargeable(TargetBilling::Included));
|
||||
/// assert!(!ScanAttribution::Rescan.chargeable(TargetBilling::Extra));
|
||||
/// ```
|
||||
pub fn chargeable(self, billing: TargetBilling) -> bool {
|
||||
match self {
|
||||
Self::Request => true,
|
||||
Self::Change => billing == TargetBilling::Extra,
|
||||
Self::Rescan | Self::Support => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How many counted Prüfungen one Prüftag allows on its target that day.
|
||||
pub const PRUEFUNGEN_PER_PRUEFTAG: u32 = 6;
|
||||
|
||||
/// What the tenant's plan allows per calendar month (Europe/Berlin).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct PlanLimits {
|
||||
/// Counted Prüfungen in the quota; `None` is unlimited (no Prüftage).
|
||||
pub monthly_pruefungen: Option<u32>,
|
||||
/// Prüftage the customer allows; `None` is no cap, `Some(0)` none.
|
||||
pub prueftag_cap: Option<u32>,
|
||||
}
|
||||
|
||||
/// What the tenant used so far this month.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct MonthUsage {
|
||||
/// Counted Prüfungen charged to the quota.
|
||||
pub pruefungen: u32,
|
||||
/// Prüftage booked.
|
||||
pub prueftage: u32,
|
||||
}
|
||||
|
||||
/// What one target used today, once the quota was used up.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct DayUsage {
|
||||
/// Whether a Prüftag is booked for the target today.
|
||||
pub prueftag_booked: bool,
|
||||
/// Counted Prüfungen charged to that Prüftag.
|
||||
pub prueftag_pruefungen: u32,
|
||||
}
|
||||
|
||||
/// What a counted Prüfung was charged to.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RunCharge {
|
||||
/// The month's quota.
|
||||
Quota,
|
||||
/// The target's Prüftag for that day.
|
||||
Prueftag,
|
||||
}
|
||||
|
||||
/// Whether a counted Prüfung may run, and what it is charged to.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Admission {
|
||||
/// Within the month's quota.
|
||||
Quota,
|
||||
/// On the target's Prüftag already booked today.
|
||||
Prueftag,
|
||||
/// The quota is used up: this Prüfung books today's Prüftag.
|
||||
BookPrueftag,
|
||||
/// It does not run.
|
||||
Refused(Refusal),
|
||||
}
|
||||
|
||||
/// Why a counted Prüfung does not run.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Refusal {
|
||||
/// Today's Prüftag on the target is used up; there is no second one.
|
||||
DailyLimit,
|
||||
/// The quota is used up and the customer's Prüftag cap is reached.
|
||||
PrueftagCap,
|
||||
}
|
||||
|
||||
/// Whether one more counted Prüfung on a target may run, by the contract
|
||||
/// (LB Prüfwerk §2 Abs. 5): the quota first; once it is used up, the first
|
||||
/// counted Prüfung on a target that day books a Prüftag (unless the cap is
|
||||
/// reached), which allows [`PRUEFUNGEN_PER_PRUEFTAG`] from then on.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use compliance_core::models::{admit, Admission, DayUsage, MonthUsage, PlanLimits};
|
||||
///
|
||||
/// let plan = PlanLimits { monthly_pruefungen: Some(100), prueftag_cap: None };
|
||||
/// let used_up = MonthUsage { pruefungen: 100, prueftage: 0 };
|
||||
/// assert_eq!(admit(plan, used_up, DayUsage::default()), Admission::BookPrueftag);
|
||||
/// ```
|
||||
pub fn admit(limits: PlanLimits, month: MonthUsage, day: DayUsage) -> Admission {
|
||||
let Some(quota) = limits.monthly_pruefungen else {
|
||||
return Admission::Quota;
|
||||
};
|
||||
if month.pruefungen < quota {
|
||||
return Admission::Quota;
|
||||
}
|
||||
if day.prueftag_booked {
|
||||
return if day.prueftag_pruefungen < PRUEFUNGEN_PER_PRUEFTAG {
|
||||
Admission::Prueftag
|
||||
} else {
|
||||
Admission::Refused(Refusal::DailyLimit)
|
||||
};
|
||||
}
|
||||
match limits.prueftag_cap {
|
||||
Some(cap) if month.prueftage >= cap => Admission::Refused(Refusal::PrueftagCap),
|
||||
_ => Admission::BookPrueftag,
|
||||
}
|
||||
}
|
||||
|
||||
/// The customer's choice for a target's billing, from a swap (t72): the
|
||||
/// target swapped in is wanted included, the one swapped out extra.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum IncludedChoice {
|
||||
/// Swapped in: included before the oldest targets.
|
||||
Included,
|
||||
/// Swapped out: extra before the newest targets.
|
||||
Extra,
|
||||
}
|
||||
|
||||
impl IncludedChoice {
|
||||
/// Where a target with `choice` comes in the split: swapped in first,
|
||||
/// swapped out last, every other target by age in between.
|
||||
fn rank(choice: Option<Self>) -> u8 {
|
||||
match choice {
|
||||
Some(Self::Included) => 0,
|
||||
None => 1,
|
||||
Some(Self::Extra) => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a swap of an extra target with an included one is not made (t72).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SwapRefusal {
|
||||
/// The plan includes every target, so there is nothing to swap.
|
||||
Unlimited,
|
||||
/// The target to swap in is not extra.
|
||||
NotExtra,
|
||||
/// The target to swap out is not included.
|
||||
NotIncluded,
|
||||
/// The target to swap out was swapped in this month and stays included
|
||||
/// until the month's end.
|
||||
Locked,
|
||||
}
|
||||
|
||||
/// Whether an extra target may be swapped with an included one, by the
|
||||
/// contract: at any time, except that a target swapped in stays included
|
||||
/// until the end of its calendar month.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `limited` - Whether the plan limits the included targets.
|
||||
/// * `incoming` - How the target to swap in is billed now.
|
||||
/// * `outgoing` - How the target to swap out is billed now.
|
||||
/// * `outgoing_locked` - Whether the target to swap out is still within
|
||||
/// the month it was swapped in.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The [`SwapRefusal`] that stops the swap.
|
||||
pub fn check_swap(
|
||||
limited: bool,
|
||||
incoming: TargetBilling,
|
||||
outgoing: TargetBilling,
|
||||
outgoing_locked: bool,
|
||||
) -> Result<(), SwapRefusal> {
|
||||
if !limited {
|
||||
return Err(SwapRefusal::Unlimited);
|
||||
}
|
||||
if incoming != TargetBilling::Extra {
|
||||
return Err(SwapRefusal::NotExtra);
|
||||
}
|
||||
if outgoing != TargetBilling::Included {
|
||||
return Err(SwapRefusal::NotIncluded);
|
||||
}
|
||||
if outgoing_locked {
|
||||
return Err(SwapRefusal::Locked);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One active target as [`split_included`] sees it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BillableTarget<Id> {
|
||||
/// The target's id.
|
||||
pub id: Id,
|
||||
/// When it was created: the oldest targets are the included ones.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// How it is billed now.
|
||||
pub billing: TargetBilling,
|
||||
/// The customer's choice from a swap, if any.
|
||||
pub choice: Option<IncludedChoice>,
|
||||
}
|
||||
|
||||
/// The targets whose billing has to change so that the `included` oldest
|
||||
/// active targets are included and the rest are extra; a target the
|
||||
/// customer swapped in comes before the oldest, one swapped out after the
|
||||
/// newest.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `targets` - The tenant's active (not archived) targets, in any order.
|
||||
/// Ties on `created_at` are broken by id, so the split is stable.
|
||||
/// * `included` - How many targets the plan includes; `None` is unlimited.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Each target whose billing differs from what it should be, with the
|
||||
/// billing it should have. Empty when nothing changes.
|
||||
pub fn split_included<Id: Ord + Clone>(
|
||||
targets: &[BillableTarget<Id>],
|
||||
included: Option<u32>,
|
||||
) -> Vec<(Id, TargetBilling)> {
|
||||
let mut ordered: Vec<&BillableTarget<Id>> = targets.iter().collect();
|
||||
ordered.sort_unstable_by(|a, b| {
|
||||
IncludedChoice::rank(a.choice)
|
||||
.cmp(&IncludedChoice::rank(b.choice))
|
||||
.then(a.created_at.cmp(&b.created_at))
|
||||
.then(a.id.cmp(&b.id))
|
||||
});
|
||||
// `usize::MAX` stands for "no limit"; a u32 always fits a usize here.
|
||||
let limit = included.map_or(usize::MAX, |n| n as usize);
|
||||
ordered
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(rank, target)| {
|
||||
let wanted = if rank < limit {
|
||||
TargetBilling::Included
|
||||
} else {
|
||||
TargetBilling::Extra
|
||||
};
|
||||
(target.billing != wanted).then(|| (target.id.clone(), wanted))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
|
||||
fn target(id: u32, day: u32, billing: TargetBilling) -> BillableTarget<u32> {
|
||||
BillableTarget {
|
||||
id,
|
||||
created_at: Utc
|
||||
.with_ymd_and_hms(2026, 11, day, 0, 0, 0)
|
||||
.single()
|
||||
.expect("valid date"),
|
||||
billing,
|
||||
choice: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_swap_moves_one_in_and_one_out() {
|
||||
// Arrange: two included (days 1, 2) and one extra (day 3); the
|
||||
// customer swaps 3 in for 1.
|
||||
let mut incoming = target(3, 3, TargetBilling::Extra);
|
||||
incoming.choice = Some(IncludedChoice::Included);
|
||||
let mut outgoing = target(1, 1, TargetBilling::Included);
|
||||
outgoing.choice = Some(IncludedChoice::Extra);
|
||||
let targets = [outgoing, target(2, 2, TargetBilling::Included), incoming];
|
||||
|
||||
// Act
|
||||
let mut changes = split_included(&targets, Some(2));
|
||||
changes.sort_unstable_by_key(|(id, _)| *id);
|
||||
|
||||
// Assert: the count of extra targets is the same.
|
||||
assert_eq!(
|
||||
changes,
|
||||
vec![(1, TargetBilling::Extra), (3, TargetBilling::Included)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_target_swapped_in_this_month_cannot_go_out() {
|
||||
use TargetBilling::{Extra, Included};
|
||||
assert_eq!(check_swap(true, Extra, Included, false), Ok(()));
|
||||
assert_eq!(
|
||||
check_swap(true, Extra, Included, true),
|
||||
Err(SwapRefusal::Locked)
|
||||
);
|
||||
assert_eq!(
|
||||
check_swap(true, Included, Included, false),
|
||||
Err(SwapRefusal::NotExtra)
|
||||
);
|
||||
assert_eq!(
|
||||
check_swap(true, Extra, Extra, false),
|
||||
Err(SwapRefusal::NotIncluded)
|
||||
);
|
||||
assert_eq!(
|
||||
check_swap(false, Extra, Included, false),
|
||||
Err(SwapRefusal::Unlimited)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_oldest_targets_are_included_and_the_rest_extra() {
|
||||
// Arrange: three included targets, created on days 3, 1 and 2.
|
||||
let targets = [
|
||||
target(1, 3, TargetBilling::Included),
|
||||
target(2, 1, TargetBilling::Included),
|
||||
target(3, 2, TargetBilling::Included),
|
||||
];
|
||||
|
||||
// Act
|
||||
let changes = split_included(&targets, Some(2));
|
||||
|
||||
// Assert: only the newest one moves to extra.
|
||||
assert_eq!(changes, vec![(1, TargetBilling::Extra)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_extra_target_moves_up_when_an_included_one_leaves() {
|
||||
let targets = [
|
||||
target(2, 2, TargetBilling::Included),
|
||||
target(3, 3, TargetBilling::Extra),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
split_included(&targets, Some(2)),
|
||||
vec![(3, TargetBilling::Included)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_limit_every_target_is_included() {
|
||||
let targets = [
|
||||
target(1, 1, TargetBilling::Extra),
|
||||
target(2, 2, TargetBilling::Included),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
split_included(&targets, None),
|
||||
vec![(1, TargetBilling::Included)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_creation_times_split_by_id() {
|
||||
let targets = [
|
||||
target(9, 1, TargetBilling::Included),
|
||||
target(4, 1, TargetBilling::Included),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
split_included(&targets, Some(1)),
|
||||
vec![(9, TargetBilling::Extra)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_a_person_started_keeps_its_attribution() {
|
||||
assert_eq!(
|
||||
ScanAttribution::detected(&ScanTrigger::Manual, false),
|
||||
ScanAttribution::Request
|
||||
);
|
||||
assert_eq!(
|
||||
ScanAttribution::detected(&ScanTrigger::Support, true),
|
||||
ScanAttribution::Support
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scheduled_scan_is_a_change_or_our_rescan() {
|
||||
assert_eq!(
|
||||
ScanAttribution::detected(&ScanTrigger::Scheduled, true),
|
||||
ScanAttribution::Change
|
||||
);
|
||||
assert_eq!(
|
||||
ScanAttribution::detected(&ScanTrigger::Webhook, false),
|
||||
ScanAttribution::Rescan
|
||||
);
|
||||
assert_eq!(
|
||||
ScanAttribution::detected(&ScanTrigger::NewContent, true),
|
||||
ScanAttribution::Change,
|
||||
"an upload is the customer's change"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_counts_follows_the_contract() {
|
||||
use ScanAttribution::{Change, Request, Rescan, Support};
|
||||
use TargetBilling::{Extra, Included};
|
||||
|
||||
let counted: Vec<(ScanAttribution, TargetBilling)> = [Change, Request, Rescan, Support]
|
||||
.into_iter()
|
||||
.flat_map(|a| [(a, Included), (a, Extra)])
|
||||
.filter(|(a, b)| a.chargeable(*b))
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
counted,
|
||||
vec![(Change, Extra), (Request, Included), (Request, Extra)]
|
||||
);
|
||||
}
|
||||
|
||||
const PLAN: PlanLimits = PlanLimits {
|
||||
monthly_pruefungen: Some(100),
|
||||
prueftag_cap: Some(2),
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn the_quota_comes_first() {
|
||||
let month = MonthUsage {
|
||||
pruefungen: 99,
|
||||
prueftage: 0,
|
||||
};
|
||||
assert_eq!(admit(PLAN, month, DayUsage::default()), Admission::Quota);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_used_up_quota_books_a_prueftag_that_allows_six() {
|
||||
let month = MonthUsage {
|
||||
pruefungen: 100,
|
||||
prueftage: 1,
|
||||
};
|
||||
assert_eq!(
|
||||
admit(PLAN, month, DayUsage::default()),
|
||||
Admission::BookPrueftag
|
||||
);
|
||||
let booked = |used| DayUsage {
|
||||
prueftag_booked: true,
|
||||
prueftag_pruefungen: used,
|
||||
};
|
||||
assert_eq!(admit(PLAN, month, booked(5)), Admission::Prueftag);
|
||||
assert_eq!(
|
||||
admit(PLAN, month, booked(PRUEFUNGEN_PER_PRUEFTAG)),
|
||||
Admission::Refused(Refusal::DailyLimit)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cap_stops_new_prueftage_but_not_a_booked_one() {
|
||||
let month = MonthUsage {
|
||||
pruefungen: 100,
|
||||
prueftage: 2,
|
||||
};
|
||||
assert_eq!(
|
||||
admit(PLAN, month, DayUsage::default()),
|
||||
Admission::Refused(Refusal::PrueftagCap)
|
||||
);
|
||||
let booked = DayUsage {
|
||||
prueftag_booked: true,
|
||||
prueftag_pruefungen: 1,
|
||||
};
|
||||
assert_eq!(admit(PLAN, month, booked), Admission::Prueftag);
|
||||
let none_allowed = PlanLimits {
|
||||
prueftag_cap: Some(0),
|
||||
..PLAN
|
||||
};
|
||||
let nothing_booked = MonthUsage {
|
||||
pruefungen: 100,
|
||||
prueftage: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
admit(none_allowed, nothing_booked, DayUsage::default()),
|
||||
Admission::Refused(Refusal::PrueftagCap)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_quota_everything_runs() {
|
||||
let unlimited = PlanLimits::default();
|
||||
let month = MonthUsage {
|
||||
pruefungen: 10_000,
|
||||
prueftage: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
admit(unlimited, month, DayUsage::default()),
|
||||
Admission::Quota
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stored_names_are_snake_case() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(TargetBilling::Extra).expect("serializes"),
|
||||
"extra"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(ScanAttribution::Rescan).expect("serializes"),
|
||||
"rescan"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod license;
|
||||
pub mod license_policy;
|
||||
pub mod mcp;
|
||||
pub mod mcp_token;
|
||||
pub mod metering;
|
||||
pub mod notification;
|
||||
pub mod onboarding;
|
||||
pub mod oscal;
|
||||
@@ -57,6 +58,11 @@ pub use license_policy::{
|
||||
};
|
||||
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
|
||||
pub use mcp_token::{McpToken, McpTokenView};
|
||||
pub use metering::{
|
||||
admit, check_swap, split_included, Admission, BillableTarget, DayUsage, IncludedChoice,
|
||||
MonthUsage, PlanLimits, Refusal, RunCharge, ScanAttribution, SwapRefusal, TargetBilling,
|
||||
PRUEFUNGEN_PER_PRUEFTAG,
|
||||
};
|
||||
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
|
||||
pub use onboarding::{
|
||||
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
|
||||
|
||||
@@ -660,6 +660,23 @@ pub struct OnboardedTarget {
|
||||
/// its last scan; `None` for every other target.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub layer_pins: Option<super::yocto::LayerPins>,
|
||||
/// Whether the target is one of the plan's included targets or an extra
|
||||
/// one (t72). The agent sets it from the plan; stored, so it never flips
|
||||
/// unseen.
|
||||
#[serde(default)]
|
||||
pub billing: super::metering::TargetBilling,
|
||||
/// The customer's choice from a swap of an extra target with an
|
||||
/// included one (t72); `None` until one is made.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub included_choice: Option<super::metering::IncludedChoice>,
|
||||
/// Until when a target swapped in stays included: the end of the
|
||||
/// calendar month (Europe/Berlin) it was swapped in.
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "super::serde_helpers::opt_bson_datetime"
|
||||
)]
|
||||
pub included_until: Option<DateTime<Utc>>,
|
||||
/// Creation timestamp.
|
||||
#[serde(
|
||||
default = "chrono::Utc::now",
|
||||
@@ -700,6 +717,9 @@ impl OnboardedTarget {
|
||||
archived_at: None,
|
||||
last_scan: None,
|
||||
layer_pins: None,
|
||||
billing: super::metering::TargetBilling::default(),
|
||||
included_choice: None,
|
||||
included_until: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
|
||||
@@ -10,6 +10,10 @@ pub enum ScanTrigger {
|
||||
/// Started by BreakPilot support in the customer's tenant; not counted
|
||||
/// as the customer's usage.
|
||||
Support,
|
||||
/// Started after the customer gave the target new content: created it,
|
||||
/// or uploaded files (t72). Like a scheduled scan, it runs only when
|
||||
/// something changed, and then it is a change-driven Prüfung.
|
||||
NewContent,
|
||||
}
|
||||
|
||||
impl ScanTrigger {
|
||||
@@ -18,7 +22,7 @@ impl ScanTrigger {
|
||||
pub fn started_by_person(&self) -> bool {
|
||||
match self {
|
||||
Self::Manual | Self::Support => true,
|
||||
Self::Scheduled | Self::Webhook => false,
|
||||
Self::Scheduled | Self::Webhook | Self::NewContent => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,9 @@ impl std::fmt::Display for ScanType {
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScanRunStatus {
|
||||
/// Requested and waiting for one of the agent's scan slots (t84). Moves
|
||||
/// to `running` when it gets one.
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
/// The scan itself hit an error on the target (clone, tool, pipeline).
|
||||
@@ -80,6 +83,16 @@ pub enum ScanRunStatus {
|
||||
Interrupted,
|
||||
}
|
||||
|
||||
impl ScanRunStatus {
|
||||
/// Whether the run has not ended yet: it waits for a slot or runs.
|
||||
pub fn is_open(&self) -> bool {
|
||||
match self {
|
||||
Self::Queued | Self::Running => true,
|
||||
Self::Completed | Self::Failed | Self::Interrupted => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ScanPhase {
|
||||
@@ -154,8 +167,18 @@ pub struct ScanRun {
|
||||
/// absent on runs recorded before it existed.
|
||||
#[serde(default)]
|
||||
pub error_code: Option<RunErrorCode>,
|
||||
/// When the run started; for a queued run, when it was requested, until
|
||||
/// it starts.
|
||||
#[serde(with = "super::serde_helpers::bson_datetime")]
|
||||
pub started_at: DateTime<Utc>,
|
||||
/// When a run that waited for a slot was requested (t84); `None` for a
|
||||
/// run that started at once, and in runs from before it was recorded.
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "super::serde_helpers::opt_bson_datetime"
|
||||
)]
|
||||
pub queued_at: Option<DateTime<Utc>>,
|
||||
#[serde(default, with = "super::serde_helpers::opt_bson_datetime")]
|
||||
pub completed_at: Option<DateTime<Utc>>,
|
||||
/// Stages the pipeline deliberately did not run (e.g. a deployment
|
||||
@@ -184,6 +207,26 @@ pub struct ScanRun {
|
||||
/// at the end of this run (sbomqs, #496); `None` when it was not scored.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub sbom_quality: Option<super::sbom::SbomQuality>,
|
||||
/// Why the run ran, for metering (t72): set when it starts for a scan a
|
||||
/// person started, and by change detection otherwise. `None` for a run
|
||||
/// skipped because nothing changed, and in runs from before metering.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub attribution: Option<super::metering::ScanAttribution>,
|
||||
/// Whether the run counts toward the customer's usage once it completes
|
||||
/// ([`super::metering::ScanAttribution::chargeable`] for the target's
|
||||
/// billing when it was attributed).
|
||||
#[serde(default)]
|
||||
pub chargeable: bool,
|
||||
/// For a person's request that took over a scheduled, webhook or
|
||||
/// new-content scan still waiting for a slot (t84): that scan's trigger.
|
||||
/// The run has the person's priority and attribution, but it counts only
|
||||
/// as that scan would have: it would have run anyway, just later.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub charged_as: Option<ScanTrigger>,
|
||||
/// What the run was charged to once it counted; `None` while it runs,
|
||||
/// and for a run that did not count.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub charge: Option<super::metering::RunCharge>,
|
||||
}
|
||||
|
||||
/// Why a stage was skipped, or what a run note is about
|
||||
@@ -270,6 +313,12 @@ pub enum SkipCode {
|
||||
/// layer pins or `LAYERSERIES_COMPAT`, so its support period was not
|
||||
/// checked.
|
||||
ReleaseUnknown,
|
||||
/// The month's quota is used up and today's Prüftag on the target has
|
||||
/// had its Prüfungen, so this counted Prüfung did not run (t72).
|
||||
PrueftagLimitReached,
|
||||
/// The month's quota is used up and the Prüftag limit the customer set
|
||||
/// is reached, so this counted Prüfung did not run (t72).
|
||||
PrueftagCapReached,
|
||||
}
|
||||
|
||||
impl SkipCode {
|
||||
@@ -304,7 +353,9 @@ impl SkipCode {
|
||||
| Self::PlatformProjectGenerated
|
||||
| Self::UploadUnchanged
|
||||
| Self::TooLargeToScan
|
||||
| Self::ReleaseUnknown => false,
|
||||
| Self::ReleaseUnknown
|
||||
| Self::PrueftagLimitReached
|
||||
| Self::PrueftagCapReached => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,12 +455,27 @@ impl ScanRun {
|
||||
error_message: None,
|
||||
error_code: None,
|
||||
started_at: Utc::now(),
|
||||
queued_at: None,
|
||||
completed_at: None,
|
||||
skipped_stages: Vec::new(),
|
||||
notes: Vec::new(),
|
||||
languages: Vec::new(),
|
||||
planned_phases: Vec::new(),
|
||||
sbom_quality: None,
|
||||
attribution: None,
|
||||
chargeable: false,
|
||||
charged_as: None,
|
||||
charge: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A run requested by `trigger` that waits for a scan slot (t84).
|
||||
pub fn queued(repo_id: String, trigger: ScanTrigger) -> Self {
|
||||
let run = Self::new(repo_id, trigger);
|
||||
Self {
|
||||
status: ScanRunStatus::Queued,
|
||||
queued_at: Some(run.started_at),
|
||||
..run
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -474,6 +540,8 @@ mod skipped_stage_tests {
|
||||
SkipCode::PlatformProjectGenerated,
|
||||
SkipCode::UploadUnchanged,
|
||||
SkipCode::TooLargeToScan,
|
||||
SkipCode::PrueftagLimitReached,
|
||||
SkipCode::PrueftagCapReached,
|
||||
];
|
||||
assert!(notes.iter().all(|c| c.is_informational()));
|
||||
assert!(skips.iter().all(|c| !c.is_informational()));
|
||||
|
||||
@@ -55,7 +55,10 @@ fn build_resource(service_name: &str) -> Resource {
|
||||
let name = std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| service_name.to_string());
|
||||
Resource::builder()
|
||||
.with_service_name(name)
|
||||
.with_attributes([KeyValue::new("service.version", env!("CARGO_PKG_VERSION"))])
|
||||
.with_attributes([KeyValue::new(
|
||||
"service.version",
|
||||
crate::build_info::BUILD_VERSION,
|
||||
)])
|
||||
.build()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,231 +1,241 @@
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Graph Visualization — vis-network wrapper for Code Knowledge Graph
|
||||
// Obsidian Control theme
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Code graph drawing: a thin vis-network wrapper.
|
||||
//
|
||||
// The dashboard's Rust code decides what is drawn (the whole graph, the
|
||||
// community overview or one community, see pages/graph_view.rs) and passes
|
||||
// the nodes, edges and the UI texts in the reader's language. This file only
|
||||
// draws them, in the colours of the current theme.
|
||||
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
// Color palette matching Obsidian Control
|
||||
const NODE_COLORS = {
|
||||
function: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
|
||||
method: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
|
||||
struct: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
|
||||
class: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
|
||||
enum: { bg: "#ffb020", border: "#cc8c18", font: "#060a13" },
|
||||
interface: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
|
||||
trait: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
|
||||
module: { bg: "#ff8a3d", border: "#cc6e30", font: "#060a13" },
|
||||
file: { bg: "#00e676", border: "#00b85e", font: "#060a13" },
|
||||
// CSS custom properties per node kind, defined in main.css from the theme
|
||||
// tokens, so the graph follows the light and dark theme.
|
||||
var KIND_TOKEN = {
|
||||
function: "--graph-function",
|
||||
method: "--graph-function",
|
||||
class: "--graph-type",
|
||||
struct: "--graph-type",
|
||||
enum: "--graph-enum",
|
||||
interface: "--graph-interface",
|
||||
trait: "--graph-interface",
|
||||
module: "--graph-module",
|
||||
file: "--graph-file",
|
||||
community: "--graph-community",
|
||||
folder: "--graph-community",
|
||||
};
|
||||
var EDGE_TOKEN = {
|
||||
calls: "--graph-function",
|
||||
imports: "--graph-enum",
|
||||
inherits: "--graph-type",
|
||||
implements: "--graph-interface",
|
||||
bundle: "--graph-community",
|
||||
};
|
||||
|
||||
const EDGE_COLORS = {
|
||||
calls: "#00c8ff",
|
||||
imports: "#ffb020",
|
||||
inherits: "#e040fb",
|
||||
implements: "#7c4dff",
|
||||
contains: "rgba(94, 114, 145, 0.6)",
|
||||
type_ref: "rgba(94, 114, 145, 0.5)",
|
||||
};
|
||||
var SHAPE = { file: "diamond", module: "square", folder: "hexagon" };
|
||||
|
||||
const DEFAULT_NODE_COLOR = { bg: "#5e7291", border: "#3d506b", font: "#e4eaf4" };
|
||||
const DEFAULT_EDGE_COLOR = "rgba(94, 114, 145, 0.3)";
|
||||
// Above this many nodes the layout runs a short while and then stops,
|
||||
// so a large drawing does not keep the CPU busy.
|
||||
var LARGE = 400;
|
||||
|
||||
let network = null;
|
||||
let nodesDataset = null;
|
||||
let edgesDataset = null;
|
||||
let rawNodes = [];
|
||||
let rawEdges = [];
|
||||
var network = null;
|
||||
var nodesDataset = null;
|
||||
var edgesDataset = null;
|
||||
var rawNodes = [];
|
||||
var rawEdges = [];
|
||||
var texts = { kinds: {}, edges: {}, program: "", plc: [], layout: "", entry: "", file: "" };
|
||||
|
||||
function getNodeColor(kind) {
|
||||
return NODE_COLORS[kind] || DEFAULT_NODE_COLOR;
|
||||
function token(name) {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
}
|
||||
|
||||
function getEdgeColor(kind) {
|
||||
return EDGE_COLORS[kind] || DEFAULT_EDGE_COLOR;
|
||||
function palette() {
|
||||
var kinds = {};
|
||||
Object.keys(KIND_TOKEN).forEach(function (k) {
|
||||
kinds[k] = token(KIND_TOKEN[k]);
|
||||
});
|
||||
var edges = {};
|
||||
Object.keys(EDGE_TOKEN).forEach(function (k) {
|
||||
edges[k] = token(EDGE_TOKEN[k]);
|
||||
});
|
||||
return {
|
||||
kinds: kinds,
|
||||
edges: edges,
|
||||
quiet: token("--border-strong"),
|
||||
text: token("--text-primary"),
|
||||
halo: token("--bg-primary"),
|
||||
ring: token("--text-primary"),
|
||||
fallback: token("--text-tertiary"),
|
||||
font: token("--font-body"),
|
||||
};
|
||||
}
|
||||
|
||||
// Build a vis-network node from raw graph data
|
||||
function toVisNode(node, edgeCounts) {
|
||||
const color = getNodeColor(node.kind);
|
||||
const connections = edgeCounts[node.qualified_name] || 0;
|
||||
const size = Math.max(8, Math.min(35, 8 + connections * 2));
|
||||
function edgeCounts(edges) {
|
||||
var counts = {};
|
||||
edges.forEach(function (e) {
|
||||
counts[e.source] = (counts[e.source] || 0) + 1;
|
||||
counts[e.target] = (counts[e.target] || 0) + 1;
|
||||
});
|
||||
return counts;
|
||||
}
|
||||
|
||||
function toVisNode(node, counts, colors) {
|
||||
var color = colors.kinds[node.kind] || colors.fallback;
|
||||
var isGroup = node.kind === "community" || node.kind === "folder";
|
||||
// A PLC PROGRAM is kept as a module; it is named a program.
|
||||
var kindName = node.kind === "module" && texts.plc.indexOf(node.language) >= 0
|
||||
? texts.program
|
||||
: texts.kinds[node.kind] || node.kind;
|
||||
// A group is sized by its members through `value`, which also scales its
|
||||
// label, so the large groups stay legible when the overview is zoomed out.
|
||||
var size = Math.max(8, Math.min(30, 8 + (counts[node.qualified_name] || 0) * 1.5));
|
||||
var title = isGroup
|
||||
? kindName + " " + node.name + ": " + node.member_count
|
||||
: kindName + ": " + node.qualified_name +
|
||||
"\n" + texts.file + ": " + node.file_path + ":" + node.start_line +
|
||||
(node.is_entry_point ? "\n" + texts.entry : "");
|
||||
return {
|
||||
id: node.qualified_name,
|
||||
label: node.name,
|
||||
title: `${node.kind}: ${node.qualified_name}\nFile: ${node.file_path}:${node.start_line}`,
|
||||
size: size,
|
||||
label: isGroup ? node.name + "\n" + node.member_count : node.name,
|
||||
title: title,
|
||||
size: isGroup ? undefined : size,
|
||||
value: isGroup ? node.member_count : undefined,
|
||||
color: {
|
||||
background: color.bg,
|
||||
border: color.border,
|
||||
highlight: { background: color.bg, border: "#ffffff" },
|
||||
hover: { background: color.bg, border: "#ffffff" },
|
||||
background: color,
|
||||
border: node.is_entry_point ? colors.ring : color,
|
||||
highlight: { background: color, border: colors.ring },
|
||||
hover: { background: color, border: colors.ring },
|
||||
},
|
||||
font: {
|
||||
color: color.font,
|
||||
size: 10,
|
||||
face: "'JetBrains Mono', monospace",
|
||||
strokeWidth: 2,
|
||||
strokeColor: "#060a13",
|
||||
color: colors.text,
|
||||
size: isGroup ? 13 : 11,
|
||||
face: colors.font,
|
||||
strokeWidth: 3,
|
||||
strokeColor: colors.halo,
|
||||
},
|
||||
borderWidth: 1,
|
||||
borderWidth: node.is_entry_point ? 3 : 1,
|
||||
borderWidthSelected: 3,
|
||||
shape: node.kind === "file" ? "diamond" : node.kind === "module" ? "square" : "dot",
|
||||
// Store raw data for click handler
|
||||
shape: SHAPE[node.kind] || "dot",
|
||||
_raw: node,
|
||||
};
|
||||
}
|
||||
|
||||
function toVisEdge(edge) {
|
||||
const color = getEdgeColor(edge.kind);
|
||||
const isDim = edge.kind === "contains" || edge.kind === "type_ref";
|
||||
|
||||
function toVisEdge(edge, colors) {
|
||||
var color = colors.edges[edge.kind] || colors.quiet;
|
||||
var count = edge.count || 1;
|
||||
var label = edge.kind === "bundle" ? String(count) : texts.edges[edge.kind] || edge.kind;
|
||||
return {
|
||||
id: edge.source + "|" + edge.target + "|" + edge.kind,
|
||||
from: edge.source,
|
||||
to: edge.target,
|
||||
color: {
|
||||
color: color,
|
||||
highlight: "#ffffff",
|
||||
highlight: colors.ring,
|
||||
hover: color,
|
||||
opacity: edge.kind === "bundle" ? 0.35 : 0.7,
|
||||
},
|
||||
width: isDim ? 1 : 2,
|
||||
arrows: {
|
||||
to: {
|
||||
enabled: edge.kind !== "contains",
|
||||
scaleFactor: 0.5,
|
||||
},
|
||||
},
|
||||
smooth: {
|
||||
enabled: true,
|
||||
type: "continuous",
|
||||
roundness: 0.3,
|
||||
},
|
||||
title: `${edge.kind}: ${edge.source} → ${edge.target}`,
|
||||
_raw: edge,
|
||||
width: edge.kind === "bundle" ? Math.min(8, 1 + Math.log2(count)) : 1,
|
||||
arrows: { to: { enabled: edge.kind !== "contains", scaleFactor: 0.4 } },
|
||||
smooth: { enabled: true, type: "continuous", roundness: 0.3 },
|
||||
title: label,
|
||||
};
|
||||
}
|
||||
|
||||
// Recolour everything after a theme change, without a new layout.
|
||||
function recolor() {
|
||||
if (!network) return;
|
||||
var colors = palette();
|
||||
var counts = edgeCounts(rawEdges);
|
||||
nodesDataset.update(rawNodes.map(function (n) {
|
||||
return toVisNode(n, counts, colors);
|
||||
}));
|
||||
edgesDataset.update(rawEdges.map(function (e) {
|
||||
return toVisEdge(e, colors);
|
||||
}));
|
||||
}
|
||||
|
||||
new MutationObserver(recolor).observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["data-theme"],
|
||||
});
|
||||
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", recolor);
|
||||
|
||||
function uniqueBy(items, key) {
|
||||
var seen = {};
|
||||
return items.filter(function (item) {
|
||||
var k = key(item);
|
||||
if (seen[k]) return false;
|
||||
seen[k] = true;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize or reload the graph visualization.
|
||||
* Called from Rust via eval().
|
||||
* Draw `nodes` and `edges`, then select and show the nodes named in
|
||||
* `focus` (may be empty). `labels` holds the UI texts. Called from Rust.
|
||||
*/
|
||||
window.__loadGraph = function (nodes, edges) {
|
||||
window.__loadGraph = function (nodes, edges, labels, focus) {
|
||||
var container = document.getElementById("graph-canvas");
|
||||
if (!container) {
|
||||
console.error("[graph-viz] #graph-canvas not found");
|
||||
return;
|
||||
}
|
||||
if (!container) return;
|
||||
texts = labels;
|
||||
|
||||
// Count edges per node for sizing
|
||||
const edgeCounts = {};
|
||||
edges.forEach(function (e) {
|
||||
edgeCounts[e.source] = (edgeCounts[e.source] || 0) + 1;
|
||||
edgeCounts[e.target] = (edgeCounts[e.target] || 0) + 1;
|
||||
});
|
||||
rawNodes = uniqueBy(nodes, function (n) { return n.qualified_name; });
|
||||
rawEdges = uniqueBy(edges, function (e) { return e.source + "|" + e.target + "|" + e.kind; });
|
||||
|
||||
// Deduplicate nodes by qualified_name (keep first occurrence)
|
||||
var seenNodes = {};
|
||||
var uniqueNodes = [];
|
||||
nodes.forEach(function (n) {
|
||||
if (!seenNodes[n.qualified_name]) {
|
||||
seenNodes[n.qualified_name] = true;
|
||||
uniqueNodes.push(n);
|
||||
}
|
||||
});
|
||||
var colors = palette();
|
||||
var counts = edgeCounts(rawEdges);
|
||||
nodesDataset = new vis.DataSet(rawNodes.map(function (n) {
|
||||
return toVisNode(n, counts, colors);
|
||||
}));
|
||||
edgesDataset = new vis.DataSet(rawEdges.map(function (e) {
|
||||
return toVisEdge(e, colors);
|
||||
}));
|
||||
|
||||
// Deduplicate edges by source+target+kind
|
||||
var seenEdges = {};
|
||||
var uniqueEdges = [];
|
||||
edges.forEach(function (e) {
|
||||
var key = e.source + "|" + e.target + "|" + e.kind;
|
||||
if (!seenEdges[key]) {
|
||||
seenEdges[key] = true;
|
||||
uniqueEdges.push(e);
|
||||
}
|
||||
});
|
||||
|
||||
rawNodes = uniqueNodes;
|
||||
rawEdges = uniqueEdges;
|
||||
|
||||
var visNodes = uniqueNodes.map(function (n) {
|
||||
return toVisNode(n, edgeCounts);
|
||||
});
|
||||
var visEdges = uniqueEdges.map(toVisEdge);
|
||||
|
||||
nodesDataset = new vis.DataSet(visNodes);
|
||||
edgesDataset = new vis.DataSet(visEdges);
|
||||
|
||||
const options = {
|
||||
var large = rawNodes.length > LARGE;
|
||||
var options = {
|
||||
nodes: {
|
||||
font: { color: "#e4eaf4", size: 10 },
|
||||
scaling: { min: 8, max: 35 },
|
||||
},
|
||||
edges: {
|
||||
font: { color: "#5e7291", size: 9, strokeWidth: 0 },
|
||||
selectionWidth: 3,
|
||||
scaling: {
|
||||
min: 12,
|
||||
max: 56,
|
||||
label: { enabled: true, min: 22, max: 48, drawThreshold: 5, maxVisible: 30 },
|
||||
},
|
||||
},
|
||||
physics: {
|
||||
enabled: true,
|
||||
solver: "forceAtlas2Based",
|
||||
forceAtlas2Based: {
|
||||
gravitationalConstant: -80,
|
||||
centralGravity: 0.005,
|
||||
springLength: 120,
|
||||
gravitationalConstant: -60,
|
||||
centralGravity: 0.008,
|
||||
springLength: 110,
|
||||
springConstant: 0.04,
|
||||
damping: 0.5,
|
||||
avoidOverlap: 0.6,
|
||||
damping: 0.6,
|
||||
avoidOverlap: 0.5,
|
||||
},
|
||||
stabilization: {
|
||||
enabled: true,
|
||||
iterations: 1500,
|
||||
updateInterval: 25,
|
||||
},
|
||||
maxVelocity: 50,
|
||||
stabilization: { enabled: true, iterations: large ? 300 : 1000, updateInterval: 25 },
|
||||
maxVelocity: 40,
|
||||
minVelocity: 0.75,
|
||||
},
|
||||
interaction: {
|
||||
hover: true,
|
||||
tooltipDelay: 200,
|
||||
hideEdgesOnDrag: false,
|
||||
hideEdgesOnZoom: false,
|
||||
multiselect: false,
|
||||
navigationButtons: false,
|
||||
keyboard: { enabled: true },
|
||||
},
|
||||
layout: {
|
||||
improvedLayout: uniqueNodes.length < 300,
|
||||
hideEdgesOnDrag: large,
|
||||
hideEdgesOnZoom: large,
|
||||
keyboard: { enabled: true, bindToWindow: false },
|
||||
},
|
||||
layout: { improvedLayout: rawNodes.length < 300 },
|
||||
};
|
||||
|
||||
// Destroy previous instance
|
||||
if (network) {
|
||||
network.destroy();
|
||||
}
|
||||
if (network) network.destroy();
|
||||
network = new vis.Network(container, { nodes: nodesDataset, edges: edgesDataset }, options);
|
||||
|
||||
network = new vis.Network(
|
||||
container,
|
||||
{ nodes: nodesDataset, edges: edgesDataset },
|
||||
options
|
||||
);
|
||||
|
||||
// Click handler — sends data to Rust
|
||||
network.on("click", function (params) {
|
||||
if (params.nodes.length > 0) {
|
||||
const nodeId = params.nodes[0];
|
||||
const visNode = nodesDataset.get(nodeId);
|
||||
if (visNode && visNode._raw && window.__onNodeClick) {
|
||||
window.__onNodeClick(JSON.stringify(visNode._raw));
|
||||
}
|
||||
}
|
||||
if (params.nodes.length === 0) return;
|
||||
var raw = rawNodes.find(function (n) { return n.qualified_name === params.nodes[0]; });
|
||||
if (raw && window.__onNodeClick) window.__onNodeClick(JSON.stringify(raw));
|
||||
});
|
||||
|
||||
// Stabilization overlay
|
||||
var overlay = document.getElementById("graph-stabilization-overlay");
|
||||
var progressFill = document.getElementById("graph-stab-progress-fill");
|
||||
var pctLabel = document.getElementById("graph-stab-pct");
|
||||
|
||||
// Show the overlay
|
||||
if (overlay) {
|
||||
overlay.classList.remove("graph-stab-fade-out");
|
||||
overlay.style.display = "flex";
|
||||
@@ -233,120 +243,35 @@
|
||||
|
||||
network.on("stabilizationProgress", function (params) {
|
||||
var pct = Math.round((params.iterations / params.total) * 100);
|
||||
if (progressFill) {
|
||||
progressFill.style.width = pct + "%";
|
||||
}
|
||||
if (pctLabel) {
|
||||
pctLabel.textContent = pct + "% — computing layout";
|
||||
}
|
||||
if (progressFill) progressFill.style.width = pct + "%";
|
||||
if (pctLabel) pctLabel.textContent = texts.layout + " · " + pct + " %";
|
||||
});
|
||||
|
||||
network.on("stabilizationIterationsDone", function () {
|
||||
network.once("stabilizationIterationsDone", function () {
|
||||
if (progressFill) progressFill.style.width = "100%";
|
||||
if (pctLabel) pctLabel.textContent = "Complete";
|
||||
|
||||
// Fade out overlay
|
||||
if (overlay) {
|
||||
overlay.classList.add("graph-stab-fade-out");
|
||||
setTimeout(function () {
|
||||
overlay.style.display = "none";
|
||||
}, 900);
|
||||
setTimeout(function () { overlay.style.display = "none"; }, 600);
|
||||
}
|
||||
// Keep physics running so nodes float and respond to dragging,
|
||||
// but reduce forces for a calm, settled feel
|
||||
network.setOptions({
|
||||
physics: {
|
||||
enabled: true,
|
||||
solver: "forceAtlas2Based",
|
||||
forceAtlas2Based: {
|
||||
gravitationalConstant: -40,
|
||||
centralGravity: 0.003,
|
||||
springLength: 120,
|
||||
springConstant: 0.03,
|
||||
damping: 0.7,
|
||||
avoidOverlap: 0.6,
|
||||
},
|
||||
maxVelocity: 20,
|
||||
minVelocity: 0.75,
|
||||
},
|
||||
});
|
||||
// A large drawing stops moving; a small one keeps settling gently
|
||||
// and answers to dragging.
|
||||
network.setOptions({ physics: large ? { enabled: false } : { maxVelocity: 15 } });
|
||||
window.__highlightNodes(focus || []);
|
||||
});
|
||||
|
||||
console.log(
|
||||
"[graph-viz] Loaded " + nodes.length + " nodes, " + edges.length + " edges"
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlight a node by qualified name. Focuses + selects it.
|
||||
*/
|
||||
window.__highlightNode = function (qualifiedName) {
|
||||
if (!network || !nodesDataset) return;
|
||||
|
||||
const node = nodesDataset.get(qualifiedName);
|
||||
if (!node) return;
|
||||
|
||||
network.selectNodes([qualifiedName]);
|
||||
network.focus(qualifiedName, {
|
||||
scale: 1.5,
|
||||
animation: { duration: 500, easingFunction: "easeInOutQuad" },
|
||||
});
|
||||
|
||||
// Trigger click callback too
|
||||
if (node._raw && window.__onNodeClick) {
|
||||
window.__onNodeClick(JSON.stringify(node._raw));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlight multiple nodes (e.g., search results or file nodes).
|
||||
*/
|
||||
/** Select the named nodes that are drawn and show them. */
|
||||
window.__highlightNodes = function (qualifiedNames) {
|
||||
if (!network || !nodesDataset) return;
|
||||
network.selectNodes(qualifiedNames);
|
||||
if (qualifiedNames.length > 0) {
|
||||
network.fit({
|
||||
nodes: qualifiedNames,
|
||||
animation: { duration: 500, easingFunction: "easeInOutQuad" },
|
||||
});
|
||||
}
|
||||
var drawn = qualifiedNames.filter(function (id) { return nodesDataset.get(id); });
|
||||
if (drawn.length === 0) return;
|
||||
network.selectNodes(drawn);
|
||||
network.fit({ nodes: drawn, animation: { duration: 500, easingFunction: "easeInOutQuad" } });
|
||||
};
|
||||
|
||||
/**
|
||||
* Highlight all nodes belonging to a specific file path.
|
||||
*/
|
||||
window.__highlightFileNodes = function (filePath) {
|
||||
if (!network || !nodesDataset) return;
|
||||
var matching = [];
|
||||
rawNodes.forEach(function (n) {
|
||||
if (n.file_path === filePath) {
|
||||
matching.push(n.qualified_name);
|
||||
}
|
||||
});
|
||||
if (matching.length > 0) {
|
||||
network.selectNodes(matching);
|
||||
network.fit({
|
||||
nodes: matching,
|
||||
animation: { duration: 500, easingFunction: "easeInOutQuad" },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Clear selection.
|
||||
*/
|
||||
window.__clearGraphSelection = function () {
|
||||
if (!network) return;
|
||||
network.unselectAll();
|
||||
};
|
||||
|
||||
/**
|
||||
* Fit entire graph in view.
|
||||
*/
|
||||
/** Fit the whole drawing in view. */
|
||||
window.__fitGraph = function () {
|
||||
if (!network) return;
|
||||
network.fit({
|
||||
animation: { duration: 400, easingFunction: "easeInOutQuad" },
|
||||
});
|
||||
network.fit({ animation: { duration: 400, easingFunction: "easeInOutQuad" } });
|
||||
};
|
||||
})();
|
||||
@@ -101,6 +101,18 @@
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
/* Code graph colours (graph-viz.js reads them), from the theme tokens, so
|
||||
they follow the light and dark theme. */
|
||||
:root {
|
||||
--graph-function: var(--accent);
|
||||
--graph-type: var(--success);
|
||||
--graph-enum: var(--warning);
|
||||
--graph-interface: var(--info);
|
||||
--graph-module: var(--orange);
|
||||
--graph-file: var(--text-faint);
|
||||
--graph-community: var(--text-tertiary);
|
||||
}
|
||||
|
||||
/* ── Dark ("Nacht") ──
|
||||
When chosen explicitly (`data-theme="dark"`), or when the OS prefers dark
|
||||
and no choice was made. */
|
||||
@@ -1762,85 +1774,6 @@ tbody tr:last-child td {
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
/* Orbital rings */
|
||||
.graph-stab-rings {
|
||||
position: relative;
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
}
|
||||
|
||||
.graph-stab-ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 50%;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.graph-stab-ring-1 {
|
||||
border-top-color: var(--accent);
|
||||
border-right-color: var(--accent-muted);
|
||||
animation: stab-orbit 2.4s linear infinite;
|
||||
}
|
||||
|
||||
.graph-stab-ring-2 {
|
||||
inset: 14px;
|
||||
border-bottom-color: rgba(224, 64, 251, 0.5);
|
||||
border-left-color: rgba(224, 64, 251, 0.1);
|
||||
animation: stab-orbit 1.8s linear infinite reverse;
|
||||
filter: drop-shadow(0 0 6px rgba(224, 64, 251, 0.25));
|
||||
}
|
||||
|
||||
.graph-stab-ring-3 {
|
||||
inset: 30px;
|
||||
border-top-color: var(--success);
|
||||
border-right-color: var(--success-bg);
|
||||
animation: stab-orbit 3.2s linear infinite;
|
||||
}
|
||||
|
||||
.graph-stab-core {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
transform: translate(-50%, -50%);
|
||||
background: var(--accent);
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 3px var(--border-accent);
|
||||
animation: stab-pulse 1.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes stab-orbit {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes stab-pulse {
|
||||
0%, 100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
|
||||
50% { transform: translate(-50%, -50%) scale(1.6); opacity: 0.6; }
|
||||
}
|
||||
|
||||
/* Text */
|
||||
.graph-stab-text {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.graph-stab-title {
|
||||
font-family: var(--font-display);
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.graph-stab-subtitle {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
/* Progress bar */
|
||||
.graph-stab-progress {
|
||||
width: 200px;
|
||||
@@ -1854,23 +1787,9 @@ tbody tr:last-child td {
|
||||
.graph-stab-progress-fill {
|
||||
height: 100%;
|
||||
width: 0%;
|
||||
background: linear-gradient(90deg, var(--accent), #e040fb);
|
||||
background: var(--accent);
|
||||
border-radius: 2px;
|
||||
transition: width 0.3s ease-out;
|
||||
box-shadow: none;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.graph-stab-progress-fill::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: -2px;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.graph-stab-pct {
|
||||
@@ -1885,16 +1804,11 @@ tbody tr:last-child td {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
min-height: 240px;
|
||||
color: var(--text-tertiary);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.graph-empty-icon {
|
||||
font-size: 48px;
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.graph-empty-state h3 {
|
||||
font-family: var(--font-display);
|
||||
font-size: 16px;
|
||||
@@ -1905,37 +1819,6 @@ tbody tr:last-child td {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* Stats Bar */
|
||||
.graph-stats-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-secondary);
|
||||
border-top: 1px solid var(--border);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.graph-stat {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.graph-stat-value {
|
||||
color: var(--accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.graph-stat-label {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.graph-stat-divider {
|
||||
color: var(--border-bright);
|
||||
}
|
||||
|
||||
/* Node Kind Badges */
|
||||
.node-label-badge {
|
||||
display: inline-flex;
|
||||
@@ -1949,40 +1832,96 @@ tbody tr:last-child td {
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.node-kind-function, .node-kind-method {
|
||||
background: var(--accent-muted);
|
||||
color: var(--accent);
|
||||
border: 1px solid var(--border-accent);
|
||||
/* Node kinds: the badge in the inspector and the legend's dots, in the
|
||||
colours graph-viz.js draws them with. */
|
||||
.node-label-badge[class*="graph-kind-"] {
|
||||
background: color-mix(in oklch, var(--kind) 12%, transparent);
|
||||
color: var(--kind);
|
||||
border: 1px solid color-mix(in oklch, var(--kind) 30%, transparent);
|
||||
}
|
||||
|
||||
.node-kind-struct, .node-kind-class {
|
||||
background: rgba(224, 64, 251, 0.12);
|
||||
color: #e040fb;
|
||||
border: 1px solid rgba(224, 64, 251, 0.2);
|
||||
.graph-kind-function, .graph-kind-method { --kind: var(--graph-function); }
|
||||
.graph-kind-class, .graph-kind-struct { --kind: var(--graph-type); }
|
||||
.graph-kind-enum { --kind: var(--graph-enum); }
|
||||
.graph-kind-interface, .graph-kind-trait { --kind: var(--graph-interface); }
|
||||
.graph-kind-module { --kind: var(--graph-module); }
|
||||
.graph-kind-file { --kind: var(--graph-file); }
|
||||
.graph-kind-community, .graph-kind-folder { --kind: var(--graph-community); }
|
||||
.graph-legend-dot.graph-kind-folder { border-radius: 2px; }
|
||||
|
||||
.graph-legend {
|
||||
position: absolute;
|
||||
left: 12px;
|
||||
bottom: 12px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
max-width: calc(100% - 24px);
|
||||
margin: 0;
|
||||
padding: 6px 10px;
|
||||
list-style: none;
|
||||
font-size: 11.5px;
|
||||
color: var(--text-secondary);
|
||||
background: color-mix(in oklch, var(--bg-card) 90%, transparent);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.node-kind-enum {
|
||||
background: rgba(255, 176, 32, 0.12);
|
||||
color: #ffb020;
|
||||
border: 1px solid rgba(255, 176, 32, 0.2);
|
||||
.graph-legend li {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.node-kind-interface, .node-kind-trait {
|
||||
background: rgba(124, 77, 255, 0.12);
|
||||
color: #7c4dff;
|
||||
border: 1px solid rgba(124, 77, 255, 0.2);
|
||||
.graph-legend-dot {
|
||||
width: 9px;
|
||||
height: 9px;
|
||||
border-radius: 50%;
|
||||
background: var(--kind);
|
||||
}
|
||||
|
||||
.node-kind-module {
|
||||
background: rgba(255, 138, 61, 0.12);
|
||||
color: #ff8a3d;
|
||||
border: 1px solid rgba(255, 138, 61, 0.2);
|
||||
.graph-legend-entry {
|
||||
background: transparent;
|
||||
border: 2px solid var(--text-primary);
|
||||
}
|
||||
|
||||
.node-kind-file {
|
||||
background: var(--success-bg);
|
||||
color: var(--success);
|
||||
border: 1px solid color-mix(in oklch, var(--success) 30%, transparent);
|
||||
.graph-note {
|
||||
margin: 0 0 12px;
|
||||
font-size: 12.5px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
/* A finding's impact: its call chains and the names around it. */
|
||||
.impact-summary {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.impact-chains,
|
||||
.impact-names {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.impact-chains li {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.impact-chains code,
|
||||
.impact-names code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.impact-chain-arrow {
|
||||
color: var(--text-faint);
|
||||
}
|
||||
|
||||
/* Code Inspector Panel */
|
||||
@@ -2243,12 +2182,23 @@ tbody tr:last-child td {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.search-suggestion-item:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.search-suggestion-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
@@ -4782,6 +4732,21 @@ tbody tr:last-child td {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.usage-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 6px 16px;
|
||||
margin: 0 0 16px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.usage-summary-title {
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.targets-type,
|
||||
.targets-ago {
|
||||
display: block;
|
||||
@@ -4793,6 +4758,25 @@ tbody tr:last-child td {
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.targets-extra {
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.target-billing {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.billing-swap-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.targets-cra {
|
||||
min-width: 220px;
|
||||
}
|
||||
@@ -4912,6 +4896,30 @@ tbody tr:last-child td {
|
||||
padding: 1px 8px;
|
||||
}
|
||||
|
||||
/* With the code graph's card, the CRA card keeps half the row. */
|
||||
.target-summary:has(.target-graph) {
|
||||
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.target-graph-languages {
|
||||
margin: 12px 0 4px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* Files the graph left out: a fact to notice, not an alarm. */
|
||||
.target-graph-unreadable {
|
||||
margin: 0 0 4px;
|
||||
font-size: 13px;
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.target-graph-note {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.target-figures {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
@@ -5170,6 +5178,7 @@ tbody tr:last-child td {
|
||||
|
||||
@media (max-width: 1000px) {
|
||||
.target-summary,
|
||||
.target-summary:has(.target-graph),
|
||||
.target-columns {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ pub enum Route {
|
||||
SbomPage { target: String },
|
||||
#[route("/issues")]
|
||||
IssuesPage {},
|
||||
#[route("/graph")]
|
||||
GraphIndexPage {},
|
||||
// The code graph opens from its card on the target page.
|
||||
#[redirect("/graph", || Route::TargetsPage {})]
|
||||
#[route("/graph/:repo_id")]
|
||||
GraphExplorerPage { repo_id: String },
|
||||
#[route("/graph/:repo_id/impact/:finding_id")]
|
||||
|
||||
@@ -6,8 +6,8 @@ use dioxus::prelude::*;
|
||||
use crate::i18n::texts::{common, kinds, onboarding as otx, targets as tx};
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::onboarding::{
|
||||
is_file_kind, plc_format_for, set_archive_password, upload_target_artifact, ArchivePassword,
|
||||
PasswordOutcome, UNSUPPORTED_ARCHIVE,
|
||||
is_file_kind, plc_format_for, set_archive_password, trigger_new_content_scan,
|
||||
upload_target_artifact, ArchivePassword, PasswordOutcome, UNSUPPORTED_ARCHIVE,
|
||||
};
|
||||
|
||||
/// The upload row for target `target_id`; `on_uploaded` runs once the file
|
||||
@@ -82,6 +82,7 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
|
||||
onclick: move |_| {
|
||||
let Some(picked) = file() else { return; };
|
||||
let (id, kind, pw) = (target_id.clone(), kind(), password());
|
||||
let scan_id = id.clone();
|
||||
let format = (kind == "plc_project").then(|| plc_format.read().clone());
|
||||
busy.set(true);
|
||||
spawn(async move {
|
||||
@@ -115,10 +116,21 @@ pub fn ArtifactUpload(target_id: String, on_uploaded: EventHandler<()>) -> Eleme
|
||||
}
|
||||
}
|
||||
};
|
||||
// New content starts its change-driven scan (t72); a
|
||||
// failed start leaves the file for the next scan.
|
||||
let scanning = match &result {
|
||||
Ok(()) => trigger_new_content_scan(scan_id).await.is_ok(),
|
||||
Err(_) => false,
|
||||
};
|
||||
busy.set(false);
|
||||
match result {
|
||||
Ok(()) => {
|
||||
note.set(Some((true, tx::UPLOADED.get(lang).to_string())));
|
||||
let uploaded = if scanning {
|
||||
tx::UPLOADED
|
||||
} else {
|
||||
tx::UPLOADED_NOT_SCANNED
|
||||
};
|
||||
note.set(Some((true, uploaded.get(lang).to_string())));
|
||||
file.set(None);
|
||||
password.set(String::new());
|
||||
on_uploaded.call(());
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! On an extra target's page: swap it with an included target (t72). The
|
||||
//! target swapped in stays included until the end of the month; the one
|
||||
//! swapped out becomes extra at once.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::i18n::texts::targets as tx;
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::onboarding::{fetch_targets_page, swap_target_billing};
|
||||
|
||||
/// The included targets one could swap out, as (id, name), from the
|
||||
/// targets list: included, not archived, and not `target_id` itself.
|
||||
fn swappable(targets: &[serde_json::Value], target_id: &str) -> Vec<(String, String)> {
|
||||
targets
|
||||
.iter()
|
||||
.filter(|t| {
|
||||
t.get("billing")
|
||||
.and_then(|b| b.as_str())
|
||||
.unwrap_or("included")
|
||||
== "included"
|
||||
})
|
||||
.filter(|t| t.get("archived_at").is_none_or(serde_json::Value::is_null))
|
||||
.filter_map(|t| {
|
||||
let id = t
|
||||
.get("_id")
|
||||
.and_then(|i| i.get("$oid").or(Some(i)))
|
||||
.and_then(|i| i.as_str())?
|
||||
.to_string();
|
||||
let name = t
|
||||
.get("name")
|
||||
.and_then(|n| n.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
(id != target_id).then_some((id, name))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The swap control for the extra target `target_id`; `on_swapped` runs
|
||||
/// once the swap is made.
|
||||
#[component]
|
||||
pub fn BillingSwap(target_id: String, on_swapped: EventHandler<()>) -> Element {
|
||||
let lang = use_lang()();
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
let targets = use_resource(move || async move { fetch_targets_page(None, 1, 100).await });
|
||||
let mut chosen = use_signal(String::new);
|
||||
let mut busy = use_signal(|| false);
|
||||
let options = match &*targets.read() {
|
||||
Some(Ok(resp)) => swappable(&resp.data, &target_id),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if options.is_empty() {
|
||||
return rsx! {};
|
||||
}
|
||||
rsx! {
|
||||
div { class: "billing-swap",
|
||||
h4 { class: "target-subhead", {tx::SWAP_TITLE.get(lang)} }
|
||||
p { class: "target-muted", {tx::SWAP_HINT.get(lang)} }
|
||||
div { class: "billing-swap-row",
|
||||
select {
|
||||
onchange: move |e| chosen.set(e.value()),
|
||||
option { value: "", {tx::SWAP_CHOOSE.get(lang)} }
|
||||
for (id, name) in options {
|
||||
option { value: "{id}", selected: chosen() == id, "{name}" }
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn btn-secondary",
|
||||
disabled: chosen().is_empty() || busy(),
|
||||
onclick: {
|
||||
let target_id = target_id.clone();
|
||||
move |_| {
|
||||
let (id, with) = (target_id.clone(), chosen());
|
||||
busy.set(true);
|
||||
spawn(async move {
|
||||
match swap_target_billing(id, with).await {
|
||||
Ok(()) => {
|
||||
toasts.push(ToastType::Success, tx::SWAPPED.get(lang));
|
||||
on_swapped.call(());
|
||||
}
|
||||
Err(e) => toasts.push(
|
||||
ToastType::Error,
|
||||
tx::swap_refused(&e.to_string(), lang),
|
||||
),
|
||||
}
|
||||
busy.set(false);
|
||||
});
|
||||
}
|
||||
},
|
||||
{tx::SWAP.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_other_included_active_targets_can_be_swapped_out() {
|
||||
let targets = serde_json::json!([
|
||||
{ "_id": { "$oid": "a" }, "name": "Pumpe", "billing": "included" },
|
||||
{ "_id": { "$oid": "b" }, "name": "Ventil", "billing": "extra" },
|
||||
{ "_id": { "$oid": "c" }, "name": "Alt" },
|
||||
{ "_id": { "$oid": "d" }, "name": "Archiv", "billing": "included",
|
||||
"archived_at": { "$date": { "$numberLong": "1" } } },
|
||||
{ "_id": { "$oid": "e" }, "name": "Selbst", "billing": "included" },
|
||||
]);
|
||||
let list = targets.as_array().cloned().unwrap_or_default();
|
||||
assert_eq!(
|
||||
swappable(&list, "e"),
|
||||
[
|
||||
("a".to_string(), "Pumpe".to_string()),
|
||||
("c".to_string(), "Alt".to_string())
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,22 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::i18n::texts::graph as tx;
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::graph::fetch_file_content;
|
||||
|
||||
/// A file of the code graph, with the selected code unit's lines marked.
|
||||
#[component]
|
||||
pub fn CodeInspector(
|
||||
repo_id: String,
|
||||
file_path: String,
|
||||
node_name: String,
|
||||
node_kind: String,
|
||||
node_language: String,
|
||||
start_line: u32,
|
||||
end_line: u32,
|
||||
on_close: EventHandler<()>,
|
||||
) -> Element {
|
||||
let lang = use_lang()();
|
||||
let file_path_clone = file_path.clone();
|
||||
let repo_id_clone = repo_id.clone();
|
||||
let file_content = use_resource(move || {
|
||||
@@ -30,18 +35,20 @@ pub fn CodeInspector(
|
||||
// Header
|
||||
div { class: "code-inspector-header",
|
||||
div { class: "code-inspector-title",
|
||||
span { class: "badge badge-info", "SELECTED" }
|
||||
span { class: "code-inspector-file-name", "{file_path}" }
|
||||
}
|
||||
div { class: "code-inspector-meta",
|
||||
span { class: "node-label-badge node-kind-{node_kind}", "{node_kind}" }
|
||||
span { class: "node-label-badge graph-kind-{node_kind}", {tx::node_kind(&node_kind, &node_language).get(lang)} }
|
||||
span { class: "code-inspector-node-name", "{node_name}" }
|
||||
if start_line > 0 && end_line > 0 {
|
||||
span { class: "code-inspector-lines", "L{start_line}–L{end_line}" }
|
||||
span { class: "code-inspector-lines", "{tx::LINES.get(lang)} {start_line}–{end_line}" }
|
||||
}
|
||||
}
|
||||
button {
|
||||
class: "btn-sm code-inspector-close",
|
||||
class: "btn btn-ghost btn-sm code-inspector-close",
|
||||
r#type: "button",
|
||||
title: tx::CLOSE.get(lang),
|
||||
"aria-label": tx::CLOSE.get(lang),
|
||||
onclick: move |_| on_close.call(()),
|
||||
"\u{2715}"
|
||||
}
|
||||
@@ -79,12 +86,10 @@ pub fn CodeInspector(
|
||||
}
|
||||
},
|
||||
Some(None) => rsx! {
|
||||
div { class: "code-inspector-empty",
|
||||
"Could not load file content."
|
||||
}
|
||||
div { class: "code-inspector-empty", {tx::FILE_FAILED.get(lang)} }
|
||||
},
|
||||
None => rsx! {
|
||||
div { class: "loading", "Loading file..." }
|
||||
div { class: "loading", {tx::FILE_LOADING.get(lang)} }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod app_shell;
|
||||
pub mod artifact_upload;
|
||||
pub mod attack_chain;
|
||||
pub mod billing_swap;
|
||||
pub mod code_inspector;
|
||||
pub mod code_snippet;
|
||||
pub mod copy_button;
|
||||
@@ -28,5 +29,6 @@ pub mod sidebar;
|
||||
pub mod support;
|
||||
pub mod theme_toggle;
|
||||
pub mod toast;
|
||||
pub mod usage_summary;
|
||||
pub mod vex_panel;
|
||||
pub mod webhook_deliveries;
|
||||
@@ -108,9 +108,7 @@ pub fn ScanRunList(
|
||||
.peek()
|
||||
.as_ref()
|
||||
.and_then(|r| r.as_ref())
|
||||
.is_some_and(|list| {
|
||||
list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running)
|
||||
});
|
||||
.is_some_and(|list| list.is_empty() || list.iter().any(|r| r.status.is_open()));
|
||||
if waiting {
|
||||
runs.restart();
|
||||
}
|
||||
@@ -161,7 +159,8 @@ fn run_transitions(
|
||||
let mut finished = Vec::new();
|
||||
for run in runs {
|
||||
let id = run.id.map(|id| id.to_hex()).unwrap_or_default();
|
||||
if run.status == ScanRunStatus::Running {
|
||||
// A queued run counts: it may finish before it is ever seen running.
|
||||
if run.status.is_open() {
|
||||
running.push(id);
|
||||
} else if seen_running.contains(&id) && !finished_here.contains(&id) {
|
||||
finished.push(id);
|
||||
@@ -176,13 +175,20 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
|
||||
let started = format_time(&run.started_at, lang);
|
||||
let finished = run.completed_at.as_ref().map(|t| format_time(t, lang));
|
||||
let running = run.status == ScanRunStatus::Running;
|
||||
// A queued run's time is when it was asked for: it has not started.
|
||||
let queued = run.status == ScanRunStatus::Queued;
|
||||
let started_label = if queued {
|
||||
scans::REQUESTED
|
||||
} else {
|
||||
scans::STARTED
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { style: "border-left: 3px solid var(--border); padding: 6px 10px; margin: 6px 0;",
|
||||
div { style: "display: flex; gap: 12px; align-items: center; flex-wrap: wrap;",
|
||||
span { class: "{badge}", {status.get(lang)} }
|
||||
span { style: "font-size: 0.9em;",
|
||||
{scans::STARTED.get(lang)} ": {started}"
|
||||
{started_label.get(lang)} ": {started}"
|
||||
}
|
||||
if let Some(finished) = finished {
|
||||
span { style: "font-size: 0.9em;",
|
||||
@@ -213,6 +219,11 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
|
||||
run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
if queued {
|
||||
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
|
||||
{scans::QUEUED_HINT.get(lang)}
|
||||
}
|
||||
}
|
||||
if run.status == ScanRunStatus::Interrupted {
|
||||
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
|
||||
{scans::INTERRUPTED_HINT.get(lang)}
|
||||
@@ -450,6 +461,7 @@ fn RunReveal(target_id: String, run_id: String, count: u32) -> Element {
|
||||
/// The badge class and label for a run status.
|
||||
pub fn status_badge(status: &ScanRunStatus) -> (&'static str, Text) {
|
||||
match status {
|
||||
ScanRunStatus::Queued => ("badge badge-neutral", scans::QUEUED),
|
||||
ScanRunStatus::Running => ("badge badge-info", scans::RUNNING),
|
||||
ScanRunStatus::Completed => ("badge badge-success", scans::COMPLETED),
|
||||
ScanRunStatus::Failed => ("badge badge-danger", scans::FAILED),
|
||||
@@ -542,6 +554,24 @@ mod tests {
|
||||
assert!(finished.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queued_run_reads_as_waiting_for_a_slot_and_is_followed_to_its_end() {
|
||||
let mut run = ScanRun::queued("t".into(), compliance_core::models::ScanTrigger::Manual);
|
||||
let (_, label) = status_badge(&run.status);
|
||||
assert_eq!(label.get(Lang::De), "Wartet auf einen Platz");
|
||||
assert_eq!(label.get(Lang::En), "Waiting for a slot");
|
||||
|
||||
// Seen while it waits, so its end is revealed even if it is never
|
||||
// seen running.
|
||||
let none = HashSet::new();
|
||||
let (seen, _) = run_transitions(std::slice::from_ref(&run), &none, &none);
|
||||
assert_eq!(seen, vec![String::new()]);
|
||||
run.status = ScanRunStatus::Completed;
|
||||
let seen = HashSet::from([String::new()]);
|
||||
let (_, finished) = run_transitions(std::slice::from_ref(&run), &seen, &none);
|
||||
assert_eq!(finished, vec![String::new()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stepper_marks_done_current_and_pending_phases() {
|
||||
let mut run = ScanRun::new("t".into(), compliance_core::models::ScanTrigger::Manual);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! The usage view on the targets page (t72): this month's Prüfungen against
|
||||
//! the quota, Prüftage against the cap, and the extra targets.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::i18n::texts::metering as tx;
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::metering::{fetch_usage, Usage};
|
||||
|
||||
/// The lines of the usage view: only the count when the plan is not known,
|
||||
/// Prüftage only where there is a quota, extra targets only where the plan
|
||||
/// limits the included ones.
|
||||
fn lines(u: &Usage, lang: crate::i18n::Lang) -> Vec<String> {
|
||||
if !u.plan_known {
|
||||
return vec![tx::counted(u.pruefungen, lang)];
|
||||
}
|
||||
let mut lines = vec![tx::pruefungen(u.pruefungen, u.monthly_pruefungen, lang)];
|
||||
if u.monthly_pruefungen.is_some() {
|
||||
lines.push(tx::prueftage(u.prueftage, u.prueftag_cap, lang));
|
||||
}
|
||||
if u.included_targets.is_some() {
|
||||
lines.push(tx::extra_targets(u.extra_targets, lang));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// This month's usage in one row. Shows nothing while it loads or when it
|
||||
/// cannot be read.
|
||||
#[component]
|
||||
pub fn UsageSummary() -> Element {
|
||||
let lang = use_lang()();
|
||||
let usage = use_resource(move || async move { fetch_usage().await });
|
||||
let Some(Ok(resp)) = usage.read().clone() else {
|
||||
return rsx! {};
|
||||
};
|
||||
rsx! {
|
||||
div { class: "usage-summary", title: tx::HINT.get(lang),
|
||||
span { class: "usage-summary-title", {tx::TITLE.get(lang)} }
|
||||
for line in lines(&resp.data, lang) {
|
||||
span { class: "usage-summary-item", "{line}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::i18n::Lang;
|
||||
|
||||
#[test]
|
||||
fn a_standard_plan_shows_quota_prueftage_and_extra_targets() {
|
||||
let u = Usage {
|
||||
pruefungen: 37,
|
||||
prueftage: 1,
|
||||
extra_targets: 2,
|
||||
plan_known: true,
|
||||
included_targets: Some(5),
|
||||
monthly_pruefungen: Some(100),
|
||||
prueftag_cap: None,
|
||||
..Usage::default()
|
||||
};
|
||||
assert_eq!(
|
||||
lines(&u, Lang::De),
|
||||
[
|
||||
"37 von 100 Prüfungen",
|
||||
"1 Prüftag",
|
||||
"2 zusätzliche Prüfobjekte"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enterprise_and_an_unknown_plan_show_only_the_count() {
|
||||
let enterprise = Usage {
|
||||
pruefungen: 12,
|
||||
plan_known: true,
|
||||
..Usage::default()
|
||||
};
|
||||
assert_eq!(lines(&enterprise, Lang::En), ["12 scans, unlimited"]);
|
||||
let unknown = Usage {
|
||||
pruefungen: 12,
|
||||
..Usage::default()
|
||||
};
|
||||
assert_eq!(lines(&unknown, Lang::En), ["12 counted scans"]);
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,24 @@ pub fn format_bytes(bytes: u64, lang: Lang) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A count with thousands separators: `12.345` in German, `12,345` in English.
|
||||
pub fn format_count(count: u64, lang: Lang) -> String {
|
||||
let separator = match lang {
|
||||
Lang::De => '.',
|
||||
Lang::En => ',',
|
||||
};
|
||||
let digits = count.to_string();
|
||||
let mut grouped = String::with_capacity(digits.len() + digits.len() / 3);
|
||||
for (i, digit) in digits.chars().enumerate() {
|
||||
// A separator before every digit that starts a group of three from the right.
|
||||
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
||||
grouped.push(separator);
|
||||
}
|
||||
grouped.push(digit);
|
||||
}
|
||||
grouped
|
||||
}
|
||||
|
||||
/// A moment in the reader's date convention, in UTC: `30.09.2026 08:05 UTC`
|
||||
/// in German, `2026-09-30 08:05 UTC` in English.
|
||||
pub fn format_time(time: &chrono::DateTime<chrono::Utc>, lang: Lang) -> String {
|
||||
@@ -195,6 +213,16 @@ fn set_document_lang(lang: Lang) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_count_has_the_languages_thousands_separator() {
|
||||
use super::{format_count, Lang};
|
||||
assert_eq!(format_count(0, Lang::De), "0");
|
||||
assert_eq!(format_count(999, Lang::De), "999");
|
||||
assert_eq!(format_count(1_000, Lang::De), "1.000");
|
||||
assert_eq!(format_count(12_345_678, Lang::De), "12.345.678");
|
||||
assert_eq!(format_count(10_000, Lang::En), "10,000");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moment_reads_as_how_long_ago_it_was() {
|
||||
use chrono::{Duration, TimeZone, Utc};
|
||||
|
||||
@@ -367,6 +367,19 @@ pub mod scans {
|
||||
de: "Noch nicht geprüft",
|
||||
en: "Not scanned yet",
|
||||
};
|
||||
pub const QUEUED: Text = Text {
|
||||
de: "Wartet auf einen Platz",
|
||||
en: "Waiting for a slot",
|
||||
};
|
||||
pub const QUEUED_HINT: Text = Text {
|
||||
de: "Alle Prüfplätze sind gerade belegt. Die Prüfung startet, sobald einer \
|
||||
frei wird.",
|
||||
en: "All scan slots are busy right now. The scan starts as soon as one is free.",
|
||||
};
|
||||
pub const REQUESTED: Text = Text {
|
||||
de: "Angefordert",
|
||||
en: "Requested",
|
||||
};
|
||||
pub const RUNNING: Text = Text {
|
||||
de: "Läuft",
|
||||
en: "Running",
|
||||
@@ -713,6 +726,28 @@ pub mod scans {
|
||||
so it was not scanned again. \"Run scan\" always scans in full."
|
||||
.into()
|
||||
}
|
||||
(SkipCode::PrueftagLimitReached, Lang::De) => {
|
||||
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und der heutige Prüftag \
|
||||
für dieses Prüfobjekt hat seine Prüfungen bereits erreicht. Morgen ist wieder \
|
||||
eine Prüfung möglich."
|
||||
.into()
|
||||
}
|
||||
(SkipCode::PrueftagLimitReached, Lang::En) => {
|
||||
"Not scanned: the monthly quota is used up and today's Prüftag for this target \
|
||||
has had all its scans. It can be scanned again tomorrow."
|
||||
.into()
|
||||
}
|
||||
(SkipCode::PrueftagCapReached, Lang::De) => {
|
||||
"Nicht geprüft: Das Monatskontingent ist aufgebraucht, und Ihr Limit für \
|
||||
Prüftage ist erreicht. Gezählte Prüfungen laufen wieder ab dem nächsten Monat \
|
||||
oder nach einer Erhöhung des Limits im Portal."
|
||||
.into()
|
||||
}
|
||||
(SkipCode::PrueftagCapReached, Lang::En) => {
|
||||
"Not scanned: the monthly quota is used up and your Prüftag limit is reached. \
|
||||
Counted scans run again next month, or once you raise the limit in the portal."
|
||||
.into()
|
||||
}
|
||||
(SkipCode::TooLargeToScan, Lang::De) => {
|
||||
format!("Zu groß für die Suche nach Schadsoftware, nicht geprüft: {subject}")
|
||||
}
|
||||
@@ -843,6 +878,67 @@ pub mod targets {
|
||||
de: "+ Prüfobjekt anlegen",
|
||||
en: "+ Add a target",
|
||||
};
|
||||
/// Badge of a target beyond the plan's included ones (t72).
|
||||
pub const EXTRA: Text = Text {
|
||||
de: "Zusätzliches Prüfobjekt",
|
||||
en: "Extra target",
|
||||
};
|
||||
pub const SWAP_TITLE: Text = Text {
|
||||
de: "Gegen ein enthaltenes Prüfobjekt tauschen",
|
||||
en: "Swap with an included target",
|
||||
};
|
||||
pub const SWAP_HINT: Text = Text {
|
||||
de: "Dieses Prüfobjekt wird enthalten und bleibt es bis Monatsende; das gewählte wird \
|
||||
sofort zusätzlich. Die Zahl der zusätzlichen Prüfobjekte bleibt gleich.",
|
||||
en: "This target becomes included and stays so until the end of the month; the one \
|
||||
you choose becomes extra at once. The number of extra targets stays the same.",
|
||||
};
|
||||
pub const SWAP_CHOOSE: Text = Text {
|
||||
de: "Enthaltenes Prüfobjekt wählen",
|
||||
en: "Choose an included target",
|
||||
};
|
||||
pub const SWAP: Text = Text {
|
||||
de: "Tauschen",
|
||||
en: "Swap",
|
||||
};
|
||||
pub const SWAPPED: Text = Text {
|
||||
de: "Getauscht. Dieses Prüfobjekt ist jetzt bis Monatsende enthalten.",
|
||||
en: "Swapped. This target is now included until the end of the month.",
|
||||
};
|
||||
/// The words for a refused swap, from the agent's `error`.
|
||||
pub fn swap_refused(error: &str, lang: super::super::Lang) -> String {
|
||||
use super::super::Lang;
|
||||
let text = if error.contains("swap_locked") {
|
||||
Text {
|
||||
de: "Das gewählte Prüfobjekt wurde in diesem Monat eingetauscht und bleibt bis \
|
||||
Monatsende enthalten. Wählen Sie ein anderes.",
|
||||
en: "The chosen target was swapped in this month and stays included until the \
|
||||
end of the month. Choose another one.",
|
||||
}
|
||||
} else if error.contains("swap_not_extra") || error.contains("swap_not_included") {
|
||||
Text {
|
||||
de: "Die Zuordnung hat sich inzwischen geändert. Laden Sie die Seite neu.",
|
||||
en: "The included targets changed in the meantime. Reload the page.",
|
||||
}
|
||||
} else if error.contains("swap_unlimited") {
|
||||
Text {
|
||||
de: "Ihr Tarif enthält alle Prüfobjekte; es gibt nichts zu tauschen.",
|
||||
en: "Your plan includes every target; there is nothing to swap.",
|
||||
}
|
||||
} else {
|
||||
return match lang {
|
||||
Lang::De => format!("Nicht getauscht: {error}"),
|
||||
Lang::En => format!("Not swapped: {error}"),
|
||||
};
|
||||
};
|
||||
text.get(lang).to_string()
|
||||
}
|
||||
pub const EXTRA_HINT: Text = Text {
|
||||
de: "Über die in Ihrem Tarif enthaltenen Prüfobjekte hinaus: wird monatlich \
|
||||
zusätzlich berechnet, und jede seiner Prüfungen zählt zu Ihrem Kontingent.",
|
||||
en: "Beyond the targets your plan includes: billed monthly on top, and each of \
|
||||
its scans counts toward your quota.",
|
||||
};
|
||||
pub const COL_NAME: Text = Text {
|
||||
de: "Name",
|
||||
en: "Name",
|
||||
@@ -1045,6 +1141,36 @@ pub mod targets {
|
||||
de: "bekannte Schwachstellen (CVE)",
|
||||
en: "known vulnerabilities (CVE)",
|
||||
};
|
||||
pub const GRAPH_TITLE: Text = Text {
|
||||
de: "Codegraph",
|
||||
en: "Code graph",
|
||||
};
|
||||
pub const CODE_UNITS: Text = Text {
|
||||
de: "Bausteine (Funktionen, Typen)",
|
||||
en: "code units (functions, types)",
|
||||
};
|
||||
pub const ENTRY_POINTS: Text = Text {
|
||||
de: "Einstiegspunkte",
|
||||
en: "entry points",
|
||||
};
|
||||
pub const GRAPH_SHOW: Text = Text {
|
||||
de: "Anzeigen",
|
||||
en: "Show",
|
||||
};
|
||||
/// The code graph's source files it could not read as text:
|
||||
/// "1 Datei nicht lesbar", "3 files unreadable".
|
||||
pub fn unreadable_files(count: u32, lang: super::super::Lang) -> String {
|
||||
match (lang, count) {
|
||||
(super::super::Lang::De, 1) => "1 Datei nicht lesbar".to_string(),
|
||||
(super::super::Lang::De, n) => format!("{n} Dateien nicht lesbar"),
|
||||
(super::super::Lang::En, 1) => "1 file unreadable".to_string(),
|
||||
(super::super::Lang::En, n) => format!("{n} files unreadable"),
|
||||
}
|
||||
}
|
||||
pub const GRAPH_NOTE: Text = Text {
|
||||
de: "Die Bewertung der Befunde berücksichtigt, ob ein Einstiegspunkt die Stelle erreicht.",
|
||||
en: "Triage takes into account whether an entry point reaches a finding.",
|
||||
};
|
||||
pub const OPEN_FINDINGS: Text = Text {
|
||||
de: "Offene Befunde",
|
||||
en: "Open findings",
|
||||
@@ -1085,9 +1211,9 @@ pub mod targets {
|
||||
};
|
||||
pub const UPLOAD_HINT: Text = Text {
|
||||
de: "Ein Archiv (zip, tar, tar.gz), ein SPS-Projekt oder ein Firmware-Image. Die Datei \
|
||||
wird sofort hochgeladen und bei der nächsten Prüfung geprüft.",
|
||||
wird sofort hochgeladen und gleich danach geprüft.",
|
||||
en: "An archive (zip, tar, tar.gz), a PLC project or a firmware image. It is uploaded \
|
||||
at once and checked by the next scan.",
|
||||
at once and scanned right after.",
|
||||
};
|
||||
pub const UPLOAD: Text = Text {
|
||||
de: "Hochladen",
|
||||
@@ -1140,8 +1266,14 @@ pub mod targets {
|
||||
}
|
||||
}
|
||||
pub const UPLOADED: Text = Text {
|
||||
de: "Hochgeladen. Starten Sie die Prüfung, um die Datei zu prüfen.",
|
||||
en: "Uploaded. Start a scan to check the file.",
|
||||
de: "Hochgeladen. Die Prüfung der neuen Datei startet.",
|
||||
en: "Uploaded. The scan of the new file is starting.",
|
||||
};
|
||||
pub const UPLOADED_NOT_SCANNED: Text = Text {
|
||||
de: "Hochgeladen. Die Prüfung konnte nicht gestartet werden; die nächste \
|
||||
geplante Prüfung liest die Datei.",
|
||||
en: "Uploaded. The scan could not be started; the next scheduled scan reads \
|
||||
the file.",
|
||||
};
|
||||
pub const EVIDENCE_BUILDING: Text = Text {
|
||||
de: "Wird erstellt …",
|
||||
@@ -1164,6 +1296,14 @@ pub mod targets {
|
||||
assert_eq!(count(1, Lang::En), "1 target");
|
||||
assert_eq!(count(0, Lang::En), "0 targets");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unreadable_files_line_reads_like_the_language() {
|
||||
assert_eq!(unreadable_files(1, Lang::De), "1 Datei nicht lesbar");
|
||||
assert_eq!(unreadable_files(4, Lang::De), "4 Dateien nicht lesbar");
|
||||
assert_eq!(unreadable_files(1, Lang::En), "1 file unreadable");
|
||||
assert_eq!(unreadable_files(4, Lang::En), "4 files unreadable");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2296,12 +2436,27 @@ pub mod sbom {
|
||||
de: "Yocto-Rezeptinventar (nicht die SBOM des Images): aus den Rezepten im Layer-Baum gelesen, ohne Build. Layer-Overrides und PACKAGECONFIG sind nicht aufgelöst; es listet daher mehr, als das Image enthält. Was ein Image-Rezept installiert, ist mit „Im Image (deklariert)“ markiert.",
|
||||
en: "Yocto recipe inventory (not the image SBOM): read from the recipes in the layer tree, without a build. Layer overrides and PACKAGECONFIG are not resolved, so it lists more than the image contains. What an image recipe installs is marked \"In the image (declared)\".",
|
||||
};
|
||||
/// A component an image recipe installs (its badge and filter).
|
||||
/// The badge of a component an image recipe installs.
|
||||
pub const IN_IMAGE: Text = Text {
|
||||
de: "Im Image (deklariert)",
|
||||
en: "In the image (declared)",
|
||||
};
|
||||
/// The badge's and the filter's tooltip; the badge adds the images.
|
||||
/// The badge of a component the build installed (its image SPDX).
|
||||
pub const IN_IMAGE_BUILT: Text = Text {
|
||||
de: "Im Image (gebaut)",
|
||||
en: "In the image (built)",
|
||||
};
|
||||
/// The in-image filter's choice: declared or built alike.
|
||||
pub const IN_IMAGE_ANY: Text = Text {
|
||||
de: "Im Image",
|
||||
en: "In the image",
|
||||
};
|
||||
/// The in-image filter's tooltip.
|
||||
pub const IN_IMAGE_FILTER_HINT: Text = Text {
|
||||
de: "Vom Build installiert (Image-SPDX) oder von den Image-Rezepten deklariert.",
|
||||
en: "Installed by the build (image SPDX) or declared by the image recipes.",
|
||||
};
|
||||
/// The declared badge's tooltip; the badge adds the images.
|
||||
pub const IN_IMAGE_HINT: Text = Text {
|
||||
de: "Aus den Rezepten gelesen (IMAGE_INSTALL, Paketgruppen eine Ebene tief, IMAGE_FEATURES), nicht von BitBake aufgelöst: Overrides, PACKAGECONFIG und von DISTRO_FEATURES abhängige Pakete sind nicht berücksichtigt.",
|
||||
en: "Read from the recipes (IMAGE_INSTALL, package groups one level deep, IMAGE_FEATURES), not resolved by bitbake: overrides, PACKAGECONFIG and packages that depend on DISTRO_FEATURES are not taken into account.",
|
||||
@@ -3016,7 +3171,10 @@ pub mod compliance {
|
||||
"php" => "PHP",
|
||||
"rust" => "Rust",
|
||||
"csharp" => "C#",
|
||||
"vb" => "Visual Basic",
|
||||
"swift" => "Swift",
|
||||
"structured_text" => "Structured Text",
|
||||
"plcopen" => "PLCopen XML",
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
@@ -3155,6 +3313,10 @@ pub mod compliance {
|
||||
not_assessed_reason(&reason, Lang::De).as_deref(),
|
||||
Some("Keine Prüfregel für den gefundenen Code: C, C++")
|
||||
);
|
||||
assert_eq!(
|
||||
language_list(&[serde_json::json!("csharp"), serde_json::json!("vb")]),
|
||||
"C#, Visual Basic"
|
||||
);
|
||||
assert_eq!(
|
||||
not_assessed_reason(&serde_json::json!({ "kind": "no_tool" }), Lang::En).as_deref(),
|
||||
Some("Checkable in code, but no rule checks it yet.")
|
||||
@@ -4379,3 +4541,413 @@ pub mod license_review {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The usage view on the targets page (t72): Prüfungen against the quota,
|
||||
/// Prüftage against the cap, extra targets.
|
||||
pub mod metering {
|
||||
use super::Text;
|
||||
use crate::i18n::Lang;
|
||||
|
||||
pub const TITLE: Text = Text {
|
||||
de: "Nutzung in diesem Monat",
|
||||
en: "Usage this month",
|
||||
};
|
||||
pub const HINT: Text = Text {
|
||||
de: "Gezählt werden Prüfungen, die Sie starten, und jede Prüfung eines zusätzlichen \
|
||||
Prüfobjekts. Prüfungen nach einer Änderung an enthaltenen Prüfobjekten zählen \
|
||||
nicht.",
|
||||
en: "Counted are the scans you start, and every scan of an extra target. Scans after \
|
||||
a change to an included target are not counted.",
|
||||
};
|
||||
|
||||
/// "37 von 100 Prüfungen", or "37 Prüfungen, unbegrenzt" without a quota.
|
||||
pub fn pruefungen(used: u32, quota: Option<u32>, lang: Lang) -> String {
|
||||
match (lang, quota) {
|
||||
(Lang::De, Some(q)) => format!("{used} von {q} Prüfungen"),
|
||||
(Lang::De, None) => format!("{used} Prüfungen, unbegrenzt"),
|
||||
(Lang::En, Some(q)) => format!("{used} of {q} scans"),
|
||||
(Lang::En, None) => format!("{used} scans, unlimited"),
|
||||
}
|
||||
}
|
||||
|
||||
/// "37 gezählte Prüfungen", when the plan's limits are not known.
|
||||
pub fn counted(used: u32, lang: Lang) -> String {
|
||||
match lang {
|
||||
Lang::De => format!("{used} gezählte Prüfungen"),
|
||||
Lang::En => format!("{used} counted scans"),
|
||||
}
|
||||
}
|
||||
|
||||
/// "2 Prüftage (Limit 5)", "1 Prüftag", or that none are allowed.
|
||||
pub fn prueftage(booked: u32, cap: Option<u32>, lang: Lang) -> String {
|
||||
let days = match (lang, booked) {
|
||||
(Lang::De, 1) => "1 Prüftag".to_string(),
|
||||
(Lang::De, n) => format!("{n} Prüftage"),
|
||||
(Lang::En, 1) => "1 Prüftag".to_string(),
|
||||
(Lang::En, n) => format!("{n} Prüftage"),
|
||||
};
|
||||
match (lang, cap) {
|
||||
(Lang::De, Some(0)) => "Keine Prüftage erlaubt".to_string(),
|
||||
(Lang::En, Some(0)) => "No Prüftage allowed".to_string(),
|
||||
(_, Some(c)) => format!("{days} (Limit {c})"),
|
||||
(_, None) => days,
|
||||
}
|
||||
}
|
||||
|
||||
/// "1 zusätzliches Prüfobjekt", or that every target is included.
|
||||
pub fn extra_targets(extra: u32, lang: Lang) -> String {
|
||||
match (lang, extra) {
|
||||
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(),
|
||||
(Lang::De, 1) => "1 zusätzliches Prüfobjekt".to_string(),
|
||||
(Lang::De, n) => format!("{n} zusätzliche Prüfobjekte"),
|
||||
(Lang::En, 0) => "All targets included in your plan".to_string(),
|
||||
(Lang::En, 1) => "1 extra target".to_string(),
|
||||
(Lang::En, n) => format!("{n} extra targets"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_quota_line_says_what_is_left_or_that_there_is_no_limit() {
|
||||
assert_eq!(pruefungen(37, Some(100), Lang::De), "37 von 100 Prüfungen");
|
||||
assert_eq!(pruefungen(37, None, Lang::En), "37 scans, unlimited");
|
||||
assert_eq!(counted(37, Lang::De), "37 gezählte Prüfungen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prueftag_line_names_the_cap() {
|
||||
assert_eq!(prueftage(2, Some(5), Lang::De), "2 Prüftage (Limit 5)");
|
||||
assert_eq!(prueftage(1, None, Lang::De), "1 Prüftag");
|
||||
assert_eq!(prueftage(0, Some(0), Lang::De), "Keine Prüftage erlaubt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extra_targets_read_naturally() {
|
||||
assert_eq!(
|
||||
extra_targets(0, Lang::De),
|
||||
"Alle Prüfobjekte im Tarif enthalten"
|
||||
);
|
||||
assert_eq!(extra_targets(1, Lang::De), "1 zusätzliches Prüfobjekt");
|
||||
assert_eq!(extra_targets(3, Lang::En), "3 extra targets");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The code graph's explorer and a finding's impact in it (t82).
|
||||
pub mod graph {
|
||||
use super::super::{format_count, Lang};
|
||||
use super::Text;
|
||||
|
||||
pub const TITLE: Text = Text {
|
||||
de: "Codegraph",
|
||||
en: "Code graph",
|
||||
};
|
||||
pub const BACK: Text = Text {
|
||||
de: "Zurück",
|
||||
en: "Back",
|
||||
};
|
||||
pub const OVERVIEW: Text = Text {
|
||||
de: "Übersicht",
|
||||
en: "Overview",
|
||||
};
|
||||
pub const SEARCH: Text = Text {
|
||||
de: "Baustein suchen …",
|
||||
en: "Search code units …",
|
||||
};
|
||||
pub const FIT: Text = Text {
|
||||
de: "Alles zeigen",
|
||||
en: "Fit view",
|
||||
};
|
||||
pub const REBUILD: Text = Text {
|
||||
de: "Neu aufbauen",
|
||||
en: "Rebuild",
|
||||
};
|
||||
pub const BUILDING: Text = Text {
|
||||
de: "Wird aufgebaut …",
|
||||
en: "Building …",
|
||||
};
|
||||
pub const BUILD_STARTED: Text = Text {
|
||||
de: "Der Codegraph wird neu aufgebaut.",
|
||||
en: "The code graph is being rebuilt.",
|
||||
};
|
||||
pub const FILES: Text = Text {
|
||||
de: "Dateien",
|
||||
en: "Files",
|
||||
};
|
||||
pub const FILTER_FILES: Text = Text {
|
||||
de: "Dateien filtern …",
|
||||
en: "Filter files …",
|
||||
};
|
||||
pub const LOADING: Text = Text {
|
||||
de: "Codegraph wird geladen …",
|
||||
en: "Loading the code graph …",
|
||||
};
|
||||
pub const LOAD_FAILED: Text = Text {
|
||||
de: "Der Codegraph konnte nicht geladen werden.",
|
||||
en: "The code graph could not be loaded.",
|
||||
};
|
||||
pub const EMPTY_TITLE: Text = Text {
|
||||
de: "Noch kein Codegraph",
|
||||
en: "No code graph yet",
|
||||
};
|
||||
pub const EMPTY_BODY: Text = Text {
|
||||
de: "Er entsteht mit der nächsten Prüfung dieses Prüfobjekts.",
|
||||
en: "It is built with this target's next scan.",
|
||||
};
|
||||
pub const LAYOUT: Text = Text {
|
||||
de: "Anordnung wird berechnet",
|
||||
en: "Computing the layout",
|
||||
};
|
||||
pub const CODE_UNITS: Text = Text {
|
||||
de: "Bausteine",
|
||||
en: "code units",
|
||||
};
|
||||
pub const EDGES: Text = Text {
|
||||
de: "Beziehungen",
|
||||
en: "relations",
|
||||
};
|
||||
pub const GROUPS: Text = Text {
|
||||
de: "Gruppen",
|
||||
en: "groups",
|
||||
};
|
||||
pub const ENTRY_POINT: Text = Text {
|
||||
de: "Einstiegspunkt",
|
||||
en: "Entry point",
|
||||
};
|
||||
pub const FILE: Text = Text {
|
||||
de: "Datei",
|
||||
en: "File",
|
||||
};
|
||||
pub const LINES: Text = Text {
|
||||
de: "Zeilen",
|
||||
en: "lines",
|
||||
};
|
||||
pub const CLOSE: Text = Text {
|
||||
de: "Schließen",
|
||||
en: "Close",
|
||||
};
|
||||
pub const FILE_FAILED: Text = Text {
|
||||
de: "Die Datei konnte nicht geladen werden.",
|
||||
en: "The file could not be loaded.",
|
||||
};
|
||||
pub const FILE_LOADING: Text = Text {
|
||||
de: "Datei wird geladen …",
|
||||
en: "Loading the file …",
|
||||
};
|
||||
pub const OVERVIEW_NOTE: Text = Text {
|
||||
de: "Der Graph ist groß: jeder Kreis ist eine Gruppe eng verbundener Bausteine, jedes Sechseck die übrigen Bausteine eines Ordners. Ein Klick öffnet sie.",
|
||||
en: "The graph is large: each circle is a group of closely connected code units, each hexagon a folder's other code units. Click one to open it.",
|
||||
};
|
||||
|
||||
/// "Ausschnitt: die ersten 10.000 von 23.456 Beziehungen".
|
||||
pub fn truncated(shown: usize, total: u64, lang: Lang) -> String {
|
||||
match lang {
|
||||
Lang::De => format!(
|
||||
"Ausschnitt: die ersten {} von {} Beziehungen",
|
||||
format_count(shown as u64, lang),
|
||||
format_count(total, lang)
|
||||
),
|
||||
Lang::En => format!(
|
||||
"Excerpt: the first {} of {} relations",
|
||||
format_count(shown as u64, lang),
|
||||
format_count(total, lang)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// "Die 1.200 meistverbundenen von 3.400 Bausteinen dieser Gruppe".
|
||||
pub fn capped(shown: usize, total: usize, lang: Lang) -> String {
|
||||
let (shown, total) = (
|
||||
format_count(shown as u64, lang),
|
||||
format_count(total as u64, lang),
|
||||
);
|
||||
match lang {
|
||||
Lang::De => {
|
||||
format!("Die {shown} meistverbundenen von {total} Bausteinen dieser Gruppe")
|
||||
}
|
||||
Lang::En => format!("The {shown} most connected of this group's {total} code units"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A PLC PROGRAM, which the graph keeps as a module ("Modul" names a
|
||||
/// bookable product, so it is not used for PLC code).
|
||||
pub const PROGRAM: Text = Text {
|
||||
de: "Programm",
|
||||
en: "Program",
|
||||
};
|
||||
|
||||
/// The languages a PLC project is parsed as; their modules are programs.
|
||||
pub const PLC_LANGUAGES: [&str; 2] = ["structured_text", "plcopen"];
|
||||
|
||||
/// A node's kind name, given its language: a PLC PROGRAM is a "Programm".
|
||||
pub fn node_kind(kind: &str, language: &str) -> Text {
|
||||
if kind == "module" && PLC_LANGUAGES.contains(&language) {
|
||||
PROGRAM
|
||||
} else {
|
||||
self::kind(kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// A node kind's name, for the legend, the tooltip and the inspector.
|
||||
pub fn kind(kind: &str) -> Text {
|
||||
match kind {
|
||||
"function" => Text {
|
||||
de: "Funktion",
|
||||
en: "Function",
|
||||
},
|
||||
"method" => Text {
|
||||
de: "Methode",
|
||||
en: "Method",
|
||||
},
|
||||
"class" => Text {
|
||||
de: "Klasse",
|
||||
en: "Class",
|
||||
},
|
||||
"struct" => Text {
|
||||
de: "Struktur",
|
||||
en: "Struct",
|
||||
},
|
||||
"enum" => Text {
|
||||
de: "Aufzählung",
|
||||
en: "Enum",
|
||||
},
|
||||
"interface" => Text {
|
||||
de: "Schnittstelle",
|
||||
en: "Interface",
|
||||
},
|
||||
"trait" => Text {
|
||||
de: "Trait",
|
||||
en: "Trait",
|
||||
},
|
||||
"module" => Text {
|
||||
de: "Modul",
|
||||
en: "Module",
|
||||
},
|
||||
"file" => Text {
|
||||
de: "Datei",
|
||||
en: "File",
|
||||
},
|
||||
"community" => Text {
|
||||
de: "Gruppe",
|
||||
en: "Group",
|
||||
},
|
||||
"folder" => Text {
|
||||
de: "Ordner",
|
||||
en: "Folder",
|
||||
},
|
||||
_ => Text {
|
||||
de: "Baustein",
|
||||
en: "Code unit",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// An edge kind's name, for the tooltip.
|
||||
pub fn edge_kind(kind: &str) -> Text {
|
||||
match kind {
|
||||
"calls" => Text {
|
||||
de: "ruft auf",
|
||||
en: "calls",
|
||||
},
|
||||
"imports" => Text {
|
||||
de: "importiert",
|
||||
en: "imports",
|
||||
},
|
||||
"inherits" => Text {
|
||||
de: "erbt von",
|
||||
en: "inherits from",
|
||||
},
|
||||
"implements" => Text {
|
||||
de: "implementiert",
|
||||
en: "implements",
|
||||
},
|
||||
"contains" => Text {
|
||||
de: "enthält",
|
||||
en: "contains",
|
||||
},
|
||||
"type_ref" => Text {
|
||||
de: "verwendet Typ",
|
||||
en: "uses type",
|
||||
},
|
||||
_ => Text {
|
||||
de: "Beziehungen",
|
||||
en: "relations",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ── Impact of one finding ──
|
||||
|
||||
pub const IMPACT_TITLE: Text = Text {
|
||||
de: "Auswirkung im Codegraph",
|
||||
en: "Impact in the code graph",
|
||||
};
|
||||
pub const IMPACT_SUBTITLE: Text = Text {
|
||||
de: "Welche Einstiegspunkte die Stelle des Befunds erreichen und was von ihr aus erreichbar ist.",
|
||||
en: "Which entry points reach the finding's location and what it reaches in turn.",
|
||||
};
|
||||
pub const IMPACT_NONE: Text = Text {
|
||||
de: "Für diesen Befund gibt es im Codegraph keine Stelle.",
|
||||
en: "The code graph has no location for this finding.",
|
||||
};
|
||||
pub const IMPACT_LOADING: Text = Text {
|
||||
de: "Auswirkung wird geladen …",
|
||||
en: "Loading the impact …",
|
||||
};
|
||||
pub const REACHED_BY: Text = Text {
|
||||
de: "Einstiegspunkte erreichen die Stelle",
|
||||
en: "entry points reach the location",
|
||||
};
|
||||
pub const BLAST_RADIUS: Text = Text {
|
||||
de: "Bausteine von der Stelle aus erreichbar",
|
||||
en: "code units reachable from the location",
|
||||
};
|
||||
pub const ENTRY_POINTS: Text = Text {
|
||||
de: "Einstiegspunkte",
|
||||
en: "Entry points",
|
||||
};
|
||||
pub const CALL_CHAINS: Text = Text {
|
||||
de: "Aufrufketten",
|
||||
en: "Call chains",
|
||||
};
|
||||
pub const CALL_CHAINS_HINT: Text = Text {
|
||||
de: "Vom Einstiegspunkt bis zur Stelle des Befunds.",
|
||||
en: "From the entry point to the finding's location.",
|
||||
};
|
||||
pub const CALLERS: Text = Text {
|
||||
de: "Direkte Aufrufer",
|
||||
en: "Direct callers",
|
||||
};
|
||||
pub const CALLEES: Text = Text {
|
||||
de: "Direkt aufgerufen",
|
||||
en: "Directly called",
|
||||
};
|
||||
pub const NONE: Text = Text {
|
||||
de: "Keine.",
|
||||
en: "None.",
|
||||
};
|
||||
pub const SHOW_IMPACT: Text = Text {
|
||||
de: "Auswirkung anzeigen",
|
||||
en: "Show the impact",
|
||||
};
|
||||
pub const OPEN_GRAPH: Text = Text {
|
||||
de: "Im Codegraph öffnen",
|
||||
en: "Open in the code graph",
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_plc_program_is_named_a_program_not_a_module() {
|
||||
assert_eq!(node_kind("module", "structured_text").de, "Programm");
|
||||
assert_eq!(node_kind("module", "plcopen").de, "Programm");
|
||||
assert_eq!(node_kind("module", "python").de, "Modul");
|
||||
assert_eq!(node_kind("class", "structured_text").de, "Klasse");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,16 @@ pub struct GraphData {
|
||||
pub build: Option<serde_json::Value>,
|
||||
pub nodes: Vec<serde_json::Value>,
|
||||
pub edges: Vec<serde_json::Value>,
|
||||
/// The agent sent only the first of the graph's edges (and the nodes they
|
||||
/// connect).
|
||||
#[serde(default)]
|
||||
pub truncated: bool,
|
||||
/// Edges in the whole graph.
|
||||
#[serde(default)]
|
||||
pub total_edges: u64,
|
||||
/// Nodes in the whole graph.
|
||||
#[serde(default)]
|
||||
pub total_nodes: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
@@ -18,12 +28,6 @@ pub struct ImpactResponse {
|
||||
pub data: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct CommunitiesResponse {
|
||||
pub data: Vec<serde_json::Value>,
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct NodesResponse {
|
||||
pub data: Vec<serde_json::Value>,
|
||||
@@ -48,6 +52,42 @@ pub struct SearchResponse {
|
||||
pub total: Option<u64>,
|
||||
}
|
||||
|
||||
/// What the target page shows of a code graph: its declarations (functions,
|
||||
/// methods, types, PLC blocks), its entry points, its languages and the
|
||||
/// source files it could not read.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||
pub struct GraphSummary {
|
||||
pub units: u32,
|
||||
pub entry_points: u32,
|
||||
pub languages: Vec<String>,
|
||||
/// Source files left out as not readable as text; 0 from an agent that
|
||||
/// does not send the count yet.
|
||||
#[serde(default)]
|
||||
pub unreadable_files: u32,
|
||||
}
|
||||
|
||||
/// The latest code graph's summary for a target; `None` when it has no
|
||||
/// completed, counted build.
|
||||
#[server]
|
||||
pub async fn fetch_graph_summary(repo_id: String) -> Result<Option<GraphSummary>, ServerFnError> {
|
||||
#[derive(Deserialize)]
|
||||
struct Body {
|
||||
data: Option<GraphSummary>,
|
||||
}
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/summary"))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: Body = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
Ok(body.data)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn fetch_graph(repo_id: String) -> Result<GraphDataResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}"))
|
||||
@@ -80,32 +120,19 @@ pub async fn fetch_impact(
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn fetch_communities(repo_id: String) -> Result<CommunitiesResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/communities"))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: CommunitiesResponse = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
#[server]
|
||||
pub async fn fetch_file_content(
|
||||
repo_id: String,
|
||||
file_path: String,
|
||||
) -> Result<FileContentResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!(
|
||||
"/api/v1/graph/{repo_id}/file-content?path={file_path}"
|
||||
))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
// The path as a query parameter, encoded: file names can hold spaces,
|
||||
// `#` or `&`.
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/file-content"))
|
||||
.await?
|
||||
.query(&[("path", file_path.as_str())])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: FileContentResponse = resp
|
||||
.json()
|
||||
.await
|
||||
@@ -115,13 +142,12 @@ pub async fn fetch_file_content(
|
||||
|
||||
#[server]
|
||||
pub async fn search_nodes(repo_id: String, query: String) -> Result<SearchResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get(&format!(
|
||||
"/api/v1/graph/{repo_id}/search?q={query}&limit=50"
|
||||
))
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/search"))
|
||||
.await?
|
||||
.query(&[("q", query.as_str()), ("limit", "50")])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
let body: SearchResponse = resp
|
||||
.json()
|
||||
.await
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Server function for the usage view (t72): proxies the agent's
|
||||
//! `/api/v1/metering/usage`.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The tenant's metering this month, as the agent reports it.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Usage {
|
||||
/// The calendar month in Europe/Berlin, `YYYY-MM`.
|
||||
#[serde(default)]
|
||||
pub month: String,
|
||||
/// Counted Prüfungen charged to the quota.
|
||||
#[serde(default)]
|
||||
pub pruefungen: u32,
|
||||
/// Prüftage booked.
|
||||
#[serde(default)]
|
||||
pub prueftage: u32,
|
||||
/// Active targets that are extra now.
|
||||
#[serde(default)]
|
||||
pub extra_targets: u32,
|
||||
/// Whether the plan could be read; without it the limits are unknown.
|
||||
#[serde(default)]
|
||||
pub plan_known: bool,
|
||||
/// The plan's included targets; `None` is unlimited.
|
||||
#[serde(default)]
|
||||
pub included_targets: Option<u32>,
|
||||
/// The monthly quota; `None` is unlimited.
|
||||
#[serde(default)]
|
||||
pub monthly_pruefungen: Option<u32>,
|
||||
/// The customer's Prüftag cap; `None` is no cap.
|
||||
#[serde(default)]
|
||||
pub prueftag_cap: Option<u32>,
|
||||
}
|
||||
|
||||
/// The agent's answer.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UsageResponse {
|
||||
pub data: Usage,
|
||||
}
|
||||
|
||||
/// The tenant's Prüfungen, Prüftage and extra targets this month.
|
||||
#[server]
|
||||
pub async fn fetch_usage() -> Result<UsageResponse, ServerFnError> {
|
||||
let resp = super::agent_client::agent_get("/api/v1/metering/usage")
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::json_or_error(resp).await
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod issues;
|
||||
pub mod manual_findings;
|
||||
pub mod mcp;
|
||||
pub mod mcp_tokens;
|
||||
pub mod metering;
|
||||
pub mod notifications;
|
||||
pub mod onboarding;
|
||||
pub mod pentest;
|
||||
|
||||
@@ -113,11 +113,15 @@ pub async fn set_archive_password(
|
||||
}
|
||||
|
||||
/// Whether any of `targets` (as the list endpoint returns them) has a scan
|
||||
/// running, so a page showing them should keep refreshing.
|
||||
/// running or waiting for a slot, so a page showing them should keep
|
||||
/// refreshing.
|
||||
pub fn any_scan_running(targets: &[serde_json::Value]) -> bool {
|
||||
targets
|
||||
.iter()
|
||||
.any(|t| t["last_scan"]["status"].as_str() == Some("running"))
|
||||
targets.iter().any(|t| {
|
||||
matches!(
|
||||
t["last_scan"]["status"].as_str(),
|
||||
Some("running" | "queued")
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
@@ -545,6 +549,22 @@ pub async fn fetch_target(id: String) -> Result<TargetResponse, ServerFnError> {
|
||||
super::agent_client::json_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Swap the extra target `id` with the included target `with` (t72):
|
||||
/// `id` becomes included until the end of the month, `with` extra.
|
||||
#[server]
|
||||
pub async fn swap_target_billing(id: String, with: String) -> Result<(), ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
reqwest::Method::POST,
|
||||
&format!("/api/v1/targets/{id}/billing/swap"),
|
||||
)
|
||||
.await?
|
||||
.json(&serde_json::json!({ "with": with }))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::ok_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Run kind-based classification on a target.
|
||||
#[server]
|
||||
pub async fn detect_target(id: String) -> Result<TargetResponse, ServerFnError> {
|
||||
@@ -606,7 +626,24 @@ pub async fn delete_target(id: String) -> Result<serde_json::Value, ServerFnErro
|
||||
super::agent_client::json_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Trigger a scan for a target.
|
||||
/// Start the scan of a target that just got new content: it was created,
|
||||
/// or files were uploaded to it (t72). It runs only when something changed,
|
||||
/// as a change-driven Prüfung that does not count on an included target.
|
||||
#[server]
|
||||
pub async fn trigger_new_content_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
reqwest::Method::POST,
|
||||
&format!("/api/v1/targets/{id}/scan?reason=new_content"),
|
||||
)
|
||||
.await?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
super::agent_client::json_or_error(resp).await
|
||||
}
|
||||
|
||||
/// Trigger a scan for a target: the customer asks for a Prüfung, which
|
||||
/// always runs and counts (t72).
|
||||
#[server]
|
||||
pub async fn trigger_target_scan(id: String) -> Result<serde_json::Value, ServerFnError> {
|
||||
let resp = super::agent_client::agent_request(
|
||||
@@ -680,8 +717,10 @@ mod tests {
|
||||
let idle = serde_json::json!({ "last_scan": { "status": "completed" } });
|
||||
let fresh = serde_json::json!({ "last_scan": null });
|
||||
let busy = serde_json::json!({ "last_scan": { "status": "running" } });
|
||||
let queued = serde_json::json!({ "last_scan": { "status": "queued" } });
|
||||
assert!(!any_scan_running(&[idle.clone(), fresh.clone()]));
|
||||
assert!(any_scan_running(&[idle, fresh, busy]));
|
||||
assert!(any_scan_running(&[idle.clone(), fresh, busy]));
|
||||
assert!(any_scan_running(&[idle, queued]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,11 +7,13 @@ use crate::components::code_snippet::CodeSnippet;
|
||||
use crate::components::markdown::render_markdown;
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::i18n::texts::{common, findings as tx};
|
||||
use crate::i18n::{format_time, use_lang};
|
||||
use crate::i18n::texts::{common, findings as tx, graph as graph_tx};
|
||||
use crate::i18n::{format_count, format_time, use_lang};
|
||||
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
|
||||
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
|
||||
use crate::infrastructure::graph::fetch_impact;
|
||||
use crate::pages::findings::status_icon;
|
||||
use crate::pages::graph_view::impact_has_content;
|
||||
use compliance_core::models::{FindingStatus, ScanType};
|
||||
|
||||
/// What happened to the last save on this page, shown next to what was saved.
|
||||
@@ -57,6 +59,24 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
.ok()
|
||||
});
|
||||
|
||||
// The finding's place in the code graph, when the graph has its location.
|
||||
// Impact analyses are stored under the finding's fingerprint.
|
||||
let impact = use_resource(move || async move {
|
||||
let (repo_id, fingerprint) = finding
|
||||
.read()
|
||||
.as_ref()
|
||||
.and_then(|f| f.as_ref())
|
||||
.map(|f| (f.repo_id.clone(), f.fingerprint.clone()))?;
|
||||
let data = fetch_impact(repo_id, fingerprint.clone())
|
||||
.await
|
||||
.ok()?
|
||||
.data?;
|
||||
impact_has_content(&data).then(|| {
|
||||
let reached_by = data["affected_entry_points"].as_array().map_or(0, Vec::len);
|
||||
(fingerprint, reached_by as u64)
|
||||
})
|
||||
});
|
||||
|
||||
let snapshot = finding.read().clone();
|
||||
|
||||
match snapshot {
|
||||
@@ -194,6 +214,21 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((fingerprint, reached_by)) = impact.read().clone().flatten() {
|
||||
div { class: "card",
|
||||
div { class: "target-card-head",
|
||||
div { class: "card-header", {graph_tx::TITLE.get(lang)} }
|
||||
Link {
|
||||
to: Route::ImpactAnalysisPage { repo_id: f.repo_id.clone(), finding_id: fingerprint },
|
||||
class: "target-card-link",
|
||||
{graph_tx::SHOW_IMPACT.get(lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
}
|
||||
p { "{format_count(reached_by, lang)} {graph_tx::REACHED_BY.get(lang)}" }
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(rationale) = &f.triage_rationale {
|
||||
div { class: "card",
|
||||
div { class: "card-header", {tx::TRIAGE.get(lang)} }
|
||||
|
||||
@@ -1,253 +1,350 @@
|
||||
//! One target's code graph, drawn: its files, its code units and how they
|
||||
//! call and use each other. Opened from the code graph card on the target
|
||||
//! page. A large graph opens as its groups (see [`super::graph_view`]).
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::*;
|
||||
use dioxus_free_icons::Icon;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::graph_view::{draw, node_id, GraphView, Group, Grouping};
|
||||
use crate::app::Route;
|
||||
use crate::components::code_inspector::CodeInspector;
|
||||
use crate::components::file_tree::{build_file_tree, FileTree};
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build};
|
||||
use crate::i18n::texts::{compliance::language_name, graph as tx};
|
||||
use crate::i18n::{format_count, use_lang, Lang};
|
||||
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build, GraphData};
|
||||
use crate::infrastructure::onboarding::fetch_target;
|
||||
|
||||
/// The node kinds in the legend, in the order shown.
|
||||
const LEGEND_KINDS: [&str; 6] = ["function", "class", "interface", "enum", "module", "file"];
|
||||
|
||||
/// What stands for a group in the legend, outside the whole view.
|
||||
const LEGEND_GROUPS: [&str; 2] = ["community", "folder"];
|
||||
|
||||
/// The texts `graph-viz.js` shows, in `lang`.
|
||||
fn viz_labels(lang: Lang) -> Value {
|
||||
let kinds: serde_json::Map<String, Value> = [
|
||||
"function",
|
||||
"method",
|
||||
"class",
|
||||
"struct",
|
||||
"enum",
|
||||
"interface",
|
||||
"trait",
|
||||
"module",
|
||||
"file",
|
||||
"community",
|
||||
"folder",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|k| (k.to_string(), tx::kind(k).get(lang).into()))
|
||||
.collect();
|
||||
let edges: serde_json::Map<String, Value> = [
|
||||
"calls",
|
||||
"imports",
|
||||
"inherits",
|
||||
"implements",
|
||||
"contains",
|
||||
"type_ref",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|k| (k.to_string(), tx::edge_kind(k).get(lang).into()))
|
||||
.collect();
|
||||
json!({
|
||||
"kinds": kinds,
|
||||
"program": tx::PROGRAM.get(lang),
|
||||
"plc": tx::PLC_LANGUAGES,
|
||||
"edges": edges,
|
||||
"layout": tx::LAYOUT.get(lang),
|
||||
"entry": tx::ENTRY_POINT.get(lang),
|
||||
"file": tx::FILE.get(lang),
|
||||
})
|
||||
}
|
||||
|
||||
/// What the page's header and notes say about the loaded graph.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct GraphFacts {
|
||||
/// Nodes the agent sent, so the ones that can be drawn.
|
||||
drawable: usize,
|
||||
/// Code units, relations and groups in the whole graph.
|
||||
units: u64,
|
||||
relations: u64,
|
||||
groups: u64,
|
||||
/// The languages parsed, by name.
|
||||
languages: Vec<String>,
|
||||
/// Whether the graph has PLC code, and code in other languages: which
|
||||
/// names its modules get in the legend.
|
||||
has_plc: bool,
|
||||
has_other: bool,
|
||||
/// `(edges sent, edges in the graph)` when the agent sent only part.
|
||||
truncated: Option<(usize, u64)>,
|
||||
}
|
||||
|
||||
impl GraphFacts {
|
||||
fn of(data: &GraphData) -> Self {
|
||||
let build = data.build.as_ref();
|
||||
let count = |key: &str| build.and_then(|b| b[key].as_u64()).unwrap_or(0);
|
||||
let codes: Vec<&str> = build
|
||||
.and_then(|b| b["languages_parsed"].as_array())
|
||||
.map(|codes| codes.iter().filter_map(Value::as_str).collect())
|
||||
.unwrap_or_default();
|
||||
let is_plc = |code: &&str| tx::PLC_LANGUAGES.contains(code);
|
||||
Self {
|
||||
drawable: data.nodes.len(),
|
||||
units: data.total_nodes.max(count("node_count")),
|
||||
relations: data.total_edges.max(count("edge_count")),
|
||||
groups: count("community_count"),
|
||||
languages: codes
|
||||
.iter()
|
||||
.map(|code| language_name(code).to_string())
|
||||
.collect(),
|
||||
has_plc: codes.iter().any(is_plc),
|
||||
has_other: !codes.iter().all(is_plc),
|
||||
truncated: data
|
||||
.truncated
|
||||
.then_some((data.edges.len(), data.total_edges)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn GraphExplorerPage(repo_id: String) -> Element {
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
button {
|
||||
class: "btn btn-ghost btn-back",
|
||||
onclick: move |_| { navigator().go_back(); },
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
"Back"
|
||||
}
|
||||
}
|
||||
|
||||
PageHeader {
|
||||
title: "Code Knowledge Graph",
|
||||
description: "Interactive visualization of code structure and relationships",
|
||||
}
|
||||
|
||||
GraphExplorerBody { repo_id: repo_id }
|
||||
}
|
||||
}
|
||||
|
||||
/// Inline variant without back button and page header — for embedding in other pages.
|
||||
#[component]
|
||||
pub fn GraphExplorerInline(repo_id: String) -> Element {
|
||||
rsx! {
|
||||
GraphExplorerBody { repo_id: repo_id }
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared graph explorer body used by both the full page and inline variants.
|
||||
#[component]
|
||||
fn GraphExplorerBody(repo_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
let can_write = crate::components::no_access::use_can_write();
|
||||
let repo_id_clone = repo_id.clone();
|
||||
let mut graph_data = use_resource(move || {
|
||||
let rid = repo_id_clone.clone();
|
||||
async move {
|
||||
if rid.is_empty() {
|
||||
return None;
|
||||
}
|
||||
fetch_graph(rid).await.ok()
|
||||
}
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
|
||||
let rid = repo_id.clone();
|
||||
let target = use_resource(move || {
|
||||
let rid = rid.clone();
|
||||
async move { fetch_target(rid).await.ok() }
|
||||
});
|
||||
let rid = repo_id.clone();
|
||||
let mut graph = use_resource(move || {
|
||||
let rid = rid.clone();
|
||||
async move { fetch_graph(rid).await.ok() }
|
||||
});
|
||||
|
||||
// The view chosen by a click; `None` is the one the graph opens with.
|
||||
let mut view = use_signal(|| Option::<GraphView>::None);
|
||||
// Nodes to select once the next drawing has its layout.
|
||||
let mut pending_focus = use_signal(Vec::<String>::new);
|
||||
let mut building = use_signal(|| false);
|
||||
let mut toasts = use_context::<Toasts>();
|
||||
let mut selected_node = use_signal(|| Option::<serde_json::Value>::None);
|
||||
let mut inspector_open = use_signal(|| false);
|
||||
let mut selected = use_signal(|| Option::<Value>::None);
|
||||
let mut search_query = use_signal(String::new);
|
||||
let mut search_results = use_signal(Vec::<serde_json::Value>::new);
|
||||
let mut search_results = use_signal(Vec::<Value>::new);
|
||||
let mut file_filter = use_signal(String::new);
|
||||
let mut nodes_json = use_signal(String::new);
|
||||
let mut edges_json = use_signal(String::new);
|
||||
let mut graph_ready = use_signal(|| false);
|
||||
|
||||
let graph_data_read = graph_data.read();
|
||||
if let Some(Some(data)) = &*graph_data_read {
|
||||
if !data.data.nodes.is_empty() && !graph_ready() {
|
||||
let nj = serde_json::to_string(&data.data.nodes).unwrap_or_else(|_| "[]".into());
|
||||
let ej = serde_json::to_string(&data.data.edges).unwrap_or_else(|_| "[]".into());
|
||||
nodes_json.set(nj);
|
||||
edges_json.set(ej);
|
||||
graph_ready.set(true);
|
||||
}
|
||||
}
|
||||
|
||||
let (node_count, edge_count, community_count, languages, file_tree_data) =
|
||||
if let Some(Some(data)) = &*graph_data_read {
|
||||
let build = data.data.build.clone().unwrap_or_default();
|
||||
let nc = build
|
||||
.get("node_count")
|
||||
.and_then(|n| n.as_u64())
|
||||
.unwrap_or(0);
|
||||
let ec = build
|
||||
.get("edge_count")
|
||||
.and_then(|n| n.as_u64())
|
||||
.unwrap_or(0);
|
||||
let cc = build
|
||||
.get("community_count")
|
||||
.and_then(|n| n.as_u64())
|
||||
.unwrap_or(0);
|
||||
let langs: Vec<String> = build
|
||||
.get("languages_parsed")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|arr| {
|
||||
arr.iter()
|
||||
.filter_map(|v| v.as_str().map(String::from))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let tree = build_file_tree(&data.data.nodes);
|
||||
(nc, ec, cc, langs, tree)
|
||||
} else {
|
||||
(0, 0, 0, Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
let has_graph_data = matches!(&*graph_data_read, Some(Some(d)) if !d.data.nodes.is_empty());
|
||||
drop(graph_data_read);
|
||||
// Each node's group, the view drawn, and what is drawn: recomputed only
|
||||
// when the graph or the chosen view changes.
|
||||
let grouping = use_memo(move || {
|
||||
let graph = graph.read();
|
||||
Some(Grouping::new(&graph.as_ref()?.as_ref()?.data.nodes))
|
||||
});
|
||||
let shown_view = use_memo(move || {
|
||||
let graph = graph.read();
|
||||
let count = graph.as_ref()?.as_ref()?.data.nodes.len();
|
||||
Some(view().unwrap_or_else(|| GraphView::initial(count)))
|
||||
});
|
||||
// The header's figures and the file tree, so a render (a keystroke in the
|
||||
// search box) doesn't copy or walk the graph.
|
||||
let facts = use_memo(move || Some(GraphFacts::of(&graph.read().as_ref()?.as_ref()?.data)));
|
||||
let file_tree = use_memo(move || {
|
||||
let graph = graph.read();
|
||||
graph
|
||||
.as_ref()
|
||||
.and_then(|g| g.as_ref())
|
||||
.map(|g| build_file_tree(&g.data.nodes))
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let drawn = use_memo(move || {
|
||||
let graph = graph.read();
|
||||
let d = &graph.as_ref()?.as_ref()?.data;
|
||||
Some(draw(
|
||||
&d.nodes,
|
||||
&d.edges,
|
||||
grouping.read().as_ref()?,
|
||||
shown_view.read().as_ref()?,
|
||||
))
|
||||
});
|
||||
|
||||
use_effect(move || {
|
||||
let ready = graph_ready();
|
||||
if !ready {
|
||||
let drawn = drawn.read();
|
||||
let Some(drawn) = drawn.as_ref().filter(|d| !d.nodes.is_empty()) else {
|
||||
return;
|
||||
}
|
||||
let nj = nodes_json();
|
||||
let ej = edges_json();
|
||||
if nj.is_empty() {
|
||||
return;
|
||||
}
|
||||
spawn(async move {
|
||||
let js = format!(
|
||||
r#"
|
||||
window.__onNodeClick = function(nodeJson) {{
|
||||
var el = document.getElementById('graph-node-click-data');
|
||||
if (el) {{
|
||||
el.value = nodeJson;
|
||||
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
|
||||
}}
|
||||
}};
|
||||
setTimeout(function() {{
|
||||
if (window.__loadGraph) {{
|
||||
window.__loadGraph({nj}, {ej});
|
||||
}}
|
||||
}}, 300);
|
||||
"#
|
||||
);
|
||||
let _ = document::eval(&js);
|
||||
});
|
||||
};
|
||||
let nodes = serde_json::to_string(&drawn.nodes).unwrap_or_else(|_| "[]".into());
|
||||
let edges = serde_json::to_string(&drawn.edges).unwrap_or_else(|_| "[]".into());
|
||||
let focus = serde_json::to_string(&*pending_focus.peek()).unwrap_or_else(|_| "[]".into());
|
||||
let labels = viz_labels(lang);
|
||||
// The canvas is in the DOM once this render is committed; the timeout
|
||||
// lets vis-network measure it.
|
||||
let js = format!(
|
||||
r#"
|
||||
window.__onNodeClick = function (nodeJson) {{
|
||||
var el = document.getElementById('graph-node-click-data');
|
||||
if (el) {{
|
||||
el.value = nodeJson;
|
||||
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
|
||||
}}
|
||||
}};
|
||||
setTimeout(function () {{
|
||||
if (window.__loadGraph) window.__loadGraph({nodes}, {edges}, {labels}, {focus});
|
||||
}}, 50);
|
||||
"#
|
||||
);
|
||||
let _ = document::eval(&js);
|
||||
});
|
||||
|
||||
let sel = selected_node();
|
||||
let sel_file = sel
|
||||
// Show the nodes named `names`: open their group first when its members
|
||||
// aren't drawn. The group is the first name's.
|
||||
let mut reveal = move |names: Vec<String>| {
|
||||
let Some(group) = names
|
||||
.first()
|
||||
.and_then(|first| grouping.read().as_ref()?.of(first).cloned())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if shown_view().is_some_and(|v| v.shows_members_of(&group)) {
|
||||
let names = serde_json::to_string(&names).unwrap_or_else(|_| "[]".into());
|
||||
let _ = document::eval(&format!(
|
||||
"window.__highlightNodes && window.__highlightNodes({names});"
|
||||
));
|
||||
} else {
|
||||
pending_focus.set(names);
|
||||
view.set(Some(GraphView::Group(group)));
|
||||
}
|
||||
};
|
||||
|
||||
let target_name = target
|
||||
.read()
|
||||
.as_ref()
|
||||
.and_then(|n| n.get("file_path").and_then(|v| v.as_str()))
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let sel_name = sel
|
||||
.as_ref()
|
||||
.and_then(|n| n.get("name").and_then(|v| v.as_str()))
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let sel_kind = sel
|
||||
.as_ref()
|
||||
.and_then(|n| n.get("kind").and_then(|v| v.as_str()))
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let sel_start = sel
|
||||
.as_ref()
|
||||
.and_then(|n| n.get("start_line").and_then(|v| v.as_u64()))
|
||||
.unwrap_or(0) as u32;
|
||||
let sel_end = sel
|
||||
.as_ref()
|
||||
.and_then(|n| n.get("end_line").and_then(|v| v.as_u64()))
|
||||
.unwrap_or(0) as u32;
|
||||
.and_then(|t| t.as_ref()?.data["name"].as_str().map(String::from));
|
||||
|
||||
let Some(facts) = facts() else {
|
||||
return rsx! {
|
||||
GraphBack { repo_id: repo_id.clone() }
|
||||
match graph.read().as_ref() {
|
||||
Some(None) => rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } },
|
||||
_ => rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
let opens_as_overview = GraphView::initial(facts.drawable) == GraphView::Overview;
|
||||
let current = shown_view().unwrap_or(GraphView::All);
|
||||
let units = format_count(facts.units, lang);
|
||||
let relations = format_count(facts.relations, lang);
|
||||
let groups = format_count(facts.groups, lang);
|
||||
let capped = drawn.read().as_ref().and_then(|d| d.capped);
|
||||
// A module is a "Programm" in PLC code; a graph with both shows both.
|
||||
let legend: Vec<(&str, &str)> = LEGEND_KINDS
|
||||
.into_iter()
|
||||
.flat_map(|kind| match kind {
|
||||
"module" => [
|
||||
facts.has_other.then(|| (kind, tx::kind(kind).get(lang))),
|
||||
facts.has_plc.then(|| (kind, tx::PROGRAM.get(lang))),
|
||||
],
|
||||
_ => [Some((kind, tx::kind(kind).get(lang))), None],
|
||||
})
|
||||
.flatten()
|
||||
.collect();
|
||||
let sel = selected();
|
||||
let layout_class = if sel.is_some() {
|
||||
"graph-explorer-layout inspector-open"
|
||||
} else {
|
||||
"graph-explorer-layout"
|
||||
};
|
||||
|
||||
rsx! {
|
||||
if repo_id.is_empty() {
|
||||
div { class: "card",
|
||||
p { "Select a repository to view its code graph." }
|
||||
GraphBack { repo_id: repo_id.clone() }
|
||||
|
||||
header { class: "target-head",
|
||||
div { class: "target-head-text",
|
||||
h2 { {tx::TITLE.get(lang)} }
|
||||
p { class: "target-head-meta",
|
||||
if let Some(name) = target_name {
|
||||
span { "{name}" }
|
||||
}
|
||||
span { "{units} {tx::CODE_UNITS.get(lang)}" }
|
||||
span { "{relations} {tx::EDGES.get(lang)}" }
|
||||
span { "{groups} {tx::GROUPS.get(lang)}" }
|
||||
if !facts.languages.is_empty() {
|
||||
span { {facts.languages.join(", ")} }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Toolbar
|
||||
div { class: "graph-toolbar",
|
||||
if can_write {
|
||||
if can_write {
|
||||
div { class: "target-head-actions",
|
||||
button {
|
||||
class: "btn btn-primary",
|
||||
class: "btn btn-secondary",
|
||||
disabled: building(),
|
||||
onclick: {
|
||||
let rid = repo_id.clone();
|
||||
move |_| {
|
||||
let rid = rid.clone();
|
||||
building.set(true);
|
||||
graph_ready.set(false);
|
||||
nodes_json.set(String::new());
|
||||
edges_json.set(String::new());
|
||||
spawn(async move {
|
||||
match trigger_graph_build(rid).await {
|
||||
Ok(_) => toasts.push(ToastType::Success, "Graph build triggered"),
|
||||
Ok(()) => toasts.push(ToastType::Success, tx::BUILD_STARTED.get(lang)),
|
||||
Err(e) => toasts.push(ToastType::Error, e.to_string()),
|
||||
}
|
||||
building.set(false);
|
||||
graph_data.restart();
|
||||
view.set(None);
|
||||
graph.restart();
|
||||
});
|
||||
}
|
||||
},
|
||||
if building() { "Building..." } else { "Build Graph" }
|
||||
Icon { icon: BsArrowRepeat, width: 14, height: 14 }
|
||||
if building() { {tx::BUILDING.get(lang)} } else { {tx::REBUILD.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if facts.drawable == 0 {
|
||||
div { class: "card graph-empty-state",
|
||||
h3 { {tx::EMPTY_TITLE.get(lang)} }
|
||||
p { {tx::EMPTY_BODY.get(lang)} }
|
||||
}
|
||||
} else {
|
||||
div { class: "graph-toolbar",
|
||||
if opens_as_overview && current != GraphView::Overview {
|
||||
button {
|
||||
class: "btn btn-secondary btn-sm",
|
||||
onclick: move |_| {
|
||||
pending_focus.set(Vec::new());
|
||||
view.set(Some(GraphView::Overview));
|
||||
},
|
||||
Icon { icon: BsArrowLeft, width: 14, height: 14 }
|
||||
{tx::OVERVIEW.get(lang)}
|
||||
}
|
||||
}
|
||||
div { class: "graph-search-bar",
|
||||
input {
|
||||
r#type: "text",
|
||||
placeholder: "Search nodes...",
|
||||
r#type: "search",
|
||||
placeholder: tx::SEARCH.get(lang),
|
||||
"aria-label": tx::SEARCH.get(lang),
|
||||
value: "{search_query}",
|
||||
oninput: {
|
||||
let rid = repo_id.clone();
|
||||
move |e: FormEvent| {
|
||||
let val = e.value();
|
||||
search_query.set(val.clone());
|
||||
if val.len() >= 2 {
|
||||
let rid = rid.clone();
|
||||
spawn(async move {
|
||||
if let Ok(resp) = search_nodes(rid, val).await {
|
||||
let q = e.value();
|
||||
search_query.set(q.clone());
|
||||
if q.chars().count() < 2 {
|
||||
search_results.set(Vec::new());
|
||||
return;
|
||||
}
|
||||
let rid = rid.clone();
|
||||
spawn(async move {
|
||||
// A stale answer for an older query is dropped.
|
||||
if let Ok(resp) = search_nodes(rid, q.clone()).await {
|
||||
if search_query() == q {
|
||||
search_results.set(resp.data);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
search_results.set(Vec::new());
|
||||
}
|
||||
}
|
||||
},
|
||||
onkeypress: {
|
||||
let rid = repo_id.clone();
|
||||
move |e: KeyboardEvent| {
|
||||
if e.key() == Key::Enter {
|
||||
search_results.set(Vec::new());
|
||||
let q = search_query();
|
||||
let rid = rid.clone();
|
||||
if !q.is_empty() {
|
||||
spawn(async move {
|
||||
match search_nodes(rid, q).await {
|
||||
Ok(resp) => {
|
||||
let names: Vec<String> = resp.data.iter()
|
||||
.filter_map(|n| n.get("qualified_name").and_then(|v| v.as_str()).map(String::from))
|
||||
.collect();
|
||||
let names_json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".into());
|
||||
let js = format!("if (window.__highlightNodes) {{ window.__highlightNodes({names_json}); }}");
|
||||
let _ = document::eval(&js);
|
||||
},
|
||||
Err(e) => {
|
||||
toasts.push(ToastType::Error, e.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
spawn(async move {
|
||||
let _ = document::eval("if (window.__clearGraphSelection) { window.__clearGraphSelection(); }");
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -255,29 +352,22 @@ fn GraphExplorerBody(repo_id: String) -> Element {
|
||||
div { class: "search-suggestions",
|
||||
for node in search_results() {
|
||||
{
|
||||
let name = node.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||
let kind = node.get("kind").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||
let file_path = node.get("file_path").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||
let node_clone = node.clone();
|
||||
let qname = node.get("qualified_name").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||
let kind = node["kind"].as_str().unwrap_or_default().to_string();
|
||||
let language = node["language"].as_str().unwrap_or_default().to_string();
|
||||
let name = node["name"].as_str().unwrap_or_default().to_string();
|
||||
let path = node["file_path"].as_str().unwrap_or_default().to_string();
|
||||
rsx! {
|
||||
div {
|
||||
button {
|
||||
class: "search-suggestion-item",
|
||||
r#type: "button",
|
||||
onclick: move |_| {
|
||||
let nc = node_clone.clone();
|
||||
let qn = qname.clone();
|
||||
selected_node.set(Some(nc));
|
||||
inspector_open.set(true);
|
||||
reveal(vec![node_id(&node).to_string()]);
|
||||
selected.set(Some(node.clone()));
|
||||
search_results.set(Vec::new());
|
||||
spawn(async move {
|
||||
let names_json = serde_json::to_string(&vec![&qn]).unwrap_or_else(|_| "[]".into());
|
||||
let js = format!("if (window.__highlightNodes) {{ window.__highlightNodes({names_json}); }}");
|
||||
let _ = document::eval(&js);
|
||||
});
|
||||
},
|
||||
span { class: "search-suggestion-name", "{name}" }
|
||||
span { class: "search-suggestion-kind", "{kind}" }
|
||||
span { class: "search-suggestion-path", "{file_path}" }
|
||||
span { class: "search-suggestion-kind", {tx::node_kind(&kind, &language).get(lang)} }
|
||||
span { class: "search-suggestion-path", "{path}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -285,177 +375,134 @@ fn GraphExplorerBody(repo_id: String) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
button {
|
||||
class: "btn-sm",
|
||||
class: "btn btn-secondary btn-sm",
|
||||
onclick: move |_| {
|
||||
spawn(async move {
|
||||
let _ = document::eval("if (window.__fitGraph) { window.__fitGraph(); }");
|
||||
});
|
||||
let _ = document::eval("window.__fitGraph && window.__fitGraph();");
|
||||
},
|
||||
"Fit View"
|
||||
Icon { icon: BsArrowsFullscreen, width: 14, height: 14 }
|
||||
{tx::FIT.get(lang)}
|
||||
}
|
||||
}
|
||||
|
||||
// Hidden input for JS → Rust node click communication
|
||||
if current == GraphView::Overview {
|
||||
p { class: "graph-note", {tx::OVERVIEW_NOTE.get(lang)} }
|
||||
}
|
||||
if let Some((shown, total)) = capped {
|
||||
p { class: "graph-note", {tx::capped(shown, total, lang)} }
|
||||
}
|
||||
if let Some((shown, total)) = facts.truncated {
|
||||
p { class: "graph-note", {tx::truncated(shown, total, lang)} }
|
||||
}
|
||||
|
||||
// graph-viz.js reports a clicked node here.
|
||||
input {
|
||||
id: "graph-node-click-data",
|
||||
r#type: "hidden",
|
||||
value: "",
|
||||
oninput: move |e| {
|
||||
let val = e.value();
|
||||
if !val.is_empty() {
|
||||
if let Ok(node) = serde_json::from_str::<serde_json::Value>(&val) {
|
||||
selected_node.set(Some(node));
|
||||
inspector_open.set(true);
|
||||
let Ok(node) = serde_json::from_str::<Value>(&e.value()) else { return };
|
||||
// A group's node opens the group; any other node is shown
|
||||
// in the inspector.
|
||||
match serde_json::from_value::<Group>(node["group"].clone()) {
|
||||
Ok(group) => {
|
||||
pending_focus.set(Vec::new());
|
||||
view.set(Some(GraphView::Group(group)));
|
||||
}
|
||||
Err(_) => selected.set(Some(node)),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// 3-panel layout: file-tree | [code-inspector] | graph-canvas
|
||||
div { class: if inspector_open() { "graph-explorer-layout inspector-open" } else { "graph-explorer-layout" },
|
||||
|
||||
// Left: File Tree
|
||||
div { class: layout_class,
|
||||
div { class: "file-tree-panel",
|
||||
div { class: "file-tree-header",
|
||||
h4 { "Files" }
|
||||
}
|
||||
div { class: "file-tree-header", h4 { {tx::FILES.get(lang)} } }
|
||||
div { class: "file-tree-search",
|
||||
input {
|
||||
r#type: "text",
|
||||
placeholder: "Filter files...",
|
||||
r#type: "search",
|
||||
placeholder: tx::FILTER_FILES.get(lang),
|
||||
"aria-label": tx::FILTER_FILES.get(lang),
|
||||
value: "{file_filter}",
|
||||
oninput: move |e| file_filter.set(e.value()),
|
||||
}
|
||||
}
|
||||
div { class: "file-tree-content",
|
||||
if file_tree_data.is_empty() {
|
||||
div { class: "file-tree-empty", "No files. Build the graph first." }
|
||||
} else {
|
||||
FileTree {
|
||||
tree: file_tree_data,
|
||||
filter: file_filter(),
|
||||
on_file_click: move |path: String| {
|
||||
// Open code inspector for this file
|
||||
let file_node = serde_json::json!({
|
||||
"file_path": &path,
|
||||
"name": path.rsplit('/').next().unwrap_or(&path),
|
||||
"kind": "file",
|
||||
"start_line": 1,
|
||||
"end_line": 0,
|
||||
});
|
||||
selected_node.set(Some(file_node));
|
||||
inspector_open.set(true);
|
||||
// Also highlight in graph
|
||||
spawn(async move {
|
||||
let js = format!(
|
||||
"if (window.__highlightFileNodes) {{ window.__highlightFileNodes('{path}'); }}"
|
||||
);
|
||||
let _ = document::eval(&js);
|
||||
});
|
||||
},
|
||||
}
|
||||
FileTree {
|
||||
tree: file_tree(),
|
||||
filter: file_filter(),
|
||||
on_file_click: move |path: String| {
|
||||
let in_file = graph
|
||||
.read()
|
||||
.as_ref()
|
||||
.and_then(|g| g.as_ref())
|
||||
.map(|g| {
|
||||
g.data
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|n| n["file_path"] == path.as_str())
|
||||
.map(|n| node_id(n).to_string())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
reveal(in_file);
|
||||
selected.set(Some(json!({
|
||||
"file_path": &path,
|
||||
"name": path.rsplit('/').next().unwrap_or(&path),
|
||||
"kind": "file",
|
||||
})));
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Left-center: Code Inspector (between file tree and graph)
|
||||
if inspector_open() && selected_node().is_some() {
|
||||
if let Some(node) = sel {
|
||||
CodeInspector {
|
||||
repo_id: repo_id.clone(),
|
||||
file_path: sel_file,
|
||||
node_name: sel_name,
|
||||
node_kind: sel_kind,
|
||||
start_line: sel_start,
|
||||
end_line: sel_end,
|
||||
on_close: move |_| {
|
||||
inspector_open.set(false);
|
||||
selected_node.set(None);
|
||||
},
|
||||
file_path: node["file_path"].as_str().unwrap_or_default().to_string(),
|
||||
node_name: node["name"].as_str().unwrap_or_default().to_string(),
|
||||
node_kind: node["kind"].as_str().unwrap_or_default().to_string(),
|
||||
node_language: node["language"].as_str().unwrap_or_default().to_string(),
|
||||
start_line: node["start_line"].as_u64().unwrap_or(0) as u32,
|
||||
end_line: node["end_line"].as_u64().unwrap_or(0) as u32,
|
||||
on_close: move |_| selected.set(None),
|
||||
}
|
||||
}
|
||||
|
||||
// Right: Graph Canvas
|
||||
div { class: "graph-canvas-panel",
|
||||
if has_graph_data {
|
||||
div {
|
||||
id: "graph-canvas",
|
||||
class: "graph-canvas",
|
||||
}
|
||||
// Stabilization overlay
|
||||
div {
|
||||
id: "graph-stabilization-overlay",
|
||||
class: "graph-stab-overlay",
|
||||
div { class: "graph-stab-content",
|
||||
// Orbital rings
|
||||
div { class: "graph-stab-rings",
|
||||
div { class: "graph-stab-ring graph-stab-ring-1" }
|
||||
div { class: "graph-stab-ring graph-stab-ring-2" }
|
||||
div { class: "graph-stab-ring graph-stab-ring-3" }
|
||||
div { class: "graph-stab-core" }
|
||||
}
|
||||
div { class: "graph-stab-text",
|
||||
div { class: "graph-stab-title", "Rendering Graph" }
|
||||
div { class: "graph-stab-subtitle",
|
||||
id: "graph-stab-node-info",
|
||||
"{node_count} nodes \u{00B7} {edge_count} edges"
|
||||
}
|
||||
}
|
||||
// Progress bar
|
||||
div { class: "graph-stab-progress",
|
||||
div {
|
||||
class: "graph-stab-progress-fill",
|
||||
id: "graph-stab-progress-fill",
|
||||
}
|
||||
}
|
||||
div {
|
||||
class: "graph-stab-pct",
|
||||
id: "graph-stab-pct",
|
||||
"Initializing\u{2026}"
|
||||
}
|
||||
div { id: "graph-canvas", class: "graph-canvas" }
|
||||
div { id: "graph-stabilization-overlay", class: "graph-stab-overlay",
|
||||
div { class: "graph-stab-content",
|
||||
div { class: "graph-stab-progress",
|
||||
div { class: "graph-stab-progress-fill", id: "graph-stab-progress-fill" }
|
||||
}
|
||||
}
|
||||
} else if node_count > 0 {
|
||||
// Data exists but nodes array was empty (shouldn't happen)
|
||||
div { class: "loading", "Loading graph visualization..." }
|
||||
} else if (*graph_data.read()).is_none() {
|
||||
div { class: "loading", "Loading graph data..." }
|
||||
} else {
|
||||
div { class: "graph-empty-state",
|
||||
div { class: "graph-empty-icon", "\u{29BB}" }
|
||||
h3 { "No Graph Data" }
|
||||
p { "Click \"Build Graph\" to analyze the repository's code structure." }
|
||||
div { class: "graph-stab-pct", id: "graph-stab-pct", {tx::LAYOUT.get(lang)} }
|
||||
}
|
||||
}
|
||||
|
||||
// Stats bar
|
||||
if node_count > 0 {
|
||||
div { class: "graph-stats-bar",
|
||||
span { class: "graph-stat",
|
||||
span { class: "graph-stat-value", "{node_count}" }
|
||||
span { class: "graph-stat-label", " nodes" }
|
||||
}
|
||||
span { class: "graph-stat-divider", "|" }
|
||||
span { class: "graph-stat",
|
||||
span { class: "graph-stat-value", "{edge_count}" }
|
||||
span { class: "graph-stat-label", " edges" }
|
||||
}
|
||||
span { class: "graph-stat-divider", "|" }
|
||||
span { class: "graph-stat",
|
||||
span { class: "graph-stat-value", "{community_count}" }
|
||||
span { class: "graph-stat-label", " communities" }
|
||||
}
|
||||
if !languages.is_empty() {
|
||||
span { class: "graph-stat-divider", "|" }
|
||||
span { class: "graph-stat",
|
||||
span { class: "graph-stat-label", "{languages.join(\", \")}" }
|
||||
}
|
||||
ul { class: "graph-legend",
|
||||
for (kind, name) in legend {
|
||||
li { span { class: "graph-legend-dot graph-kind-{kind}" } {name} }
|
||||
}
|
||||
li { span { class: "graph-legend-dot graph-legend-entry" } {tx::ENTRY_POINT.get(lang)} }
|
||||
if current != GraphView::All {
|
||||
for kind in LEGEND_GROUPS {
|
||||
li { span { class: "graph-legend-dot graph-kind-{kind}" } {tx::kind(kind).get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Back to the target the graph belongs to.
|
||||
#[component]
|
||||
fn GraphBack(repo_id: String) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
Link { to: Route::TargetPage { id: repo_id }, class: "btn btn-ghost btn-back",
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
{tx::BACK.get(lang)}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
use dioxus::prelude::*;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::infrastructure::onboarding::fetch_targets;
|
||||
|
||||
#[component]
|
||||
pub fn GraphIndexPage() -> Element {
|
||||
let repos = use_resource(|| async { fetch_targets().await.ok() });
|
||||
|
||||
rsx! {
|
||||
PageHeader {
|
||||
title: "Code Knowledge Graph",
|
||||
description: "Select a repository to explore its code graph",
|
||||
}
|
||||
|
||||
match &*repos.read() {
|
||||
Some(Some(data)) => {
|
||||
let repo_list = &data.data;
|
||||
if repo_list.is_empty() {
|
||||
rsx! {
|
||||
div { class: "card",
|
||||
p { "No repositories found. Add a repository first." }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
rsx! {
|
||||
div { class: "graph-index-grid",
|
||||
for repo in repo_list {
|
||||
{
|
||||
let repo_id = repo.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string();
|
||||
let name = repo.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
|
||||
let url = repo
|
||||
.get("artifacts")
|
||||
.and_then(|a| a.as_array())
|
||||
.and_then(|arr| {
|
||||
arr.iter().find(|a| {
|
||||
a.get("kind").and_then(|k| k.as_str()) == Some("git_repo")
|
||||
})
|
||||
})
|
||||
.and_then(|a| a.get("source_ref"))
|
||||
.and_then(|s| s.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let branch = repo
|
||||
.get("artifacts")
|
||||
.and_then(|a| a.as_array())
|
||||
.and_then(|arr| {
|
||||
arr.iter().find_map(|a| {
|
||||
a.get("git")
|
||||
.and_then(|g| g.get("default_branch"))
|
||||
.and_then(|b| b.as_str())
|
||||
})
|
||||
})
|
||||
.unwrap_or("main")
|
||||
.to_string();
|
||||
let findings = repo.get("findings_count").and_then(|n| n.as_u64()).unwrap_or(0);
|
||||
let findings_label = if findings != 1 { format!("{findings} findings") } else { "1 finding".to_string() };
|
||||
rsx! {
|
||||
Link {
|
||||
to: Route::GraphExplorerPage { repo_id },
|
||||
class: "graph-repo-card",
|
||||
div { class: "graph-repo-card-header",
|
||||
div { class: "graph-repo-card-icon", "\u{29BB}" }
|
||||
h3 { class: "graph-repo-card-name", "{name}" }
|
||||
}
|
||||
if !url.is_empty() {
|
||||
p { class: "graph-repo-card-url", "{url}" }
|
||||
}
|
||||
div { class: "graph-repo-card-meta",
|
||||
span { class: "graph-repo-card-tag",
|
||||
"\u{E0A0} {branch}"
|
||||
}
|
||||
span { class: "graph-repo-card-tag graph-repo-card-tag-findings",
|
||||
"{findings_label}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(None) => rsx! {
|
||||
div { class: "card", p { "Failed to load repositories." } }
|
||||
},
|
||||
None => rsx! {
|
||||
div { class: "loading", "Loading repositories..." }
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
//! What the code graph explorer draws.
|
||||
//!
|
||||
//! A force-directed layout stays readable up to about a thousand nodes, and a
|
||||
//! repository's graph can have tens of thousands. So a small graph is drawn
|
||||
//! whole. A larger one is first drawn as one node per group, and a click opens
|
||||
//! one group with its members, while its links to other groups stay visible as
|
||||
//! those groups' nodes. A group is a community the graph build computed
|
||||
//! (closely connected code units); communities too small to be worth a node
|
||||
//! of their own are pooled by folder.
|
||||
//!
|
||||
//! The functions here are pure and run in the browser's WASM, not in
|
||||
//! JavaScript; `graph-viz.js` only draws what they return.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// The most code units drawn at once.
|
||||
pub const VIEW_NODE_LIMIT: usize = 1_200;
|
||||
|
||||
/// Communities with fewer members are pooled by folder: the build makes many
|
||||
/// of two to ten (a file and its few functions), which would crowd the
|
||||
/// overview. On this repository's agent (4,356 nodes) that is 839
|
||||
/// communities, but about 150 groups.
|
||||
pub const MIN_COMMUNITY: usize = 10;
|
||||
|
||||
/// A group of nodes drawn as one node until it is opened.
|
||||
///
|
||||
/// Serialized into the group's drawn node, so a click on it names the group.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(tag = "by", content = "key", rename_all = "snake_case")]
|
||||
pub enum Group {
|
||||
/// A community of the graph build.
|
||||
Community(u32),
|
||||
/// The nodes of one folder that are in no community of their own size.
|
||||
Folder(String),
|
||||
}
|
||||
|
||||
impl Group {
|
||||
/// The group's node id in the drawing.
|
||||
fn id(&self) -> String {
|
||||
match self {
|
||||
Self::Community(id) => format!("group:community:{id}"),
|
||||
Self::Folder(dir) => format!("group:folder:{dir}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind its node is drawn as.
|
||||
fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Community(_) => "community",
|
||||
Self::Folder(_) => "folder",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which part of the graph is drawn.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum GraphView {
|
||||
/// Every node: the graph is small enough.
|
||||
All,
|
||||
/// One node per group.
|
||||
Overview,
|
||||
/// One group's members and the groups linked to them.
|
||||
Group(Group),
|
||||
}
|
||||
|
||||
impl GraphView {
|
||||
/// The view a graph with `node_count` nodes opens with.
|
||||
pub fn initial(node_count: usize) -> Self {
|
||||
if node_count <= VIEW_NODE_LIMIT {
|
||||
Self::All
|
||||
} else {
|
||||
Self::Overview
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `group`'s members are drawn as themselves in this view.
|
||||
pub fn shows_members_of(&self, group: &Group) -> bool {
|
||||
match self {
|
||||
Self::All => true,
|
||||
Self::Overview => false,
|
||||
Self::Group(shown) => shown == group,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The group of every node, by `qualified_name`.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Grouping(HashMap<String, Group>);
|
||||
|
||||
impl Grouping {
|
||||
/// Groups `nodes`: by community when it has at least [`MIN_COMMUNITY`]
|
||||
/// members, else by folder.
|
||||
pub fn new(nodes: &[Value]) -> Self {
|
||||
let mut sizes: HashMap<u32, usize> = HashMap::new();
|
||||
for id in nodes.iter().filter_map(community) {
|
||||
*sizes.entry(id).or_default() += 1;
|
||||
}
|
||||
Self(
|
||||
nodes
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let group = match community(node) {
|
||||
Some(id) if sizes[&id] >= MIN_COMMUNITY => Group::Community(id),
|
||||
_ => Group::Folder(folder(node).to_string()),
|
||||
};
|
||||
(node_id(node).to_string(), group)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The group of the node named `id`, if the graph has it.
|
||||
pub fn of(&self, id: &str) -> Option<&Group> {
|
||||
self.0.get(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes and edges to draw, in the JSON shape `graph-viz.js` reads.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Drawn {
|
||||
pub nodes: Vec<Value>,
|
||||
pub edges: Vec<Value>,
|
||||
/// When the opened group has more members than [`VIEW_NODE_LIMIT`]:
|
||||
/// `(shown, total)`.
|
||||
pub capped: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
/// A node's `qualified_name`, its id in the drawing.
|
||||
pub fn node_id(node: &Value) -> &str {
|
||||
node["qualified_name"].as_str().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A node's community, if the build put it in one.
|
||||
fn community(node: &Value) -> Option<u32> {
|
||||
node["community_id"]
|
||||
.as_u64()
|
||||
.and_then(|id| u32::try_from(id).ok())
|
||||
}
|
||||
|
||||
/// The folder of a node's file; empty at the repository's root.
|
||||
fn folder(node: &Value) -> &str {
|
||||
let path = node["file_path"].as_str().unwrap_or_default();
|
||||
path.rsplit_once('/').map_or("", |(dir, _)| dir)
|
||||
}
|
||||
|
||||
/// What to draw of `nodes` and `edges` in `view`, with `grouping` made from
|
||||
/// the same nodes.
|
||||
///
|
||||
/// Linear in the number of nodes and edges. Edges that end in a group drawn
|
||||
/// as one node become one edge per pair of ends, carrying how many it stands
|
||||
/// for in `count`.
|
||||
pub fn draw(nodes: &[Value], edges: &[Value], grouping: &Grouping, view: &GraphView) -> Drawn {
|
||||
let opened = match view {
|
||||
GraphView::All => {
|
||||
return Drawn {
|
||||
nodes: nodes.to_vec(),
|
||||
edges: edges.to_vec(),
|
||||
capped: None,
|
||||
}
|
||||
}
|
||||
GraphView::Overview => None,
|
||||
GraphView::Group(group) => Some(group),
|
||||
};
|
||||
|
||||
// The opened group's members, the most connected first when there are
|
||||
// more than the limit.
|
||||
let mut members: Vec<&Value> = nodes
|
||||
.iter()
|
||||
.filter(|n| opened.is_some() && grouping.of(node_id(n)) == opened)
|
||||
.collect();
|
||||
let member_total = members.len();
|
||||
if member_total > VIEW_NODE_LIMIT {
|
||||
let mut degree: HashMap<&str, usize> = HashMap::with_capacity(member_total);
|
||||
for end in edges.iter().flat_map(|e| [&e["source"], &e["target"]]) {
|
||||
if let Some(id) = end.as_str() {
|
||||
*degree.entry(id).or_default() += 1;
|
||||
}
|
||||
}
|
||||
// Ties broken by name so the same graph always shows the same members.
|
||||
members.sort_by(|a, b| {
|
||||
let (da, db) = (degree.get(node_id(a)), degree.get(node_id(b)));
|
||||
db.cmp(&da).then_with(|| node_id(a).cmp(node_id(b)))
|
||||
});
|
||||
members.truncate(VIEW_NODE_LIMIT);
|
||||
}
|
||||
let shown: HashSet<&str> = members.iter().map(|n| node_id(n)).collect();
|
||||
|
||||
// Where an edge end is drawn: the member itself, or its group's node.
|
||||
// `None` drops the edge: a member left out by the cap, or a name the
|
||||
// graph has no node for.
|
||||
let endpoint = |id: &str| -> Option<String> {
|
||||
let group = grouping.of(id)?;
|
||||
if opened == Some(group) {
|
||||
shown.contains(id).then(|| id.to_string())
|
||||
} else {
|
||||
Some(group.id())
|
||||
}
|
||||
};
|
||||
|
||||
let mut drawn_edges = Vec::new();
|
||||
let mut bundled: HashMap<(String, String), usize> = HashMap::new();
|
||||
for edge in edges {
|
||||
let (Some(source), Some(target)) = (
|
||||
edge["source"].as_str().and_then(endpoint),
|
||||
edge["target"].as_str().and_then(endpoint),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let (source_shown, target_shown) = (
|
||||
shown.contains(source.as_str()),
|
||||
shown.contains(target.as_str()),
|
||||
);
|
||||
if source_shown && target_shown {
|
||||
drawn_edges.push(edge.clone());
|
||||
} else if source != target && (opened.is_none() || source_shown || target_shown) {
|
||||
// With a group opened, only edges that touch one of its members.
|
||||
*bundled.entry((source, target)).or_default() += 1;
|
||||
}
|
||||
}
|
||||
// With a group opened, only the groups linked to it are drawn.
|
||||
let linked: HashSet<&str> = bundled
|
||||
.keys()
|
||||
.flat_map(|(s, t)| [s.as_str(), t.as_str()])
|
||||
.collect();
|
||||
|
||||
// Each other group with its size and the folder most of its members are
|
||||
// in, as its label.
|
||||
let mut stats: HashMap<&Group, (usize, HashMap<&str, usize>)> = HashMap::new();
|
||||
for node in nodes {
|
||||
let Some(group) = grouping.of(node_id(node)) else {
|
||||
continue;
|
||||
};
|
||||
if opened == Some(group) {
|
||||
continue;
|
||||
}
|
||||
let (size, folders) = stats.entry(group).or_default();
|
||||
*size += 1;
|
||||
*folders.entry(folder(node)).or_default() += 1;
|
||||
}
|
||||
let mut groups: Vec<(&Group, usize, &str)> = stats
|
||||
.into_iter()
|
||||
.map(|(group, (size, folders))| {
|
||||
let label = match group {
|
||||
Group::Folder(dir) => dir.as_str(),
|
||||
// The most common folder, the first by name on a tie.
|
||||
Group::Community(_) => folders
|
||||
.into_iter()
|
||||
.max_by(|(fa, ca), (fb, cb)| ca.cmp(cb).then_with(|| fb.cmp(fa)))
|
||||
.map_or("", |(dir, _)| dir),
|
||||
};
|
||||
(group, size, label)
|
||||
})
|
||||
.filter(|(group, _, _)| opened.is_none() || linked.contains(group.id().as_str()))
|
||||
.collect();
|
||||
groups.sort_by(|a, b| a.0.cmp(b.0));
|
||||
|
||||
drawn_edges.extend(bundled.into_iter().map(|((source, target), count)| {
|
||||
json!({ "source": source, "target": target, "kind": "bundle", "count": count })
|
||||
}));
|
||||
let mut drawn_nodes: Vec<Value> = members.into_iter().cloned().collect();
|
||||
drawn_nodes.extend(groups.into_iter().map(|(group, size, label)| {
|
||||
json!({
|
||||
"qualified_name": group.id(),
|
||||
"name": if label.is_empty() { "/" } else { label },
|
||||
"kind": group.kind(),
|
||||
"group": group,
|
||||
"member_count": size,
|
||||
"file_path": "",
|
||||
})
|
||||
}));
|
||||
|
||||
Drawn {
|
||||
nodes: drawn_nodes,
|
||||
edges: drawn_edges,
|
||||
capped: (member_total > VIEW_NODE_LIMIT).then_some((VIEW_NODE_LIMIT, member_total)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a stored impact analysis has anything to show: the analysis is
|
||||
/// stored for every finding with a file, also when the graph has no node at
|
||||
/// the finding's location.
|
||||
pub fn impact_has_content(impact: &Value) -> bool {
|
||||
let non_empty = |key: &str| impact[key].as_array().is_some_and(|a| !a.is_empty());
|
||||
impact["blast_radius"].as_u64().unwrap_or(0) > 0
|
||||
|| [
|
||||
"affected_entry_points",
|
||||
"call_chains",
|
||||
"direct_callers",
|
||||
"direct_callees",
|
||||
]
|
||||
.into_iter()
|
||||
.any(non_empty)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn node(name: &str, community: Option<u32>, file: &str) -> Value {
|
||||
json!({ "qualified_name": name, "name": name, "kind": "function",
|
||||
"community_id": community, "file_path": file })
|
||||
}
|
||||
|
||||
fn edge(source: &str, target: &str) -> Value {
|
||||
json!({ "source": source, "target": target, "kind": "calls" })
|
||||
}
|
||||
|
||||
fn ids(values: &[Value]) -> Vec<&str> {
|
||||
values.iter().map(node_id).collect()
|
||||
}
|
||||
|
||||
/// `(source, target, count)` of the bundled edges, sorted.
|
||||
fn bundles(drawn: &Drawn) -> Vec<(String, String, u64)> {
|
||||
let mut bundles: Vec<_> = drawn
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| e["kind"] == "bundle")
|
||||
.map(|e| {
|
||||
(
|
||||
e["source"].as_str().unwrap().to_string(),
|
||||
e["target"].as_str().unwrap().to_string(),
|
||||
e["count"].as_u64().unwrap(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
bundles.sort();
|
||||
bundles
|
||||
}
|
||||
|
||||
/// Community 0 with `MIN_COMMUNITY` members in src/net, community 1 with
|
||||
/// two members in src/ui (pooled), and a node in no community at the root.
|
||||
fn sample() -> (Vec<Value>, Vec<Value>) {
|
||||
let mut nodes: Vec<Value> = (0..MIN_COMMUNITY)
|
||||
.map(|i| node(&format!("a{i}"), Some(0), "src/net/a.c"))
|
||||
.collect();
|
||||
nodes.push(node("b0", Some(1), "src/ui/b.c"));
|
||||
nodes.push(node("b1", Some(1), "src/ui/c.c"));
|
||||
nodes.push(node("x", None, "main.c"));
|
||||
let edges = vec![
|
||||
edge("a0", "b0"),
|
||||
edge("a1", "b0"),
|
||||
edge("a0", "a1"),
|
||||
edge("x", "a0"),
|
||||
];
|
||||
(nodes, edges)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_graph_opens_whole_and_a_large_one_as_the_overview() {
|
||||
assert_eq!(GraphView::initial(VIEW_NODE_LIMIT), GraphView::All);
|
||||
assert_eq!(GraphView::initial(VIEW_NODE_LIMIT + 1), GraphView::Overview);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_communities_and_nodes_in_none_are_pooled_by_folder() {
|
||||
let (nodes, _) = sample();
|
||||
let grouping = Grouping::new(&nodes);
|
||||
|
||||
assert_eq!(grouping.of("a0"), Some(&Group::Community(0)));
|
||||
assert_eq!(grouping.of("b1"), Some(&Group::Folder("src/ui".into())));
|
||||
assert_eq!(grouping.of("x"), Some(&Group::Folder(String::new())));
|
||||
assert_eq!(grouping.of("missing"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_overview_has_one_node_per_group_and_bundled_edges() {
|
||||
let (nodes, edges) = sample();
|
||||
|
||||
let drawn = draw(&nodes, &edges, &Grouping::new(&nodes), &GraphView::Overview);
|
||||
|
||||
assert_eq!(
|
||||
ids(&drawn.nodes),
|
||||
["group:community:0", "group:folder:", "group:folder:src/ui"]
|
||||
);
|
||||
assert_eq!(drawn.nodes[0]["name"], "src/net");
|
||||
assert_eq!(drawn.nodes[0]["member_count"], MIN_COMMUNITY);
|
||||
assert_eq!(drawn.nodes[0]["kind"], "community");
|
||||
// The root folder is named "/".
|
||||
assert_eq!(drawn.nodes[1]["name"], "/");
|
||||
assert_eq!(drawn.nodes[2]["kind"], "folder");
|
||||
// A click on a group's node names the group.
|
||||
let clicked: Group = serde_json::from_value(drawn.nodes[2]["group"].clone()).unwrap();
|
||||
assert_eq!(clicked, Group::Folder("src/ui".into()));
|
||||
// The edge inside community 0 is not drawn in the overview.
|
||||
assert_eq!(
|
||||
bundles(&drawn),
|
||||
[
|
||||
("group:community:0".into(), "group:folder:src/ui".into(), 2),
|
||||
("group:folder:".into(), "group:community:0".into(), 1),
|
||||
]
|
||||
);
|
||||
assert_eq!(drawn.capped, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opened_group_shows_its_members_and_only_the_groups_linked_to_it() {
|
||||
let (mut nodes, mut edges) = sample();
|
||||
// Another community with no link to the folder src/ui.
|
||||
nodes.extend((0..MIN_COMMUNITY).map(|i| node(&format!("c{i}"), Some(2), "lib/c.c")));
|
||||
edges.push(edge("c0", "a0"));
|
||||
|
||||
let ui = Group::Folder("src/ui".into());
|
||||
let drawn = draw(
|
||||
&nodes,
|
||||
&edges,
|
||||
&Grouping::new(&nodes),
|
||||
&GraphView::Group(ui),
|
||||
);
|
||||
|
||||
assert_eq!(ids(&drawn.nodes), ["b0", "b1", "group:community:0"]);
|
||||
assert_eq!(
|
||||
bundles(&drawn),
|
||||
[("group:community:0".into(), "b0".into(), 2)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_between_members_are_drawn_as_they_are() {
|
||||
let (nodes, edges) = sample();
|
||||
|
||||
let drawn = draw(
|
||||
&nodes,
|
||||
&edges,
|
||||
&Grouping::new(&nodes),
|
||||
&GraphView::Group(Group::Community(0)),
|
||||
);
|
||||
|
||||
assert!(drawn.edges.contains(&edges[2]));
|
||||
assert_eq!(drawn.nodes.len(), MIN_COMMUNITY + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_above_the_limit_keeps_its_most_connected_members() {
|
||||
let mut nodes: Vec<Value> = (0..VIEW_NODE_LIMIT + 10)
|
||||
.map(|i| node(&format!("n{i:05}"), Some(3), "src/big.c"))
|
||||
.collect();
|
||||
nodes.push(node("hub", Some(3), "src/big.c"));
|
||||
let edges: Vec<Value> = (0..20).map(|i| edge("hub", &format!("n{i:05}"))).collect();
|
||||
|
||||
let drawn = draw(
|
||||
&nodes,
|
||||
&edges,
|
||||
&Grouping::new(&nodes),
|
||||
&GraphView::Group(Group::Community(3)),
|
||||
);
|
||||
|
||||
assert_eq!(drawn.nodes.len(), VIEW_NODE_LIMIT);
|
||||
assert_eq!(node_id(&drawn.nodes[0]), "hub");
|
||||
assert_eq!(drawn.capped, Some((VIEW_NODE_LIMIT, VIEW_NODE_LIMIT + 11)));
|
||||
// Only edges between drawn members remain.
|
||||
assert!(drawn.edges.iter().all(|e| e["kind"] == "calls"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_whole_view_draws_the_graph_as_it_is() {
|
||||
let (nodes, edges) = sample();
|
||||
let community = Group::Community(0);
|
||||
|
||||
let drawn = draw(&nodes, &edges, &Grouping::new(&nodes), &GraphView::All);
|
||||
|
||||
assert_eq!(drawn.nodes, nodes);
|
||||
assert_eq!(drawn.edges, edges);
|
||||
assert!(GraphView::All.shows_members_of(&community));
|
||||
assert!(!GraphView::Overview.shows_members_of(&community));
|
||||
assert!(GraphView::Group(community.clone()).shows_members_of(&community));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_impact_without_a_location_in_the_graph_has_nothing_to_show() {
|
||||
let empty = json!({ "blast_radius": 0, "affected_entry_points": [],
|
||||
"call_chains": [], "direct_callers": [], "direct_callees": [] });
|
||||
assert!(!impact_has_content(&empty));
|
||||
assert!(impact_has_content(&json!({ "blast_radius": 3 })));
|
||||
assert!(impact_has_content(&json!({ "direct_callers": ["main"] })));
|
||||
}
|
||||
}
|
||||
@@ -1,107 +1,144 @@
|
||||
//! One finding's place in the code graph: the entry points that reach it,
|
||||
//! the call chains from them, and what it reaches in turn. Opened from the
|
||||
//! finding's page when the graph has its location.
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_free_icons::icons::bs_icons::*;
|
||||
use dioxus_free_icons::Icon;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::components::page_header::PageHeader;
|
||||
use super::graph_view::impact_has_content;
|
||||
use crate::app::Route;
|
||||
use crate::i18n::texts::graph as tx;
|
||||
use crate::i18n::{format_count, use_lang};
|
||||
use crate::infrastructure::graph::fetch_impact;
|
||||
|
||||
/// `finding_id` is the finding's fingerprint, the key impact analyses are
|
||||
/// stored under.
|
||||
#[component]
|
||||
pub fn ImpactAnalysisPage(repo_id: String, finding_id: String) -> Element {
|
||||
let impact_data = use_resource(move || {
|
||||
let rid = repo_id.clone();
|
||||
let fid = finding_id.clone();
|
||||
async move { fetch_impact(rid, fid).await.ok() }
|
||||
let lang = use_lang()();
|
||||
let rid = repo_id.clone();
|
||||
let impact = use_resource(move || {
|
||||
let (rid, fid) = (rid.clone(), finding_id.clone());
|
||||
async move { fetch_impact(rid, fid).await.ok().map(|r| r.data) }
|
||||
});
|
||||
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
button {
|
||||
class: "btn btn-ghost btn-back",
|
||||
onclick: move |_| { navigator().go_back(); },
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
"Back"
|
||||
}
|
||||
}
|
||||
let names = |impact: &Value, key: &str| -> Vec<String> {
|
||||
impact[key]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(String::from)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
|
||||
PageHeader {
|
||||
title: "Impact Analysis",
|
||||
description: "Blast radius and affected entry points for a security finding",
|
||||
}
|
||||
|
||||
div { class: "card",
|
||||
match &*impact_data.read() {
|
||||
Some(Some(resp)) => {
|
||||
let impact = resp.data.clone().unwrap_or_default();
|
||||
rsx! {
|
||||
div { class: "grid grid-cols-2 gap-4 mb-4",
|
||||
div { class: "stat-card",
|
||||
div { class: "stat-value",
|
||||
"{impact.get(\"blast_radius\").and_then(|v| v.as_u64()).unwrap_or(0)}"
|
||||
}
|
||||
div { class: "stat-label", "Blast Radius (nodes affected)" }
|
||||
let body = match impact.read().clone() {
|
||||
None => rsx! { div { class: "loading", {tx::IMPACT_LOADING.get(lang)} } },
|
||||
Some(Some(Some(data))) if impact_has_content(&data) => {
|
||||
let entry_points = names(&data, "affected_entry_points");
|
||||
let chains: Vec<Vec<String>> = data["call_chains"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(Value::as_array)
|
||||
.map(|c| {
|
||||
c.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(String::from)
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let blast_radius = format_count(data["blast_radius"].as_u64().unwrap_or(0), lang);
|
||||
let reached_by = format_count(entry_points.len() as u64, lang);
|
||||
rsx! {
|
||||
div { class: "target-summary impact-summary",
|
||||
section { class: "card",
|
||||
div { class: "target-figures",
|
||||
div {
|
||||
span { class: "target-figure", "{reached_by}" }
|
||||
span { class: "target-figure-label", {tx::REACHED_BY.get(lang)} }
|
||||
}
|
||||
div { class: "stat-card",
|
||||
div { class: "stat-value",
|
||||
"{impact.get(\"affected_entry_points\").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0)}"
|
||||
}
|
||||
div { class: "stat-label", "Entry Points Affected" }
|
||||
div {
|
||||
span { class: "target-figure", "{blast_radius}" }
|
||||
span { class: "target-figure-label", {tx::BLAST_RADIUS.get(lang)} }
|
||||
}
|
||||
}
|
||||
|
||||
h3 { "Affected Entry Points" }
|
||||
if let Some(entries) = impact.get("affected_entry_points").and_then(|v| v.as_array()) {
|
||||
if entries.is_empty() {
|
||||
p { class: "text-muted", "No entry points affected." }
|
||||
} else {
|
||||
ul { class: "list",
|
||||
for entry in entries {
|
||||
li { "{entry.as_str().unwrap_or(\"-\")}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h3 { class: "mt-4", "Call Chains" }
|
||||
if let Some(chains) = impact.get("call_chains").and_then(|v| v.as_array()) {
|
||||
if chains.is_empty() {
|
||||
p { class: "text-muted", "No call chains found." }
|
||||
} else {
|
||||
for (i, chain) in chains.iter().enumerate() {
|
||||
div { class: "card mb-2",
|
||||
strong { "Chain {i + 1}: " }
|
||||
if let Some(steps) = chain.as_array() {
|
||||
for (j, step) in steps.iter().enumerate() {
|
||||
span { "{step.as_str().unwrap_or(\"-\")}" }
|
||||
if j < steps.len() - 1 {
|
||||
span { class: "text-muted", " → " }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
section { class: "card",
|
||||
div { class: "card-header", {tx::CALL_CHAINS.get(lang)} }
|
||||
p { class: "graph-note", {tx::CALL_CHAINS_HINT.get(lang)} }
|
||||
if chains.is_empty() {
|
||||
p { class: "text-muted", {tx::NONE.get(lang)} }
|
||||
} else {
|
||||
ol { class: "impact-chains",
|
||||
for chain in chains {
|
||||
li {
|
||||
for (i, step) in chain.iter().enumerate() {
|
||||
if i > 0 {
|
||||
span { class: "impact-chain-arrow", "aria-hidden": "true", "\u{2192}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
h3 { class: "mt-4", "Direct Callers" }
|
||||
if let Some(callers) = impact.get("direct_callers").and_then(|v| v.as_array()) {
|
||||
if callers.is_empty() {
|
||||
p { class: "text-muted", "No direct callers." }
|
||||
} else {
|
||||
ul { class: "list",
|
||||
for caller in callers {
|
||||
li { code { "{caller.as_str().unwrap_or(\"-\")}" } }
|
||||
code { "{step}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Some(None) => rsx! {
|
||||
p { "No impact analysis data available for this finding." }
|
||||
},
|
||||
None => rsx! {
|
||||
p { "Loading impact analysis..." }
|
||||
},
|
||||
}
|
||||
NameList { title: tx::ENTRY_POINTS.get(lang), names: entry_points }
|
||||
NameList { title: tx::CALLERS.get(lang), names: names(&data, "direct_callers") }
|
||||
NameList { title: tx::CALLEES.get(lang), names: names(&data, "direct_callees") }
|
||||
}
|
||||
}
|
||||
Some(_) => rsx! { div { class: "card", p { {tx::IMPACT_NONE.get(lang)} } } },
|
||||
};
|
||||
|
||||
rsx! {
|
||||
div { class: "back-nav",
|
||||
button {
|
||||
class: "btn btn-ghost btn-back",
|
||||
onclick: move |_| navigator().go_back(),
|
||||
Icon { icon: BsArrowLeft, width: 16, height: 16 }
|
||||
{tx::BACK.get(lang)}
|
||||
}
|
||||
}
|
||||
header { class: "target-head",
|
||||
div { class: "target-head-text",
|
||||
h2 { {tx::IMPACT_TITLE.get(lang)} }
|
||||
p { class: "target-head-meta", {tx::IMPACT_SUBTITLE.get(lang)} }
|
||||
}
|
||||
div { class: "target-head-actions",
|
||||
Link { to: Route::GraphExplorerPage { repo_id }, class: "btn btn-secondary",
|
||||
{tx::OPEN_GRAPH.get(lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
}
|
||||
}
|
||||
{body}
|
||||
}
|
||||
}
|
||||
|
||||
/// A titled list of qualified names.
|
||||
#[component]
|
||||
fn NameList(title: &'static str, names: Vec<String>) -> Element {
|
||||
let lang = use_lang()();
|
||||
rsx! {
|
||||
section { class: "card",
|
||||
div { class: "card-header", "{title}" }
|
||||
if names.is_empty() {
|
||||
p { class: "text-muted", {tx::NONE.get(lang)} }
|
||||
} else {
|
||||
ul { class: "impact-names",
|
||||
for name in names {
|
||||
li { code { "{name}" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ pub mod dast_targets;
|
||||
pub mod finding_detail;
|
||||
pub mod findings;
|
||||
pub mod graph_explorer;
|
||||
pub mod graph_index;
|
||||
pub(crate) mod graph_view;
|
||||
pub mod impact_analysis;
|
||||
pub mod issues;
|
||||
pub mod mcp_servers;
|
||||
@@ -31,7 +31,6 @@ pub use dast_targets::DastTargetsPage;
|
||||
pub use finding_detail::FindingDetailPage;
|
||||
pub use findings::FindingsPage;
|
||||
pub use graph_explorer::GraphExplorerPage;
|
||||
pub use graph_index::GraphIndexPage;
|
||||
pub use impact_analysis::ImpactAnalysisPage;
|
||||
pub use issues::IssuesPage;
|
||||
pub use mcp_servers::McpServersPage;
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::i18n::texts::{common, kinds, onboarding as tx};
|
||||
use crate::i18n::{format_bytes, use_lang};
|
||||
use crate::infrastructure::onboarding::{
|
||||
create_target, detect_target, enable_target_scans, fetch_applicable_scans, is_file_kind,
|
||||
plc_format_for, set_archive_password, trigger_target_scan, upload_target_artifact,
|
||||
plc_format_for, set_archive_password, trigger_new_content_scan, upload_target_artifact,
|
||||
validate_artifact_ref, validate_target_name, ArchivePassword, ArtifactInputDto,
|
||||
PasswordOutcome, UNSUPPORTED_ARCHIVE,
|
||||
};
|
||||
@@ -591,7 +591,7 @@ pub fn OnboardingPage() -> Element {
|
||||
return;
|
||||
}
|
||||
}
|
||||
first_scan.set(match trigger_target_scan(id).await {
|
||||
first_scan.set(match trigger_new_content_scan(id).await {
|
||||
Ok(_) => FirstScan::Started,
|
||||
Err(e) => FirstScan::Failed(e.to_string()),
|
||||
});
|
||||
@@ -750,7 +750,7 @@ pub fn OnboardingPage() -> Element {
|
||||
let offers_optin = !source_only && !optin_scans(&applicable).is_empty();
|
||||
scans.set(applicable);
|
||||
if upload_errors.read().is_empty() && !offers_optin {
|
||||
first_scan.set(match trigger_target_scan(id).await {
|
||||
first_scan.set(match trigger_new_content_scan(id).await {
|
||||
Ok(_) => FirstScan::Started,
|
||||
Err(e) => FirstScan::Failed(e.to_string()),
|
||||
});
|
||||
|
||||
@@ -206,13 +206,13 @@ pub fn SbomPage(target: String) -> Element {
|
||||
}
|
||||
select {
|
||||
class: "sbom-filter-select",
|
||||
title: tx::IN_IMAGE_HINT.get(lang),
|
||||
title: tx::IN_IMAGE_FILTER_HINT.get(lang),
|
||||
onchange: move |e| {
|
||||
in_image_filter.set((e.value() == "true").then_some(true));
|
||||
page.set(1);
|
||||
},
|
||||
option { value: "", {tx::ALL_COMPONENTS.get(lang)} }
|
||||
option { value: "true", {tx::IN_IMAGE.get(lang)} }
|
||||
option { value: "true", {tx::IN_IMAGE_ANY.get(lang)} }
|
||||
}
|
||||
select {
|
||||
class: "sbom-filter-select",
|
||||
@@ -354,13 +354,14 @@ pub fn SbomPage(target: String) -> Element {
|
||||
let edit_target = target.clone();
|
||||
let edit_existing = entry.concluded.clone();
|
||||
let row_key_click = row_key.clone();
|
||||
// Which images hold it, and how that is known, on the badge's tooltip.
|
||||
let in_image_title = entry.in_image.as_ref().map(|i| {
|
||||
let hint = match i.basis {
|
||||
compliance_core::models::InImageBasis::Declared => tx::IN_IMAGE_HINT,
|
||||
compliance_core::models::InImageBasis::Built => tx::IN_IMAGE_BUILT_HINT,
|
||||
// How it is known to be in the image names the badge; the
|
||||
// tooltip adds which images hold it.
|
||||
let in_image_badge = entry.in_image.as_ref().map(|i| {
|
||||
let (label, hint) = match i.basis {
|
||||
compliance_core::models::InImageBasis::Declared => (tx::IN_IMAGE, tx::IN_IMAGE_HINT),
|
||||
compliance_core::models::InImageBasis::Built => (tx::IN_IMAGE_BUILT, tx::IN_IMAGE_BUILT_HINT),
|
||||
};
|
||||
format!("{} (Images: {})", hint.get(lang), i.images.join(", "))
|
||||
(label.get(lang), format!("{} (Images: {})", hint.get(lang), i.images.join(", ")))
|
||||
});
|
||||
rsx! {
|
||||
tr {
|
||||
@@ -385,12 +386,12 @@ pub fn SbomPage(target: String) -> Element {
|
||||
td {
|
||||
style: "font-weight: 500;",
|
||||
"{entry.name}"
|
||||
if let Some(title) = in_image_title {
|
||||
if let Some((label, title)) = in_image_badge {
|
||||
" "
|
||||
span {
|
||||
class: "badge badge-success",
|
||||
title: "{title}",
|
||||
{tx::IN_IMAGE.get(lang)}
|
||||
{label}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use dioxus_free_icons::Icon;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::artifact_upload::ArtifactUpload;
|
||||
use crate::components::billing_swap::BillingSwap;
|
||||
use crate::components::cra_bar::CraBar;
|
||||
use crate::components::evidence_button::EvidencePackButton;
|
||||
use crate::components::layer_pins::LayerPinsCard;
|
||||
@@ -20,10 +21,11 @@ use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::components::vex_panel::VexPanel;
|
||||
use crate::components::webhook_deliveries::WebhookDeliveries;
|
||||
use crate::i18n::texts::{common, kinds, targets as tx};
|
||||
use crate::i18n::texts::{common, compliance::language_name, kinds, targets as tx};
|
||||
use crate::i18n::use_lang;
|
||||
use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
|
||||
use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery};
|
||||
use crate::infrastructure::graph::fetch_graph_summary;
|
||||
use crate::infrastructure::onboarding::{
|
||||
delete_target, fetch_applicable_scans, fetch_target, is_file_kind, set_archive_password,
|
||||
trigger_target_scan, update_target, validate_artifact_ref, validate_target_name,
|
||||
@@ -111,6 +113,8 @@ pub fn TargetPage(id: String) -> Element {
|
||||
.await
|
||||
.ok()
|
||||
});
|
||||
let graph =
|
||||
use_resource(move || async move { fetch_graph_summary(target_id()).await.ok().flatten() });
|
||||
let mut editing = use_signal(|| false);
|
||||
let mut confirm_delete = use_signal(|| false);
|
||||
let mut adding_manual = use_signal(|| false);
|
||||
@@ -154,6 +158,9 @@ pub fn TargetPage(id: String) -> Element {
|
||||
.as_ref()
|
||||
.and_then(|d| d["sbom_components"].as_u64());
|
||||
let cves = status_data.as_ref().and_then(|d| d["cve_alerts"].as_u64());
|
||||
let is_extra = str_at(&t, "billing") == "extra";
|
||||
// The code graph's card, once a scan built one with declarations in it.
|
||||
let graph = graph.read().clone().flatten().filter(|g| g.units > 0);
|
||||
|
||||
rsx! {
|
||||
BackLink {}
|
||||
@@ -222,6 +229,16 @@ pub fn TargetPage(id: String) -> Element {
|
||||
}
|
||||
}
|
||||
|
||||
// An extra target can be swapped with an included one (t72).
|
||||
if is_extra {
|
||||
div { class: "card target-billing",
|
||||
span { class: "badge badge-neutral", title: tx::EXTRA_HINT.get(lang), {tx::EXTRA.get(lang)} }
|
||||
if can_write {
|
||||
BillingSwap { target_id: id.clone(), on_swapped: move |_| target.restart() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
div { class: "target-summary",
|
||||
section { class: "card target-cra",
|
||||
div { class: "target-card-head",
|
||||
@@ -254,6 +271,36 @@ pub fn TargetPage(id: String) -> Element {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(graph) = graph {
|
||||
section { class: "card target-graph",
|
||||
div { class: "target-card-head",
|
||||
h3 { {tx::GRAPH_TITLE.get(lang)} }
|
||||
Link { to: Route::GraphExplorerPage { repo_id: id.clone() }, class: "target-card-link",
|
||||
{tx::GRAPH_SHOW.get(lang)}
|
||||
Icon { icon: BsArrowRight, width: 14, height: 14 }
|
||||
}
|
||||
}
|
||||
div { class: "target-figures",
|
||||
div {
|
||||
span { class: "target-figure", "{graph.units}" }
|
||||
span { class: "target-figure-label", {tx::CODE_UNITS.get(lang)} }
|
||||
}
|
||||
div {
|
||||
span { class: "target-figure", "{graph.entry_points}" }
|
||||
span { class: "target-figure-label", {tx::ENTRY_POINTS.get(lang)} }
|
||||
}
|
||||
}
|
||||
p { class: "target-graph-languages",
|
||||
{graph.languages.iter().map(|l| language_name(l)).collect::<Vec<_>>().join(", ")}
|
||||
}
|
||||
if graph.unreadable_files > 0 {
|
||||
p { class: "target-graph-unreadable",
|
||||
{tx::unreadable_files(graph.unreadable_files, lang)}
|
||||
}
|
||||
}
|
||||
p { class: "target-graph-note", {tx::GRAPH_NOTE.get(lang)} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
section { class: "card target-open",
|
||||
|
||||
@@ -15,6 +15,7 @@ use crate::components::pagination::Pagination;
|
||||
use crate::components::projects::ProjectChips;
|
||||
use crate::components::scan_runs::status_badge;
|
||||
use crate::components::toast::{ToastType, Toasts};
|
||||
use crate::components::usage_summary::UsageSummary;
|
||||
use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx};
|
||||
use crate::i18n::{format_ago, use_lang, Lang};
|
||||
use crate::infrastructure::auth_check::{go_to_login, is_session_expired};
|
||||
@@ -132,6 +133,7 @@ pub fn TargetsPage() -> Element {
|
||||
title: tx::TITLE.get(lang),
|
||||
description: tx::SUBTITLE.get(lang),
|
||||
}
|
||||
UsageSummary {}
|
||||
|
||||
div { class: "page-actions",
|
||||
if can_write {
|
||||
@@ -233,6 +235,13 @@ pub fn TargetsPage() -> Element {
|
||||
"{name}"
|
||||
}
|
||||
span { class: "targets-type", "{ttype}" }
|
||||
if str_at(t, "billing") == "extra" {
|
||||
span {
|
||||
class: "badge badge-neutral targets-extra",
|
||||
title: tx::EXTRA_HINT.get(lang),
|
||||
{tx::EXTRA.get(lang)}
|
||||
}
|
||||
}
|
||||
if let Some(Ok(all)) = projects.read().clone() {
|
||||
ProjectChips { ids: project_ids_of(t), projects: all }
|
||||
}
|
||||
|
||||
@@ -13,13 +13,19 @@ chrono = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
mongodb = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
|
||||
# Tree-sitter parsing
|
||||
tree-sitter = "0.24"
|
||||
tree-sitter = "0.25"
|
||||
tree-sitter-rust = "0.23"
|
||||
tree-sitter-python = "0.23"
|
||||
tree-sitter-javascript = "0.23"
|
||||
tree-sitter-typescript = "0.23"
|
||||
tree-sitter-c = "0.23"
|
||||
tree-sitter-c-sharp = "=0.23.1"
|
||||
# VB.NET, CodeAnt-AI grammar (MIT), ABI 15: needs tree-sitter 0.25
|
||||
tree-sitter-vb-dotnet = "=0.1.0"
|
||||
|
||||
# Graph algorithms
|
||||
petgraph = "0.7"
|
||||
|
||||
@@ -29,7 +29,8 @@ pub fn extract_chunks(
|
||||
|
||||
for node in nodes {
|
||||
let file = repo_path.join(&node.file_path);
|
||||
let source = match std::fs::read_to_string(&file) {
|
||||
// Decoded as the graph's parser read it, so every node has its lines.
|
||||
let source = match compliance_core::encoding::read_source(&file) {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
@@ -1,257 +1,143 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use petgraph::graph::NodeIndex;
|
||||
use petgraph::visit::EdgeRef;
|
||||
use petgraph::Direction;
|
||||
use tracing::info;
|
||||
|
||||
use super::engine::CodeGraph;
|
||||
|
||||
/// Louvain's local-move phase over the graph, read as undirected: each node
|
||||
/// starts in its own community and moves to the neighbouring community with
|
||||
/// the best modularity gain until no move helps (at most 50 passes).
|
||||
///
|
||||
/// The community degree totals are kept up to date on every move instead of
|
||||
/// being summed again for every node, and a node's edges per neighbouring
|
||||
/// community are counted in a scratch array, so one pass costs
|
||||
/// O(nodes + edges). Communities are numbered 0.. in node order, so the
|
||||
/// same graph always gets the same numbers.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The community of every node, indexed by node index.
|
||||
fn louvain(code_graph: &CodeGraph) -> Vec<u32> {
|
||||
let graph = &code_graph.graph;
|
||||
let node_count = graph.node_count();
|
||||
let mut community: Vec<u32> = (0..node_count as u32).collect();
|
||||
if graph.edge_count() == 0 {
|
||||
return community;
|
||||
}
|
||||
let m2 = 2.0 * graph.edge_count() as f64;
|
||||
|
||||
// Neighbours in both directions, once, as plain indices.
|
||||
let neighbours: Vec<Vec<usize>> = graph
|
||||
.node_indices()
|
||||
.map(|idx| {
|
||||
graph
|
||||
.edges_directed(idx, Direction::Outgoing)
|
||||
.map(|e| e.target().index())
|
||||
.chain(
|
||||
graph
|
||||
.edges_directed(idx, Direction::Incoming)
|
||||
.map(|e| e.source().index()),
|
||||
)
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let degree: Vec<f64> = neighbours.iter().map(|n| n.len() as f64).collect();
|
||||
let mut totals = degree.clone();
|
||||
|
||||
// Edges from the current node into each community; `touched` lists the
|
||||
// communities set, so only those are reset.
|
||||
let mut edges_to = vec![0.0_f64; node_count];
|
||||
let mut touched: Vec<u32> = Vec::new();
|
||||
|
||||
for _ in 0..50 {
|
||||
let mut improved = false;
|
||||
for node in 0..node_count {
|
||||
let current = community[node];
|
||||
let node_degree = degree[node];
|
||||
for &neighbour in &neighbours[node] {
|
||||
let c = community[neighbour];
|
||||
if edges_to[c as usize] == 0.0 {
|
||||
touched.push(c);
|
||||
}
|
||||
edges_to[c as usize] += 1.0;
|
||||
}
|
||||
|
||||
let remove_cost = edges_to[current as usize]
|
||||
- (totals[current as usize] - node_degree) * node_degree / m2;
|
||||
let mut best = current;
|
||||
let mut best_gain = 0.0;
|
||||
for &candidate in &touched {
|
||||
if candidate == current {
|
||||
continue;
|
||||
}
|
||||
let gain = edges_to[candidate as usize]
|
||||
- totals[candidate as usize] * node_degree / m2
|
||||
- remove_cost;
|
||||
if gain > best_gain {
|
||||
best_gain = gain;
|
||||
best = candidate;
|
||||
}
|
||||
}
|
||||
for &c in &touched {
|
||||
edges_to[c as usize] = 0.0;
|
||||
}
|
||||
touched.clear();
|
||||
|
||||
if best != current {
|
||||
totals[current as usize] -= node_degree;
|
||||
totals[best as usize] += node_degree;
|
||||
community[node] = best;
|
||||
improved = true;
|
||||
}
|
||||
}
|
||||
if !improved {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Renumber 0.. in order of first appearance.
|
||||
let mut renumbered = vec![u32::MAX; node_count];
|
||||
let mut next = 0;
|
||||
for c in &mut community {
|
||||
let slot = &mut renumbered[*c as usize];
|
||||
if *slot == u32::MAX {
|
||||
*slot = next;
|
||||
next += 1;
|
||||
}
|
||||
*c = *slot;
|
||||
}
|
||||
community
|
||||
}
|
||||
|
||||
/// The number of communities in a node assignment numbered 0...
|
||||
fn count(communities: &[u32]) -> u32 {
|
||||
communities.iter().max().map_or(0, |max| max + 1)
|
||||
}
|
||||
|
||||
/// Run Louvain community detection on the code graph.
|
||||
/// Returns the number of communities detected.
|
||||
/// Mutates node community_id in place.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The number of communities detected.
|
||||
pub fn detect_communities(code_graph: &CodeGraph) -> u32 {
|
||||
let graph = &code_graph.graph;
|
||||
let node_count = graph.node_count();
|
||||
|
||||
if node_count == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Initialize: each node in its own community
|
||||
let mut community: HashMap<NodeIndex, u32> = HashMap::new();
|
||||
for idx in graph.node_indices() {
|
||||
community.insert(idx, idx.index() as u32);
|
||||
}
|
||||
|
||||
// Compute total edge weight (all edges weight 1.0)
|
||||
let total_edges = graph.edge_count() as f64;
|
||||
if total_edges == 0.0 {
|
||||
// All nodes are isolated, each is its own community
|
||||
return node_count as u32;
|
||||
}
|
||||
|
||||
let m2 = 2.0 * total_edges;
|
||||
|
||||
// Pre-compute node degrees
|
||||
let mut degree: HashMap<NodeIndex, f64> = HashMap::new();
|
||||
for idx in graph.node_indices() {
|
||||
let d = graph.edges(idx).count() as f64;
|
||||
degree.insert(idx, d);
|
||||
}
|
||||
|
||||
// Louvain phase 1: local moves
|
||||
let mut improved = true;
|
||||
let mut iterations = 0;
|
||||
let max_iterations = 50;
|
||||
|
||||
while improved && iterations < max_iterations {
|
||||
improved = false;
|
||||
iterations += 1;
|
||||
|
||||
for node in graph.node_indices() {
|
||||
let current_comm = community[&node];
|
||||
let node_deg = degree[&node];
|
||||
|
||||
// Compute edges to each neighboring community
|
||||
let mut comm_edges: HashMap<u32, f64> = HashMap::new();
|
||||
for edge in graph.edges(node) {
|
||||
let neighbor = edge.target();
|
||||
let neighbor_comm = community[&neighbor];
|
||||
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
|
||||
}
|
||||
// Also check incoming edges (undirected treatment)
|
||||
for edge in graph.edges_directed(node, petgraph::Direction::Incoming) {
|
||||
let neighbor = edge.source();
|
||||
let neighbor_comm = community[&neighbor];
|
||||
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
|
||||
}
|
||||
|
||||
// Compute community totals (sum of degrees in each community)
|
||||
let mut comm_totals: HashMap<u32, f64> = HashMap::new();
|
||||
for (n, &c) in &community {
|
||||
*comm_totals.entry(c).or_insert(0.0) += degree[n];
|
||||
}
|
||||
|
||||
// Find best community
|
||||
let current_total = comm_totals.get(¤t_comm).copied().unwrap_or(0.0);
|
||||
let edges_to_current = comm_edges.get(¤t_comm).copied().unwrap_or(0.0);
|
||||
|
||||
// Modularity gain from removing node from current community
|
||||
let remove_cost = edges_to_current - (current_total - node_deg) * node_deg / m2;
|
||||
|
||||
let mut best_comm = current_comm;
|
||||
let mut best_gain = 0.0;
|
||||
|
||||
for (&candidate_comm, &edges_to_candidate) in &comm_edges {
|
||||
if candidate_comm == current_comm {
|
||||
continue;
|
||||
}
|
||||
let candidate_total = comm_totals.get(&candidate_comm).copied().unwrap_or(0.0);
|
||||
|
||||
// Modularity gain from adding node to candidate community
|
||||
let add_gain = edges_to_candidate - candidate_total * node_deg / m2;
|
||||
let gain = add_gain - remove_cost;
|
||||
|
||||
if gain > best_gain {
|
||||
best_gain = gain;
|
||||
best_comm = candidate_comm;
|
||||
}
|
||||
}
|
||||
|
||||
if best_comm != current_comm {
|
||||
community.insert(node, best_comm);
|
||||
improved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Renumber communities to be contiguous
|
||||
let mut comm_remap: HashMap<u32, u32> = HashMap::new();
|
||||
let mut next_id: u32 = 0;
|
||||
for &c in community.values() {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = comm_remap.entry(c) {
|
||||
e.insert(next_id);
|
||||
next_id += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply to community map
|
||||
for c in community.values_mut() {
|
||||
if let Some(&new_id) = comm_remap.get(c) {
|
||||
*c = new_id;
|
||||
}
|
||||
}
|
||||
|
||||
let num_communities = next_id;
|
||||
info!(
|
||||
communities = num_communities,
|
||||
iterations, "Community detection complete"
|
||||
);
|
||||
|
||||
// NOTE: community IDs are stored in the HashMap but need to be applied
|
||||
// back to the CodeGraph nodes by the caller (engine) if needed for persistence.
|
||||
// For now we return the count; the full assignment is available via the map.
|
||||
|
||||
num_communities
|
||||
count(&louvain(code_graph))
|
||||
}
|
||||
|
||||
/// Apply community assignments back to code nodes
|
||||
/// Detect communities and write each node's community into `community_id`.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The number of communities detected.
|
||||
pub fn apply_communities(code_graph: &mut CodeGraph) -> u32 {
|
||||
detect_communities_with_assignment(code_graph)
|
||||
}
|
||||
|
||||
/// Detect communities and write assignments into the nodes
|
||||
fn detect_communities_with_assignment(code_graph: &mut CodeGraph) -> u32 {
|
||||
let graph = &code_graph.graph;
|
||||
let node_count = graph.node_count();
|
||||
|
||||
if node_count == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let mut community: HashMap<NodeIndex, u32> = HashMap::new();
|
||||
for idx in graph.node_indices() {
|
||||
community.insert(idx, idx.index() as u32);
|
||||
}
|
||||
|
||||
let total_edges = graph.edge_count() as f64;
|
||||
if total_edges == 0.0 {
|
||||
for node in &mut code_graph.nodes {
|
||||
if let Some(gi) = node.graph_index {
|
||||
node.community_id = Some(gi);
|
||||
}
|
||||
}
|
||||
return node_count as u32;
|
||||
}
|
||||
|
||||
let m2 = 2.0 * total_edges;
|
||||
|
||||
let mut degree: HashMap<NodeIndex, f64> = HashMap::new();
|
||||
for idx in graph.node_indices() {
|
||||
let d = (graph.edges(idx).count()
|
||||
+ graph
|
||||
.edges_directed(idx, petgraph::Direction::Incoming)
|
||||
.count()) as f64;
|
||||
degree.insert(idx, d);
|
||||
}
|
||||
|
||||
let mut improved = true;
|
||||
let mut iterations = 0;
|
||||
let max_iterations = 50;
|
||||
|
||||
while improved && iterations < max_iterations {
|
||||
improved = false;
|
||||
iterations += 1;
|
||||
|
||||
for node in graph.node_indices() {
|
||||
let current_comm = community[&node];
|
||||
let node_deg = degree[&node];
|
||||
|
||||
let mut comm_edges: HashMap<u32, f64> = HashMap::new();
|
||||
for edge in graph.edges(node) {
|
||||
let neighbor_comm = community[&edge.target()];
|
||||
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
|
||||
}
|
||||
for edge in graph.edges_directed(node, petgraph::Direction::Incoming) {
|
||||
let neighbor_comm = community[&edge.source()];
|
||||
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
|
||||
}
|
||||
|
||||
let mut comm_totals: HashMap<u32, f64> = HashMap::new();
|
||||
for (n, &c) in &community {
|
||||
*comm_totals.entry(c).or_insert(0.0) += degree[n];
|
||||
}
|
||||
|
||||
let current_total = comm_totals.get(¤t_comm).copied().unwrap_or(0.0);
|
||||
let edges_to_current = comm_edges.get(¤t_comm).copied().unwrap_or(0.0);
|
||||
let remove_cost = edges_to_current - (current_total - node_deg) * node_deg / m2;
|
||||
|
||||
let mut best_comm = current_comm;
|
||||
let mut best_gain = 0.0;
|
||||
|
||||
for (&candidate_comm, &edges_to_candidate) in &comm_edges {
|
||||
if candidate_comm == current_comm {
|
||||
continue;
|
||||
}
|
||||
let candidate_total = comm_totals.get(&candidate_comm).copied().unwrap_or(0.0);
|
||||
let add_gain = edges_to_candidate - candidate_total * node_deg / m2;
|
||||
let gain = add_gain - remove_cost;
|
||||
|
||||
if gain > best_gain {
|
||||
best_gain = gain;
|
||||
best_comm = candidate_comm;
|
||||
}
|
||||
}
|
||||
|
||||
if best_comm != current_comm {
|
||||
community.insert(node, best_comm);
|
||||
improved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Renumber
|
||||
let mut comm_remap: HashMap<u32, u32> = HashMap::new();
|
||||
let mut next_id: u32 = 0;
|
||||
for &c in community.values() {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = comm_remap.entry(c) {
|
||||
e.insert(next_id);
|
||||
next_id += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply to nodes
|
||||
let communities = louvain(code_graph);
|
||||
for node in &mut code_graph.nodes {
|
||||
if let Some(gi) = node.graph_index {
|
||||
let idx = NodeIndex::new(gi as usize);
|
||||
if let Some(&comm) = community.get(&idx) {
|
||||
let remapped = comm_remap.get(&comm).copied().unwrap_or(comm);
|
||||
node.community_id = Some(remapped);
|
||||
}
|
||||
if let Some(&community) = node.graph_index.and_then(|gi| communities.get(gi as usize)) {
|
||||
node.community_id = Some(community);
|
||||
}
|
||||
}
|
||||
|
||||
next_id
|
||||
let communities = count(&communities);
|
||||
info!(communities, "Community detection complete");
|
||||
communities
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -259,6 +145,7 @@ mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::graph::{CodeEdgeKind, CodeNode, CodeNodeKind};
|
||||
use petgraph::graph::DiGraph;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn make_node(qualified_name: &str, graph_index: u32) -> CodeNode {
|
||||
CodeNode {
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::path::Path;
|
||||
use chrono::Utc;
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::{
|
||||
CodeEdge, CodeEdgeKind, CodeNode, GraphBuildRun, GraphBuildStatus,
|
||||
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus,
|
||||
};
|
||||
use compliance_core::traits::graph_builder::ParseOutput;
|
||||
use petgraph::graph::{DiGraph, NodeIndex};
|
||||
@@ -12,7 +12,7 @@ use tracing::info;
|
||||
|
||||
use crate::parsers::registry::ParserRegistry;
|
||||
|
||||
use super::community::detect_communities;
|
||||
use super::community::apply_communities;
|
||||
use super::impact::ImpactAnalyzer;
|
||||
|
||||
/// Walk up the qualified-name hierarchy to find the closest ancestor
|
||||
@@ -39,6 +39,141 @@ fn find_parent_qname(qname: &str, node_map: &HashMap<String, NodeIndex>) -> Opti
|
||||
}
|
||||
}
|
||||
|
||||
/// The last segment of a qualified name or edge target, after the last
|
||||
/// `::` and then the last `.`: `src/a.py::Cls.run` and `self.run` both end
|
||||
/// in `run`. Every name a target can match by suffix shares the target's
|
||||
/// last segment, so it is the key the candidates are found by.
|
||||
fn last_segment(name: &str) -> &str {
|
||||
let after_path = name.rsplit("::").next().unwrap_or(name);
|
||||
after_path.rsplit('.').next().unwrap_or(after_path)
|
||||
}
|
||||
|
||||
/// One node an edge target may resolve to.
|
||||
struct Candidate<'a> {
|
||||
qualified: &'a str,
|
||||
file_path: &'a str,
|
||||
idx: NodeIndex,
|
||||
}
|
||||
|
||||
/// Resolves edge targets to nodes. Candidates are found by the target's
|
||||
/// last segment instead of scanning every node per edge, and when several
|
||||
/// match, the one in the edge's own file wins (C's `static` functions,
|
||||
/// same-named helpers), then the first by qualified name, so a rebuild
|
||||
/// links the same way every time.
|
||||
struct NameIndex<'a> {
|
||||
exact: &'a HashMap<String, NodeIndex>,
|
||||
by_last: HashMap<&'a str, Vec<Candidate<'a>>>,
|
||||
/// File nodes by file name, for `#include "uart.h"` and other targets
|
||||
/// that are paths.
|
||||
files_by_name: HashMap<&'a str, Vec<Candidate<'a>>>,
|
||||
}
|
||||
|
||||
impl<'a> NameIndex<'a> {
|
||||
fn new(nodes: &'a [CodeNode], exact: &'a HashMap<String, NodeIndex>) -> Self {
|
||||
let mut by_last: HashMap<&str, Vec<Candidate<'_>>> = HashMap::new();
|
||||
let mut files_by_name: HashMap<&str, Vec<Candidate<'_>>> = HashMap::new();
|
||||
for node in nodes {
|
||||
let Some(&idx) = exact.get(&node.qualified_name) else {
|
||||
continue;
|
||||
};
|
||||
let candidate = || Candidate {
|
||||
qualified: &node.qualified_name,
|
||||
file_path: &node.file_path,
|
||||
idx,
|
||||
};
|
||||
by_last
|
||||
.entry(last_segment(&node.qualified_name))
|
||||
.or_default()
|
||||
.push(candidate());
|
||||
if matches!(node.kind, CodeNodeKind::File) {
|
||||
let name = node.qualified_name.rsplit('/').next().unwrap_or_default();
|
||||
files_by_name.entry(name).or_default().push(candidate());
|
||||
}
|
||||
}
|
||||
for list in by_last.values_mut().chain(files_by_name.values_mut()) {
|
||||
list.sort_unstable_by(|a, b| a.qualified.cmp(b.qualified));
|
||||
}
|
||||
Self {
|
||||
exact,
|
||||
by_last,
|
||||
files_by_name,
|
||||
}
|
||||
}
|
||||
|
||||
/// The node `target` names, seen from an edge in `from_file`.
|
||||
///
|
||||
/// Resolution strategies (in order):
|
||||
/// 1. Direct qualified-name match
|
||||
/// 2. Suffix match: "foo" matches "src/main.rs::mod::foo" and "src/app.js.foo"
|
||||
/// 3. Module-path match: "crate::config::load" matches "src/config.rs::load"
|
||||
/// 4. Self-method: "self.method" matches "::method"
|
||||
/// 5. File path: "uart.h" and "./lib/uart.h" match the file "src/lib/uart.h"
|
||||
fn resolve(&self, target: &str, from_file: &str) -> Option<NodeIndex> {
|
||||
if let Some(&idx) = self.exact.get(target) {
|
||||
return Some(idx);
|
||||
}
|
||||
let candidates = self.by_last.get(last_segment(target));
|
||||
|
||||
// 2. Suffix match
|
||||
let colon = format!("::{target}");
|
||||
let dot = format!(".{target}");
|
||||
if let Some(idx) = pick(candidates, from_file, |q| {
|
||||
q.ends_with(&colon) || q.ends_with(&dot)
|
||||
}) {
|
||||
return Some(idx);
|
||||
}
|
||||
|
||||
// 3. Module path: match progressively shorter suffixes of the path,
|
||||
// without Rust's relative prefixes.
|
||||
if target.contains("::") {
|
||||
let stripped = target
|
||||
.strip_prefix("crate::")
|
||||
.or_else(|| target.strip_prefix("super::"))
|
||||
.or_else(|| target.strip_prefix("self::"))
|
||||
.unwrap_or(target);
|
||||
let segments: Vec<&str> = stripped.split("::").collect();
|
||||
for start in 0..segments.len() {
|
||||
let pattern = format!("::{}", segments[start..].join("::"));
|
||||
if let Some(idx) = pick(candidates, from_file, |q| q.ends_with(&pattern)) {
|
||||
return Some(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Self-method
|
||||
if let Some(method) = target.strip_prefix("self.") {
|
||||
let pattern = format!("::{method}");
|
||||
if let Some(idx) = pick(candidates, from_file, |q| q.ends_with(&pattern)) {
|
||||
return Some(idx);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. File path
|
||||
let path = target.trim_start_matches("./");
|
||||
let file_name = path.rsplit('/').next().unwrap_or(path);
|
||||
let in_dir = format!("/{path}");
|
||||
pick(self.files_by_name.get(file_name), from_file, |q| {
|
||||
q == path || q.ends_with(&in_dir)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The first candidate that `matches`, preferring one in `from_file`.
|
||||
fn pick(
|
||||
candidates: Option<&Vec<Candidate<'_>>>,
|
||||
from_file: &str,
|
||||
matches: impl Fn(&str) -> bool,
|
||||
) -> Option<NodeIndex> {
|
||||
let mut first = None;
|
||||
for candidate in candidates?.iter().filter(|c| matches(c.qualified)) {
|
||||
if candidate.file_path == from_file {
|
||||
return Some(candidate.idx);
|
||||
}
|
||||
first.get_or_insert(candidate.idx);
|
||||
}
|
||||
first
|
||||
}
|
||||
|
||||
/// The main graph engine that builds and manages code knowledge graphs
|
||||
pub struct GraphEngine {
|
||||
parser_registry: ParserRegistry,
|
||||
@@ -68,38 +203,56 @@ impl GraphEngine {
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
|
||||
let mut build_run = GraphBuildRun::new(repo_id.to_string());
|
||||
|
||||
info!(repo_id, path = %repo_path.display(), "Starting graph build");
|
||||
|
||||
// Phase 1: Parse all files
|
||||
let parse_output = self.parser_registry.parse_directory(
|
||||
let parsed = self.parser_registry.parse_directory(
|
||||
repo_path,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
self.max_nodes,
|
||||
)?;
|
||||
let (code_graph, mut build_run) = self.assemble(parsed.output, repo_id)?;
|
||||
build_run.unreadable_file_count = Some(parsed.unreadable_files);
|
||||
Ok((code_graph, build_run))
|
||||
}
|
||||
|
||||
// Phase 2: Build petgraph
|
||||
let code_graph = self.build_petgraph(parse_output)?;
|
||||
/// Build a code graph from nodes and edges parsed elsewhere, e.g. by a
|
||||
/// parser outside this crate through [`crate::parsers::FileGraph`]: link
|
||||
/// the edges, detect communities and count what was built.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `parse_output` - every file's nodes and edges, kept within the
|
||||
/// engine's node limit by the caller
|
||||
/// * `repo_id` - the repository the build run belongs to
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `CoreError::Graph` when the graph can't be assembled.
|
||||
pub fn assemble(
|
||||
&self,
|
||||
parse_output: ParseOutput,
|
||||
repo_id: &str,
|
||||
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
|
||||
let mut build_run = GraphBuildRun::new(repo_id.to_string());
|
||||
let mut code_graph = self.build_petgraph(parse_output)?;
|
||||
|
||||
// Phase 3: Run community detection
|
||||
let community_count = detect_communities(&code_graph);
|
||||
let community_count = apply_communities(&mut code_graph);
|
||||
|
||||
// Collect language stats
|
||||
let mut languages: Vec<String> = code_graph
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|n| n.language.clone())
|
||||
.collect::<std::collections::HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
languages.sort();
|
||||
// The languages (sorted), files and entry points, in one pass.
|
||||
let mut languages = std::collections::BTreeSet::new();
|
||||
let (mut files, mut entry_points) = (0u32, 0u32);
|
||||
for node in &code_graph.nodes {
|
||||
languages.insert(node.language.as_str());
|
||||
files += u32::from(node.kind == CodeNodeKind::File);
|
||||
entry_points += u32::from(node.is_entry_point);
|
||||
}
|
||||
|
||||
build_run.node_count = code_graph.nodes.len() as u32;
|
||||
build_run.edge_count = code_graph.edges.len() as u32;
|
||||
build_run.community_count = community_count;
|
||||
build_run.languages_parsed = languages;
|
||||
build_run.languages_parsed = languages.into_iter().map(str::to_string).collect();
|
||||
build_run.file_count = Some(files);
|
||||
build_run.entry_point_count = Some(entry_points);
|
||||
build_run.status = GraphBuildStatus::Completed;
|
||||
build_run.completed_at = Some(Utc::now());
|
||||
|
||||
@@ -132,19 +285,15 @@ impl GraphEngine {
|
||||
}
|
||||
|
||||
// Resolve and add explicit edges from parsers
|
||||
let index = NameIndex::new(&nodes, &node_map);
|
||||
let mut resolved_edges = Vec::new();
|
||||
for mut edge in parse_output.edges {
|
||||
let source_idx = node_map.get(&edge.source);
|
||||
let resolved = self.resolve_edge_target(&edge.target, &node_map);
|
||||
let resolved = index.resolve(&edge.target, &edge.file_path);
|
||||
|
||||
if let (Some(&src), Some(tgt)) = (source_idx, resolved) {
|
||||
let resolved_name = node_map
|
||||
.iter()
|
||||
.find(|(_, &idx)| idx == tgt)
|
||||
.map(|(name, _)| name.clone());
|
||||
if let Some(name) = resolved_name {
|
||||
edge.target = name;
|
||||
}
|
||||
// A node's weight is its qualified name.
|
||||
edge.target = graph[tgt].clone();
|
||||
graph.add_edge(src, tgt, edge.kind.clone());
|
||||
resolved_edges.push(edge);
|
||||
}
|
||||
@@ -200,70 +349,6 @@ impl GraphEngine {
|
||||
})
|
||||
}
|
||||
|
||||
/// Try to resolve an edge target to a known node.
|
||||
///
|
||||
/// Resolution strategies (in order):
|
||||
/// 1. Direct qualified-name match
|
||||
/// 2. Suffix match: "foo" matches "src/main.rs::mod::foo"
|
||||
/// 3. Module-path match: "config::load" matches "src/config.rs::load"
|
||||
/// 4. Self-method: "self.method" matches "::method"
|
||||
fn resolve_edge_target(
|
||||
&self,
|
||||
target: &str,
|
||||
node_map: &HashMap<String, NodeIndex>,
|
||||
) -> Option<NodeIndex> {
|
||||
// 1. Direct match
|
||||
if let Some(idx) = node_map.get(target) {
|
||||
return Some(*idx);
|
||||
}
|
||||
|
||||
// 2. Suffix match: "foo" → "path/file.rs::foo"
|
||||
let suffix_pattern = format!("::{target}");
|
||||
let dot_pattern = format!(".{target}");
|
||||
for (qualified, idx) in node_map {
|
||||
if qualified.ends_with(&suffix_pattern) || qualified.ends_with(&dot_pattern) {
|
||||
return Some(*idx);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Module-path match: "config::load" → try matching the last N
|
||||
// segments of the target against node qualified names.
|
||||
// This handles cross-file calls like `crate::config::load` or
|
||||
// `super::handlers::process` where the prefix differs.
|
||||
if target.contains("::") {
|
||||
// Strip common Rust path prefixes
|
||||
let stripped = target
|
||||
.strip_prefix("crate::")
|
||||
.or_else(|| target.strip_prefix("super::"))
|
||||
.or_else(|| target.strip_prefix("self::"))
|
||||
.unwrap_or(target);
|
||||
|
||||
let segments: Vec<&str> = stripped.split("::").collect();
|
||||
// Try matching progressively shorter suffixes
|
||||
for start in 0..segments.len() {
|
||||
let suffix = segments[start..].join("::");
|
||||
let pattern = format!("::{suffix}");
|
||||
for (qualified, idx) in node_map {
|
||||
if qualified.ends_with(&pattern) {
|
||||
return Some(*idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Self-method: "self.method" → "::method"
|
||||
if let Some(method_name) = target.strip_prefix("self.") {
|
||||
let pattern = format!("::{method_name}");
|
||||
for (qualified, idx) in node_map {
|
||||
if qualified.ends_with(&pattern) {
|
||||
return Some(*idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Get the impact analyzer for a built graph
|
||||
pub fn impact_analyzer(code_graph: &CodeGraph) -> ImpactAnalyzer<'_> {
|
||||
ImpactAnalyzer::new(code_graph)
|
||||
@@ -307,61 +392,62 @@ mod tests {
|
||||
map
|
||||
}
|
||||
|
||||
/// Resolve `target` from `src/main.rs` against nodes named `names`,
|
||||
/// returning the qualified name it resolved to.
|
||||
fn resolve(names: &[&str], target: &str) -> Option<String> {
|
||||
resolve_from(names, target, "src/main.rs")
|
||||
}
|
||||
|
||||
fn resolve_from(names: &[&str], target: &str, from_file: &str) -> Option<String> {
|
||||
let nodes: Vec<CodeNode> = names.iter().map(|n| make_node(n)).collect();
|
||||
let node_map = build_test_node_map(names);
|
||||
NameIndex::new(&nodes, &node_map)
|
||||
.resolve(target, from_file)
|
||||
.map(|idx| names[idx.index()].to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_direct_match() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/main.rs::foo", "src/main.rs::bar"]);
|
||||
let result = engine.resolve_edge_target("src/main.rs::foo", &node_map);
|
||||
assert!(result.is_some());
|
||||
assert_eq!(result.unwrap(), node_map["src/main.rs::foo"]);
|
||||
let result = resolve(
|
||||
&["src/main.rs::foo", "src/main.rs::bar"],
|
||||
"src/main.rs::foo",
|
||||
);
|
||||
assert_eq!(result.as_deref(), Some("src/main.rs::foo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_short_name_match() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/main.rs::foo", "src/main.rs::bar"]);
|
||||
let result = engine.resolve_edge_target("foo", &node_map);
|
||||
assert!(result.is_some());
|
||||
assert_eq!(result.unwrap(), node_map["src/main.rs::foo"]);
|
||||
let result = resolve(&["src/main.rs::foo", "src/main.rs::bar"], "foo");
|
||||
assert_eq!(result.as_deref(), Some("src/main.rs::foo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_method_match() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/main.rs::MyStruct::do_thing"]);
|
||||
let result = engine.resolve_edge_target("do_thing", &node_map);
|
||||
let result = resolve(&["src/main.rs::MyStruct::do_thing"], "do_thing");
|
||||
assert!(result.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_self_method() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/main.rs::MyStruct::process"]);
|
||||
let result = engine.resolve_edge_target("self.process", &node_map);
|
||||
let result = resolve(&["src/main.rs::MyStruct::process"], "self.process");
|
||||
assert!(result.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_no_match() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/main.rs::foo"]);
|
||||
let result = engine.resolve_edge_target("nonexistent", &node_map);
|
||||
let result = resolve(&["src/main.rs::foo"], "nonexistent");
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_empty_map() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = HashMap::new();
|
||||
let result = engine.resolve_edge_target("anything", &node_map);
|
||||
let result = resolve(&[], "anything");
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_edge_target_dot_notation() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/app.js.handler"]);
|
||||
let result = engine.resolve_edge_target("handler", &node_map);
|
||||
let result = resolve(&["src/app.js.handler"], "handler");
|
||||
assert!(result.is_some());
|
||||
}
|
||||
|
||||
@@ -504,13 +590,127 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_cross_file_resolution_with_module_path() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let node_map = build_test_node_map(&["src/config.rs::load_config", "src/main.rs::main"]);
|
||||
// "crate::config::load_config" should resolve to "src/config.rs::load_config"
|
||||
let result = engine.resolve_edge_target("crate::config::load_config", &node_map);
|
||||
let result = resolve(
|
||||
&["src/config.rs::load_config", "src/main.rs::main"],
|
||||
"crate::config::load_config",
|
||||
);
|
||||
assert!(result.is_some(), "cross-file crate:: path should resolve");
|
||||
}
|
||||
|
||||
fn node_in(qualified_name: &str, file_path: &str, kind: CodeNodeKind) -> CodeNode {
|
||||
CodeNode {
|
||||
file_path: file_path.to_string(),
|
||||
kind,
|
||||
..make_node(qualified_name)
|
||||
}
|
||||
}
|
||||
|
||||
fn edge_in(source: &str, target: &str, file_path: &str, kind: CodeEdgeKind) -> CodeEdge {
|
||||
CodeEdge {
|
||||
id: None,
|
||||
repo_id: "test".to_string(),
|
||||
graph_build_id: "build1".to_string(),
|
||||
source: source.to_string(),
|
||||
target: target.to_string(),
|
||||
kind,
|
||||
file_path: file_path.to_string(),
|
||||
line_number: Some(1),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_named_functions_resolve_within_the_calling_file() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let mut output = ParseOutput::default();
|
||||
for (name, file) in [
|
||||
("b.c::helper", "b.c"),
|
||||
("a.c::helper", "a.c"),
|
||||
("a.c::main", "a.c"),
|
||||
("b.c::run", "b.c"),
|
||||
] {
|
||||
output
|
||||
.nodes
|
||||
.push(node_in(name, file, CodeNodeKind::Function));
|
||||
}
|
||||
output
|
||||
.edges
|
||||
.push(edge_in("a.c::main", "helper", "a.c", CodeEdgeKind::Calls));
|
||||
output
|
||||
.edges
|
||||
.push(edge_in("b.c::run", "helper", "b.c", CodeEdgeKind::Calls));
|
||||
|
||||
let code_graph = engine.build_petgraph(output).unwrap();
|
||||
let targets: Vec<(&str, &str)> = code_graph
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| matches!(e.kind, CodeEdgeKind::Calls))
|
||||
.map(|e| (e.source.as_str(), e.target.as_str()))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
targets,
|
||||
[("a.c::main", "a.c::helper"), ("b.c::run", "b.c::helper")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_names_resolve_the_same_way_every_time() {
|
||||
let names = ["src/z.rs::helper", "src/b.rs::helper", "src/m.rs::helper"];
|
||||
for _ in 0..20 {
|
||||
assert_eq!(
|
||||
resolve_from(&names, "helper", "src/other.rs").as_deref(),
|
||||
Some("src/b.rs::helper")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn includes_resolve_to_the_header_file() {
|
||||
let engine = GraphEngine::new(1000);
|
||||
let mut output = ParseOutput::default();
|
||||
output
|
||||
.nodes
|
||||
.push(node_in("src/main.c", "src/main.c", CodeNodeKind::File));
|
||||
output.nodes.push(node_in(
|
||||
"src/lib/uart.h",
|
||||
"src/lib/uart.h",
|
||||
CodeNodeKind::File,
|
||||
));
|
||||
for target in [
|
||||
"uart.h",
|
||||
"lib/uart.h",
|
||||
"./lib/uart.h",
|
||||
"stdio.h",
|
||||
"b/uart.h",
|
||||
] {
|
||||
output.edges.push(edge_in(
|
||||
"src/main.c",
|
||||
target,
|
||||
"src/main.c",
|
||||
CodeEdgeKind::Imports,
|
||||
));
|
||||
}
|
||||
|
||||
let code_graph = engine.build_petgraph(output).unwrap();
|
||||
let imports: Vec<&str> = code_graph
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| matches!(e.kind, CodeEdgeKind::Imports))
|
||||
.map(|e| e.target.as_str())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
imports,
|
||||
["src/lib/uart.h", "src/lib/uart.h", "src/lib/uart.h"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_segment_splits_paths_then_members() {
|
||||
assert_eq!(last_segment("src/a.py::Cls.run"), "run");
|
||||
assert_eq!(last_segment("self.run"), "run");
|
||||
assert_eq!(last_segment("crate::config::load"), "load");
|
||||
assert_eq!(last_segment("main"), "main");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_parent_qname() {
|
||||
let node_map = build_test_node_map(&[
|
||||
@@ -529,4 +729,49 @@ mod tests {
|
||||
);
|
||||
assert_eq!(find_parent_qname("src/main.rs", &node_map), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_build_run_counts_files_entry_points_and_languages() {
|
||||
let main = CodeNode {
|
||||
is_entry_point: true,
|
||||
..node_in("src/main.rs::main", "src/main.rs", CodeNodeKind::Function)
|
||||
};
|
||||
let header = CodeNode {
|
||||
language: "c".to_string(),
|
||||
..node_in("inc/x.h", "inc/x.h", CodeNodeKind::File)
|
||||
};
|
||||
let output = ParseOutput {
|
||||
nodes: vec![
|
||||
node_in("src/main.rs", "src/main.rs", CodeNodeKind::File),
|
||||
main,
|
||||
node_in("src/main.rs::helper", "src/main.rs", CodeNodeKind::Function),
|
||||
header,
|
||||
],
|
||||
edges: Vec::new(),
|
||||
};
|
||||
|
||||
let (_, run) = GraphEngine::new(100)
|
||||
.assemble(output, "test")
|
||||
.expect("assembles");
|
||||
|
||||
assert_eq!(run.node_count, 4);
|
||||
assert_eq!(run.file_count, Some(2));
|
||||
assert_eq!(run.entry_point_count, Some(1));
|
||||
assert_eq!(run.languages_parsed, ["c", "rust"]);
|
||||
// Assembled from nodes parsed elsewhere: nothing was read here.
|
||||
assert_eq!(run.unreadable_file_count, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tree_build_records_its_unreadable_files() {
|
||||
let tree = crate::test_tree::TempTree::in_every_encoding("engine");
|
||||
|
||||
let (_, run) = GraphEngine::new(1000)
|
||||
.build_graph(tree.path(), "test", "build")
|
||||
.expect("builds");
|
||||
|
||||
// Five readable files, the broken UTF-16 one and the binary not.
|
||||
assert_eq!(run.file_count, Some(5));
|
||||
assert_eq!(run.unreadable_file_count, Some(2));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
pub mod graph;
|
||||
pub mod parsers;
|
||||
pub mod search;
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::expect_used)]
|
||||
mod test_tree;
|
||||
|
||||
pub use graph::engine::GraphEngine;
|
||||
pub use parsers::registry::ParserRegistry;
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
//! C, as in embedded firmware: functions, structs, unions and enums, calls
|
||||
//! and `#include`s. Interrupt handlers count as entry points, in the
|
||||
//! spellings of the compilers our customers use: avr-gcc's `ISR(vector)`,
|
||||
//! CodeVision's `interrupt [vector]`, SDCC's `__interrupt(n)`, IAR's
|
||||
//! `__interrupt` and GCC's `__attribute__((interrupt))` / `((signal))`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
|
||||
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::common::{parse, text, walk, FileGraph};
|
||||
|
||||
/// avr-gcc's interrupt macros, which tree-sitter reads as a function whose
|
||||
/// return type is the macro and whose name is the vector: `ISR(TIMER1_vect)`.
|
||||
const ISR_MACROS: [&str; 3] = ["ISR", "SIGNAL", "INTERRUPT"];
|
||||
|
||||
/// Parses C sources and headers.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CParser;
|
||||
|
||||
impl CParser {
|
||||
/// A C parser.
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
/// Visit the declarations of a translation unit, including those inside
|
||||
/// `#if`/`#ifdef` blocks, without descending into function bodies.
|
||||
fn walk_declarations(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
walk(root, |node| match node.kind() {
|
||||
"function_definition" => {
|
||||
Self::function(node, source, graph);
|
||||
false
|
||||
}
|
||||
"type_definition" => {
|
||||
Self::typedef(node, source, graph);
|
||||
false
|
||||
}
|
||||
"struct_specifier" | "union_specifier" | "enum_specifier" => {
|
||||
Self::record(node, None, source, graph);
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
|
||||
fn function(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
let Some(declarator) = node.child_by_field_name("declarator") else {
|
||||
return;
|
||||
};
|
||||
let Some(name_node) = declarator_name(declarator) else {
|
||||
return;
|
||||
};
|
||||
let raw_name = text(name_node, source);
|
||||
let return_type = node
|
||||
.child_by_field_name("type")
|
||||
.map(|t| text(t, source))
|
||||
.unwrap_or("");
|
||||
|
||||
// `ISR(TIMER1_vect)` is named after its vector.
|
||||
let isr_macro = ISR_MACROS.contains(&return_type);
|
||||
let name = if isr_macro {
|
||||
format!("{return_type}({raw_name})")
|
||||
} else {
|
||||
raw_name.to_string()
|
||||
};
|
||||
let is_entry = name == "main" || isr_macro || is_interrupt_handler(node, name_node, source);
|
||||
|
||||
let qualified = graph.top_level(&name);
|
||||
graph.node(
|
||||
qualified.clone(),
|
||||
&name,
|
||||
CodeNodeKind::Function,
|
||||
node,
|
||||
is_entry,
|
||||
);
|
||||
if let Some(body) = node.child_by_field_name("body") {
|
||||
Self::calls(body, &qualified, source, graph);
|
||||
}
|
||||
}
|
||||
|
||||
/// `typedef struct { … } name_t;` declares the struct under the typedef's
|
||||
/// name when the struct itself has none.
|
||||
fn typedef(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
let Some(ty) = node.child_by_field_name("type") else {
|
||||
return;
|
||||
};
|
||||
if !matches!(
|
||||
ty.kind(),
|
||||
"struct_specifier" | "union_specifier" | "enum_specifier"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let alias = node
|
||||
.child_by_field_name("declarator")
|
||||
.filter(|d| d.kind() == "type_identifier")
|
||||
.map(|d| text(d, source));
|
||||
Self::record(ty, alias, source, graph);
|
||||
}
|
||||
|
||||
/// A struct, union or enum with a body; a bare reference such as
|
||||
/// `struct point p;` declares nothing.
|
||||
fn record(node: Node<'_>, alias: Option<&str>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
if node.child_by_field_name("body").is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(name) = node
|
||||
.child_by_field_name("name")
|
||||
.map(|n| text(n, source))
|
||||
.or(alias)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let kind = if node.kind() == "enum_specifier" {
|
||||
CodeNodeKind::Enum
|
||||
} else {
|
||||
CodeNodeKind::Struct
|
||||
};
|
||||
let qualified = graph.top_level(name);
|
||||
graph.node(qualified, name, kind, node, false);
|
||||
}
|
||||
|
||||
/// Calls by name inside a function body. Calls through a function pointer
|
||||
/// (`s->cb()`) are left out: their target can't be known from the source.
|
||||
fn calls(body: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) {
|
||||
walk(body, |node| {
|
||||
if node.kind() == "call_expression" {
|
||||
if let Some(callee) = node
|
||||
.child_by_field_name("function")
|
||||
.filter(|f| f.kind() == "identifier")
|
||||
{
|
||||
graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node);
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
fn includes(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
let file = graph.file_path().to_string();
|
||||
walk(root, |node| {
|
||||
if node.kind() == "preproc_include" {
|
||||
if let Some(path) = node.child_by_field_name("path") {
|
||||
let target = text(path, source).trim_matches(['"', '<', '>']);
|
||||
graph.edge(&file, target, CodeEdgeKind::Imports, node);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// Includes sit at file level or inside preprocessor blocks.
|
||||
node.kind() == "translation_unit" || node.kind().starts_with("preproc_")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier a declarator names, through pointers, parentheses and
|
||||
/// attributes: `*make(void)` names `make`.
|
||||
fn declarator_name(declarator: Node<'_>) -> Option<Node<'_>> {
|
||||
let mut current = declarator;
|
||||
loop {
|
||||
if current.kind() == "identifier" {
|
||||
return Some(current);
|
||||
}
|
||||
current = current
|
||||
.child_by_field_name("declarator")
|
||||
.or_else(|| current.named_child(0))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Header tokens that mark an interrupt handler: IAR's and CodeVision's
|
||||
/// `interrupt`, SDCC's `__interrupt(n)`, GCC's `__attribute__((interrupt))`
|
||||
/// and avr-gcc's `__attribute__((signal))`.
|
||||
const INTERRUPT_TOKENS: [&str; 5] = [
|
||||
"interrupt",
|
||||
"__interrupt",
|
||||
"__interrupt__",
|
||||
"signal",
|
||||
"__signal__",
|
||||
];
|
||||
|
||||
/// Whether the function header marks an interrupt handler. The header is
|
||||
/// everything before the body except the name and the parameter list, so
|
||||
/// neither `interrupt_flag_clear` nor a parameter named `signal` counts.
|
||||
/// CodeVision's `interrupt [vector]` stands right before the function, and
|
||||
/// tree-sitter reads it as a separate statement.
|
||||
fn is_interrupt_handler(function: Node<'_>, name: Node<'_>, source: &str) -> bool {
|
||||
let header_end = function
|
||||
.child_by_field_name("body")
|
||||
.map_or(function.end_byte(), |b| b.start_byte());
|
||||
let after_name = parameter_list(function)
|
||||
.map_or(name.end_byte(), |p| p.end_byte())
|
||||
.min(header_end);
|
||||
let header = [
|
||||
&source[function.start_byte()..name.start_byte()],
|
||||
&source[after_name..header_end],
|
||||
];
|
||||
let marked = header.iter().any(|part| {
|
||||
part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.any(|token| INTERRUPT_TOKENS.contains(&token))
|
||||
});
|
||||
marked
|
||||
|| function
|
||||
.prev_named_sibling()
|
||||
.filter(|prev| prev.kind() == "expression_statement")
|
||||
.is_some_and(|prev| text(prev, source).trim_start().starts_with("interrupt"))
|
||||
}
|
||||
|
||||
/// The parameter list of a function definition, found through the same
|
||||
/// declarator chain as its name.
|
||||
fn parameter_list(function: Node<'_>) -> Option<Node<'_>> {
|
||||
let mut current = function.child_by_field_name("declarator")?;
|
||||
loop {
|
||||
if current.kind() == "function_declarator" {
|
||||
return current.child_by_field_name("parameters");
|
||||
}
|
||||
current = current
|
||||
.child_by_field_name("declarator")
|
||||
.or_else(|| current.named_child(0))?;
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageParser for CParser {
|
||||
fn language(&self) -> &str {
|
||||
"c"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["c", "h"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let tree = parse(tree_sitter_c::LANGUAGE.into(), source, "C")?;
|
||||
let mut graph = FileGraph::new(
|
||||
file_path,
|
||||
source.lines().count() as u32,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
"c",
|
||||
);
|
||||
Self::walk_declarations(tree.root_node(), source, &mut graph);
|
||||
Self::includes(tree.root_node(), source, &mut graph);
|
||||
Ok(graph.finish())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::graph::CodeNode;
|
||||
|
||||
const FIRMWARE: &str = r#"
|
||||
#include "uart.h"
|
||||
#include <avr/io.h>
|
||||
static int helper(int a) { return a + 1; }
|
||||
int *make(void) { return 0; }
|
||||
struct point { int x; int y; };
|
||||
struct point origin;
|
||||
typedef struct { int a; } cfg_t;
|
||||
enum mode { A, B };
|
||||
#ifdef DEBUG
|
||||
void trace(void) { helper(0); }
|
||||
#endif
|
||||
interrupt [TIM0_OVF] void timer0_ovf_isr(void) { helper(2); }
|
||||
void ext_isr(void) __interrupt(1) { helper(3); }
|
||||
__attribute__((__interrupt__)) static void avr32_isr(void) { helper(4); }
|
||||
ISR(TIMER1_vect) { helper(5); }
|
||||
void interrupt_flag_clear(void) { }
|
||||
void on_event(int signal) { }
|
||||
interrupt_state_t save_state(void) { return 0; }
|
||||
int main(void) { uart_init(); helper(1); s->cb(2); return 0; }
|
||||
"#;
|
||||
|
||||
fn parsed() -> ParseOutput {
|
||||
CParser::new()
|
||||
.parse_file(Path::new("src/main.c"), FIRMWARE, "repo", "build")
|
||||
.expect("C parses")
|
||||
}
|
||||
|
||||
fn node<'a>(out: &'a ParseOutput, name: &str) -> &'a CodeNode {
|
||||
out.nodes
|
||||
.iter()
|
||||
.find(|n| n.name == name)
|
||||
.unwrap_or_else(|| panic!("no node {name}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_records_and_the_file_become_nodes() {
|
||||
let out = parsed();
|
||||
assert!(matches!(node(&out, "main.c").kind, CodeNodeKind::File));
|
||||
for function in ["helper", "make", "trace", "main"] {
|
||||
assert!(matches!(node(&out, function).kind, CodeNodeKind::Function));
|
||||
}
|
||||
assert!(matches!(node(&out, "point").kind, CodeNodeKind::Struct));
|
||||
assert!(matches!(node(&out, "cfg_t").kind, CodeNodeKind::Struct));
|
||||
assert!(matches!(node(&out, "mode").kind, CodeNodeKind::Enum));
|
||||
assert_eq!(node(&out, "helper").qualified_name, "src/main.c::helper");
|
||||
assert_eq!(node(&out, "helper").start_line, 4);
|
||||
// `struct point origin;` only uses the struct.
|
||||
assert_eq!(out.nodes.iter().filter(|n| n.name == "point").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn main_and_every_interrupt_spelling_are_entry_points() {
|
||||
let out = parsed();
|
||||
for entry in [
|
||||
"main",
|
||||
"timer0_ovf_isr",
|
||||
"ext_isr",
|
||||
"avr32_isr",
|
||||
"ISR(TIMER1_vect)",
|
||||
] {
|
||||
assert!(
|
||||
node(&out, entry).is_entry_point,
|
||||
"{entry} is an entry point"
|
||||
);
|
||||
}
|
||||
for plain in [
|
||||
"helper",
|
||||
"make",
|
||||
"trace",
|
||||
"interrupt_flag_clear",
|
||||
"on_event",
|
||||
"save_state",
|
||||
] {
|
||||
assert!(!node(&out, plain).is_entry_point, "{plain} is not");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calls_by_name_and_includes_become_edges() {
|
||||
let out = parsed();
|
||||
let calls: Vec<(&str, &str)> = out
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| matches!(e.kind, CodeEdgeKind::Calls))
|
||||
.map(|e| (e.source.as_str(), e.target.as_str()))
|
||||
.collect();
|
||||
assert!(calls.contains(&("src/main.c::main", "uart_init")));
|
||||
assert!(calls.contains(&("src/main.c::main", "helper")));
|
||||
assert!(calls.contains(&("src/main.c::ISR(TIMER1_vect)", "helper")));
|
||||
// A call through a function pointer has no target we can name.
|
||||
assert!(!calls.iter().any(|(_, target)| target.contains("cb")));
|
||||
|
||||
let includes: Vec<&str> = out
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| matches!(e.kind, CodeEdgeKind::Imports))
|
||||
.map(|e| e.target.as_str())
|
||||
.collect();
|
||||
assert_eq!(includes, ["uart.h", "avr/io.h"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ifdef_alternatives_share_one_node() {
|
||||
let source = "#ifdef FAST\nvoid init(void) { fast(); }\n#else\nvoid init(void) { slow(); }\n#endif\n";
|
||||
let out = CParser::new()
|
||||
.parse_file(Path::new("i.c"), source, "r", "b")
|
||||
.expect("C parses");
|
||||
assert_eq!(out.nodes.iter().filter(|n| n.name == "init").count(), 1);
|
||||
let callees: Vec<&str> = out
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| matches!(e.kind, CodeEdgeKind::Calls))
|
||||
.map(|e| e.target.as_str())
|
||||
.collect();
|
||||
assert_eq!(callees, ["fast", "slow"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_code_still_yields_what_parses() {
|
||||
let out = CParser::new()
|
||||
.parse_file(
|
||||
Path::new("bad.c"),
|
||||
"void ok(void) {}\nint broken( {\n",
|
||||
"r",
|
||||
"b",
|
||||
)
|
||||
.expect("a syntax error is not a failure");
|
||||
assert!(out.nodes.iter().any(|n| n.name == "ok"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Shared building blocks for the tree-sitter parsers: parsing a file with a
|
||||
//! grammar, collecting its nodes and edges, and walking a subtree without
|
||||
//! recursion.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::{CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind};
|
||||
use compliance_core::traits::graph_builder::ParseOutput;
|
||||
use tree_sitter::{Language, Node, Parser, Tree};
|
||||
|
||||
/// Parse `source` with `language`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `CoreError::Graph` when the grammar can't be loaded (an ABI the
|
||||
/// tree-sitter core doesn't support) or the parser gives up.
|
||||
pub(crate) fn parse(language: Language, source: &str, name: &str) -> Result<Tree, CoreError> {
|
||||
let mut parser = Parser::new();
|
||||
parser
|
||||
.set_language(&language)
|
||||
.map_err(|e| CoreError::Graph(format!("Failed to set {name} language: {e}")))?;
|
||||
parser
|
||||
.parse(source, None)
|
||||
.ok_or_else(|| CoreError::Graph(format!("Failed to parse {name} file")))
|
||||
}
|
||||
|
||||
/// The source text a syntax node covers.
|
||||
pub(crate) fn text<'s>(node: Node<'_>, source: &'s str) -> &'s str {
|
||||
&source[node.byte_range()]
|
||||
}
|
||||
|
||||
/// The 1-based line a syntax node starts on.
|
||||
pub(crate) fn line(node: Node<'_>) -> u32 {
|
||||
node.start_position().row as u32 + 1
|
||||
}
|
||||
|
||||
/// Call `visit` on `root` and every node below it, depth first, with a
|
||||
/// cursor instead of recursion, so deeply nested generated code can't
|
||||
/// overflow the stack. `visit` returns whether to descend into that node.
|
||||
pub(crate) fn walk(root: Node<'_>, mut visit: impl FnMut(Node<'_>) -> bool) {
|
||||
let mut cursor = root.walk();
|
||||
loop {
|
||||
if visit(cursor.node()) && cursor.goto_first_child() {
|
||||
continue;
|
||||
}
|
||||
// No (wanted) children: move to the next sibling, climbing up until
|
||||
// one exists or we are back at `root`.
|
||||
loop {
|
||||
if cursor.node() == root {
|
||||
return;
|
||||
}
|
||||
if cursor.goto_next_sibling() {
|
||||
break;
|
||||
}
|
||||
if !cursor.goto_parent() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes and edges of one file, with the identifiers every one of them
|
||||
/// carries filled in once. The tree-sitter parsers use it, and so can a
|
||||
/// parser outside this crate (the agent's IEC 61131-3 one), which hands the
|
||||
/// result to [`crate::GraphEngine::assemble`].
|
||||
pub struct FileGraph<'a> {
|
||||
repo_id: &'a str,
|
||||
graph_build_id: &'a str,
|
||||
file_path: String,
|
||||
language: &'static str,
|
||||
output: ParseOutput,
|
||||
/// Qualified names already added: overloads (`Get(int)`, `Get(string)`)
|
||||
/// and `#ifdef`/`#else` alternatives share one, and the graph keys nodes
|
||||
/// by it.
|
||||
seen: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl<'a> FileGraph<'a> {
|
||||
/// Start a file's graph with its `File` node.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `file_path` - the file's path relative to the scanned tree
|
||||
/// * `line_count` - the file's number of lines, the `File` node's end line
|
||||
/// * `repo_id`, `graph_build_id` - stamped on every node and edge
|
||||
/// * `language` - the language name the nodes carry, e.g. `"c"`
|
||||
pub fn new(
|
||||
file_path: &Path,
|
||||
line_count: u32,
|
||||
repo_id: &'a str,
|
||||
graph_build_id: &'a str,
|
||||
language: &'static str,
|
||||
) -> Self {
|
||||
let file_path_str = file_path.to_string_lossy().into_owned();
|
||||
let mut graph = Self {
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
file_path: file_path_str.clone(),
|
||||
language,
|
||||
output: ParseOutput::default(),
|
||||
seen: HashMap::new(),
|
||||
};
|
||||
let name = file_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
graph.node_at(
|
||||
file_path_str,
|
||||
name,
|
||||
CodeNodeKind::File,
|
||||
(1, line_count),
|
||||
false,
|
||||
);
|
||||
graph
|
||||
}
|
||||
|
||||
/// The file's path, which is also its `File` node's qualified name.
|
||||
pub fn file_path(&self) -> &str {
|
||||
&self.file_path
|
||||
}
|
||||
|
||||
/// The qualified name of a top-level declaration named `name`.
|
||||
pub fn top_level(&self, name: &str) -> String {
|
||||
format!("{}::{name}", self.file_path)
|
||||
}
|
||||
|
||||
/// Add a declaration spanning the syntax node `node`; see [`Self::node_at`].
|
||||
pub(crate) fn node(
|
||||
&mut self,
|
||||
qualified_name: String,
|
||||
name: &str,
|
||||
kind: CodeNodeKind,
|
||||
node: Node<'_>,
|
||||
is_entry_point: bool,
|
||||
) {
|
||||
let end_line = node.end_position().row as u32 + 1;
|
||||
self.node_at(
|
||||
qualified_name,
|
||||
name.to_string(),
|
||||
kind,
|
||||
(line(node), end_line),
|
||||
is_entry_point,
|
||||
);
|
||||
}
|
||||
|
||||
/// Add a declaration spanning `lines` (1-based start and end, inclusive).
|
||||
/// A second declaration under the same qualified name (an overload, an
|
||||
/// `#else` alternative) adds no node; edges from its body still count,
|
||||
/// from the first one's node, and an entry point makes it one.
|
||||
pub fn node_at(
|
||||
&mut self,
|
||||
qualified_name: String,
|
||||
name: String,
|
||||
kind: CodeNodeKind,
|
||||
(start_line, end_line): (u32, u32),
|
||||
is_entry_point: bool,
|
||||
) {
|
||||
if let Some(&first) = self.seen.get(&qualified_name) {
|
||||
self.output.nodes[first].is_entry_point |= is_entry_point;
|
||||
return;
|
||||
}
|
||||
self.seen
|
||||
.insert(qualified_name.clone(), self.output.nodes.len());
|
||||
self.output.nodes.push(CodeNode {
|
||||
id: None,
|
||||
repo_id: self.repo_id.to_string(),
|
||||
graph_build_id: self.graph_build_id.to_string(),
|
||||
qualified_name,
|
||||
name,
|
||||
kind,
|
||||
file_path: self.file_path.clone(),
|
||||
start_line,
|
||||
end_line,
|
||||
language: self.language.to_string(),
|
||||
community_id: None,
|
||||
is_entry_point,
|
||||
graph_index: None,
|
||||
});
|
||||
}
|
||||
|
||||
/// Add an edge found at the syntax node `at`; see [`Self::edge_at`].
|
||||
pub(crate) fn edge(&mut self, source: &str, target: &str, kind: CodeEdgeKind, at: Node<'_>) {
|
||||
self.edge_at(source, target, kind, line(at));
|
||||
}
|
||||
|
||||
/// Add an edge from `source` to `target`, found on `line`. The engine
|
||||
/// resolves `target` later, so a bare name is fine; one that matches no
|
||||
/// node is dropped.
|
||||
pub fn edge_at(&mut self, source: &str, target: &str, kind: CodeEdgeKind, line: u32) {
|
||||
self.output.edges.push(CodeEdge {
|
||||
id: None,
|
||||
repo_id: self.repo_id.to_string(),
|
||||
graph_build_id: self.graph_build_id.to_string(),
|
||||
source: source.to_string(),
|
||||
target: target.to_string(),
|
||||
kind,
|
||||
file_path: self.file_path.clone(),
|
||||
line_number: Some(line),
|
||||
});
|
||||
}
|
||||
|
||||
/// The finished nodes and edges.
|
||||
pub fn finish(self) -> ParseOutput {
|
||||
self.output
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
//! C#: classes, structs, interfaces, records and enums, their methods and
|
||||
//! constructors, base types, and calls. Entry points are `Main` and what a
|
||||
//! web framework calls from outside: ASP.NET controller actions, Razor page
|
||||
//! handlers, Web Forms pages and controls, ASMX web methods and HTTP
|
||||
//! handlers.
|
||||
//!
|
||||
//! `using` directives are left out: the graph has no namespace nodes they
|
||||
//! could point to.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
|
||||
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::common::{parse, text, walk, FileGraph};
|
||||
|
||||
/// Base types whose methods a web framework calls: MVC and API
|
||||
/// controllers, Razor pages, SignalR hubs, Web Forms pages, controls and
|
||||
/// master pages, and ASMX services.
|
||||
pub(super) const WEB_BASES: [&str; 9] = [
|
||||
"Controller",
|
||||
"ControllerBase",
|
||||
"ApiController",
|
||||
"PageModel",
|
||||
"Hub",
|
||||
"Page",
|
||||
"UserControl",
|
||||
"MasterPage",
|
||||
"WebService",
|
||||
];
|
||||
|
||||
/// Attributes that expose a method over HTTP.
|
||||
pub(super) const ENDPOINT_ATTRIBUTES: [&str; 10] = [
|
||||
"HttpGet",
|
||||
"HttpPost",
|
||||
"HttpPut",
|
||||
"HttpDelete",
|
||||
"HttpPatch",
|
||||
"HttpHead",
|
||||
"HttpOptions",
|
||||
"AcceptVerbs",
|
||||
"Route",
|
||||
"WebMethod",
|
||||
];
|
||||
|
||||
/// Parses C# sources.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CSharpParser;
|
||||
|
||||
/// What a method's entry-point rule needs to know about its type.
|
||||
#[derive(Clone, Copy)]
|
||||
struct TypeContext<'a> {
|
||||
qualified: &'a str,
|
||||
/// The type derives from a web framework base or is an `[ApiController]`.
|
||||
web: bool,
|
||||
/// The type implements `IHttpHandler`, whose `ProcessRequest` the server calls.
|
||||
http_handler: bool,
|
||||
}
|
||||
|
||||
impl CSharpParser {
|
||||
/// A C# parser.
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
/// Visit type declarations at file level, in namespaces (block and
|
||||
/// file-scoped alike), and nested in other types.
|
||||
fn declarations(
|
||||
root: Node<'_>,
|
||||
parent: Option<TypeContext<'_>>,
|
||||
source: &str,
|
||||
graph: &mut FileGraph<'_>,
|
||||
) {
|
||||
walk(root, |node| {
|
||||
if node == root {
|
||||
return true;
|
||||
}
|
||||
match node.kind() {
|
||||
"class_declaration"
|
||||
| "struct_declaration"
|
||||
| "interface_declaration"
|
||||
| "record_declaration"
|
||||
| "enum_declaration" => {
|
||||
Self::type_declaration(node, parent, source, graph);
|
||||
false
|
||||
}
|
||||
"method_declaration" | "constructor_declaration" => {
|
||||
if let Some(ty) = parent {
|
||||
Self::method(node, ty, source, graph);
|
||||
}
|
||||
false
|
||||
}
|
||||
"compilation_unit" | "namespace_declaration" | "declaration_list" => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn type_declaration(
|
||||
node: Node<'_>,
|
||||
parent: Option<TypeContext<'_>>,
|
||||
source: &str,
|
||||
graph: &mut FileGraph<'_>,
|
||||
) {
|
||||
let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else {
|
||||
return;
|
||||
};
|
||||
let qualified = match parent {
|
||||
Some(p) => format!("{}.{name}", p.qualified),
|
||||
None => graph.top_level(name),
|
||||
};
|
||||
let kind = match node.kind() {
|
||||
"struct_declaration" => CodeNodeKind::Struct,
|
||||
"interface_declaration" => CodeNodeKind::Interface,
|
||||
"enum_declaration" => CodeNodeKind::Enum,
|
||||
_ => CodeNodeKind::Class,
|
||||
};
|
||||
graph.node(qualified.clone(), name, kind, node, false);
|
||||
|
||||
let bases = base_types(node, source);
|
||||
for (base, at) in &bases {
|
||||
let edge = if is_interface_name(base) {
|
||||
CodeEdgeKind::Implements
|
||||
} else {
|
||||
CodeEdgeKind::Inherits
|
||||
};
|
||||
graph.edge(&qualified, base, edge, *at);
|
||||
}
|
||||
|
||||
let context = TypeContext {
|
||||
qualified: &qualified,
|
||||
web: bases.iter().any(|(b, _)| WEB_BASES.contains(b))
|
||||
|| attributes(node, source).any(|a| a == "ApiController"),
|
||||
http_handler: bases.iter().any(|(b, _)| *b == "IHttpHandler"),
|
||||
};
|
||||
if let Some(body) = node.child_by_field_name("body") {
|
||||
Self::declarations(body, Some(context), source, graph);
|
||||
}
|
||||
}
|
||||
|
||||
fn method(node: Node<'_>, ty: TypeContext<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else {
|
||||
return;
|
||||
};
|
||||
let qualified = format!("{}.{name}", ty.qualified);
|
||||
let is_entry =
|
||||
node.kind() == "method_declaration" && is_entry_point(node, name, ty, source);
|
||||
graph.node(
|
||||
qualified.clone(),
|
||||
name,
|
||||
CodeNodeKind::Method,
|
||||
node,
|
||||
is_entry,
|
||||
);
|
||||
if let Some(body) = node.child_by_field_name("body") {
|
||||
Self::calls(body, &qualified, source, graph);
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls by method name (`repo.Find(id)` calls `Find`) and constructions
|
||||
/// (`new OrderDto(o)` calls `OrderDto`).
|
||||
fn calls(body: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) {
|
||||
walk(body, |node| {
|
||||
let callee = match node.kind() {
|
||||
"invocation_expression" => {
|
||||
node.child_by_field_name("function").and_then(simple_name)
|
||||
}
|
||||
"object_creation_expression" => {
|
||||
node.child_by_field_name("type").and_then(simple_name)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(callee) = callee {
|
||||
graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node);
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the framework, not our own code, calls this method.
|
||||
fn is_entry_point(method: Node<'_>, name: &str, ty: TypeContext<'_>, source: &str) -> bool {
|
||||
let mut cursor = method.walk();
|
||||
let modifiers: Vec<&str> = method
|
||||
.children(&mut cursor)
|
||||
.filter(|c| c.kind() == "modifier")
|
||||
.map(|c| text(c, source))
|
||||
.collect();
|
||||
let has_modifier = |wanted: &str| modifiers.contains(&wanted);
|
||||
if name == "Main" && has_modifier("static") {
|
||||
return true;
|
||||
}
|
||||
if attributes(method, source).any(|a| ENDPOINT_ATTRIBUTES.contains(&a)) {
|
||||
return true;
|
||||
}
|
||||
if ty.http_handler && name == "ProcessRequest" {
|
||||
return true;
|
||||
}
|
||||
// Controller actions are public. Web Forms event handlers such as
|
||||
// `Page_Load` or `BtnSave_Click` are usually protected; the markup
|
||||
// wires them up.
|
||||
ty.web && (has_modifier("public") || has_modifier("protected"))
|
||||
}
|
||||
|
||||
/// The simple names of a declaration's attributes, without namespace or
|
||||
/// the `Attribute` suffix: `[System.Web.Services.WebMethodAttribute]` is
|
||||
/// `WebMethod`.
|
||||
fn attributes<'s>(declaration: Node<'_>, source: &'s str) -> impl Iterator<Item = &'s str> {
|
||||
let mut names = Vec::new();
|
||||
let mut cursor = declaration.walk();
|
||||
for list in declaration
|
||||
.children(&mut cursor)
|
||||
.filter(|c| c.kind() == "attribute_list")
|
||||
{
|
||||
let mut inner = list.walk();
|
||||
for attribute in list.named_children(&mut inner) {
|
||||
if let Some(name) = attribute.child_by_field_name("name").and_then(simple_name) {
|
||||
let name = text(name, source);
|
||||
names.push(name.strip_suffix("Attribute").unwrap_or(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
names.into_iter()
|
||||
}
|
||||
|
||||
/// The simple names of the types in a declaration's base list, with the
|
||||
/// node each one was named at.
|
||||
fn base_types<'t, 's>(declaration: Node<'t>, source: &'s str) -> Vec<(&'s str, Node<'t>)> {
|
||||
let mut cursor = declaration.walk();
|
||||
let Some(list) = declaration
|
||||
.children(&mut cursor)
|
||||
.find(|c| c.kind() == "base_list")
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut inner = list.walk();
|
||||
list.named_children(&mut inner)
|
||||
.filter_map(|ty| simple_name(ty).map(|n| (text(n, source), ty)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The last identifier of a name: `System.Web.UI.Page` is `Page`,
|
||||
/// `List<int>` is `List`, `repo.Find` is `Find`.
|
||||
fn simple_name(node: Node<'_>) -> Option<Node<'_>> {
|
||||
match node.kind() {
|
||||
"identifier" => Some(node),
|
||||
"qualified_name" | "member_access_expression" => {
|
||||
node.child_by_field_name("name").and_then(simple_name)
|
||||
}
|
||||
"generic_name" => node.named_child(0).filter(|n| n.kind() == "identifier"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// .NET names interfaces `IName`; the base list doesn't say which base is
|
||||
/// the class and which are interfaces, so the convention decides.
|
||||
fn is_interface_name(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
chars.next() == Some('I') && chars.next().is_some_and(|c| c.is_ascii_uppercase())
|
||||
}
|
||||
|
||||
impl LanguageParser for CSharpParser {
|
||||
fn language(&self) -> &str {
|
||||
"csharp"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["cs"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let tree = parse(tree_sitter_c_sharp::LANGUAGE.into(), source, "C#")?;
|
||||
let mut graph = FileGraph::new(
|
||||
file_path,
|
||||
source.lines().count() as u32,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
"csharp",
|
||||
);
|
||||
Self::declarations(tree.root_node(), None, source, &mut graph);
|
||||
Ok(graph.finish())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::graph::CodeNode;
|
||||
|
||||
const WEB_APP: &str = r#"
|
||||
using System;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
namespace Plant.Web.Controllers {
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class OrdersController : ControllerBase, IDisposable {
|
||||
private readonly IRepo _repo;
|
||||
public OrdersController(IRepo repo) { _repo = repo; }
|
||||
[HttpGet("{id}")]
|
||||
public IActionResult Get(int id) { var o = _repo.Find(id); Log(o); return Ok(new OrderDto(o)); }
|
||||
private void Log(object o) { Console.WriteLine(o); }
|
||||
public void Dispose() {}
|
||||
public class Nested { public void Inner() {} }
|
||||
}
|
||||
public interface IRepo { Order Find(int id); }
|
||||
public struct Pt { public int X; }
|
||||
public enum Kind { A, B }
|
||||
public record OrderDto(Order O);
|
||||
public class Repo : IRepo { public Order Find(int id) { return null; } }
|
||||
}
|
||||
namespace Other;
|
||||
public partial class Default : System.Web.UI.Page {
|
||||
protected void Page_Load(object sender, EventArgs e) { Bind(); }
|
||||
private void Bind() { }
|
||||
[System.Web.Services.WebMethodAttribute] public static string Ping() => "pong";
|
||||
}
|
||||
public class Download : IHttpHandler { public void ProcessRequest(HttpContext c) { } }
|
||||
public static class Program { static async Task Main(string[] args) { await Run(); } }
|
||||
"#;
|
||||
|
||||
fn parsed() -> ParseOutput {
|
||||
CSharpParser::new()
|
||||
.parse_file(Path::new("Web/Orders.cs"), WEB_APP, "repo", "build")
|
||||
.expect("C# parses")
|
||||
}
|
||||
|
||||
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
|
||||
let qualified = format!("Web/Orders.cs::{qualified}");
|
||||
out.nodes
|
||||
.iter()
|
||||
.find(|n| n.qualified_name == qualified)
|
||||
.unwrap_or_else(|| panic!("no node {qualified}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types_and_methods_become_nodes_in_every_namespace_form() {
|
||||
let out = parsed();
|
||||
assert!(matches!(
|
||||
node(&out, "OrdersController").kind,
|
||||
CodeNodeKind::Class
|
||||
));
|
||||
assert!(matches!(node(&out, "IRepo").kind, CodeNodeKind::Interface));
|
||||
assert!(matches!(node(&out, "Pt").kind, CodeNodeKind::Struct));
|
||||
assert!(matches!(node(&out, "Kind").kind, CodeNodeKind::Enum));
|
||||
assert!(matches!(node(&out, "OrderDto").kind, CodeNodeKind::Class));
|
||||
// A file-scoped namespace's types are siblings of its declaration.
|
||||
assert!(matches!(node(&out, "Default").kind, CodeNodeKind::Class));
|
||||
for method in [
|
||||
"OrdersController.OrdersController",
|
||||
"OrdersController.Get",
|
||||
"OrdersController.Log",
|
||||
"OrdersController.Nested.Inner",
|
||||
"IRepo.Find",
|
||||
"Default.Page_Load",
|
||||
] {
|
||||
assert!(
|
||||
matches!(node(&out, method).kind, CodeNodeKind::Method),
|
||||
"{method}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framework_called_methods_are_entry_points() {
|
||||
let out = parsed();
|
||||
for entry in [
|
||||
"OrdersController.Get",
|
||||
"OrdersController.Dispose",
|
||||
"Default.Page_Load",
|
||||
"Default.Ping",
|
||||
"Download.ProcessRequest",
|
||||
"Program.Main",
|
||||
] {
|
||||
assert!(
|
||||
node(&out, entry).is_entry_point,
|
||||
"{entry} is an entry point"
|
||||
);
|
||||
}
|
||||
for internal in [
|
||||
"OrdersController.Log",
|
||||
"OrdersController.OrdersController",
|
||||
"OrdersController.Nested.Inner",
|
||||
"Default.Bind",
|
||||
"Repo.Find",
|
||||
] {
|
||||
assert!(!node(&out, internal).is_entry_point, "{internal} is not");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bases_and_calls_become_edges() {
|
||||
let out = parsed();
|
||||
let edges: Vec<(&str, &str, &str)> = out
|
||||
.edges
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let kind = match e.kind {
|
||||
CodeEdgeKind::Calls => "calls",
|
||||
CodeEdgeKind::Inherits => "inherits",
|
||||
CodeEdgeKind::Implements => "implements",
|
||||
_ => "other",
|
||||
};
|
||||
(kind, e.source.as_str(), e.target.as_str())
|
||||
})
|
||||
.collect();
|
||||
let controller = "Web/Orders.cs::OrdersController";
|
||||
assert!(edges.contains(&("inherits", controller, "ControllerBase")));
|
||||
assert!(edges.contains(&("implements", controller, "IDisposable")));
|
||||
assert!(edges.contains(&("inherits", "Web/Orders.cs::Default", "Page")));
|
||||
let get = "Web/Orders.cs::OrdersController.Get";
|
||||
for callee in ["Find", "Log", "Ok", "OrderDto"] {
|
||||
assert!(
|
||||
edges.contains(&("calls", get, callee)),
|
||||
"Get calls {callee}"
|
||||
);
|
||||
}
|
||||
assert!(edges.contains(&("calls", "Web/Orders.cs::Program.Main", "Run")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overloads_share_one_node_and_keep_all_their_calls() {
|
||||
let source = r#"
|
||||
public class Orders : ControllerBase {
|
||||
private void Find(int id) { ById(id); }
|
||||
[HttpGet] public void Find(string name) { ByName(name); }
|
||||
}
|
||||
"#;
|
||||
let out = CSharpParser::new()
|
||||
.parse_file(Path::new("O.cs"), source, "r", "b")
|
||||
.expect("C# parses");
|
||||
let finds: Vec<&CodeNode> = out
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|n| n.qualified_name == "O.cs::Orders.Find")
|
||||
.collect();
|
||||
assert_eq!(finds.len(), 1);
|
||||
assert!(finds[0].is_entry_point, "one overload is an endpoint");
|
||||
let callees: Vec<&str> = out
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| e.source == "O.cs::Orders.Find")
|
||||
.map(|e| e.target.as_str())
|
||||
.collect();
|
||||
assert_eq!(callees, ["ById", "ByName"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interface_names_follow_the_dotnet_convention() {
|
||||
assert!(is_interface_name("IRepo"));
|
||||
assert!(!is_interface_name("Item"));
|
||||
assert!(!is_interface_name("I"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,664 @@
|
||||
//! ASP.NET markup: Razor components and views (`.razor`, `.cshtml`) and Web
|
||||
//! Forms pages, user controls and master pages (`.aspx`, `.ascx`,
|
||||
//! `.master`). Only their code regions hold declarations:
|
||||
//!
|
||||
//! - Razor: `@code { … }` and `@functions { … }` blocks, C# members;
|
||||
//! - Web Forms: `<script runat="server"> … </script>` blocks, members in the
|
||||
//! language the `<%@ Page/Control/Master Language="…" %>` directive names
|
||||
//! (C# when it names none).
|
||||
//!
|
||||
//! Everything else is blanked out, line breaks kept, and each region is
|
||||
//! wrapped in a class named after the file, so the C# or VB parser reads the
|
||||
//! members and every line it reports is the line in the markup file.
|
||||
//! Inline Razor (`@{ … }`, `@if`, `@x.Y()`) and Web Forms render blocks
|
||||
//! (`<% … %>`) mix code with markup and are left out.
|
||||
//!
|
||||
//! The framework calls a markup file's methods from the markup itself
|
||||
//! (`@onclick="Save"`, `OnClick="BtnSave_Click"`, `<%# GetTitle() %>`) and
|
||||
//! through lifecycle hooks (`OnInitialized`, `Page_Load`), so those are
|
||||
//! entry points.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::CodeNodeKind;
|
||||
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
|
||||
|
||||
use super::common::FileGraph;
|
||||
use super::csharp::CSharpParser;
|
||||
use super::vb::VbParser;
|
||||
|
||||
/// Methods a Razor component's or Web Forms page's framework calls without
|
||||
/// the markup naming them.
|
||||
const LIFECYCLE_HOOKS: [&str; 22] = [
|
||||
// Blazor components
|
||||
"OnInitialized",
|
||||
"OnInitializedAsync",
|
||||
"OnParametersSet",
|
||||
"OnParametersSetAsync",
|
||||
"OnAfterRender",
|
||||
"OnAfterRenderAsync",
|
||||
"SetParametersAsync",
|
||||
"ShouldRender",
|
||||
"Dispose",
|
||||
"DisposeAsync",
|
||||
// Web Forms, wired by AutoEventWireup
|
||||
"Page_PreInit",
|
||||
"Page_Init",
|
||||
"Page_InitComplete",
|
||||
"Page_PreLoad",
|
||||
"Page_Load",
|
||||
"Page_LoadComplete",
|
||||
"Page_PreRender",
|
||||
"Page_PreRenderComplete",
|
||||
"Page_SaveStateComplete",
|
||||
"Page_Unload",
|
||||
"Page_Error",
|
||||
"Page_DataBind",
|
||||
];
|
||||
|
||||
/// Parses the code regions of ASP.NET markup files.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MarkupParser;
|
||||
|
||||
/// The language of a markup file's code regions.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum CodeLanguage {
|
||||
CSharp,
|
||||
Vb,
|
||||
}
|
||||
|
||||
/// One code region: the markup in `markup_start..code_start` (the
|
||||
/// `@code` keyword, the `<script>` tag) is replaced by `open`, the code in
|
||||
/// `code_start..code_end` is kept, and the markup in `code_end..markup_end`
|
||||
/// (the `</script>` tag) is replaced by `close`.
|
||||
#[derive(Debug)]
|
||||
struct Region {
|
||||
markup_start: usize,
|
||||
code_start: usize,
|
||||
code_end: usize,
|
||||
markup_end: usize,
|
||||
}
|
||||
|
||||
impl MarkupParser {
|
||||
/// An ASP.NET markup parser.
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageParser for MarkupParser {
|
||||
fn language(&self) -> &str {
|
||||
"aspnet-markup"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["razor", "cshtml", "aspx", "ascx", "master"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let ext = file_path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
let razor = matches!(ext.as_str(), "razor" | "cshtml");
|
||||
let (language, inherits, regions) = if razor {
|
||||
(CodeLanguage::CSharp, None, razor_regions(source))
|
||||
} else {
|
||||
let (language, inherits) = web_forms_directive(source);
|
||||
(language, inherits, web_forms_regions(source))
|
||||
};
|
||||
if regions.is_empty() {
|
||||
// Markup only: the file is part of the application all the same.
|
||||
let lines = source.lines().count() as u32;
|
||||
let name = match language {
|
||||
CodeLanguage::CSharp => "csharp",
|
||||
CodeLanguage::Vb => "vb",
|
||||
};
|
||||
return Ok(FileGraph::new(file_path, lines, repo_id, graph_build_id, name).finish());
|
||||
}
|
||||
// A Web Forms page's class is the one its directive names (Visual
|
||||
// Studio names `Default.aspx`'s `_Default`, `Default` being a VB
|
||||
// keyword); a Razor file's is named after the file.
|
||||
let class = inherits.unwrap_or_else(|| class_name(file_path));
|
||||
let (open, close) = match (razor, language) {
|
||||
// The `@code` keyword is followed by the block's own braces.
|
||||
(true, _) => (format!("class {class} "), ""),
|
||||
(false, CodeLanguage::CSharp) => (format!("class {class} {{"), "}"),
|
||||
(false, CodeLanguage::Vb) => (format!("Class {class}"), "End Class"),
|
||||
};
|
||||
let code = blank_markup(source, ®ions, &open, close);
|
||||
let mut output = match language {
|
||||
CodeLanguage::CSharp => {
|
||||
CSharpParser::new().parse_file(file_path, &code, repo_id, graph_build_id)?
|
||||
}
|
||||
CodeLanguage::Vb => {
|
||||
VbParser::new().parse_file(file_path, &code, repo_id, graph_build_id)?
|
||||
}
|
||||
};
|
||||
let referenced = markup_references(source, ®ions);
|
||||
for node in output
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.filter(|n| matches!(n.kind, CodeNodeKind::Method))
|
||||
{
|
||||
let name = node.name.to_ascii_lowercase();
|
||||
if referenced.contains(&name)
|
||||
|| LIFECYCLE_HOOKS
|
||||
.iter()
|
||||
.any(|h| h.eq_ignore_ascii_case(&name))
|
||||
{
|
||||
node.is_entry_point = true;
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
/// The class a markup file compiles to, named after the file: `Counter` for
|
||||
/// `Counter.razor`, `_Layout` for `_Layout.cshtml`, as an identifier.
|
||||
fn class_name(file_path: &Path) -> String {
|
||||
let stem = file_path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("Page");
|
||||
let mut name: String = stem
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || c == '_' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if name.starts_with(|c: char| c.is_ascii_digit()) || name.is_empty() {
|
||||
name.insert(0, '_');
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
/// `source` with everything outside `regions` replaced by spaces (line
|
||||
/// breaks kept), each region's opening markup by `open` and its closing
|
||||
/// markup by `close`.
|
||||
fn blank_markup(source: &str, regions: &[Region], open: &str, close: &str) -> String {
|
||||
let mut code = String::with_capacity(source.len());
|
||||
let blank = |code: &mut String, markup: &str| {
|
||||
code.extend(markup.chars().map(|c| if c == '\n' { '\n' } else { ' ' }));
|
||||
};
|
||||
let mut at = 0;
|
||||
for region in regions {
|
||||
blank(&mut code, &source[at..region.markup_start]);
|
||||
code.push_str(open);
|
||||
// The rest of the opening markup, if it spans lines (a `<script>`
|
||||
// tag with its attributes on several), keeps its line breaks.
|
||||
blank(&mut code, &source[region.markup_start..region.code_start]);
|
||||
code.push_str(&source[region.code_start..region.code_end]);
|
||||
code.push_str(close);
|
||||
blank(&mut code, &source[region.code_end..region.markup_end]);
|
||||
at = region.markup_end;
|
||||
}
|
||||
blank(&mut code, &source[at..]);
|
||||
code
|
||||
}
|
||||
|
||||
/// The `@code { … }` and `@functions { … }` blocks of a Razor file, outside
|
||||
/// Razor comments (`@* … *@`). The opening markup is the keyword; the block
|
||||
/// with its braces is the code.
|
||||
fn razor_regions(source: &str) -> Vec<Region> {
|
||||
let bytes = source.as_bytes();
|
||||
let mut regions = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < bytes.len() {
|
||||
if bytes[at..].starts_with(b"@*") {
|
||||
at = find(bytes, at + 2, b"*@").map_or(bytes.len(), |end| end + 2);
|
||||
continue;
|
||||
}
|
||||
if bytes[at] == b'@' && (at == 0 || !is_identifier_byte(bytes[at - 1])) {
|
||||
let keyword = [b"code".as_slice(), b"functions"]
|
||||
.into_iter()
|
||||
.find(|k| bytes[at + 1..].starts_with(k));
|
||||
if let Some(keyword) = keyword {
|
||||
let after = at + 1 + keyword.len();
|
||||
let open = after
|
||||
+ bytes[after..]
|
||||
.iter()
|
||||
.take_while(|b| b.is_ascii_whitespace())
|
||||
.count();
|
||||
if bytes.get(open) == Some(&b'{') {
|
||||
if let Some(close) = matching_brace(bytes, open) {
|
||||
regions.push(Region {
|
||||
markup_start: at,
|
||||
code_start: after,
|
||||
code_end: close + 1,
|
||||
markup_end: close + 1,
|
||||
});
|
||||
at = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// The `<script runat="server">` blocks of a Web Forms file. The opening
|
||||
/// markup is the tag, the closing markup the `</script>` tag.
|
||||
fn web_forms_regions(source: &str) -> Vec<Region> {
|
||||
// ASCII lowercase keeps every byte offset.
|
||||
let lower = source.to_ascii_lowercase();
|
||||
let bytes = lower.as_bytes();
|
||||
let mut regions = Vec::new();
|
||||
let mut at = 0;
|
||||
while let Some(tag) = find(bytes, at, b"<script") {
|
||||
let Some(tag_end) = find(bytes, tag, b">") else {
|
||||
break;
|
||||
};
|
||||
let attributes: String = lower[tag..tag_end]
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect();
|
||||
let server = ["runat=\"server\"", "runat='server'", "runat=server"]
|
||||
.iter()
|
||||
.any(|a| attributes.contains(a));
|
||||
let Some(close) = find(bytes, tag_end, b"</script") else {
|
||||
break;
|
||||
};
|
||||
let close_end = find(bytes, close, b">").map_or(bytes.len(), |end| end + 1);
|
||||
if server {
|
||||
regions.push(Region {
|
||||
markup_start: tag,
|
||||
code_start: tag_end + 1,
|
||||
code_end: close,
|
||||
markup_end: close_end,
|
||||
});
|
||||
}
|
||||
at = close_end;
|
||||
}
|
||||
regions
|
||||
}
|
||||
|
||||
/// The language and class a Web Forms file's directive names: `<%@ Page
|
||||
/// Language="VB" Inherits="Plant._Default" %>` is VB and `_Default`. No
|
||||
/// language, or another one, is C#.
|
||||
fn web_forms_directive(source: &str) -> (CodeLanguage, Option<String>) {
|
||||
// ASCII lowercase keeps every byte offset, so a match in `lower` is the
|
||||
// same range in `source`.
|
||||
let lower = source.to_ascii_lowercase();
|
||||
let bytes = lower.as_bytes();
|
||||
let mut at = 0;
|
||||
while let Some(start) = find(bytes, at, b"<%@") {
|
||||
let end = find(bytes, start, b"%>").unwrap_or(bytes.len());
|
||||
let directive = start + 3..end;
|
||||
let kind = lower[directive.clone()]
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
if matches!(kind, "page" | "control" | "master") {
|
||||
let value = |name: &str| {
|
||||
attribute_value(&lower, &source[directive.clone()], directive.start, name)
|
||||
};
|
||||
let language = match value("language") {
|
||||
Some(v) if v.to_ascii_lowercase().starts_with("vb") => CodeLanguage::Vb,
|
||||
_ => CodeLanguage::CSharp,
|
||||
};
|
||||
// `Plant._Default, Plant` names the class with its assembly.
|
||||
let inherits = value("inherits")
|
||||
.and_then(|v| v.split(',').next())
|
||||
.and_then(|v| v.trim().rsplit('.').next())
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_string);
|
||||
return (language, inherits);
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
(CodeLanguage::CSharp, None)
|
||||
}
|
||||
|
||||
/// The value of the attribute `name` in a directive, `directive` being its
|
||||
/// text in the original case and `offset` where it starts in `lower`.
|
||||
fn attribute_value<'s>(
|
||||
lower: &str,
|
||||
directive: &'s str,
|
||||
offset: usize,
|
||||
name: &str,
|
||||
) -> Option<&'s str> {
|
||||
let lower_directive = &lower[offset..offset + directive.len()];
|
||||
let mut from = 0;
|
||||
while let Some(found) = lower_directive[from..].find(name) {
|
||||
let at = from + found;
|
||||
from = at + name.len();
|
||||
// A whole attribute name: not the end of a longer one.
|
||||
if at > 0 && is_identifier_byte(lower_directive.as_bytes()[at - 1]) {
|
||||
continue;
|
||||
}
|
||||
let rest = directive[from..].trim_start();
|
||||
let Some(rest) = rest.strip_prefix('=') else {
|
||||
continue;
|
||||
};
|
||||
let rest = rest.trim_start();
|
||||
let (quote, rest) = match rest.chars().next() {
|
||||
Some(q @ ('"' | '\'')) => (Some(q), &rest[1..]),
|
||||
_ => (None, rest),
|
||||
};
|
||||
let end = match quote {
|
||||
Some(q) => rest.find(q),
|
||||
None => rest.find(char::is_whitespace),
|
||||
}
|
||||
.unwrap_or(rest.len());
|
||||
return Some(&rest[..end]);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Lowercased identifiers the markup outside `regions` refers to: in
|
||||
/// attribute values (`OnClick="BtnSave_Click"`, `@onclick="Save"`), right
|
||||
/// after an `@` (`@Title()`), and in Web Forms code blocks (`<%# Eval(…) %>`).
|
||||
/// Text between tags is not code and doesn't count.
|
||||
fn markup_references(source: &str, regions: &[Region]) -> HashSet<String> {
|
||||
let mut slices = Vec::with_capacity(regions.len() + 1);
|
||||
let mut at = 0;
|
||||
for region in regions {
|
||||
slices.push(&source[at..region.markup_start]);
|
||||
at = region.markup_end;
|
||||
}
|
||||
slices.push(&source[at..]);
|
||||
|
||||
let mut found = HashSet::new();
|
||||
for slice in slices {
|
||||
let bytes = slice.as_bytes();
|
||||
let (mut in_tag, mut quote, mut server_block) = (false, None::<u8>, false);
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let b = bytes[i];
|
||||
if quote.is_none() && !server_block && bytes[i..].starts_with(b"<%") {
|
||||
server_block = true;
|
||||
} else if server_block && bytes[i..].starts_with(b"%>") {
|
||||
server_block = false;
|
||||
} else if !server_block && quote == Some(b) {
|
||||
quote = None;
|
||||
} else if in_tag && !server_block && quote.is_none() && (b == b'"' || b == b'\'') {
|
||||
quote = Some(b);
|
||||
} else if !server_block && quote.is_none() && b == b'<' {
|
||||
in_tag = bytes
|
||||
.get(i + 1)
|
||||
.is_some_and(|n| n.is_ascii_alphabetic() || *n == b'/');
|
||||
} else if !server_block && quote.is_none() && b == b'>' {
|
||||
in_tag = false;
|
||||
} else if is_identifier_start(b) && (i == 0 || !is_identifier_byte(bytes[i - 1])) {
|
||||
let len = bytes[i..]
|
||||
.iter()
|
||||
.take_while(|&&c| is_identifier_byte(c))
|
||||
.count();
|
||||
let after_at = i > 0 && bytes[i - 1] == b'@';
|
||||
if quote.is_some() || server_block || after_at {
|
||||
found.insert(slice[i..i + len].to_ascii_lowercase());
|
||||
}
|
||||
i += len;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The index of the `}` that closes the `{` at `open`, skipping C# strings,
|
||||
/// characters and comments.
|
||||
fn matching_brace(bytes: &[u8], open: usize) -> Option<usize> {
|
||||
let mut depth = 0usize;
|
||||
let mut i = open;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'{' => depth += 1,
|
||||
b'}' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Some(i);
|
||||
}
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'/') => {
|
||||
i = find(bytes, i, b"\n").unwrap_or(bytes.len());
|
||||
continue;
|
||||
}
|
||||
b'/' if bytes.get(i + 1) == Some(&b'*') => {
|
||||
i = find(bytes, i + 2, b"*/").map_or(bytes.len(), |end| end + 2);
|
||||
continue;
|
||||
}
|
||||
b'"' if bytes[i..].starts_with(b"\"\"\"") => {
|
||||
i = find(bytes, i + 3, b"\"\"\"").map_or(bytes.len(), |end| end + 3);
|
||||
continue;
|
||||
}
|
||||
b'"' => {
|
||||
let verbatim = i > 0
|
||||
&& (bytes[i - 1] == b'@'
|
||||
|| (bytes[i - 1] == b'$' && i > 1 && bytes[i - 2] == b'@'));
|
||||
i = string_end(bytes, i + 1, verbatim);
|
||||
continue;
|
||||
}
|
||||
b'\'' => {
|
||||
// `'x'`, `'\''`: skip the escaped character, then to the quote.
|
||||
let start = i + 1 + usize::from(bytes.get(i + 1) == Some(&b'\\'));
|
||||
i = find(bytes, start + 1, b"'").map_or(bytes.len(), |end| end + 1);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The index after the `"` that ends a string starting at `from`: a
|
||||
/// verbatim string (`@"…"`) escapes a quote by doubling it, a regular one
|
||||
/// with a backslash and ends at the line's end at the latest.
|
||||
fn string_end(bytes: &[u8], from: usize, verbatim: bool) -> usize {
|
||||
let mut i = from;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'"' if verbatim && bytes.get(i + 1) == Some(&b'"') => i += 2,
|
||||
b'"' => return i + 1,
|
||||
b'\\' if !verbatim => i += 2,
|
||||
b'\n' if !verbatim => return i,
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
bytes.len()
|
||||
}
|
||||
|
||||
/// The first index of `needle` in `bytes` at or after `from`.
|
||||
fn find(bytes: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
|
||||
bytes
|
||||
.get(from..)?
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
.map(|at| from + at)
|
||||
}
|
||||
|
||||
fn is_identifier_start(b: u8) -> bool {
|
||||
b.is_ascii_alphabetic() || b == b'_'
|
||||
}
|
||||
|
||||
fn is_identifier_byte(b: u8) -> bool {
|
||||
b.is_ascii_alphanumeric() || b == b'_'
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::graph::CodeNode;
|
||||
|
||||
const COUNTER: &str = r#"@page "/counter"
|
||||
@* @code { void Commented() { } } *@
|
||||
<h1>Counter: @currentCount</h1>
|
||||
<p>Save your work</p>
|
||||
<button class="btn" @onclick="IncrementCount">Click me</button>
|
||||
|
||||
@code {
|
||||
private int currentCount = 0;
|
||||
private string label = "}";
|
||||
|
||||
protected override void OnInitialized() { Reset(); }
|
||||
|
||||
private void IncrementCount()
|
||||
{
|
||||
// a brace in a comment: }
|
||||
currentCount++;
|
||||
Log(@"C:\path ""quoted"" }");
|
||||
}
|
||||
|
||||
private void Reset() { currentCount = 0; }
|
||||
|
||||
private void Save() { }
|
||||
}
|
||||
"#;
|
||||
|
||||
const DEFAULT_ASPX: &str = r#"<%@ Page Language="VB" AutoEventWireup="true" Inherits="Plant.DefaultPage" %>
|
||||
<html>
|
||||
<body>
|
||||
<script runat="server">
|
||||
Protected Sub Page_Load(sender As Object, e As EventArgs)
|
||||
Bind()
|
||||
End Sub
|
||||
|
||||
Protected Sub BtnSave_Click(sender As Object, e As EventArgs)
|
||||
End Sub
|
||||
|
||||
Private Sub Bind()
|
||||
End Sub
|
||||
</script>
|
||||
<script type="text/javascript">function notServer() { }</script>
|
||||
<form runat="server">
|
||||
<asp:Button ID="BtnSave" runat="server" OnClick="BtnSave_Click" Text="Save" />
|
||||
<%# Title() %>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
"#;
|
||||
|
||||
fn parse(path: &str, source: &str) -> ParseOutput {
|
||||
MarkupParser::new()
|
||||
.parse_file(Path::new(path), source, "repo", "build")
|
||||
.expect("markup parses")
|
||||
}
|
||||
|
||||
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
|
||||
out.nodes
|
||||
.iter()
|
||||
.find(|n| n.qualified_name == qualified)
|
||||
.unwrap_or_else(|| panic!("no node {qualified}: {:?}", out.nodes))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_razor_components_code_block_becomes_its_class() {
|
||||
let out = parse("Pages/Counter.razor", COUNTER);
|
||||
let class = node(&out, "Pages/Counter.razor::Counter");
|
||||
assert!(matches!(class.kind, CodeNodeKind::Class));
|
||||
assert_eq!(class.language, "csharp");
|
||||
// Lines are the markup file's lines.
|
||||
let increment = node(&out, "Pages/Counter.razor::Counter.IncrementCount");
|
||||
assert_eq!((increment.start_line, increment.end_line), (13, 18));
|
||||
// Braces in strings and comments don't end the block early.
|
||||
node(&out, "Pages/Counter.razor::Counter.Save");
|
||||
// A commented-out block is not code.
|
||||
assert!(!out.nodes.iter().any(|n| n.name == "Commented"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn methods_the_markup_or_the_framework_calls_are_entry_points() {
|
||||
let out = parse("Pages/Counter.razor", COUNTER);
|
||||
let entry =
|
||||
|name: &str| node(&out, &format!("Pages/Counter.razor::Counter.{name}")).is_entry_point;
|
||||
assert!(entry("IncrementCount"), "wired by @onclick");
|
||||
assert!(entry("OnInitialized"), "a lifecycle hook");
|
||||
assert!(!entry("Reset"), "called from code only");
|
||||
// "Save" is only text between tags.
|
||||
assert!(!entry("Save"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_forms_page_in_vb_reads_its_server_script() {
|
||||
let out = parse("Default.aspx", DEFAULT_ASPX);
|
||||
let page = node(&out, "Default.aspx::DefaultPage");
|
||||
assert_eq!(page.language, "vb");
|
||||
let load = node(&out, "Default.aspx::DefaultPage.Page_Load");
|
||||
assert_eq!((load.start_line, load.end_line), (5, 7));
|
||||
assert!(load.is_entry_point, "AutoEventWireup");
|
||||
assert!(
|
||||
node(&out, "Default.aspx::DefaultPage.BtnSave_Click").is_entry_point,
|
||||
"OnClick"
|
||||
);
|
||||
assert!(!node(&out, "Default.aspx::DefaultPage.Bind").is_entry_point);
|
||||
// The client-side script is not server code.
|
||||
assert!(!out.nodes.iter().any(|n| n.name == "notServer"));
|
||||
assert!(out
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.source == "Default.aspx::DefaultPage.Page_Load" && e.target == "Bind"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_web_forms_control_without_a_language_is_csharp() {
|
||||
let source = "<%@ Control %>\n<script runat=server>\n protected void Page_Load(object s, EventArgs e) { Go(); }\n void Go() { }\n</script>\n";
|
||||
let out = parse("Menu.ascx", source);
|
||||
let load = node(&out, "Menu.ascx::Menu.Page_Load");
|
||||
assert_eq!(load.language, "csharp");
|
||||
assert_eq!(load.start_line, 3);
|
||||
assert!(out
|
||||
.edges
|
||||
.iter()
|
||||
.any(|e| e.source == "Menu.ascx::Menu.Page_Load" && e.target == "Go"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_directive_names_the_class_and_language() {
|
||||
let (language, class) = web_forms_directive(
|
||||
"<%@ Master language='vb' Inherits=\"Plant._Site, Plant\" CodeFileBaseClass=\"X\" %>",
|
||||
);
|
||||
assert_eq!(language, CodeLanguage::Vb);
|
||||
assert_eq!(class.as_deref(), Some("_Site"));
|
||||
// `CodeFileBaseClass` doesn't count as `Inherits`, nor a later
|
||||
// directive as the page's.
|
||||
let (language, class) = web_forms_directive(
|
||||
"<%@ Register Src=\"a.ascx\" %><%@ Page CodeFileBaseClass=\"Base\" %>",
|
||||
);
|
||||
assert_eq!(language, CodeLanguage::CSharp);
|
||||
assert_eq!(class, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_view_without_code_is_a_file_only() {
|
||||
let out = parse(
|
||||
"Views/Home/Index.cshtml",
|
||||
"@model HomeVm\n<h1>@Model.Title</h1>\n",
|
||||
);
|
||||
assert_eq!(out.nodes.len(), 1);
|
||||
assert!(matches!(out.nodes[0].kind, CodeNodeKind::File));
|
||||
assert_eq!(out.nodes[0].end_line, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_hands_markup_files_to_this_parser() {
|
||||
let registry = super::super::registry::ParserRegistry::new();
|
||||
for ext in ["razor", "cshtml", "aspx", "ascx", "master"] {
|
||||
assert!(registry.supports_extension(ext), "{ext}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_name_is_an_identifier() {
|
||||
assert_eq!(class_name(Path::new("Pages/Counter.razor")), "Counter");
|
||||
assert_eq!(class_name(Path::new("_Layout.cshtml")), "_Layout");
|
||||
assert_eq!(class_name(Path::new("404-page.aspx")), "_404_page");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
pub mod c;
|
||||
mod common;
|
||||
pub mod csharp;
|
||||
pub mod javascript;
|
||||
pub mod markup;
|
||||
pub mod python;
|
||||
pub mod registry;
|
||||
pub mod rust_parser;
|
||||
pub mod typescript;
|
||||
pub mod vb;
|
||||
|
||||
pub use common::FileGraph;
|
||||
@@ -3,12 +3,26 @@ use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
|
||||
use tracing::{debug, info};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use super::c::CParser;
|
||||
use super::csharp::CSharpParser;
|
||||
use super::javascript::JavaScriptParser;
|
||||
use super::markup::MarkupParser;
|
||||
use super::python::PythonParser;
|
||||
use super::rust_parser::RustParser;
|
||||
use super::typescript::TypeScriptParser;
|
||||
use super::vb::VbParser;
|
||||
|
||||
/// What [`ParserRegistry::parse_directory`] made of a tree.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DirectoryParse {
|
||||
/// Every parsed file's nodes and edges.
|
||||
pub output: ParseOutput,
|
||||
/// Source files of a supported language that could not be read as text
|
||||
/// (I/O error, malformed UTF-16, binary): left out of `output`.
|
||||
pub unreadable_files: u32,
|
||||
}
|
||||
|
||||
/// Registry of language parsers, indexed by file extension
|
||||
pub struct ParserRegistry {
|
||||
@@ -24,6 +38,10 @@ impl ParserRegistry {
|
||||
Box::new(PythonParser::new()),
|
||||
Box::new(JavaScriptParser::new()),
|
||||
Box::new(TypeScriptParser::new()),
|
||||
Box::new(CParser::new()),
|
||||
Box::new(CSharpParser::new()),
|
||||
Box::new(VbParser::new()),
|
||||
Box::new(MarkupParser::new()),
|
||||
];
|
||||
|
||||
let mut extension_map = HashMap::new();
|
||||
@@ -75,15 +93,36 @@ impl ParserRegistry {
|
||||
Ok(Some(output))
|
||||
}
|
||||
|
||||
/// Parse all supported files in a directory tree
|
||||
/// Parse all supported files in a directory tree.
|
||||
///
|
||||
/// Each file is decoded by [`compliance_core::encoding::read_source`] (UTF-8,
|
||||
/// UTF-16 with a BOM, Windows-1252); a file still not readable as text
|
||||
/// is counted, not parsed.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `dir` - the tree's root; node paths are relative to it
|
||||
/// * `repo_id` - the repository the nodes belong to
|
||||
/// * `graph_build_id` - the build the nodes belong to
|
||||
/// * `max_nodes` - parsing stops once this many nodes are collected
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// The nodes and edges of every parsed file, and how many files could
|
||||
/// not be read.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `CoreError::Graph` when a directory can't be listed, and a
|
||||
/// parser's error.
|
||||
pub fn parse_directory(
|
||||
&self,
|
||||
dir: &Path,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
max_nodes: u32,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let mut combined = ParseOutput::default();
|
||||
) -> Result<DirectoryParse, CoreError> {
|
||||
let mut combined = DirectoryParse::default();
|
||||
let mut node_count: u32 = 0;
|
||||
|
||||
self.walk_directory(
|
||||
@@ -96,9 +135,17 @@ impl ParserRegistry {
|
||||
&mut combined,
|
||||
)?;
|
||||
|
||||
// One line per build; the paths are logged at debug level only.
|
||||
if combined.unreadable_files > 0 {
|
||||
warn!(
|
||||
unreadable_files = combined.unreadable_files,
|
||||
"Source files left out of the code graph: not readable as text"
|
||||
);
|
||||
}
|
||||
info!(
|
||||
nodes = combined.nodes.len(),
|
||||
edges = combined.edges.len(),
|
||||
nodes = combined.output.nodes.len(),
|
||||
edges = combined.output.edges.len(),
|
||||
unreadable_files = combined.unreadable_files,
|
||||
"Directory parsing complete"
|
||||
);
|
||||
|
||||
@@ -113,7 +160,7 @@ impl ParserRegistry {
|
||||
graph_build_id: &str,
|
||||
max_nodes: u32,
|
||||
node_count: &mut u32,
|
||||
combined: &mut ParseOutput,
|
||||
combined: &mut DirectoryParse,
|
||||
) -> Result<(), CoreError> {
|
||||
let entries = std::fs::read_dir(dir).map_err(|e| {
|
||||
CoreError::Graph(format!("Failed to read directory {}: {e}", dir.display()))
|
||||
@@ -132,6 +179,9 @@ impl ParserRegistry {
|
||||
|| name == "vendor"
|
||||
|| name == "dist"
|
||||
|| name == "build"
|
||||
// .NET's intermediate output: generated sources such as
|
||||
// `*.g.cs` and the Razor compiler's `*.razor.g.cs`.
|
||||
|| name == "obj"
|
||||
|| name == ".git"
|
||||
{
|
||||
continue;
|
||||
@@ -162,15 +212,19 @@ impl ParserRegistry {
|
||||
// Use relative path from base
|
||||
let rel_path = path.strip_prefix(base).unwrap_or(&path);
|
||||
|
||||
let source = match std::fs::read_to_string(&path) {
|
||||
Ok(s) => s,
|
||||
Err(_) => continue, // Skip binary/unreadable files
|
||||
let source = match compliance_core::encoding::read_source(&path) {
|
||||
Ok(text) => text,
|
||||
Err(error) => {
|
||||
debug!(file = %rel_path.display(), %error, "Source file not readable");
|
||||
combined.unreadable_files += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(output) = self.parse_file(rel_path, &source, repo_id, graph_build_id)? {
|
||||
*node_count += output.nodes.len() as u32;
|
||||
combined.nodes.extend(output.nodes);
|
||||
combined.edges.extend(output.edges);
|
||||
combined.output.nodes.extend(output.nodes);
|
||||
combined.output.edges.extend(output.edges);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -290,6 +344,76 @@ mod tests {
|
||||
assert!(!output.nodes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_in_every_encoding_parse_and_unreadable_ones_are_counted() {
|
||||
// Arrange
|
||||
let tree = crate::test_tree::TempTree::in_every_encoding("registry");
|
||||
|
||||
// Act
|
||||
let parsed = ParserRegistry::new()
|
||||
.parse_directory(tree.path(), "repo1", "build1", 1000)
|
||||
.expect("tree parses");
|
||||
|
||||
// Assert: each file's declaration is a node, under the file's path.
|
||||
let has = |file: &str, name: &str| {
|
||||
parsed
|
||||
.output
|
||||
.nodes
|
||||
.iter()
|
||||
.any(|n| n.file_path == file && n.name == name)
|
||||
};
|
||||
for (file, class) in [
|
||||
("Plain.cs", "Utf8Plain"),
|
||||
("Bom.cs", "Utf8Bom"),
|
||||
("Le.cs", "Utf16Le"),
|
||||
("Be.cs", "Utf16Be"),
|
||||
] {
|
||||
assert!(has(file, class), "no class {class} in {file}");
|
||||
assert!(has(file, "Run"), "no method Run in {file}");
|
||||
}
|
||||
assert!(
|
||||
has("legacy.c", "unit"),
|
||||
"no function in the Windows-1252 file"
|
||||
);
|
||||
// The broken UTF-16 file and the binary; not the PNG.
|
||||
assert_eq!(parsed.unreadable_files, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vb_files_parse_and_dotnet_build_output_is_left_out() {
|
||||
// Arrange: a Windows-1252 VB module ("für" as 0xFC) and what a .NET
|
||||
// build leaves in `obj/`.
|
||||
let tree = crate::test_tree::TempTree::new("registry-vb");
|
||||
tree.write(
|
||||
"Pump.vb",
|
||||
b"' Pumpe f\xFCr Halle 2\nModule Pump\n Sub Main()\n End Sub\nEnd Module\n",
|
||||
);
|
||||
std::fs::create_dir_all(tree.path().join("obj/Debug")).expect("obj dir");
|
||||
tree.write(
|
||||
"obj/Debug/App.g.cs",
|
||||
b"class Generated { void Run() { } }\n",
|
||||
);
|
||||
|
||||
// Act
|
||||
let parsed = ParserRegistry::new()
|
||||
.parse_directory(tree.path(), "repo1", "build1", 1000)
|
||||
.expect("tree parses");
|
||||
|
||||
// Assert
|
||||
let names: Vec<&str> = parsed
|
||||
.output
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|n| n.name.as_str())
|
||||
.collect();
|
||||
assert!(
|
||||
names.contains(&"Pump") && names.contains(&"Main"),
|
||||
"{names:?}"
|
||||
);
|
||||
assert!(!names.contains(&"Generated"), "{names:?}");
|
||||
assert_eq!(parsed.unreadable_files, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_trait() {
|
||||
let registry = ParserRegistry::default();
|
||||
|
||||
@@ -363,6 +363,69 @@ impl RustParser {
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageParser for RustParser {
|
||||
fn language(&self) -> &str {
|
||||
"rust"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["rs"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let mut parser = Parser::new();
|
||||
let language = tree_sitter_rust::LANGUAGE;
|
||||
parser
|
||||
.set_language(&language.into())
|
||||
.map_err(|e| CoreError::Graph(format!("Failed to set Rust language: {e}")))?;
|
||||
|
||||
let tree = parser
|
||||
.parse(source, None)
|
||||
.ok_or_else(|| CoreError::Graph("Failed to parse Rust file".to_string()))?;
|
||||
|
||||
let file_path_str = file_path.to_string_lossy().to_string();
|
||||
let mut output = ParseOutput::default();
|
||||
|
||||
// Add file node
|
||||
output.nodes.push(CodeNode {
|
||||
id: None,
|
||||
repo_id: repo_id.to_string(),
|
||||
graph_build_id: graph_build_id.to_string(),
|
||||
qualified_name: file_path_str.clone(),
|
||||
name: file_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
kind: CodeNodeKind::File,
|
||||
file_path: file_path_str.clone(),
|
||||
start_line: 1,
|
||||
end_line: source.lines().count() as u32,
|
||||
language: "rust".to_string(),
|
||||
community_id: None,
|
||||
is_entry_point: false,
|
||||
graph_index: None,
|
||||
});
|
||||
|
||||
self.walk_tree(
|
||||
tree.root_node(),
|
||||
source,
|
||||
&file_path_str,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
None,
|
||||
&mut output,
|
||||
);
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -570,66 +633,3 @@ mod tests {
|
||||
assert_eq!(parser.extensions(), &["rs"]);
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageParser for RustParser {
|
||||
fn language(&self) -> &str {
|
||||
"rust"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["rs"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let mut parser = Parser::new();
|
||||
let language = tree_sitter_rust::LANGUAGE;
|
||||
parser
|
||||
.set_language(&language.into())
|
||||
.map_err(|e| CoreError::Graph(format!("Failed to set Rust language: {e}")))?;
|
||||
|
||||
let tree = parser
|
||||
.parse(source, None)
|
||||
.ok_or_else(|| CoreError::Graph("Failed to parse Rust file".to_string()))?;
|
||||
|
||||
let file_path_str = file_path.to_string_lossy().to_string();
|
||||
let mut output = ParseOutput::default();
|
||||
|
||||
// Add file node
|
||||
output.nodes.push(CodeNode {
|
||||
id: None,
|
||||
repo_id: repo_id.to_string(),
|
||||
graph_build_id: graph_build_id.to_string(),
|
||||
qualified_name: file_path_str.clone(),
|
||||
name: file_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default(),
|
||||
kind: CodeNodeKind::File,
|
||||
file_path: file_path_str.clone(),
|
||||
start_line: 1,
|
||||
end_line: source.lines().count() as u32,
|
||||
language: "rust".to_string(),
|
||||
community_id: None,
|
||||
is_entry_point: false,
|
||||
graph_index: None,
|
||||
});
|
||||
|
||||
self.walk_tree(
|
||||
tree.root_node(),
|
||||
source,
|
||||
&file_path_str,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
None,
|
||||
&mut output,
|
||||
);
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
//! Visual Basic .NET: classes, modules, structures, interfaces and enums,
|
||||
//! their methods and constructors, base types, and calls. Entry points are
|
||||
//! `Main` and what a framework calls from outside, as for C#: ASP.NET
|
||||
//! controller actions, Web Forms pages and controls, ASMX web methods, HTTP
|
||||
//! handlers, and event handlers wired with `Handles`.
|
||||
//!
|
||||
//! VB is case-insensitive, so keywords, modifiers, attribute and base type
|
||||
//! names are compared ignoring case; names keep the case they are written in.
|
||||
//!
|
||||
//! The grammar (CodeAnt-AI's tree-sitter-vb-dotnet) expects `Inherits` and
|
||||
//! `Implements` on the `Class` line itself, while VB puts them on the lines
|
||||
//! after it, so base types are read from the source text instead.
|
||||
//! `Imports` statements are left out: the graph has no namespace nodes they
|
||||
//! could point to.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use compliance_core::error::CoreError;
|
||||
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
|
||||
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
|
||||
use tree_sitter::Node;
|
||||
|
||||
use super::common::{line, parse, text, walk, FileGraph};
|
||||
use super::csharp::{ENDPOINT_ATTRIBUTES, WEB_BASES};
|
||||
|
||||
/// Parses Visual Basic .NET sources.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct VbParser;
|
||||
|
||||
/// What a method's entry-point rule needs to know about its type.
|
||||
#[derive(Clone, Copy)]
|
||||
struct TypeContext<'a> {
|
||||
qualified: &'a str,
|
||||
/// A `Module`, whose members are all `Shared`.
|
||||
module: bool,
|
||||
/// The type inherits a web framework base or is an `<ApiController>`.
|
||||
web: bool,
|
||||
/// The type implements `IHttpHandler`, whose `ProcessRequest` the server calls.
|
||||
http_handler: bool,
|
||||
}
|
||||
|
||||
/// A type named in an `Inherits` or `Implements` statement.
|
||||
struct BaseType<'s> {
|
||||
name: &'s str,
|
||||
kind: CodeEdgeKind,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
impl VbParser {
|
||||
/// A Visual Basic .NET parser.
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
/// Visit type blocks at file level and in namespaces.
|
||||
fn declarations(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
walk(root, |node| match node.kind() {
|
||||
"class_block" | "module_block" | "structure_block" | "interface_block"
|
||||
| "enum_block" => {
|
||||
Self::type_block(node, source, graph);
|
||||
false
|
||||
}
|
||||
"source_file" | "namespace_block" | "type_declaration" => true,
|
||||
_ => false,
|
||||
});
|
||||
}
|
||||
|
||||
fn type_block(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else {
|
||||
return;
|
||||
};
|
||||
let qualified = graph.top_level(name);
|
||||
let kind = match node.kind() {
|
||||
"module_block" => CodeNodeKind::Module,
|
||||
"structure_block" => CodeNodeKind::Struct,
|
||||
"interface_block" => CodeNodeKind::Interface,
|
||||
"enum_block" => CodeNodeKind::Enum,
|
||||
_ => CodeNodeKind::Class,
|
||||
};
|
||||
graph.node_at(
|
||||
qualified.clone(),
|
||||
name.to_string(),
|
||||
kind,
|
||||
lines(node),
|
||||
false,
|
||||
);
|
||||
|
||||
let bases = base_types(node, source);
|
||||
for base in &bases {
|
||||
graph.edge_at(&qualified, base.name, base.kind.clone(), base.line);
|
||||
}
|
||||
let named = |kind: CodeEdgeKind, wanted: &[&str]| {
|
||||
bases
|
||||
.iter()
|
||||
.any(|b| b.kind == kind && wanted.iter().any(|w| b.name.eq_ignore_ascii_case(w)))
|
||||
};
|
||||
let context = TypeContext {
|
||||
qualified: &qualified,
|
||||
module: node.kind() == "module_block",
|
||||
web: named(CodeEdgeKind::Inherits, &WEB_BASES)
|
||||
|| attributes(node, source).any(|a| a.eq_ignore_ascii_case("ApiController")),
|
||||
http_handler: named(CodeEdgeKind::Implements, &["IHttpHandler"]),
|
||||
};
|
||||
let mut cursor = node.walk();
|
||||
for member in node.named_children(&mut cursor) {
|
||||
if matches!(
|
||||
member.kind(),
|
||||
"method_declaration" | "constructor_declaration"
|
||||
) {
|
||||
Self::method(member, context, source, graph);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn method(node: Node<'_>, ty: TypeContext<'_>, source: &str, graph: &mut FileGraph<'_>) {
|
||||
// A constructor is `Sub New`, and has no name field.
|
||||
let name = match node.child_by_field_name("name") {
|
||||
Some(name) => text(name, source),
|
||||
None if node.kind() == "constructor_declaration" => "New",
|
||||
None => return,
|
||||
};
|
||||
let qualified = format!("{}.{name}", ty.qualified);
|
||||
let is_entry =
|
||||
node.kind() == "method_declaration" && is_entry_point(node, name, ty, source);
|
||||
graph.node_at(
|
||||
qualified.clone(),
|
||||
name.to_string(),
|
||||
CodeNodeKind::Method,
|
||||
lines(node),
|
||||
is_entry,
|
||||
);
|
||||
Self::calls(node, &qualified, source, graph);
|
||||
}
|
||||
|
||||
/// Calls by method name (`repo.Find(id)` and `Init` without parentheses
|
||||
/// call `Find` and `Init`) and constructions (`New OrderDto(o)` calls
|
||||
/// `OrderDto`).
|
||||
fn calls(method: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) {
|
||||
walk(method, |node| {
|
||||
let callee = match node.kind() {
|
||||
"invocation" => node.child_by_field_name("target").and_then(simple_name),
|
||||
"new_expression" => node.child_by_field_name("type").and_then(simple_name),
|
||||
// A statement that is only a name calls it: `Init`, `Me.Save`.
|
||||
"call_statement" => node
|
||||
.named_child(0)
|
||||
.and_then(|expression| expression.named_child(0))
|
||||
.filter(|e| matches!(e.kind(), "identifier" | "member_access"))
|
||||
.and_then(simple_name),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(callee) = callee {
|
||||
graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node);
|
||||
}
|
||||
true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the framework, not our own code, calls this method.
|
||||
fn is_entry_point(method: Node<'_>, name: &str, ty: TypeContext<'_>, source: &str) -> bool {
|
||||
let modifiers: Vec<&str> = method
|
||||
.child_by_field_name("modifiers")
|
||||
.map(|list| {
|
||||
let mut cursor = list.walk();
|
||||
list.named_children(&mut cursor)
|
||||
.map(|m| text(m, source))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let has_modifier = |wanted: &str| modifiers.iter().any(|m| m.eq_ignore_ascii_case(wanted));
|
||||
if name.eq_ignore_ascii_case("Main") && (ty.module || has_modifier("Shared")) {
|
||||
return true;
|
||||
}
|
||||
if attributes(method, source).any(|a| {
|
||||
ENDPOINT_ATTRIBUTES
|
||||
.iter()
|
||||
.any(|e| a.eq_ignore_ascii_case(e))
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
if ty.http_handler && name.eq_ignore_ascii_case("ProcessRequest") {
|
||||
return true;
|
||||
}
|
||||
// `Sub Page_Load(...) Handles Me.Load`: the framework raises the event.
|
||||
// The grammar doesn't parse the clause, so the header line decides.
|
||||
if header(method, source)
|
||||
.split_whitespace()
|
||||
.any(|word| word.eq_ignore_ascii_case("Handles"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
// Controller actions are public, Web Forms event handlers usually
|
||||
// protected.
|
||||
ty.web && (has_modifier("Public") || has_modifier("Protected"))
|
||||
}
|
||||
|
||||
/// The 1-based first and last line of a declaration. A VB block ends with
|
||||
/// its line break, so its end position is column 0 of the next line, which
|
||||
/// is not part of it.
|
||||
fn lines(node: Node<'_>) -> (u32, u32) {
|
||||
let end = node.end_position();
|
||||
let last_row = if end.column == 0 && end.row > node.start_position().row {
|
||||
end.row - 1
|
||||
} else {
|
||||
end.row
|
||||
};
|
||||
(line(node), last_row as u32 + 1)
|
||||
}
|
||||
|
||||
/// A declaration's first line, without a trailing comment.
|
||||
fn header<'s>(declaration: Node<'_>, source: &'s str) -> &'s str {
|
||||
let first = text(declaration, source).lines().next().unwrap_or_default();
|
||||
first.split('\'').next().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The simple names of a declaration's attributes, without namespace or
|
||||
/// the `Attribute` suffix: `<System.Web.Services.WebMethodAttribute()>` is
|
||||
/// `WebMethod`.
|
||||
fn attributes<'s>(declaration: Node<'_>, source: &'s str) -> impl Iterator<Item = &'s str> {
|
||||
let mut names = Vec::new();
|
||||
let mut cursor = declaration.walk();
|
||||
for block in declaration
|
||||
.children(&mut cursor)
|
||||
.filter(|c| c.kind() == "attribute_block")
|
||||
{
|
||||
let mut inner = block.walk();
|
||||
for attribute in block.named_children(&mut inner) {
|
||||
if let Some(name) = attribute.child_by_field_name("name").and_then(simple_name) {
|
||||
let name = text(name, source);
|
||||
let stem = name.len().checked_sub("Attribute".len()).filter(|&at| {
|
||||
name.is_char_boundary(at) && name[at..].eq_ignore_ascii_case("Attribute")
|
||||
});
|
||||
names.push(stem.map_or(name, |at| &name[..at]));
|
||||
}
|
||||
}
|
||||
}
|
||||
names.into_iter()
|
||||
}
|
||||
|
||||
/// The types a type block's `Inherits` and `Implements` statements name,
|
||||
/// read from the lines that open the block: the header line (`Class A :
|
||||
/// Inherits B`) and the lines after it, until the first member.
|
||||
fn base_types<'s>(block: Node<'_>, source: &'s str) -> Vec<BaseType<'s>> {
|
||||
let mut bases = Vec::new();
|
||||
let first_line = line(block);
|
||||
for (offset, line_text) in text(block, source).lines().enumerate() {
|
||||
let code = line_text.split('\'').next().unwrap_or_default().trim();
|
||||
if code.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Statements on one line are separated by `:`; the header line's
|
||||
// first one is the `Class` statement itself.
|
||||
let mut found = false;
|
||||
for statement in code
|
||||
.split(':')
|
||||
.map(str::trim)
|
||||
.skip(usize::from(offset == 0))
|
||||
{
|
||||
let (kind, types) = if let Some(types) = keyword_rest(statement, "Inherits") {
|
||||
(CodeEdgeKind::Inherits, types)
|
||||
} else if let Some(types) = keyword_rest(statement, "Implements") {
|
||||
(CodeEdgeKind::Implements, types)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
found = true;
|
||||
let line = first_line + u32::try_from(offset).unwrap_or(u32::MAX);
|
||||
bases.extend(
|
||||
split_types(types)
|
||||
.filter_map(simple_type_name)
|
||||
.map(|name| BaseType {
|
||||
name,
|
||||
kind: kind.clone(),
|
||||
line,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// `Inherits` and `Implements` come before every member.
|
||||
if offset > 0 && !found {
|
||||
break;
|
||||
}
|
||||
}
|
||||
bases
|
||||
}
|
||||
|
||||
/// What follows `keyword` (case-insensitive) at the start of `statement`.
|
||||
fn keyword_rest<'s>(statement: &'s str, keyword: &str) -> Option<&'s str> {
|
||||
let head = statement.get(..keyword.len())?;
|
||||
let rest = &statement[keyword.len()..];
|
||||
(head.eq_ignore_ascii_case(keyword) && rest.starts_with(char::is_whitespace))
|
||||
.then(|| rest.trim())
|
||||
}
|
||||
|
||||
/// The comma-separated types of a list, with commas inside `(Of K, V)`
|
||||
/// left alone.
|
||||
fn split_types(list: &str) -> impl Iterator<Item = &str> {
|
||||
let mut depth = 0usize;
|
||||
let mut start = 0;
|
||||
let mut parts = Vec::new();
|
||||
for (at, ch) in list.char_indices() {
|
||||
match ch {
|
||||
'(' => depth += 1,
|
||||
')' => depth = depth.saturating_sub(1),
|
||||
',' if depth == 0 => {
|
||||
parts.push(&list[start..at]);
|
||||
start = at + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
parts.push(&list[start..]);
|
||||
parts.into_iter().map(str::trim)
|
||||
}
|
||||
|
||||
/// The simple name of a written type: `System.Web.UI.Page` is `Page`,
|
||||
/// `List(Of Order)` is `List`.
|
||||
fn simple_type_name(written: &str) -> Option<&str> {
|
||||
let without_args = written.split('(').next().unwrap_or_default();
|
||||
let name = without_args.rsplit('.').next().unwrap_or_default().trim();
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
|
||||
/// The last identifier of a name in the syntax tree: `Me.repo.Find` is
|
||||
/// `Find`, `List(Of Integer)` is `List`.
|
||||
fn simple_name(node: Node<'_>) -> Option<Node<'_>> {
|
||||
match node.kind() {
|
||||
"identifier" => Some(node),
|
||||
"member_access" => node.child_by_field_name("member").and_then(simple_name),
|
||||
"namespace_name" => {
|
||||
let mut cursor = node.walk();
|
||||
let last = node
|
||||
.named_children(&mut cursor)
|
||||
.filter(|n| n.kind() == "identifier")
|
||||
.last();
|
||||
last
|
||||
}
|
||||
"expression" | "type" | "generic_type" => node.named_child(0).and_then(simple_name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl LanguageParser for VbParser {
|
||||
fn language(&self) -> &str {
|
||||
"vb"
|
||||
}
|
||||
|
||||
fn extensions(&self) -> &[&str] {
|
||||
&["vb"]
|
||||
}
|
||||
|
||||
fn parse_file(
|
||||
&self,
|
||||
file_path: &Path,
|
||||
source: &str,
|
||||
repo_id: &str,
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
let tree = parse(tree_sitter_vb_dotnet::LANGUAGE.into(), source, "VB.NET")?;
|
||||
let mut graph = FileGraph::new(
|
||||
file_path,
|
||||
source.lines().count() as u32,
|
||||
repo_id,
|
||||
graph_build_id,
|
||||
"vb",
|
||||
);
|
||||
Self::declarations(tree.root_node(), source, &mut graph);
|
||||
Ok(graph.finish())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use compliance_core::models::graph::CodeNode;
|
||||
|
||||
const WEB_APP: &str = r#"Imports System.Web.UI
|
||||
|
||||
Namespace Plant.Web
|
||||
Public Module Program
|
||||
Sub Main(args As String())
|
||||
Dim c = New Pump(3)
|
||||
c.Start
|
||||
End Sub
|
||||
End Module
|
||||
|
||||
Public Class OrdersPage
|
||||
Inherits System.Web.UI.Page
|
||||
Implements IDisposable, IComparable(Of OrdersPage)
|
||||
|
||||
Public Sub New()
|
||||
Init()
|
||||
End Sub
|
||||
|
||||
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
|
||||
Dim names = From p In Pumps Where p.Active Select p.Name
|
||||
Bind(names)
|
||||
End Sub
|
||||
|
||||
Private Sub Bind(names As Object)
|
||||
End Sub
|
||||
|
||||
Private Sub Init()
|
||||
End Sub
|
||||
|
||||
Public Sub Dispose() Implements IDisposable.Dispose
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Public Class Pump : Inherits Machine
|
||||
Private Sub OnTick(sender As Object, e As EventArgs) handles timer.Tick
|
||||
End Sub
|
||||
|
||||
Public Sub Start(n As Integer)
|
||||
Helper.Scale(n)
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Public Class Service
|
||||
Inherits WebService
|
||||
|
||||
<WebMethodAttribute()>
|
||||
Public Shared Function Ping() As String
|
||||
Return "pong"
|
||||
End Function
|
||||
End Class
|
||||
|
||||
Public Class Download
|
||||
Implements IHttpHandler
|
||||
|
||||
Public Sub ProcessRequest(c As HttpContext)
|
||||
End Sub
|
||||
|
||||
Public Shared Sub Main()
|
||||
End Sub
|
||||
End Class
|
||||
|
||||
Public Structure Pt
|
||||
Public X As Integer
|
||||
End Structure
|
||||
|
||||
Public Enum Kind
|
||||
A
|
||||
B
|
||||
End Enum
|
||||
End Namespace
|
||||
"#;
|
||||
|
||||
fn parsed() -> ParseOutput {
|
||||
VbParser::new()
|
||||
.parse_file(Path::new("Web/Orders.vb"), WEB_APP, "repo", "build")
|
||||
.expect("VB parses")
|
||||
}
|
||||
|
||||
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
|
||||
let qualified = format!("Web/Orders.vb::{qualified}");
|
||||
out.nodes
|
||||
.iter()
|
||||
.find(|n| n.qualified_name == qualified)
|
||||
.unwrap_or_else(|| panic!("no node {qualified}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types_and_methods_become_nodes() {
|
||||
let out = parsed();
|
||||
assert!(matches!(node(&out, "Program").kind, CodeNodeKind::Module));
|
||||
assert!(matches!(node(&out, "OrdersPage").kind, CodeNodeKind::Class));
|
||||
assert!(matches!(node(&out, "Pt").kind, CodeNodeKind::Struct));
|
||||
assert!(matches!(node(&out, "Kind").kind, CodeNodeKind::Enum));
|
||||
// Members around a LINQ query the grammar can't parse still come out.
|
||||
for method in [
|
||||
"Program.Main",
|
||||
"OrdersPage.New",
|
||||
"OrdersPage.Page_Load",
|
||||
"OrdersPage.Bind",
|
||||
"OrdersPage.Dispose",
|
||||
"Pump.Start",
|
||||
] {
|
||||
assert!(
|
||||
matches!(node(&out, method).kind, CodeNodeKind::Method),
|
||||
"{method}"
|
||||
);
|
||||
}
|
||||
let page_load = node(&out, "OrdersPage.Page_Load");
|
||||
assert_eq!((page_load.start_line, page_load.end_line), (19, 22));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framework_called_methods_are_entry_points() {
|
||||
let out = parsed();
|
||||
for entry in [
|
||||
"Program.Main",
|
||||
"OrdersPage.Page_Load",
|
||||
"OrdersPage.Dispose",
|
||||
"Pump.OnTick",
|
||||
"Service.Ping",
|
||||
"Download.ProcessRequest",
|
||||
"Download.Main",
|
||||
] {
|
||||
assert!(
|
||||
node(&out, entry).is_entry_point,
|
||||
"{entry} is an entry point"
|
||||
);
|
||||
}
|
||||
for internal in [
|
||||
"OrdersPage.New",
|
||||
"OrdersPage.Bind",
|
||||
"OrdersPage.Init",
|
||||
"Pump.Start",
|
||||
] {
|
||||
assert!(!node(&out, internal).is_entry_point, "{internal} is not");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bases_and_calls_become_edges() {
|
||||
let out = parsed();
|
||||
let edges: Vec<(&str, &str, &str, Option<u32>)> = out
|
||||
.edges
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let kind = match e.kind {
|
||||
CodeEdgeKind::Calls => "calls",
|
||||
CodeEdgeKind::Inherits => "inherits",
|
||||
CodeEdgeKind::Implements => "implements",
|
||||
_ => "other",
|
||||
};
|
||||
(kind, e.source.as_str(), e.target.as_str(), e.line_number)
|
||||
})
|
||||
.collect();
|
||||
let page = "Web/Orders.vb::OrdersPage";
|
||||
assert!(edges.contains(&("inherits", page, "Page", Some(12))));
|
||||
assert!(edges.contains(&("implements", page, "IDisposable", Some(13))));
|
||||
assert!(edges.contains(&("implements", page, "IComparable", Some(13))));
|
||||
assert!(edges.contains(&("inherits", "Web/Orders.vb::Pump", "Machine", Some(34))));
|
||||
let main = "Web/Orders.vb::Program.Main";
|
||||
assert!(edges.contains(&("calls", main, "Pump", Some(6))));
|
||||
assert!(edges.contains(&("calls", main, "Start", Some(7))));
|
||||
let calls = |source: &str| -> Vec<&str> {
|
||||
edges
|
||||
.iter()
|
||||
.filter(|(kind, s, _, _)| *kind == "calls" && *s == source)
|
||||
.map(|(_, _, target, _)| *target)
|
||||
.collect()
|
||||
};
|
||||
assert!(calls("Web/Orders.vb::OrdersPage.New").contains(&"Init"));
|
||||
assert!(calls("Web/Orders.vb::OrdersPage.Page_Load").contains(&"Bind"));
|
||||
assert!(calls("Web/Orders.vb::Pump.Start").contains(&"Scale"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_registry_parses_vb_files() {
|
||||
let registry = super::super::registry::ParserRegistry::new();
|
||||
assert!(registry.supports_extension("vb"));
|
||||
let out = registry
|
||||
.parse_file(
|
||||
Path::new("A.vb"),
|
||||
"Module M\nSub Main()\nEnd Sub\nEnd Module\n",
|
||||
"r",
|
||||
"b",
|
||||
)
|
||||
.expect("parses")
|
||||
.expect("VB is supported");
|
||||
assert!(out.nodes.iter().any(|n| n.qualified_name == "A.vb::M.Main"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! A source tree on disk for tests, in every encoding the registry reads.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// A directory under the system temp dir, removed when dropped (Rust runs
|
||||
/// `Drop::drop` when the value goes out of scope, like a `with` block's exit).
|
||||
pub(crate) struct TempTree(PathBuf);
|
||||
|
||||
impl TempTree {
|
||||
/// An empty directory named after the test and this process.
|
||||
pub(crate) fn new(test: &str) -> Self {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("compliance-graph-{test}-{}", std::process::id()));
|
||||
// A leftover from an aborted run would add files.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
Self(dir)
|
||||
}
|
||||
|
||||
/// The directory.
|
||||
pub(crate) fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Write `bytes` to `rel` in the tree.
|
||||
pub(crate) fn write(&self, rel: &str, bytes: &[u8]) {
|
||||
std::fs::write(self.0.join(rel), bytes).expect("write");
|
||||
}
|
||||
|
||||
/// A tree with one C# class or C function in each encoding the registry
|
||||
/// reads, and two files it can't read (plus a binary it doesn't try to).
|
||||
pub(crate) fn in_every_encoding(test: &str) -> Self {
|
||||
let tree = Self::new(test);
|
||||
tree.write("Plain.cs", b"class Utf8Plain { void Run() { } }\n");
|
||||
tree.write("Bom.cs", b"\xEF\xBB\xBFclass Utf8Bom { void Run() { } }\n");
|
||||
tree.write("Le.cs", &utf16("class Utf16Le { void Run() { } }\n", true));
|
||||
tree.write("Be.cs", &utf16("class Utf16Be { void Run() { } }\n", false));
|
||||
// "Größe" and "€" as Windows-1252 writes them.
|
||||
tree.write(
|
||||
"legacy.c",
|
||||
b"/* Gr\xF6\xDFe */\nconst char *unit(void) { return \"\x80\"; }\n",
|
||||
);
|
||||
// An odd byte count after a UTF-16 BOM, and a binary with a C name.
|
||||
tree.write("Broken.cs", b"\xFF\xFE\x41");
|
||||
tree.write("blob.c", b"\x7FELF\x00\xFF\xFE");
|
||||
// Not a source file: neither parsed nor counted.
|
||||
tree.write("logo.png", b"\x89PNG\x00\xFF");
|
||||
tree
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempTree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as UTF-16 with its byte-order mark.
|
||||
pub(crate) fn utf16(text: &str, little_endian: bool) -> Vec<u8> {
|
||||
let bom: [u8; 2] = if little_endian {
|
||||
[0xFF, 0xFE]
|
||||
} else {
|
||||
[0xFE, 0xFF]
|
||||
};
|
||||
let units = text.encode_utf16().flat_map(|unit| {
|
||||
if little_endian {
|
||||
unit.to_le_bytes()
|
||||
} else {
|
||||
unit.to_be_bytes()
|
||||
}
|
||||
});
|
||||
bom.into_iter().chain(units).collect()
|
||||
}
|
||||
@@ -5,7 +5,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
compliance-core = { workspace = true, features = ["mongodb", "axum"] }
|
||||
rmcp = { version = "0.16", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] }
|
||||
rmcp = { version = "3.9", features = ["server", "macros", "transport-io", "transport-streamable-http-server"] }
|
||||
tokio = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user