This is an automated email from the ASF dual-hosted git repository. yasithdev pushed a commit to branch event-graph in repository https://gitbox.apache.org/repos/asf/airavata-custos.git
commit 4d08e2e0ee5a989d7fb5a2bf4f106e4d38dc0dce Author: Yasith Jayawardana <[email protected]> AuthorDate: Tue Nov 3 22:39:21 2026 -0500 Serve the event graph from the server Generate api/event-graph.json with tools/eventgraph during go generate, embed it, and serve it at GET /events/graph. CI fails on a stale file. --- .github/workflows/core-verify.yml | 15 + Makefile | 6 +- api/README.md | 1 + api/core.openapi.yaml | 30 + api/event-graph.json | 1201 +++++++++++++++++++++++++++++++++++ api/eventgraph.go | 25 + cmd/server/main.go | 1 + internal/server/event_delivery.go | 13 + internal/server/event_graph_test.go | 40 ++ internal/server/server.go | 1 + tools/eventgraph/analyse.go | 501 +++++++++++++++ tools/eventgraph/flow.go | 156 +++++ tools/eventgraph/go.mod | 10 + tools/eventgraph/go.sum | 6 + tools/eventgraph/graph.go | 332 ++++++++++ tools/eventgraph/main.go | 851 +++++++++++++++++++++++++ tools/eventgraph/transitions.go | 197 ++++++ 17 files changed, 3383 insertions(+), 3 deletions(-) diff --git a/.github/workflows/core-verify.yml b/.github/workflows/core-verify.yml index 559b67da1..07311d355 100644 --- a/.github/workflows/core-verify.yml +++ b/.github/workflows/core-verify.yml @@ -24,6 +24,7 @@ on: - 'go.mod' - 'go.sum' - 'internal/db/migrations/**' + - 'api/**' - '.github/workflows/core-verify.yml' push: branches: [master] @@ -32,6 +33,7 @@ on: - 'go.mod' - 'go.sum' - 'internal/db/migrations/**' + - 'api/**' - '.github/workflows/core-verify.yml' workflow_dispatch: @@ -82,6 +84,19 @@ jobs: - name: Unit tests run: go test ./... + - name: Vet event graph analyser + working-directory: tools/eventgraph + run: go vet ./... + + - name: Check generated API files + run: | + go generate ./cmd/server/ + if [ -n "$(git status --porcelain api/)" ]; then + git status --porcelain api/ + echo "Generated API drift: run 'go generate ./cmd/server/' and commit the result." + exit 1 + fi + # The AMIE integration suite has its own workflow and compose stack; # this covers the core suite only. The packages share one database and # truncate tables, so they must not run in parallel. diff --git a/Makefile b/Makefile index 0fbcb7e6f..d27120ae8 100644 --- a/Makefile +++ b/Makefile @@ -3,9 +3,9 @@ SHELL := /bin/bash help: @echo "Targets:" - @echo " gen-api regenerate every OpenAPI spec from swag annotations" + @echo " gen-api regenerate every OpenAPI spec and the event graph" @echo " build gen-api, then go build ./..." - @echo " verify-no-drift gen-api, then fail if any *.openapi.yaml changed" + @echo " verify-no-drift gen-api, then fail if any generated api/ file changed" @echo " test go test ./..." @echo " integration-test full integration suite (AMIE for now)" @echo " verify verify-no-drift + go vet + test" @@ -21,7 +21,7 @@ build: gen-api verify-no-drift: gen-api @if [ -n "$$(git status --porcelain api/ connectors/*/api/ 2>/dev/null)" ]; then \ - echo "OpenAPI drift detected — run 'make gen-api' and commit the result."; \ + echo "Generated API drift detected — run 'make gen-api' and commit the result."; \ git status --porcelain api/ connectors/*/api/; \ exit 1; \ fi diff --git a/api/README.md b/api/README.md index 11f9ea4d1..f3accc85a 100644 --- a/api/README.md +++ b/api/README.md @@ -29,6 +29,7 @@ One spec per code-ownership unit: |---|---|---| | Core | `api/core.openapi.yaml` | Core REST endpoints. | | Connector | `connectors/<NAME>/api/<name>.openapi.yaml` | A connector's endpoints under `/connectors/<name>/`. | +| Event graph | `api/event-graph.json` | Core events and their transitions, from `tools/eventgraph`; served at `GET /events/graph`. | Connector specs ship alongside the connector code; the core spec never declares connector endpoints. The reference connector today is AMIE at diff --git a/api/core.openapi.yaml b/api/core.openapi.yaml index db9b87617..77b8a69eb 100644 --- a/api/core.openapi.yaml +++ b/api/core.openapi.yaml @@ -4116,6 +4116,36 @@ paths: summary: Retry a failed event delivery tags: - Events + /events/graph: + get: + description: Every core event, the core and connector transitions between them, + and the connector handlers that end a flow. Generated from this revision's + source at build time. + produces: + - application/json + responses: + "200": + description: OK + schema: + properties: + edges: + items: + type: object + type: array + events: + items: + type: object + type: array + terms: + items: + type: object + type: array + type: object + security: + - BearerAuth: [] + summary: Get the event graph + tags: + - Events /events/subscriptions: get: description: Every saved subscription and whether its subscriber is loaded in diff --git a/api/event-graph.json b/api/event-graph.json new file mode 100644 index 000000000..4ef2e206f --- /dev/null +++ b/api/event-graph.json @@ -0,0 +1,1201 @@ +{ + "events": [ + { + "id": "compute_allocation::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /compute-allocations" + } + ], + "subs": 2 + }, + { + "id": "compute_allocation::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocations/{id}" + } + ], + "subs": 3 + }, + { + "id": "compute_allocation::group_provision", + "entry": [], + "subs": 1 + }, + { + "id": "compute_allocation::update", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + } + ], + "subs": 2 + }, + { + "id": "compute_allocation_diff::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /compute-allocation-diffs" + }, + { + "kind": "API", + "label": "PUT /compute-allocation-change-requests/{id}" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_diff::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocation-diffs/{id}" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_membership::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /compute-allocation-memberships" + }, + { + "kind": "TempAccount", + "label": "POST /connectors/temp-account/assign-allocation" + } + ], + "subs": 3 + }, + { + "id": "compute_allocation_membership::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocation-memberships/{id}" + } + ], + "subs": 2 + }, + { + "id": "compute_allocation_membership::update", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "PUT /compute-allocation-memberships/{id}" + }, + { + "kind": "API", + "label": "PUT /compute-allocation-memberships/{id}/status" + }, + { + "kind": "TempAccount", + "label": "POST /connectors/temp-account/update-allocation" + } + ], + "subs": 3 + }, + { + "id": "compute_allocation_membership_resource_override::create", + "entry": [ + { + "kind": "API", + "label": "POST /compute-allocation-membership-resource-overrides" + } + ], + "subs": 1 + }, + { + "id": "compute_allocation_membership_resource_override::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocation-membership-resource-overrides/{id}" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_membership_resource_override::update", + "entry": [ + { + "kind": "API", + "label": "PUT /compute-allocation-membership-resource-overrides/{id}" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_resource::create", + "entry": [ + { + "kind": "API", + "label": "POST /compute-allocation-resources" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_resource::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocation-resources/{id}" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_resource::update", + "entry": [ + { + "kind": "API", + "label": "PUT /compute-allocation-resources/{id}" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_resource_mapping::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /compute-allocations/{id}/resources" + } + ], + "subs": 1 + }, + { + "id": "compute_allocation_resource_mapping::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /compute-allocations/{id}/resources/{resourceId}" + }, + { + "kind": "API", + "label": "PUT /compute-allocations/{id}/resources" + } + ], + "subs": 0 + }, + { + "id": "compute_allocation_resource_mapping::update", + "entry": [ + { + "kind": "API", + "label": "PUT /compute-allocations/{id}/resources/{resourceId}" + } + ], + "subs": 0 + }, + { + "id": "compute_cluster::create", + "entry": [ + { + "kind": "API", + "label": "POST /compute-clusters" + } + ], + "subs": 0 + }, + { + "id": "compute_cluster::delete", + "entry": [], + "subs": 0 + }, + { + "id": "compute_cluster::update", + "entry": [], + "subs": 0 + }, + { + "id": "compute_cluster_user::approve", + "entry": [ + { + "kind": "API", + "label": "POST /compute-cluster-users/{id}/approve" + } + ], + "subs": 3 + }, + { + "id": "compute_cluster_user::create", + "entry": [ + { + "kind": "API", + "label": "POST /compute-cluster-users" + } + ], + "subs": 1 + }, + { + "id": "compute_cluster_user::delete", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "DELETE /compute-cluster-users/{id}" + }, + { + "kind": "API", + "label": "POST /users/merge" + } + ], + "subs": 2 + }, + { + "id": "compute_cluster_user::deny", + "entry": [ + { + "kind": "API", + "label": "POST /compute-cluster-users/{id}/deny" + } + ], + "subs": 2 + }, + { + "id": "compute_cluster_user::provision", + "entry": [], + "subs": 2 + }, + { + "id": "compute_cluster_user::update", + "entry": [ + { + "kind": "API", + "label": "PUT /compute-cluster-users/{id}" + } + ], + "subs": 0 + }, + { + "id": "organization::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /organizations" + } + ], + "subs": 0 + }, + { + "id": "organization::delete", + "entry": [], + "subs": 0 + }, + { + "id": "organization::update", + "entry": [], + "subs": 0 + }, + { + "id": "project::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /projects" + } + ], + "subs": 0 + }, + { + "id": "project::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /projects/{id}" + } + ], + "subs": 0 + }, + { + "id": "project::update", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "PUT /projects/{id}" + }, + { + "kind": "API", + "label": "PUT /projects/{id}/status" + } + ], + "subs": 0 + }, + { + "id": "user::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /users" + }, + { + "kind": "TempAccount", + "label": "POST /connectors/temp-account/create" + } + ], + "subs": 0 + }, + { + "id": "user::delete", + "entry": [ + { + "kind": "TempAccount", + "label": "DELETE /connectors/temp-account/remove/{user_id}" + } + ], + "subs": 0 + }, + { + "id": "user::onboarded", + "entry": [], + "subs": 1 + }, + { + "id": "user::update", + "entry": [ + { + "kind": "API", + "label": "PUT /users/{id}" + }, + { + "kind": "API", + "label": "PUT /users/{id}/status" + } + ], + "subs": 0 + }, + { + "id": "user_agreement::publish", + "entry": [ + { + "kind": "API", + "label": "POST /agreements/{id}/publish" + } + ], + "subs": 0 + }, + { + "id": "user_agreement::remove", + "entry": [ + { + "kind": "API", + "label": "POST /agreements/{id}/remove" + } + ], + "subs": 0 + }, + { + "id": "user_agreement_acceptance::create", + "entry": [ + { + "kind": "API", + "label": "POST /me/agreements/{id}/accept" + } + ], + "subs": 0 + }, + { + "id": "user_identity::create", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "POST /me/onboarding" + }, + { + "kind": "API", + "label": "POST /user-identities" + } + ], + "subs": 0 + }, + { + "id": "user_identity::delete", + "entry": [ + { + "kind": "API", + "label": "DELETE /user-identities/{id}" + } + ], + "subs": 0 + }, + { + "id": "user_identity::update", + "entry": [ + { + "kind": "AMIE", + "label": "amie.LoadConnector$3" + }, + { + "kind": "AMIE", + "label": "worker.Processor.Run" + }, + { + "kind": "AMIE", + "label": "worker.Processor.processPendingEvents" + }, + { + "kind": "API", + "label": "PUT /user-identities/{id}" + } + ], + "subs": 0 + } + ], + "edges": [ + { + "from": "compute_allocation_resource_mapping::delete", + "to": "compute_allocation_resource_mapping::create", + "kind": "core", + "conn": "core", + "actor": "Service.SetAllocationResources", + "sites": [ + "pkg/service/compute_allocation_resource_mapping.go:138 → pkg/service/compute_allocation_resource_mapping.go:77" + ], + "chain": [ + "service.Service.DetachResourceFromAllocation$1", + "service.Service.DetachResourceFromAllocation", + "service.Service.SetAllocationResources", + "service.Service.AttachResourceToAllocation", + "service.Service.AttachResourceToAllocation$1" + ], + "cond": true, + "order": true + }, + { + "from": "compute_cluster_user::create", + "to": "compute_cluster_user::approve", + "kind": "core", + "conn": "core", + "actor": "Service.CreateComputeClusterUser", + "sites": [ + "pkg/service/compute_cluster_user.go:104 → pkg/service/compute_cluster_user.go:109" + ], + "chain": [ + "service.Service.CreateComputeClusterUser$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::create", + "to": "compute_cluster_user::approve", + "kind": "core", + "conn": "core", + "actor": "Service.OnboardUser", + "sites": [ + "pkg/service/user_onboard.go:295 → pkg/service/user_onboard.go:299" + ], + "chain": [ + "service.Service.OnboardUser$2" + ], + "cond": true + }, + { + "from": "compute_cluster_user::delete", + "to": "user::update", + "kind": "core", + "conn": "core", + "actor": "Service.MergeUsersTx", + "sites": [ + "pkg/service/user_merge.go:118 → pkg/service/user_merge.go:135", + "pkg/service/user_merge.go:118 → pkg/service/user_merge.go:138" + ], + "chain": [ + "service.Service.MergeUsersTx$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::update", + "to": "compute_cluster_user::provision", + "kind": "core", + "conn": "core", + "actor": "Service.MarkComputeClusterUserProvisioned", + "sites": [ + "pkg/service/compute_cluster_user.go:375 → pkg/service/compute_cluster_user.go:379" + ], + "chain": [ + "service.Service.MarkComputeClusterUserProvisioned$1" + ], + "cond": true + }, + { + "from": "user::create", + "to": "compute_cluster_user::approve", + "kind": "core", + "conn": "core", + "actor": "Service.OnboardUser", + "sites": [ + "pkg/service/user_onboard.go:291 → pkg/service/user_onboard.go:299" + ], + "chain": [ + "service.Service.OnboardUser$2" + ], + "cond": true + }, + { + "from": "user::create", + "to": "compute_cluster_user::create", + "kind": "core", + "conn": "core", + "actor": "Service.OnboardUser", + "sites": [ + "pkg/service/user_onboard.go:291 → pkg/service/user_onboard.go:295" + ], + "chain": [ + "service.Service.OnboardUser$2" + ], + "cond": true + }, + { + "from": "user_agreement_acceptance::create", + "to": "user::onboarded", + "kind": "core", + "conn": "core", + "actor": "Service.CompleteOnboarding", + "sites": [ + "pkg/service/user_consent.go:77 → pkg/service/user_onboard.go:439" + ], + "chain": [ + "service.Service.acceptTx", + "service.Service.CompleteOnboarding$1" + ], + "cond": true, + "order": true + }, + { + "from": "user_identity::create", + "to": "user::onboarded", + "kind": "core", + "conn": "core", + "actor": "Service.CompleteOnboarding", + "sites": [ + "pkg/service/identity_resolver.go:229 → pkg/service/user_onboard.go:439" + ], + "chain": [ + "service.Service.bindSubTx", + "service.Service.CompleteOnboarding$1" + ], + "cond": true, + "order": true + }, + { + "from": "user_identity::create", + "to": "user_agreement_acceptance::create", + "kind": "core", + "conn": "core", + "actor": "Service.CompleteOnboarding", + "sites": [ + "pkg/service/identity_resolver.go:229 → pkg/service/user_consent.go:77" + ], + "chain": [ + "service.Service.bindSubTx", + "service.Service.CompleteOnboarding$1", + "service.Service.acceptTx" + ], + "cond": true, + "order": true + }, + { + "from": "compute_allocation::create", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleComputeAllocationChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:73 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleComputeAllocationChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation::update", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleComputeAllocationChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:74 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleComputeAllocationChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::create", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleMembershipChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:76 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleMembershipChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::delete", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleMembershipChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:78 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleMembershipChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::update", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleMembershipChanged", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:77 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleMembershipChanged", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::approve", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleClusterUserApproved", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:69 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleClusterUserApproved", + "subscribers.Subscriber.syncUserAllocations", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::approve", + "to": "compute_cluster_user::update", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleClusterUserApproved", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:69 → pkg/service/compute_cluster_user.go:375" + ], + "chain": [ + "subscribers.Subscriber.handleClusterUserApproved", + "operations.Orchestrator.EnsureClusterAccount", + "operations.Orchestrator.ensureClusterAccountImpl", + "service.Service.MarkComputeClusterUserProvisioned", + "service.Service.MarkComputeClusterUserProvisioned$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::approve", + "to": "user_identity::create", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleClusterUserApproved", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:69 → pkg/service/user_identity.go:65" + ], + "chain": [ + "subscribers.Subscriber.handleClusterUserApproved", + "operations.Orchestrator.EnsureClusterAccount", + "operations.Orchestrator.ensureClusterAccountImpl", + "operations.Orchestrator.storePersonID", + "service.Service.CreateUserIdentity", + "service.Service.CreateUserIdentity$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::approve", + "to": "user_identity::update", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleClusterUserApproved", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:69 → pkg/service/user_identity.go:170" + ], + "chain": [ + "subscribers.Subscriber.handleClusterUserApproved", + "operations.Orchestrator.EnsureClusterAccount", + "operations.Orchestrator.ensureClusterAccountImpl", + "operations.Orchestrator.storePersonID", + "service.Service.UpdateUserIdentity", + "service.Service.UpdateUserIdentity$1" + ], + "cond": true + }, + { + "from": "compute_cluster_user::delete", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleClusterUserDeleted", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:70 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleClusterUserDeleted", + "subscribers.Subscriber.syncUserAllocations", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "user::onboarded", + "to": "compute_allocation::group_provision", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleUserOnboarded", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:71 → pkg/service/compute_allocation.go:194" + ], + "chain": [ + "subscribers.Subscriber.handleUserOnboarded", + "subscribers.Subscriber.syncUserAllocations", + "subscribers.Subscriber.syncAllocation", + "operations.Orchestrator.EnsureAllocationGroup", + "service.Service.MarkComputeAllocationGroupProvisioned", + "service.Service.MarkComputeAllocationGroupProvisioned$1" + ], + "cond": true + }, + { + "from": "user::onboarded", + "to": "compute_cluster_user::update", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleUserOnboarded", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:71 → pkg/service/compute_cluster_user.go:375" + ], + "chain": [ + "subscribers.Subscriber.handleUserOnboarded", + "operations.Orchestrator.EnsureClusterAccount", + "operations.Orchestrator.ensureClusterAccountImpl", + "service.Service.MarkComputeClusterUserProvisioned", + "service.Service.MarkComputeClusterUserProvisioned$1" + ], + "cond": true + }, + { + "from": "user::onboarded", + "to": "user_identity::create", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleUserOnboarded", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:71 → pkg/service/user_identity.go:65" + ], + "chain": [ + "subscribers.Subscriber.handleUserOnboarded", + "operations.Orchestrator.EnsureClusterAccount", + "operations.Orchestrator.ensureClusterAccountImpl", + "operations.Orchestrator.storePersonID", + "service.Service.CreateUserIdentity", + "service.Service.CreateUserIdentity$1" + ], + "cond": true + }, + { + "from": "user::onboarded", + "to": "user_identity::update", + "kind": "conn", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleUserOnboarded", + "sites": [ + "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:71 → pkg/service/user_identity.go:170" + ], + "chain": [ + "subscribers.Subscriber.handleUserOnboarded", + "operations.Orchestrator.EnsureClusterAccount", + "operations.Orchestrator.ensureClusterAccountImpl", + "operations.Orchestrator.storePersonID", + "service.Service.UpdateUserIdentity", + "service.Service.UpdateUserIdentity$1" + ], + "cond": true + } + ], + "terms": [ + { + "from": "compute_cluster_user::approve", + "conn": "AMIE", + "actor": "AMIE.HeldReplies.approved", + "site": "connectors/ACCESS/AMIE-Processor/handler/held_reply.go:73", + "effects": [ + "amieclient.Client.ReplyToPacket", + "store.pgAuditExtrasStore.Save", + "store.pgPacketStore.Update" + ], + "cond": true + }, + { + "from": "compute_cluster_user::deny", + "conn": "AMIE", + "actor": "AMIE.HeldReplies.denied", + "site": "connectors/ACCESS/AMIE-Processor/handler/held_reply.go:74", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation::delete", + "conn": "COmanage", + "actor": "COmanage.Subscriber.handleComputeAllocationDeleted", + "site": "connectors/COmanage/Identity-Provisioner/internal/subscribers/cluster_user.go:75", + "effects": [ + "client.Client.DeleteCoGroup", + "client.Client.DeleteUnixClusterGroup" + ], + "cond": true + }, + { + "from": "compute_cluster_user::approve", + "conn": "Email", + "actor": "Email.Notifier.requestApproved", + "site": "connectors/Notification/Email/internal/notify/notifier.go:52", + "effects": [ + "notify.SMTP.Send" + ], + "cond": true + }, + { + "from": "compute_cluster_user::create", + "conn": "Email", + "actor": "Email.Notifier.requestReceived", + "site": "connectors/Notification/Email/internal/notify/notifier.go:51", + "effects": [], + "cond": true + }, + { + "from": "compute_cluster_user::deny", + "conn": "Email", + "actor": "Email.Notifier.requestDenied", + "site": "connectors/Notification/Email/internal/notify/notifier.go:54", + "effects": [], + "cond": true + }, + { + "from": "compute_cluster_user::provision", + "conn": "Email", + "actor": "Email.Notifier.accountReady", + "site": "connectors/Notification/Email/internal/notify/notifier.go:53", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation::create", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationCreated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:67", + "effects": [ + "client.Client.CreateAccount", + "client.Client.do" + ], + "cond": true + }, + { + "from": "compute_allocation::delete", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationDeleted", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:68", + "effects": [ + "client.Client.DeleteAssociation", + "client.Client.ListAssociations" + ], + "cond": true + }, + { + "from": "compute_allocation::update", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationUpdated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:69", + "effects": [ + "client.Client.SetDefaultAccount", + "client.Client.UpsertAssociation" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::create", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationMembershipCreated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:70", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation_membership::delete", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationMembershipDeleted", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:72", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation_membership::update", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationMembershipUpdated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:71", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation_membership_resource_override::create", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationMembershipResourceOverrideCreated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:73", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation_resource_mapping::create", + "conn": "SLURM", + "actor": "SLURM.AssociationSubscriber.handleComputeAllocationResourceMappingCreated", + "site": "connectors/SLURM/Association-Mapper/internal/subscribers/subscriber.go:74", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation::delete", + "conn": "VAST", + "actor": "VAST.StorageSubscriber.markAllocation", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:89", + "effects": [ + "folders.Registry.MarkFoldersForDeletion" + ], + "cond": true + }, + { + "from": "compute_allocation::group_provision", + "conn": "VAST", + "actor": "VAST.StorageSubscriber.ensureAllocation", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:85", + "effects": [ + "client.Client.CreateFolder", + "client.Client.CreateQuota", + "client.Client.CreateView", + "client.Client.do", + "folders.Registry.Record" + ], + "cond": true + }, + { + "from": "compute_allocation_membership::create", + "conn": "VAST", + "actor": "VAST.StorageSubscriber.ensureMember", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:86", + "effects": [], + "cond": true + }, + { + "from": "compute_allocation_membership::update", + "conn": "VAST", + "actor": "VAST.StorageSubscriber.ensureMember", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:87", + "effects": [], + "cond": true + }, + { + "from": "compute_cluster_user::delete", + "conn": "VAST", + "actor": "VAST.StorageSubscriber.markUser", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:88", + "effects": [], + "cond": true + }, + { + "from": "compute_cluster_user::provision", + "conn": "VAST", + "actor": "VAST.StorageSubscriber.ensureUser", + "site": "connectors/Storage/VAST-Provisioner/internal/subscribers/subscriber.go:84", + "effects": [], + "cond": true + } + ] +} diff --git a/api/eventgraph.go b/api/eventgraph.go new file mode 100644 index 000000000..3be501adb --- /dev/null +++ b/api/eventgraph.go @@ -0,0 +1,25 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package api + +import _ "embed" + +// EventGraph is the event graph of this revision, written by tools/eventgraph. +// +//go:embed event-graph.json +var EventGraph []byte diff --git a/cmd/server/main.go b/cmd/server/main.go index a33c26f8a..47fafbc4b 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -20,6 +20,7 @@ package main //go:generate go run github.com/swaggo/swag/cmd/swag init -g main.go -d .,../../internal/server,../../internal/connectors,../../pkg/models -o ../../api --outputTypes yaml --parseDependency --useStructName //go:generate mv ../../api/swagger.yaml ../../api/core.openapi.yaml +//go:generate go run -C ../../tools/eventgraph . -root ../.. -o ../../api/event-graph.json import ( "context" diff --git a/internal/server/event_delivery.go b/internal/server/event_delivery.go index ee0c3862c..b21d436c9 100644 --- a/internal/server/event_delivery.go +++ b/internal/server/event_delivery.go @@ -18,10 +18,12 @@ package server import ( + "encoding/json" "errors" "fmt" "net/http" + "github.com/apache/airavata-custos/api" "github.com/apache/airavata-custos/pkg/common" "github.com/apache/airavata-custos/pkg/events" "github.com/apache/airavata-custos/pkg/models" @@ -127,3 +129,14 @@ func (s *Server) listEventSubscriptions(w http.ResponseWriter, r *http.Request) } common.WriteJSON(w, http.StatusOK, map[string]any{"items": rows}) } + +// @Summary Get the event graph +// @Description Every core event, the core and connector transitions between them, and the connector handlers that end a flow. Generated from this revision's source at build time. +// @Tags Events +// @Security BearerAuth +// @Produce json +// @Success 200 {object} object{events=[]object,edges=[]object,terms=[]object} +// @Router /events/graph [get] +func (s *Server) getEventGraph(w http.ResponseWriter, _ *http.Request) { + common.WriteJSON(w, http.StatusOK, json.RawMessage(api.EventGraph)) +} diff --git a/internal/server/event_graph_test.go b/internal/server/event_graph_test.go new file mode 100644 index 000000000..4f0838bf0 --- /dev/null +++ b/internal/server/event_graph_test.go @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestGetEventGraph(t *testing.T) { + rec := httptest.NewRecorder() + (&Server{}).getEventGraph(rec, httptest.NewRequest(http.MethodGet, "/events/graph", nil)) + var g struct { + Events []struct{ ID string } `json:"events"` + Edges []struct{ Kind string } `json:"edges"` + } + if err := json.NewDecoder(rec.Body).Decode(&g); err != nil || rec.Code != http.StatusOK { + t.Fatalf("status %d, decode: %v", rec.Code, err) + } + if len(g.Events) == 0 || len(g.Edges) == 0 { + t.Fatalf("empty graph: %d events, %d edges", len(g.Events), len(g.Edges)) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 6507f2dad..f201b3eab 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -208,6 +208,7 @@ func (s *Server) routes() { s.router.RequirePrivilege("GET /events/deliveries/{id}", models.TracesRead, s.getEventDelivery) s.router.RequirePrivilege("POST /events/deliveries/{id}/retry", models.EventsManage, s.retryEventDelivery) s.router.RequirePrivilege("GET /events/subscriptions", models.TracesRead, s.listEventSubscriptions) + s.router.RequirePrivilege("GET /events/graph", models.TracesRead, s.getEventGraph) } func (s *Server) healthz(w http.ResponseWriter, _ *http.Request) { diff --git a/tools/eventgraph/analyse.go b/tools/eventgraph/analyse.go new file mode 100644 index 000000000..8a1369d74 --- /dev/null +++ b/tools/eventgraph/analyse.go @@ -0,0 +1,501 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package main + +import ( + "go/constant" + "go/types" + "regexp" + "sort" + "strings" + + "golang.org/x/tools/go/callgraph/cha" + "golang.org/x/tools/go/callgraph/vta" + "golang.org/x/tools/go/packages" + "golang.org/x/tools/go/ssa" + "golang.org/x/tools/go/ssa/ssautil" +) + +type Publisher struct { + Func string `json:"func"` + File string `json:"file"` + PublishSite string `json:"publish_site"` + Via []string `json:"via,omitempty"` +} +type Topic struct { + Topic string `json:"topic"` + Const string `json:"const"` + Publishers []Publisher `json:"publishers"` +} +type Subscription struct { + Subscriber string `json:"subscriber"` + Connector string `json:"connector"` + Topic string `json:"topic"` + Handler string `json:"handler"` + File string `json:"file"` + How string `json:"how"` + Conditional bool `json:"conditional"` + Condition string `json:"condition,omitempty"` + ResolvedAt string `json:"resolved_at"` + Chain []string `json:"chain"` + hfn *ssa.Function + regFn *ssa.Function +} +type Emit struct { + Subscriber string `json:"subscriber"` + Handler string `json:"handler"` + RootKind string `json:"root_kind"` + Layer string `json:"layer"` + Topic string `json:"topic"` + Chain []string `json:"chain"` + Conditional bool `json:"conditional"` + Condition string `json:"condition,omitempty"` + PublishSite string `json:"publish_site"` + ArtefactProne bool `json:"artefact_prone,omitempty"` +} + +type origin struct { + topic string + fn *ssa.Function + chain []string + sites []ssa.Instruction + pubPos string +} + +type rootT struct { + fn *ssa.Function + kind string + subscriber string + layer string // base or the connector dir + key string +} + +// connectorOf maps a file to connectors/<A>/<B> or its top two path elements. +func connectorOf(file string) string { + parts := strings.Split(file, "/") + if len(parts) >= 3 && parts[0] == "connectors" { + switch parts[2] { + case "internal", "pkg", "api", "cmd": + return "connectors/" + parts[1] + } + if len(parts) == 3 { + return "connectors/" + parts[1] + } + return "connectors/" + parts[1] + "/" + parts[2] + } + if len(parts) >= 2 { + return parts[0] + "/" + parts[1] + } + return file +} + +func layerOf(f *ssa.Function) string { + if inConnectors(f) { + return connectorOf(pos(f.Pos())) + } + return "base" +} + +var routeRe = regexp.MustCompile(`^(GET|POST|PUT|PATCH|DELETE|HEAD) /`) + +type state struct { + pkgs []*packages.Package + all map[*ssa.Function]bool + modFns []*ssa.Function + topicOrder []string + constName map[string]string + origins []origin + originsBy map[*ssa.Function][]origin + topics []Topic + subs []Subscription + roots []rootT + reach map[*ssa.Function]map[*ssa.Function]pathEl + emits []Emit + routeOf map[*ssa.Function]string + connType map[string]string + sinks map[*ssa.Function]*Sink + unresolved []map[string]any + loadErrs []string + trans []Transition +} + +func analyse() *state { + modPath = readModPath() + eventsPkg = modPath + "/pkg/events" + st := &state{constName: map[string]string{}, originsBy: map[*ssa.Function][]origin{}, + reach: map[*ssa.Function]map[*ssa.Function]pathEl{}, routeOf: map[*ssa.Function]string{}, + connType: map[string]string{}} + cfg := &packages.Config{ + Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | + packages.NeedDeps | packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedTypesSizes | packages.NeedModule, + Dir: repoRoot, + Tests: false, + } + pkgs, err := packages.Load(cfg, "./...") + if err != nil { + panic(err) + } + st.pkgs = pkgs + packages.Visit(pkgs, nil, func(p *packages.Package) { + for _, e := range p.Errors { + st.loadErrs = append(st.loadErrs, e.Error()) + } + }) + fset = pkgs[0].Fset + var ssapkgs []*ssa.Package + prog, ssapkgs = ssautil.AllPackages(pkgs, ssa.InstantiateGenerics) + prog.Build() + st.all = ssautil.AllFunctions(prog) + cg = vta.CallGraph(st.all, cha.CallGraph(prog)) + + var evp *ssa.Package + for _, p := range ssapkgs { + if p != nil && p.Pkg.Path() == eventsPkg { + evp = p + } + } + if evp == nil { + panic("events package not found") + } + for f := range st.all { + if inModule(f) && !isMock(f) && !inEvents(f) && len(f.Blocks) > 0 { + st.modFns = append(st.modFns, f) + } + } + sort.Slice(st.modFns, func(i, j int) bool { return fname(st.modFns[i]) < fname(st.modFns[j]) }) + + etype := evp.Pkg.Scope().Lookup("EventType") + for _, n := range evp.Pkg.Scope().Names() { + if c, ok := evp.Pkg.Scope().Lookup(n).(*types.Const); ok && types.Identical(c.Type(), etype.Type()) { + v := constant.StringVal(c.Val()) + st.constName[v] = n + st.topicOrder = append(st.topicOrder, v) + } + } + sort.Strings(st.topicOrder) + + busPtr := types.NewPointer(evp.Pkg.Scope().Lookup("Bus").Type()) + mset := prog.MethodSets.MethodSet(busPtr) + method := func(n string) *ssa.Function { + if s := mset.Lookup(evp.Pkg, n); s != nil { + return prog.MethodValue(s) + } + return nil + } + st.findPublishes(method("Publish")) + st.findSubscriptions(method("Subscribe")) + st.findRoutes() + st.findConnectorTypes() + st.findRoots() + st.classifySinks() + + for _, r := range st.roots { + par := bfs(r.fn, r.layer == "base") + st.reach[r.fn] = par + best := map[string]Emit{} + for _, f := range sortedFns(par) { + for _, o := range st.originsBy[f] { + names, sites, art := pathTo(par, r.fn, f) + chain := append(names, o.chain[1:]...) + if old, ok := best[o.topic]; ok && len(old.Chain) <= len(chain) { + continue + } + c, why := condOf(append(sites, o.sites...)) + e := Emit{Subscriber: r.subscriber, Handler: fname(r.fn), RootKind: r.kind, Layer: r.layer, Topic: o.topic, Chain: chain, + Conditional: c, Condition: why, PublishSite: o.pubPos, ArtefactProne: art} + best[o.topic] = e + } + } + for _, t := range sortedKeys(best) { + st.emits = append(st.emits, best[t]) + } + } + st.trans = st.coreTransitions() + return st +} + +func (st *state) findPublishes(publish *ssa.Function) { + for _, e := range sortedIn(cg.Nodes[publish]) { + if isMock(e.Caller.Func) { + continue + } + ts := lift(e.Caller.Func, []aval{{v: argAt(e.Site, publish, 3)}}, []hop{{e.Caller.Func, e.Site}}, map[*ssa.Function]bool{}) + for _, t := range ts { + if t.Vals[0].Kind != "str" { + st.unresolved = append(st.unresolved, map[string]any{"kind": "publish topic", "site": instrPos(e.Site), "why": t.Vals[0].S}) + continue + } + o := origin{topic: t.Vals[0].S, fn: t.Hops[len(t.Hops)-1].Fn, pubPos: instrPos(e.Site)} + for i := len(t.Hops) - 1; i >= 0; i-- { + o.chain = append(o.chain, fname(t.Hops[i].Fn)) + o.sites = append(o.sites, t.Hops[i].Site) + } + st.origins = append(st.origins, o) + st.originsBy[o.fn] = append(st.originsBy[o.fn], o) + } + } + pubBy := map[string][]Publisher{} + for _, o := range st.origins { + p := Publisher{Func: o.chain[0], File: instrPos(o.sites[0]), PublishSite: o.pubPos} + if len(o.chain) > 1 { + p.Via = o.chain[1:] + } + pubBy[o.topic] = append(pubBy[o.topic], p) + } + for _, t := range st.topicOrder { + ps := pubBy[t] + sort.Slice(ps, func(i, j int) bool { return ps[i].File < ps[j].File }) + st.topics = append(st.topics, Topic{Topic: t, Const: st.constName[t], Publishers: ps}) + } + for _, t := range sortedKeys(pubBy) { + if _, ok := st.constName[t]; !ok { + st.topics = append(st.topics, Topic{Topic: t, Const: "(not a pkg/events constant)", Publishers: pubBy[t]}) + } + } +} + +func (st *state) findSubscriptions(subscribe *ssa.Function) { + for _, e := range sortedIn(cg.Nodes[subscribe]) { + if isMock(e.Caller.Func) { + continue + } + vals := []aval{{v: argAt(e.Site, subscribe, 1)}, {v: argAt(e.Site, subscribe, 2)}, {v: argAt(e.Site, subscribe, 3)}} + for _, t := range lift(e.Caller.Func, vals, []hop{{e.Caller.Func, e.Site}}, map[*ssa.Function]bool{}) { + if allInEvents(t.Hops) { + continue + } + s := Subscription{} + var chain []string + for i := len(t.Hops) - 1; i >= 0; i-- { + chain = append(chain, fname(t.Hops[i].Fn)) + } + s.Chain = append(chain, fname(subscribe)) + s.ResolvedAt = instrPos(t.Hops[len(t.Hops)-1].Site) + helper := "" + var outer []ssa.Instruction + for _, h := range t.Hops { + if !inEvents(h.Fn) { + if s.regFn == nil { + s.File = instrPos(h.Site) + s.regFn = h.Fn + } + outer = append(outer, h.Site) + } else if s.regFn == nil && strings.HasPrefix(h.Fn.Name(), "Subscribe") { + helper = h.Fn.Name() + } + } + switch { + case helper != "": + s.How = "helper Bus." + helper + " -> subscribeTyped -> Bus.Subscribe" + case inEvents(t.Hops[0].Fn): + s.How = "generic subscribeTyped -> Bus.Subscribe" + default: + s.How = "direct Bus.Subscribe" + } + s.Subscriber, s.Topic = t.Vals[0].S, t.Vals[1].S + if t.Vals[0].Kind != "str" { + s.Subscriber = "UNRESOLVED(" + t.Vals[0].S + ")" + st.unresolved = append(st.unresolved, map[string]any{"kind": "subscriber name", "site": s.File, "why": t.Vals[0].S}) + } + if t.Vals[1].Kind != "str" { + s.Topic = "UNRESOLVED(" + t.Vals[1].S + ")" + s.How += "; topic not constant (config or dynamic)" + st.unresolved = append(st.unresolved, map[string]any{"kind": "subscription topic", "site": s.File, "why": t.Vals[1].S}) + } + if t.Vals[2].Kind == "func" { + s.hfn = t.Vals[2].Fn + s.Handler = fname(s.hfn) + } else { + s.Handler = "UNRESOLVED(" + t.Vals[2].S + ")" + st.unresolved = append(st.unresolved, map[string]any{"kind": "handler", "site": s.File, "why": t.Vals[2].S}) + } + s.Connector = connectorOf(s.File) + if !strings.HasPrefix(s.File, "connectors/") { + s.Connector = "core" + } + s.Conditional, s.Condition = condOf(outer) + st.subs = append(st.subs, s) + } + } + sort.Slice(st.subs, func(i, j int) bool { + a, b := st.subs[i], st.subs[j] + if a.Subscriber != b.Subscriber { + return a.Subscriber < b.Subscriber + } + if a.Topic != b.Topic { + return a.Topic < b.Topic + } + return a.Handler < b.Handler + }) +} + +// findRoutes maps HTTP handler funcs to the "METHOD /path" constant passed with them. +func (st *state) findRoutes() { + for _, f := range st.modFns { + for _, b := range f.Blocks { + for _, in := range b.Instrs { + c, ok := in.(ssa.CallInstruction) + if !ok { + continue + } + route := "" + for _, a := range c.Common().Args { + if k, ok := a.(*ssa.Const); ok && k.Value != nil && k.Value.Kind() == constant.String && routeRe.MatchString(constant.StringVal(k.Value)) { + route = constant.StringVal(k.Value) + } + } + if route == "" { + continue + } + for _, a := range c.Common().Args { + if _, ok := a.Type().Underlying().(*types.Signature); !ok { + continue + } + for _, o := range local(a, 0) { + if o.l != nil && o.l.Kind == "func" { + if old, ok := st.routeOf[o.l.Fn]; !ok || old > route { + st.routeOf[o.l.Fn] = route + } + } + } + } + } + } + } +} + +// findConnectorTypes records the package-level "Type" constant of each connector. +func (st *state) findConnectorTypes() { + packages.Visit(st.pkgs, nil, func(p *packages.Package) { + if !strings.HasPrefix(p.PkgPath, modPath+"/connectors/") || p.Types == nil { + return + } + if c, ok := p.Types.Scope().Lookup("Type").(*types.Const); ok && c.Val().Kind() == constant.String { + st.connType[connectorOf(pos(c.Pos()))] = constant.StringVal(c.Val()) + } + }) +} + +func (st *state) findRoots() { + seen := map[*ssa.Function]bool{} + add := func(f *ssa.Function, kind, sub string) { + if f == nil || seen[f] || strings.HasPrefix(pos(f.Pos()), "dev-ops/") { + return + } + seen[f] = true + r := rootT{fn: f, kind: kind, subscriber: sub, layer: layerOf(f)} + r.key = fname(f) + if rt, ok := st.routeOf[f]; ok { + r.key = "route " + rt + } + st.roots = append(st.roots, r) + } + handlerSubs := map[*ssa.Function][]string{} + for _, s := range st.subs { + if s.hfn != nil { + handlerSubs[s.hfn] = appendU(handlerSubs[s.hfn], s.Subscriber) + } + } + for _, s := range st.subs { + if s.hfn != nil { + add(s.hfn, "handler", strings.Join(handlerSubs[s.hfn], ",")) + } + } + for _, f := range st.modFns { + if f.Name() == "main" && f.Pkg != nil && f.Pkg.Pkg.Name() == "main" && f.Parent() == nil { + add(f, "main", "server") + } + } + for _, f := range st.modFns { + if _, ok := st.routeOf[f]; ok { + add(f, "http route", connectorOf(pos(f.Pos()))) + } + } + for _, f := range st.modFns { + if f.Parent() == nil && f.Synthetic == "" && httpSig(f) && !strings.HasPrefix(pos(f.Pos()), "pkg/identity/") { + add(f, "http handler (no route constant found)", connectorOf(pos(f.Pos()))) + } + } + loopName := regexp.MustCompile(`(?i)^(run|start|reconcile|poll|sweep|process|loop|tick|drain|scan|watch|monitor|expire)`) + for _, f := range st.modFns { + file := pos(f.Pos()) + for _, b := range f.Blocks { + for _, in := range b.Instrs { + if g, ok := in.(*ssa.Go); ok { + if c := g.Call.StaticCallee(); c != nil && inModule(c) { + add(c, "goroutine (go stmt in "+fname(f)+")", connectorOf(file)) + } + } + if c, ok := in.(ssa.CallInstruction); ok { + if s := c.Common().StaticCallee(); s != nil && s.Pkg != nil && s.Pkg.Pkg.Path() == "time" && + (s.Name() == "NewTicker" || s.Name() == "Tick" || s.Name() == "NewTimer" || s.Name() == "After") { + add(f, "ticker loop", connectorOf(file)) + } + } + } + } + } + for _, f := range st.modFns { + file := pos(f.Pos()) + if (strings.HasPrefix(file, "connectors/") || strings.HasPrefix(file, "internal/") || strings.HasPrefix(file, "pkg/")) && + f.Parent() == nil && f.Synthetic == "" && loopName.MatchString(f.Name()) && f.Object() != nil { + add(f, "loop-named func", connectorOf(file)) + } + } +} + +func httpSig(f *ssa.Function) bool { + p := f.Signature.Params() + return p.Len() == 2 && p.At(0).Type().String() == "net/http.ResponseWriter" && p.At(1).Type().String() == "*net/http.Request" +} + +func appendU(s []string, v string) []string { + for _, x := range s { + if x == v { + return s + } + } + return append(s, v) +} + +func sortedKeys[V any](m map[string]V) []string { + var k []string + for x := range m { + k = append(k, x) + } + sort.Strings(k) + return k +} + +func allInEvents(hops []hop) bool { + for _, h := range hops { + if !inEvents(h.Fn) { + return false + } + } + return true +} + +func sortedFns(par map[*ssa.Function]pathEl) []*ssa.Function { + out := make([]*ssa.Function, 0, len(par)) + for f := range par { + out = append(out, f) + } + sort.Slice(out, func(i, j int) bool { return fname(out[i]) < fname(out[j]) }) + return out +} diff --git a/tools/eventgraph/flow.go b/tools/eventgraph/flow.go new file mode 100644 index 000000000..39367c3d9 --- /dev/null +++ b/tools/eventgraph/flow.go @@ -0,0 +1,156 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package main + +import ( + "go/constant" + "regexp" + "sort" + "strings" + + "golang.org/x/tools/go/ssa" +) + +// Sink is a function that leaves the process or writes the database. +type Sink struct { + Name string `json:"name"` + Class string `json:"class"` // external or db write + Scope string `json:"scope"` // core or connector dir + Detail string `json:"detail"` + Tables []string `json:"tables,omitempty"` +} + +var sqlWrite = regexp.MustCompile(`(?is)\b(insert\s+into|delete\s+from)\s+([a-z_][a-z0-9_."]*)|\b(update)\s+([a-z_][a-z0-9_."]*)(?:\s+(?:as\s+)?[a-z_][a-z0-9_]*)?\s+set\b`) + +var extCallees = map[string]bool{ + "(*net/http.Client).Do": true, "(*net/http.Client).Get": true, "(*net/http.Client).Post": true, + "(*net/http.Client).PostForm": true, "(*net/http.Client).Head": true, + "net/http.Get": true, "net/http.Post": true, "net/http.PostForm": true, "net/http.Head": true, + "net/smtp.SendMail": true, "os/exec.Command": true, "os/exec.CommandContext": true, +} + +func extIO(c *ssa.Function) bool { + if c == nil || inModule(c) { + return false + } + s := c.String() + if extCallees[s] { + return true + } + p := pkgOf(c) + n := c.Name() + if strings.Contains(p, "mail") && (strings.HasPrefix(n, "DialAndSend") || n == "Send") { + return true + } + return strings.Contains(p, "ldap") || strings.Contains(p, "x/crypto/ssh") +} + +// classifySinks marks module functions that call an external I/O function +// (HTTP client, SMTP, exec, LDAP, SSH) or carry an SQL INSERT/UPDATE/DELETE literal. +func (st *state) classifySinks() { + st.sinks = map[*ssa.Function]*Sink{} + for _, f := range st.modFns { + file := pos(f.Pos()) + if strings.HasPrefix(file, "dev-ops/") { + continue + } + scope := "core" + if strings.HasPrefix(file, "connectors/") { + scope = connectorOf(file) + } + var ext, methods []string + var tables []string + node := cg.Nodes[f] + for _, b := range f.Blocks { + for _, in := range b.Instrs { + for _, op := range in.Operands(nil) { + if k, ok := (*op).(*ssa.Const); ok && k.Value != nil && k.Value.Kind() == constant.String { + for _, m := range sqlWrite.FindAllStringSubmatch(constant.StringVal(k.Value), -1) { + verb, tbl := m[1], m[2] + if verb == "" { + verb, tbl = m[3], m[4] + } + tables = appendU(tables, strings.ToUpper(strings.Fields(verb)[0])+" "+strings.Trim(tbl, `"`)) + } + } + } + c, ok := in.(ssa.CallInstruction) + if !ok { + continue + } + callee := c.Common().StaticCallee() + if callee != nil && (callee.Name() == "NewRequest" || callee.Name() == "NewRequestWithContext") && pkgOf(callee) == "net/http" { + i := 0 + if callee.Name() == "NewRequestWithContext" { + i = 1 + } + if k, ok := c.Common().Args[i].(*ssa.Const); ok && k.Value != nil { + methods = appendU(methods, constant.StringVal(k.Value)) + } else { + methods = appendU(methods, "method from variable") + } + } + if extIO(callee) { + ext = appendU(ext, callee.String()) + } + if node != nil { + for _, e := range node.Out { + if e.Site == c && extIO(e.Callee.Func) { + ext = appendU(ext, e.Callee.Func.String()) + } + } + } + } + } + sort.Strings(tables) + switch { + case len(ext) > 0: + d := "calls " + strings.Join(ext, ", ") + if len(methods) > 0 { + d += "; http methods " + strings.Join(methods, ",") + } + st.sinks[f] = &Sink{Name: fname(f), Class: "external", Scope: scope, Detail: d} + case len(tables) > 0: + st.sinks[f] = &Sink{Name: fname(f), Class: "db write", Scope: scope, Detail: "SQL literal", Tables: tables} + } + } + // Exported functions of a client package that reach its transport are the external API methods. + transport := map[string][]*ssa.Function{} + for f, s := range st.sinks { + if s.Class == "external" { + s.Class = "external transport" + transport[pkgOf(f)] = append(transport[pkgOf(f)], f) + } + } + for k := range transport { + sort.Slice(transport[k], func(i, j int) bool { return fname(transport[k][i]) < fname(transport[k][j]) }) + } + for _, f := range st.modFns { + ts := transport[pkgOf(f)] + if len(ts) == 0 || st.sinks[f] != nil || f.Parent() != nil || f.Object() == nil || !f.Object().Exported() { + continue + } + par := bfs(f, false) + for _, t := range ts { + if _, ok := par[t]; ok { + st.sinks[f] = &Sink{Name: fname(f), Class: "external API method", Scope: st.sinks[t].Scope, Detail: "exported in " + strings.TrimPrefix(pkgOf(f), modPath+"/") + "; reaches " + fname(t)} + break + } + } + } +} diff --git a/tools/eventgraph/go.mod b/tools/eventgraph/go.mod new file mode 100644 index 000000000..e8ca7b8c9 --- /dev/null +++ b/tools/eventgraph/go.mod @@ -0,0 +1,10 @@ +module github.com/apache/airavata-custos/tools/eventgraph + +go 1.26.0 + +require golang.org/x/tools v0.52.0 + +require ( + golang.org/x/mod v0.42.0 // indirect + golang.org/x/sync v0.24.0 // indirect +) diff --git a/tools/eventgraph/go.sum b/tools/eventgraph/go.sum new file mode 100644 index 000000000..5f746ef04 --- /dev/null +++ b/tools/eventgraph/go.sum @@ -0,0 +1,6 @@ +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= diff --git a/tools/eventgraph/graph.go b/tools/eventgraph/graph.go new file mode 100644 index 000000000..d0d4ebc9d --- /dev/null +++ b/tools/eventgraph/graph.go @@ -0,0 +1,332 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package main + +import ( + "regexp" + "sort" + "strings" +) + +type Entry struct { + Kind string `json:"kind"` + Label string `json:"label"` +} + +type Event struct { + ID string `json:"id"` + Entry []Entry `json:"entry"` + Subs int `json:"subs"` +} + +// Edge is a transition: a core function publishes To after From (core), or a +// connector handler subscribed to From emits To as a primary emission (conn). +type Edge struct { + From string `json:"from"` + To string `json:"to"` + Kind string `json:"kind"` + Conn string `json:"conn"` + Actor string `json:"actor"` + Sites []string `json:"sites"` + Chain []string `json:"chain"` + Cond bool `json:"cond"` + // Order marks a core pair published in a helper and then its caller: sequence, not cause. + Order bool `json:"order,omitempty"` +} + +// Term is a handler subscribed to From that emits no event. +type Term struct { + From string `json:"from"` + Conn string `json:"conn"` + Actor string `json:"actor"` + Site string `json:"site"` + Effects []string `json:"effects"` + Cond bool `json:"cond"` +} + +type Graph struct { + Events []*Event `json:"events"` + Edges []*Edge `json:"edges"` + Terms []*Term `json:"terms"` +} + +var connNames = map[string]string{"amie-processor": "AMIE", "comanage-identity-provisioner": "COmanage", "email-notifier": "Email", + "slurm-association-mapper": "SLURM", "slurm-usage-monitor": "SLURMUsage", "vast-storage-provisioner": "VAST", + "temp-account": "TempAccount", "analytics": "Analytics"} + +var ( + tagRe = regexp.MustCompile(` \[[^]]*\]$`) + closRe = regexp.MustCompile(`\$\d+$`) + recvRe = regexp.MustCompile(`^\(\*?`) + tickerRe = regexp.MustCompile(`ticker|loop|goroutine`) +) + +func bare(f string) string { return tagRe.ReplaceAllString(f, "") } + +func short(f string) string { + s := strings.ReplaceAll(recvRe.ReplaceAllString(bare(f), ""), ")", "") + return s[strings.LastIndex(s, "/")+1:] +} + +func actor(f string) string { + s := short(f) + if i := strings.Index(s, "."); i >= 0 { + s = s[i+1:] + } + return closRe.ReplaceAllString(s, "") +} + +func shorts(xs []string) []string { + out := make([]string, len(xs)) + for i, x := range xs { + out[i] = short(x) + } + return out +} + +func rootLabel(key string) string { + if l, ok := strings.CutPrefix(key, "route "); ok { + return l + } + return short(key) +} + +func coreEntryKind(kind string) string { + switch { + case kind == "http route": + return "API" + case kind == "main": + return "startup" + case tickerRe.MatchString(kind): + return "timer" + } + return kind +} + +// overlayKey names a connector directory by its registered type when it has one. +func (st *state) overlayKey(dir string) string { + if t := st.connType[dir]; t != "" { + return t + } + return dir +} + +// graph reduces the analysis to events, transitions and end steps. +func (st *state) graph() Graph { + var g Graph + events, edges, terms := map[string]*Event{}, map[[3]string]*Edge{}, map[[2]string]*Term{} + node := func(t string) *Event { + if events[t] == nil { + events[t] = &Event{ID: t, Entry: []Entry{}} + g.Events = append(g.Events, events[t]) + } + return events[t] + } + edge := func(e *Edge) { + node(e.From) + node(e.To) + k := [3]string{e.From, e.To, e.Actor} + o := edges[k] + if o == nil { + edges[k] = e + g.Edges = append(g.Edges, e) + return + } + o.Cond = o.Cond && e.Cond + o.Order = o.Order && e.Order + for _, s := range e.Sites { + o.Sites = appendU(o.Sites, s) + } + } + + pubSite := map[string]string{} + for _, t := range st.topics { + for _, p := range t.Publishers { + pubSite[bare(p.Func)] = p.PublishSite + } + if len(t.Publishers) > 0 { + node(t.Topic) + } + } + trans := map[[2]string]bool{} + for _, x := range st.trans { + if x.From == x.To { + continue + } + trans[[2]string{x.From, x.To}] = true + edge(&Edge{From: x.From, To: x.To, Kind: "core", Conn: "core", Actor: actor(x.Func), Sites: []string{x.SiteFrom + " → " + x.SiteTo}, + Chain: shorts(x.Chain), Cond: x.Conditional, Order: actor(x.Chain[0]) != actor(x.Func)}) + } + + // Entries: topics an entry point emits that no transition from another of its topics explains. + var entryKeys []Entry + entryTopics := map[Entry][]string{} + addEntry := func(k Entry, t string) { + if entryTopics[k] == nil { + entryKeys = append(entryKeys, k) + } + entryTopics[k] = appendU(entryTopics[k], t) + } + baseRoot := map[string]rootT{} + for _, r := range st.roots { + if r.layer == "base" && r.kind != "handler" { + baseRoot[fname(r.fn)] = r + } + } + for _, e := range st.emits { + if e.Layer == "base" && e.RootKind != "handler" { + r, ok := baseRoot[e.Handler] + key := e.Handler + if ok { + key = r.key + } + addEntry(Entry{coreEntryKind(r.kind), rootLabel(key)}, e.Topic) + } + } + dirs := sortedKeys(st.connType) + for _, s := range st.subs { + if s.Connector != "core" { + dirs = appendU(dirs, s.Connector) + } + } + for _, e := range st.emits { + if e.Layer != "base" { + dirs = appendU(dirs, e.Layer) + } + } + for _, r := range st.roots { + if r.layer != "base" { + dirs = appendU(dirs, r.layer) + } + } + sort.Slice(dirs, func(i, j int) bool { return st.overlayKey(dirs[i]) < st.overlayKey(dirs[j]) }) + connName := func(dir string) string { + if n := connNames[st.overlayKey(dir)]; n != "" { + return n + } + return st.overlayKey(dir) + } + for _, dir := range dirs { + for _, r := range st.roots { + if r.layer != dir || r.kind == "handler" { + continue + } + for _, e := range st.emits { + if e.Handler == fname(r.fn) && e.RootKind == r.kind { + addEntry(Entry{connName(dir), rootLabel(r.key)}, e.Topic) + } + } + } + } + for _, k := range entryKeys { + ts := entryTopics[k] + for _, t := range ts { + explained := false + for _, a := range ts { + explained = explained || (a != t && trans[[2]string{a, t}]) + } + if !explained { + node(t).Entry = append(node(t).Entry, k) + } + } + } + + for _, dir := range dirs { + c := connName(dir) + emits := map[string][]Emit{} + for _, e := range st.emits { + if e.Layer == dir && e.RootKind == "handler" { + emits[e.Handler] = append(emits[e.Handler], e) + } + } + primary := map[string]map[string]bool{} + for _, s := range st.subs { + if s.Connector == dir && s.hfn != nil && primary[s.Handler] == nil { + primary[s.Handler] = map[string]bool{} + for _, t := range st.handlerPrimary(st.trans, s.Handler, s.hfn) { + primary[s.Handler][t] = true + } + } + } + effects := st.externalEffects(dir) + for _, s := range st.subs { + if s.Connector != dir { + continue + } + name := c + "." + actor(s.Handler) + node(s.Topic).Subs++ + var out []Emit + for _, e := range emits[s.Handler] { + if p, ok := primary[s.Handler]; !ok || p[e.Topic] { + out = append(out, e) + } + } + for _, e := range out { + site, ok := pubSite[bare(e.Chain[len(e.Chain)-1])] + if !ok { + site = "?" + } + edge(&Edge{From: s.Topic, To: e.Topic, Kind: "conn", Conn: c, Actor: name, Sites: []string{s.File + " → " + site}, + Chain: shorts(e.Chain), Cond: e.Conditional}) + } + if len(out) == 0 { + k := [2]string{s.Topic, name} + t := &Term{From: s.Topic, Conn: c, Actor: name, Site: s.File, Effects: append([]string{}, effects[s.Handler]...), Cond: s.Conditional} + if terms[k] == nil { + g.Terms = append(g.Terms, t) + } else { + *terms[k] = *t + t = terms[k] + } + terms[k] = t + } + } + } + for _, n := range g.Events { + sort.Slice(n.Entry, func(i, j int) bool { + a, b := n.Entry[i], n.Entry[j] + return a.Kind < b.Kind || a.Kind == b.Kind && a.Label < b.Label + }) + } + return g +} + +// externalEffects maps each root of a connector to the external sinks it is +// the first root of that connector to reach. +func (st *state) externalEffects(dir string) map[string][]string { + out := map[string][]string{} + have := map[string]bool{} + for _, r := range st.roots { + if r.layer != dir { + continue + } + par := st.reach[r.fn] + for _, f := range sortedFns(par) { + s := st.sinks[f] + if s == nil || have[s.Name] || (!strings.HasPrefix(s.Class, "external") && s.Scope == "core") { + continue + } + have[s.Name] = true + out[fname(r.fn)] = appendU(out[fname(r.fn)], short(s.Name)) + } + } + for k := range out { + sort.Strings(out[k]) + } + return out +} diff --git a/tools/eventgraph/main.go b/tools/eventgraph/main.go new file mode 100644 index 000000000..bdcfb2adf --- /dev/null +++ b/tools/eventgraph/main.go @@ -0,0 +1,851 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Command eventgraph maps the Custos event bus of one revision into the event +// graph served at GET /events/graph. It builds SSA and a VTA call graph over ./..., +// resolves every bus Publish and Subscribe call back to its constant topic, and +// follows each handler, loop, HTTP and startup root to the topics it publishes. +// Callbacks passed as arguments count as called at the passing site; mocks and the +// bus internals are not followed. It runs from go generate, never at request time. +package main + +import ( + "bufio" + "encoding/json" + "flag" + "fmt" + "go/constant" + "go/token" + "go/types" + "os" + "path/filepath" + "sort" + "strings" + + "golang.org/x/tools/go/callgraph" + "golang.org/x/tools/go/ssa" +) + +var ( + repoRoot, modPath, eventsPkg string + prog *ssa.Program + cg *callgraph.Graph + fset *token.FileSet +) + +func main() { + flag.StringVar(&repoRoot, "root", ".", "repository root") + out := flag.String("o", "", "output json, stdout if empty") + flag.Parse() + repoRoot, _ = filepath.Abs(repoRoot) + st := analyse() + // A load error or an unresolved bus call would drop events from the graph silently. + if len(st.loadErrs)+len(st.unresolved) > 0 { + fmt.Fprintln(os.Stderr, strings.Join(st.loadErrs, "\n")) + for _, u := range st.unresolved { + fmt.Fprintf(os.Stderr, "unresolved %s at %s: %s\n", u["kind"], u["site"], u["why"]) + } + os.Exit(1) + } + b, err := json.MarshalIndent(st.graph(), "", " ") + if err != nil { + panic(err) + } + b = append(b, '\n') + if *out == "" { + os.Stdout.Write(b) + } else if err := os.WriteFile(*out, b, 0o644); err != nil { + panic(err) + } +} + +func readModPath() string { + f, err := os.Open(filepath.Join(repoRoot, "go.mod")) + if err != nil { + panic(err) + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + if l := strings.TrimSpace(sc.Text()); strings.HasPrefix(l, "module ") { + return strings.TrimSpace(strings.TrimPrefix(l, "module ")) + } + } + panic("no module line") +} + +// ---------- naming helpers ---------- + +func inModule(f *ssa.Function) bool { + if f == nil { + return false + } + if f.Pkg != nil { + return strings.HasPrefix(f.Pkg.Pkg.Path(), modPath) + } + if f.Origin() != nil && f.Origin().Pkg != nil { + return strings.HasPrefix(f.Origin().Pkg.Pkg.Path(), modPath) + } + return false +} + +func pkgOf(f *ssa.Function) string { + if f.Pkg != nil { + return f.Pkg.Pkg.Path() + } + if o := f.Origin(); o != nil && o.Pkg != nil { + return o.Pkg.Pkg.Path() + } + if f.Parent() != nil { + return pkgOf(f.Parent()) + } + return "" +} + +func inEvents(f *ssa.Function) bool { return pkgOf(f) == eventsPkg } + +func fname(f *ssa.Function) string { + s := f.String() + s = strings.ReplaceAll(s, modPath+"/", "") + return s +} + +func pos(p token.Pos) string { + if !p.IsValid() { + return "" + } + ps := fset.Position(p) + r, err := filepath.Rel(repoRoot, ps.Filename) + if err != nil { + r = ps.Filename + } + return fmt.Sprintf("%s:%d", r, ps.Line) +} + +func instrPos(i ssa.Instruction) string { + if i == nil { + return "" + } + if p := i.Pos(); p.IsValid() { + return pos(p) + } + if c, ok := i.(ssa.CallInstruction); ok { + if v := c.Common().Value; v != nil && v.Pos().IsValid() { + return pos(v.Pos()) + } + } + return pos(i.Parent().Pos()) +} + +var srcCache = map[string][]string{} + +func srcLine(p token.Pos) string { + if !p.IsValid() { + return "" + } + ps := fset.Position(p) + lines, ok := srcCache[ps.Filename] + if !ok { + b, _ := os.ReadFile(ps.Filename) + lines = strings.Split(string(b), "\n") + srcCache[ps.Filename] = lines + } + if ps.Line-1 < len(lines) { + return strings.TrimSpace(lines[ps.Line-1]) + } + return "" +} + +func isMock(f *ssa.Function) bool { + if r := f.Signature.Recv(); r != nil { + t := r.Type() + if p, ok := t.(*types.Pointer); ok { + t = p.Elem() + } + if n, ok := t.(*types.Named); ok && strings.HasSuffix(n.Obj().Name(), "Mock") { + return true + } + } + return strings.HasSuffix(fset.Position(f.Pos()).Filename, "/mock.go") +} + +// boundTarget returns the method a bound-method wrapper calls. +func boundTarget(f *ssa.Function) *ssa.Function { + if !strings.HasPrefix(f.Synthetic, "bound method wrapper") { + return f + } + for _, b := range f.Blocks { + for _, in := range b.Instrs { + if c, ok := in.(ssa.CallInstruction); ok { + if s := c.Common().StaticCallee(); s != nil { + return s + } + if c.Common().IsInvoke() { + // Interface method value; keep the wrapper. + return f + } + } + } + } + return f +} + +// ---------- value resolution ---------- + +type leaf struct { + Kind string // str, func, unres + S string + Fn *ssa.Function +} + +type dep struct { + param, free int // one of them >= 0 +} + +type opt struct { + l *leaf + d *dep +} + +func unres(why string) opt { return opt{l: &leaf{Kind: "unres", S: why}} } + +func local(v ssa.Value, depth int) []opt { + if depth > 12 { + return []opt{unres("depth")} + } + switch x := v.(type) { + case *ssa.Const: + if x.Value != nil && x.Value.Kind() == constant.String { + return []opt{{l: &leaf{Kind: "str", S: constant.StringVal(x.Value)}}} + } + return []opt{unres("non-string const " + x.String())} + case *ssa.ChangeType: + return local(x.X, depth+1) + case *ssa.Convert: + return local(x.X, depth+1) + case *ssa.MakeInterface: + return local(x.X, depth+1) + case *ssa.Phi: + var r []opt + for _, e := range x.Edges { + r = append(r, local(e, depth+1)...) + } + return r + case *ssa.Parameter: + for i, p := range x.Parent().Params { + if p == x { + return []opt{{d: &dep{param: i, free: -1}}} + } + } + case *ssa.FreeVar: + for i, p := range x.Parent().FreeVars { + if p == x { + return []opt{{d: &dep{param: -1, free: i}}} + } + } + case *ssa.Function: + return []opt{{l: &leaf{Kind: "func", Fn: x}}} + case *ssa.MakeClosure: + fn := x.Fn.(*ssa.Function) + if strings.HasPrefix(fn.Synthetic, "bound method wrapper") { + return []opt{{l: &leaf{Kind: "func", Fn: boundTarget(fn)}}} + } + if inEvents(fn) && fn.Parent() != nil { + // The bus's typed adapter closure: the user handler is its func-typed binding. + for _, b := range x.Bindings { + if isFuncish(b.Type()) { + return local(b, depth+1) + } + } + } + return []opt{{l: &leaf{Kind: "func", Fn: fn}}} + case *ssa.Call: + if g := x.Common().StaticCallee(); g != nil && inModule(g) && len(g.Blocks) > 0 { + var r []opt + for _, b := range g.Blocks { + if ret, ok := b.Instrs[len(b.Instrs)-1].(*ssa.Return); ok && len(ret.Results) > 0 { + for _, o := range local(ret.Results[0], depth+1) { + if o.d != nil { + o = unres("call result depends on args: " + fname(g)) + } + r = append(r, o) + } + } + } + if len(r) > 0 { + return r + } + } + return []opt{unres("call result " + x.String())} + case *ssa.Alloc: + return stored(x, depth) + case *ssa.UnOp: + if a, ok := x.X.(*ssa.Alloc); ok && x.Op == token.MUL { + return stored(a, depth) + } + return []opt{unres("load " + srcLine(x.Pos()))} + case *ssa.Field, *ssa.FieldAddr, *ssa.Lookup, *ssa.Extract: + return []opt{unres(fmt.Sprintf("%T %s", v, srcLine(v.Pos())))} + } + return []opt{unres(fmt.Sprintf("%T", v))} +} + +// argAt returns the argument a call site passes for the callee's parameter p. +func argAt(site ssa.CallInstruction, callee *ssa.Function, p int) ssa.Value { + c := site.Common() + if c.IsInvoke() { + if p == 0 { + return c.Value + } + p-- + } + if p < len(c.Args) { + return c.Args[p] + } + return nil +} + +type hop struct { + Fn *ssa.Function + Site ssa.Instruction +} + +type tuple struct { + Vals []leaf + Hops []hop // from the sink's caller outward +} + +type aval struct { + v ssa.Value + fixed *leaf +} + +func product(opts [][]opt) [][]opt { + res := [][]opt{{}} + for _, os := range opts { + var nx [][]opt + for _, r := range res { + for _, o := range os { + c := append(append([]opt{}, r...), o) + nx = append(nx, c) + } + } + res = nx + } + return res +} + +func lift(F *ssa.Function, vals []aval, hops []hop, seen map[*ssa.Function]bool) []tuple { + opts := make([][]opt, len(vals)) + for i, a := range vals { + if a.fixed != nil { + opts[i] = []opt{{l: a.fixed}} + } else if a.v == nil { + opts[i] = []opt{unres("missing arg")} + } else { + opts[i] = local(a.v, 0) + } + } + var out []tuple + for _, combo := range product(opts) { + var params, frees bool + for _, o := range combo { + if o.d != nil { + if o.d.param >= 0 { + params = true + } else { + frees = true + } + } + } + if !params && !frees { + t := tuple{Hops: hops} + for _, o := range combo { + t.Vals = append(t.Vals, *o.l) + } + out = append(out, t) + continue + } + if seen[F] || len(hops) > 16 || (params && frees) { + why := "recursion" + if params && frees { + why = "param and free var mix" + } + out = append(out, fixUnres(combo, why, hops)) + continue + } + seen[F] = true + found := false + if params { + node := cg.Nodes[F] + if node != nil { + for _, e := range sortedIn(node) { + if isMock(e.Caller.Func) { + continue + } + found = true + nv := make([]aval, len(combo)) + for i, o := range combo { + if o.d != nil { + nv[i] = aval{v: argAt(e.Site, F, o.d.param)} + } else { + nv[i] = aval{fixed: o.l} + } + } + out = append(out, lift(e.Caller.Func, nv, append(append([]hop{}, hops...), hop{e.Caller.Func, e.Site}), seen)...) + } + } + } else if par := F.Parent(); par != nil { + for _, b := range par.Blocks { + for _, in := range b.Instrs { + mc, ok := in.(*ssa.MakeClosure) + if !ok || mc.Fn != F { + continue + } + found = true + nv := make([]aval, len(combo)) + for i, o := range combo { + if o.d != nil { + nv[i] = aval{v: mc.Bindings[o.d.free]} + } else { + nv[i] = aval{fixed: o.l} + } + } + out = append(out, lift(par, nv, append(append([]hop{}, hops...), hop{par, mc}), seen)...) + } + } + } + delete(seen, F) + if !found { + out = append(out, fixUnres(combo, "no caller of "+fname(F), hops)) + } + } + return out +} + +func fixUnres(combo []opt, why string, hops []hop) tuple { + t := tuple{Hops: hops} + for _, o := range combo { + if o.l != nil { + t.Vals = append(t.Vals, *o.l) + } else { + t.Vals = append(t.Vals, leaf{Kind: "unres", S: why}) + } + } + return t +} + +// ---------- control dependence ---------- + +func exitBlock(b *ssa.BasicBlock) bool { return len(b.Succs) == 0 } + +// postdominates reports whether every path from F's entry to an exit passes b. +func postdominates(b *ssa.BasicBlock) bool { + F := b.Parent() + entry := F.Blocks[0] + if b == entry { + return true + } + seen := map[*ssa.BasicBlock]bool{b: true} + stack := []*ssa.BasicBlock{entry} + seen[entry] = true + for len(stack) > 0 { + x := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if exitBlock(x) { + return false + } + for _, s := range x.Succs { + if !seen[s] { + seen[s] = true + stack = append(stack, s) + } + } + } + return true +} + +func controlling(b *ssa.BasicBlock) string { + for d := b.Idom(); d != nil; d = d.Idom() { + last := d.Instrs[len(d.Instrs)-1] + if iff, ok := last.(*ssa.If); ok { + p := iff.Cond.Pos() + if !p.IsValid() { + for _, in := range d.Instrs { + if in.Pos().IsValid() { + p = in.Pos() + } + } + } + return pos(p) + " " + srcLine(p) + } + } + return pos(b.Parent().Pos()) + " (branch not located)" +} + +// condOf returns whether any site does not post-dominate its function's +// entry, and the first such site's controlling branch. +func condOf(sites []ssa.Instruction) (bool, string) { + for _, s := range sites { + if s == nil || s.Block() == nil { + continue + } + if !postdominates(s.Block()) { + return true, controlling(s.Block()) + } + } + return false, "" +} + +// ---------- graph traversal ---------- + +type step struct { + callee *ssa.Function + site ssa.Instruction + kind string +} + +var succCache = map[*ssa.Function][]step{} + +func succs(F *ssa.Function) []step { + if s, ok := succCache[F]; ok { + return s + } + var out []step + seen := map[[2]any]bool{} + add := func(c *ssa.Function, site ssa.Instruction, kind string) { + if c == nil || isMock(c) || inEvents(c) { + return + } + if !inModule(c) && c.Synthetic == "" { + return + } + k := [2]any{c, site} + if seen[k] { + return + } + seen[k] = true + out = append(out, step{c, site, kind}) + } + if n := cg.Nodes[F]; n != nil { + for _, e := range n.Out { + c := e.Site.Common() + kind := "static" + if c.IsInvoke() { + kind = "iface" + } else if c.StaticCallee() == nil { + if paramDerived(c.Value) { + continue + } + kind = "dyn" + } + if _, ok := e.Site.(*ssa.Go); ok { + kind = "go:" + kind + } + if _, ok := e.Site.(*ssa.Defer); ok { + kind = "defer:" + kind + } + add(e.Callee.Func, e.Site, kind) + } + } + for _, b := range F.Blocks { + for _, in := range b.Instrs { + call, ok := in.(ssa.CallInstruction) + if !ok { + continue + } + for j, a := range call.Common().Args { + var cb *ssa.Function + switch x := a.(type) { + case *ssa.MakeClosure: + cb = boundTarget(x.Fn.(*ssa.Function)) + case *ssa.Function: + cb = x + } + if cb != nil && callInvokesArg(call, j) { + add(cb, in, "callback") + } + } + } + } + sort.SliceStable(out, func(i, j int) bool { + a, b := instrPos(out[i].site), instrPos(out[j].site) + if a != b { + return a < b + } + return fname(out[i].callee) < fname(out[j].callee) + }) + succCache[F] = out + return out +} + +type pathEl struct { + prev *ssa.Function + st step +} + +// inConnectors reports whether f is declared under connectors/. +func inConnectors(f *ssa.Function) bool { return strings.HasPrefix(pos(f.Pos()), "connectors/") } + +// bfs walks the pruned graph from r; base keeps the walk out of connector code. +func bfs(r *ssa.Function, base bool) map[*ssa.Function]pathEl { + par := map[*ssa.Function]pathEl{r: {}} + q := []*ssa.Function{r} + for len(q) > 0 { + f := q[0] + q = q[1:] + for _, s := range succs(f) { + if base && inConnectors(s.callee) { + continue + } + if _, ok := par[s.callee]; !ok { + par[s.callee] = pathEl{f, s} + q = append(q, s.callee) + } + } + } + return par +} + +// siteFanout counts the non-mock module callees the call graph gives a site. +var siteFanout = map[ssa.Instruction]int{} + +func fanout(site ssa.Instruction) int { + if n, ok := siteFanout[site]; ok { + return n + } + n := 0 + if c, ok := site.(ssa.CallInstruction); ok { + if node := cg.Nodes[site.Parent()]; node != nil { + for _, e := range node.Out { + if e.Site == c && !isMock(e.Callee.Func) { + n++ + } + } + } + } + siteFanout[site] = n + return n +} + +// pathTo returns the chain r..f, its call sites, and whether any edge is a +// dynamic or multi-target interface call (a possible analysis artefact). +func pathTo(par map[*ssa.Function]pathEl, r, f *ssa.Function) ([]string, []ssa.Instruction, bool) { + var names []string + var sites []ssa.Instruction + art := false + for x := f; x != r; { + pe := par[x] + n := fname(x) + if pe.st.kind != "static" { + k := pe.st.kind + if strings.Contains(k, "iface") || strings.Contains(k, "dyn") { + if c := fanout(pe.st.site); c > 1 { + k += fmt.Sprintf(" x%d", c) + art = true + } + } + n += " [" + k + "]" + } + names = append([]string{n}, names...) + sites = append([]ssa.Instruction{pe.st.site}, sites...) + x = pe.prev + } + return append([]string{fname(r)}, names...), sites, art +} + +func isFuncish(t types.Type) bool { + if p, ok := t.Underlying().(*types.Pointer); ok { + t = p.Elem() + } + _, ok := t.Underlying().(*types.Signature) + return ok +} + +// stored resolves a local variable to the values stored into it. +func stored(a *ssa.Alloc, depth int) []opt { + var r []opt + for _, ref := range *a.Referrers() { + if s, ok := ref.(*ssa.Store); ok && s.Addr == a { + r = append(r, local(s.Val, depth+1)...) + } + } + if len(r) == 0 { + return []opt{unres("alloc without store")} + } + return r +} + +// paramDerived reports whether a called func value comes from the caller's +// parameters or captures; those calls are modelled at the passing site. +func paramDerived(v ssa.Value) bool { + switch x := v.(type) { + case *ssa.Parameter, *ssa.FreeVar: + return true + case *ssa.UnOp: + if x.Op != token.MUL { + return false + } + switch y := x.X.(type) { + case *ssa.FreeVar: + return true + case *ssa.Alloc: + n := 0 + for _, r := range *y.Referrers() { + if s, ok := r.(*ssa.Store); ok && s.Addr == y { + n++ + if !paramDerived(s.Val) { + return false + } + } + } + return n > 0 + } + } + return false +} + +// callInvokesArg reports whether some callee of the call runs its j-th +// argument, rather than only storing or registering it. +func callInvokesArg(call ssa.CallInstruction, j int) bool { + c := call.Common() + var callees []*ssa.Function + if s := c.StaticCallee(); s != nil { + callees = []*ssa.Function{s} + } else if n := cg.Nodes[call.Parent()]; n != nil { + for _, e := range n.Out { + if e.Site == call { + callees = append(callees, e.Callee.Func) + } + } + } + for _, g := range callees { + p := j + if c.IsInvoke() { + p = j + 1 + } + if invokesParam(g, p, map[*ssa.Function]bool{}) { + return true + } + } + return false +} + +var invokeMemo = map[[2]any]bool{} + +// invokesParam reports whether g calls its parameter p, directly, through a +// local, through a closure it runs, or by passing it to a callee that does. +// Outside the module every func is assumed to run its func arguments, except net/http. +func invokesParam(g *ssa.Function, p int, seen map[*ssa.Function]bool) bool { + if !inModule(g) && g.Synthetic == "" { + return pkgOf(g) != "net/http" + } + if inEvents(g) || p >= len(g.Params) || len(g.Blocks) == 0 { + return false + } + k := [2]any{g, p} + if v, ok := invokeMemo[k]; ok { + return v + } + if seen[g] { + return false + } + seen[g] = true + r := valueInvoked(g.Params[p], seen) + invokeMemo[k] = r + return r +} + +func valueInvoked(v ssa.Value, seen map[*ssa.Function]bool) bool { + refs := v.Referrers() + if refs == nil { + return false + } + for _, r := range *refs { + switch x := r.(type) { + case ssa.CallInstruction: + c := x.Common() + if c.Value == v && !c.IsInvoke() { + return true + } + for j, a := range c.Args { + if a == v && callInvokesArgSeen(x, j, seen) { + return true + } + } + case *ssa.Store: + if x.Val == v { + if a, ok := x.Addr.(*ssa.Alloc); ok { + for _, rr := range *a.Referrers() { + if l, ok := rr.(*ssa.UnOp); ok && l.Op == token.MUL && valueInvoked(l, seen) { + return true + } + } + } + } + case *ssa.MakeClosure: + for k, b := range x.Bindings { + if b == v { + fn := x.Fn.(*ssa.Function) + if valueInvoked(fn.FreeVars[k], seen) && closureRuns(x, seen) { + return true + } + } + } + case *ssa.ChangeType, *ssa.MakeInterface: + if valueInvoked(x.(ssa.Value), seen) { + return true + } + } + } + return false +} + +// closureRuns reports whether the closure value is called or handed to a callee that runs it. +func closureRuns(mc *ssa.MakeClosure, seen map[*ssa.Function]bool) bool { + for _, r := range *mc.Referrers() { + if c, ok := r.(ssa.CallInstruction); ok { + if c.Common().Value == mc { + return true + } + for j, a := range c.Common().Args { + if a == mc && callInvokesArgSeen(c, j, seen) { + return true + } + } + } + } + return false +} + +func callInvokesArgSeen(call ssa.CallInstruction, j int, seen map[*ssa.Function]bool) bool { + c := call.Common() + if s := c.StaticCallee(); s != nil { + return invokesParam(s, j, seen) + } + return callInvokesArg(call, j) +} + +// sortedIn orders a node's in-edges by caller and site so output is stable. +func sortedIn(n *callgraph.Node) []*callgraph.Edge { + in := append([]*callgraph.Edge{}, n.In...) + sort.SliceStable(in, func(i, j int) bool { + a, b := fname(in[i].Caller.Func)+instrPos(in[i].Site), fname(in[j].Caller.Func)+instrPos(in[j].Site) + return a < b + }) + return in +} diff --git a/tools/eventgraph/transitions.go b/tools/eventgraph/transitions.go new file mode 100644 index 000000000..0ac627ba6 --- /dev/null +++ b/tools/eventgraph/transitions.go @@ -0,0 +1,197 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package main + +import ( + "sort" + "strings" + + "golang.org/x/tools/go/ssa" +) + +// Transition is topic B published after topic A on one core code path. +type Transition struct { + From string `json:"from"` + To string `json:"to"` + SiteFrom string `json:"site_from"` + SiteTo string `json:"site_to"` + Func string `json:"func"` + Chain []string `json:"chain"` + Conditional bool `json:"conditional"` + Condition string `json:"condition,omitempty"` + fromFn *ssa.Function +} + +// laterInstrs returns the instructions CFG-reachable after s in its function. +func laterInstrs(s ssa.Instruction) []ssa.Instruction { + b := s.Block() + var out []ssa.Instruction + after := false + for _, in := range b.Instrs { + if after { + out = append(out, in) + } + if in == s { + after = true + } + } + seen := map[*ssa.BasicBlock]bool{} + stack := append([]*ssa.BasicBlock{}, b.Succs...) + for len(stack) > 0 { + x := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if seen[x] { + continue + } + seen[x] = true + out = append(out, x.Instrs...) + stack = append(stack, x.Succs...) + } + return out +} + +var baseReach = map[*ssa.Function]map[*ssa.Function]pathEl{} + +func (st *state) coreTransitions() []Transition { + type key struct{ from, to, sf, stt string } + best := map[key]Transition{} + put := func(t Transition) { + k := key{t.From, t.To, t.SiteFrom, t.SiteTo} + if old, ok := best[k]; ok && len(old.Chain) <= len(t.Chain) { + return + } + best[k] = t + } + // Origin entry instruction per function: the site in F that leads to the publish. + byEntry := map[ssa.Instruction][]origin{} + for _, o := range st.origins { + byEntry[o.sites[0]] = append(byEntry[o.sites[0]], o) + } + // Callers on the pruned core graph; callbacks point at the passing site, not the runner. + callers := map[*ssa.Function][]step{} + for _, h := range st.modFns { + if inConnectors(h) || strings.HasPrefix(pos(h.Pos()), "dev-ops/") { + continue + } + for _, stp := range succs(h) { + if !inConnectors(stp.callee) { + callers[stp.callee] = append(callers[stp.callee], step{callee: h, site: stp.site, kind: stp.kind}) + } + } + } + // scan applies the "later in G" rule after instruction at; prefix is the chain from F up to G. + scan := func(a origin, G *ssa.Function, at ssa.Instruction, prefix []string) { + for _, in := range laterInstrs(at) { + for _, b := range byEntry[in] { + c, why := condOf(append([]ssa.Instruction{in}, b.sites[1:]...)) + put(Transition{From: a.topic, To: b.topic, SiteFrom: a.pubPos, SiteTo: b.pubPos, Func: fname(G), + Chain: append(append([]string{}, prefix...), b.chain[1:]...), Conditional: c, Condition: why, fromFn: a.fn}) + } + if _, ok := in.(ssa.CallInstruction); !ok { + continue + } + for _, stp := range succs(G) { + if stp.site != in || inConnectors(stp.callee) { + continue + } + par := baseReach[stp.callee] + if par == nil { + par = bfs(stp.callee, true) + baseReach[stp.callee] = par + } + for _, g := range sortedFns(par) { + for _, b := range st.originsBy[g] { + names, sites, _ := pathTo(par, stp.callee, g) + chain := append(append(append([]string{}, prefix...), names...), b.chain[1:]...) + c, why := condOf(append(append([]ssa.Instruction{in}, sites...), b.sites...)) + put(Transition{From: a.topic, To: b.topic, SiteFrom: a.pubPos, SiteTo: b.pubPos, Func: fname(G), + Chain: chain, Conditional: c, Condition: why, fromFn: a.fn}) + } + } + } + } + } + type up struct { + G *ssa.Function + at ssa.Instruction + prefix []string + } + for _, a := range st.origins { + if inConnectors(a.fn) { + continue + } + seen := map[ssa.Instruction]bool{a.sites[0]: true} + q := []up{{a.fn, a.sites[0], []string{fname(a.fn)}}} + for len(q) > 0 { + u := q[0] + q = q[1:] + scan(a, u.G, u.at, u.prefix) + for _, cl := range callers[u.G] { + if seen[cl.site] { + continue + } + seen[cl.site] = true + q = append(q, up{cl.callee, cl.site, append(append([]string{}, u.prefix...), "^ "+fname(cl.callee))}) + } + } + } + out := make([]Transition, 0, len(best)) + for _, t := range best { + out = append(out, t) + } + sort.Slice(out, func(i, j int) bool { + a, b := out[i], out[j] + if a.From != b.From { + return a.From < b.From + } + if a.To != b.To { + return a.To < b.To + } + if a.SiteFrom != b.SiteFrom { + return a.SiteFrom < b.SiteFrom + } + return a.SiteTo < b.SiteTo + }) + return out +} + +// handlerPrimary lists, per handler, emitted topics that no transition from +// another of its emitted topics explains, using transitions inside its reach. +func (st *state) handlerPrimary(trans []Transition, handler string, fn *ssa.Function) []string { + emitted := map[string]bool{} + for _, e := range st.emits { + if e.RootKind == "handler" && e.Handler == handler { + emitted[e.Topic] = true + } + } + par := st.reach[fn] + explained := map[string][]string{} + for _, t := range trans { + if _, ok := par[t.fromFn]; !ok || t.From == t.To || !emitted[t.From] || !emitted[t.To] { + continue + } + explained[t.To] = appendU(explained[t.To], t.From) + } + var primary []string + for _, t := range sortedKeys(emitted) { + if len(explained[t]) == 0 { + primary = append(primary, t) + } + } + return primary +}
