diff --git a/charts/console-backend-rbac/templates/rbac.yaml b/charts/console-backend-rbac/templates/rbac.yaml index 4db9c23ea..fe1686fca 100644 --- a/charts/console-backend-rbac/templates/rbac.yaml +++ b/charts/console-backend-rbac/templates/rbac.yaml @@ -166,16 +166,6 @@ rules: - get - create - delete - - apiGroups: - - "nais.io" - resources: - - postgresbranches - verbs: - - get - - list - - watch - - create - - delete - apiGroups: - postgresql.cnpg.io resources: @@ -369,15 +359,6 @@ rules: - get - create - delete - - apiGroups: - - "nais.io" - resources: - - postgresbranches - verbs: - - get - - list - - watch - - delete - apiGroups: - postgresql.cnpg.io resources: diff --git a/data/k8s/dev/devteam/postgres.yaml b/data/k8s/dev/devteam/postgres.yaml index 0898045cc..12311906a 100644 --- a/data/k8s/dev/devteam/postgres.yaml +++ b/data/k8s/dev/devteam/postgres.yaml @@ -9,13 +9,11 @@ metadata: spec: majorVersion: "18" highAvailability: false - activeBranch: main resources: cpu: 100m memory: 512Mi diskSize: 10Gi status: - activeBranch: main clusterName: pg-postgres-1-main-7adae74b reconcilePhase: Completed observedGeneration: 0 @@ -36,13 +34,11 @@ metadata: spec: majorVersion: "17" highAvailability: true - activeBranch: main resources: cpu: 200m memory: 1Gi diskSize: 20Gi status: - activeBranch: main clusterName: pg-postgres-2-main-41c0e281 reconcilePhase: Completed observedGeneration: 0 diff --git a/data/k8s/dev/postgres-crd.yaml b/data/k8s/dev/postgres-crd.yaml index ee1cccb00..a4a95a2e0 100644 --- a/data/k8s/dev/postgres-crd.yaml +++ b/data/k8s/dev/postgres-crd.yaml @@ -39,9 +39,6 @@ spec: - jsonPath: .spec.resources.memory name: Memory type: string - - jsonPath: .status.activeBranch - name: Active branch - type: string - jsonPath: .status.reconcileTime name: Last reconcile type: string @@ -70,11 +67,6 @@ spec: spec: description: spec defines the desired state of Postgres properties: - activeBranch: - description: |- - ActiveBranch selects the local branch name within this Postgres for normal workloads. - When omitted, pgrator retains the current active branch. - type: string extensions: description: Extensions to enable in the Postgres database. items: @@ -137,10 +129,6 @@ spec: status: description: status defines the observed state of Postgres properties: - activeBranch: - description: ActiveBranch is the local branch name currently selected - by pgrator. - type: string conditions: description: |- conditions represent the current state of the controlled resource. diff --git a/integration_tests/create_postgres_access.lua b/integration_tests/create_postgres_access.lua index f5b4afd4e..49251ea01 100644 --- a/integration_tests/create_postgres_access.lua +++ b/integration_tests/create_postgres_access.lua @@ -99,8 +99,8 @@ Test.gql("Create personal postgres access rejects an unknown instance", function t.check { errors = { { - extensions = { field = "branch" }, - message = Contains("Could not find PostgresBranch"), + extensions = { field = "postgres" }, + message = Contains("Could not find Postgres"), path = { "createPostgresAccess" }, }, }, @@ -118,7 +118,7 @@ Test.gql("Create personal postgres access rejects a logical Postgres without a p }) { name } } ]] t.check { - errors = { { extensions = { field = "branch" }, message = Contains("is not available"), path = { "createPostgresAccess" } } }, + errors = { { extensions = { field = "postgres" }, message = Contains("is not available"), path = { "createPostgresAccess" } } }, data = Null, } end) @@ -143,7 +143,7 @@ Test.gql("Create personal postgres access rejects an unavailable instance", func t.check { errors = { { - extensions = { field = "branch" }, + extensions = { field = "postgres" }, message = Contains("is not available"), path = { "createPostgresAccess" }, }, @@ -268,18 +268,6 @@ Test.gql("Changing access level revokes and recreates live access", function(t) } } } } } end) -Test.gql("Personal access rejects retired non-main selection", function(t) - t.addHeader("x-user-email", user:email()) - t.query [[ - mutation { createPostgresAccess(input: { - postgres: "foobar", branch: "recovered", environmentName: "dev", - teamSlug: "someteamname", accessLevel: READ, - reason: "Testing access to a recovered instance" - }) { name } } - ]] - t.check { data = Null, errors = { { extensions = { code = "GRAPHQL_VALIDATION_FAILED" }, locations = NotNull(), message = Contains('Field "branch" is not defined') } } } -end) - Test.gql("PostgresAccess status is visible to authorized team members", function(t) t.addHeader("x-user-email", otherMemberUser:email()) for _, test in ipairs({ diff --git a/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/accesses.yaml b/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/accesses.yaml index 2b256863f..be43abdd0 100644 --- a/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/accesses.yaml +++ b/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/accesses.yaml @@ -6,7 +6,7 @@ metadata: namespace: someteamname uid: 11111111-1111-4111-8111-111111111111 spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: user@usersen.com accessLevel: readwrite expiresAt: "2099-09-17T12:00:00Z" @@ -30,7 +30,7 @@ metadata: namespace: someteamname uid: 44444444-4444-4444-8444-444444444444 spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: user@usersen.com accessLevel: read expiresAt: "2099-09-17T12:00:00Z" @@ -50,7 +50,7 @@ metadata: name: recovered-access namespace: someteamname spec: - postgresBranch: foobar-recovered-b88d8360 + postgres: foobar username: user@usersen.com accessLevel: read expiresAt: "2099-09-17T12:00:00Z" @@ -65,7 +65,7 @@ metadata: name: pending-access namespace: someteamname spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: user@usersen.com accessLevel: read expiresAt: "2099-09-17T12:00:00Z" @@ -80,7 +80,7 @@ metadata: name: failed-access namespace: someteamname spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: user@usersen.com accessLevel: readwritecreate expiresAt: "2099-09-17T12:00:00Z" @@ -97,7 +97,7 @@ metadata: name: expired-access namespace: someteamname spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: user@usersen.com accessLevel: read expiresAt: "2000-01-01T00:00:00Z" @@ -113,7 +113,7 @@ metadata: namespace: someteamname uid: 22222222-2222-4222-8222-222222222222 spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: user@usersen.com accessLevel: read expiresAt: "2099-09-17T12:00:00Z" @@ -135,7 +135,7 @@ metadata: namespace: someteamname uid: 33333333-3333-4333-8333-333333333333 spec: - postgresBranch: foobar-main-a4f04c0c + postgres: foobar username: stale@usersen.com accessLevel: read expiresAt: "2000-01-01T00:00:00Z" diff --git a/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/postgres.yaml b/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/postgres.yaml index 4660e303a..f24912117 100644 --- a/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/postgres.yaml +++ b/integration_tests/k8s_resources/create_postgres_access/dev/someteamname/postgres.yaml @@ -7,7 +7,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-foobar-main-a4f04c0c reconcilePhase: Completed conditions: @@ -24,8 +23,6 @@ metadata: namespace: someteamname spec: majorVersion: "17" -status: - activeBranch: main --- apiVersion: nais.io/v1 kind: Postgres @@ -35,57 +32,6 @@ metadata: spec: majorVersion: "17" --- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: foobar-main-a4f04c0c - namespace: someteamname -spec: - postgres: foobar - branchName: main -status: - reconcilePhase: Completed - conditions: - - type: cluster.postgresql.cnpg.io/ObservedState - status: "True" - reason: Reconciled - message: "Cluster is in phase: Cluster in healthy state" - lastTransitionTime: "2026-09-17T00:00:00Z" ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: progressing-main-6cb99f88 - namespace: someteamname -spec: - postgres: progressing - branchName: main -status: - reconcilePhase: Preparing - conditions: - - type: cluster.postgresql.cnpg.io/ObservedState - status: "False" - reason: Reconciling - message: "Cluster is in phase: " - lastTransitionTime: "2026-09-17T00:00:00Z" ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: foobar-recovered-b88d8360 - namespace: someteamname -spec: - postgres: foobar - branchName: recovered -status: - reconcilePhase: Completed - conditions: - - type: cluster.postgresql.cnpg.io/ObservedState - status: "True" - reason: Reconciled - message: "Cluster is in phase: Cluster in healthy state" - lastTransitionTime: "2026-09-17T00:00:00Z" ---- apiVersion: postgresql.cnpg.io/v1 kind: Cluster metadata: @@ -101,19 +47,3 @@ status: status: "True" reason: ClusterReady lastTransitionTime: "2026-09-17T00:00:00Z" ---- -apiVersion: postgresql.cnpg.io/v1 -kind: Cluster -metadata: - name: pg-foobar-recovered-b88d8360 - namespace: someteamname -spec: - certificates: - serverCASecret: pg-foobar-ca -status: - phase: Cluster in healthy state - conditions: - - type: Ready - status: "True" - reason: ClusterReady - lastTransitionTime: "2026-09-17T00:00:00Z" diff --git a/integration_tests/k8s_resources/label_selectors/dev/labelteam/postgres.yaml b/integration_tests/k8s_resources/label_selectors/dev/labelteam/postgres.yaml index 4ccf0a916..cd74ca104 100644 --- a/integration_tests/k8s_resources/label_selectors/dev/labelteam/postgres.yaml +++ b/integration_tests/k8s_resources/label_selectors/dev/labelteam/postgres.yaml @@ -10,7 +10,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-postgres-one-main-e58682b9 reconcilePhase: Completed conditions: @@ -30,7 +29,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-postgres-two-main-935c2b2a reconcilePhase: Completed conditions: @@ -50,7 +48,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-postgres-three-main-1013cb94 reconcilePhase: Completed conditions: diff --git a/integration_tests/k8s_resources/postgres_audit_log/dev-gcp/audit-postgres-team/postgres_with_audit.yaml b/integration_tests/k8s_resources/postgres_audit_log/dev-gcp/audit-postgres-team/postgres_with_audit.yaml index 4e5de2c53..81a2a922b 100644 --- a/integration_tests/k8s_resources/postgres_audit_log/dev-gcp/audit-postgres-team/postgres_with_audit.yaml +++ b/integration_tests/k8s_resources/postgres_audit_log/dev-gcp/audit-postgres-team/postgres_with_audit.yaml @@ -7,7 +7,6 @@ metadata: spec: majorVersion: "16" status: - activeBranch: main clusterName: pg-audit-enabled-main-74f70e60 reconcilePhase: Completed conditions: diff --git a/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres.yaml b/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres.yaml index dfe481cc4..621384346 100644 --- a/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres.yaml +++ b/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres.yaml @@ -11,23 +11,6 @@ spec: memory: 512Mi diskSize: 10Gi --- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: existing-main-f68e5aa4 - namespace: pg-crud-team -spec: - postgres: existing - branchName: main -status: - reconcilePhase: Completed - conditions: - - type: cluster.postgresql.cnpg.io/ObservedState - status: "True" - reason: Reconciled - message: "Cluster is in phase: Cluster in healthy state" - lastTransitionTime: "2026-09-17T00:00:00Z" ---- apiVersion: postgresql.cnpg.io/v1 kind: Cluster metadata: diff --git a/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres_branchless.yaml b/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres_awaiting_cluster.yaml similarity index 89% rename from integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres_branchless.yaml rename to integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres_awaiting_cluster.yaml index 7485d4cf3..2d6ebe103 100644 --- a/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres_branchless.yaml +++ b/integration_tests/k8s_resources/postgres_crud/dev/pg-crud-team/postgres_awaiting_cluster.yaml @@ -1,7 +1,7 @@ apiVersion: nais.io/v1 kind: Postgres metadata: - name: branchless + name: awaiting-cluster namespace: pg-crud-team labels: usecase: reporting diff --git a/integration_tests/k8s_resources/postgres_branches/dev/postgres-other-team/resources.yaml b/integration_tests/k8s_resources/postgres_databases/dev/postgres-other-team/resources.yaml similarity index 94% rename from integration_tests/k8s_resources/postgres_branches/dev/postgres-other-team/resources.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/postgres-other-team/resources.yaml index 57a3e21ea..b9374c910 100644 --- a/integration_tests/k8s_resources/postgres_branches/dev/postgres-other-team/resources.yaml +++ b/integration_tests/k8s_resources/postgres_databases/dev/postgres-other-team/resources.yaml @@ -5,7 +5,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-foobar-main-a4f04c0c configuration: parameters: diff --git a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/applications.yaml b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/applications.yaml similarity index 100% rename from integration_tests/k8s_resources/postgres_branches/dev/someteamname/applications.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/someteamname/applications.yaml diff --git a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_another_db.yaml b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_another_db.yaml similarity index 95% rename from integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_another_db.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_another_db.yaml index c8169ecdc..5c737d677 100644 --- a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_another_db.yaml +++ b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_another_db.yaml @@ -7,7 +7,6 @@ metadata: spec: majorVersion: "16" status: - activeBranch: main clusterName: pg-another-db-main-72a85261 reconcilePhase: Completed configuration: diff --git a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_foobar.yaml b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_foobar.yaml similarity index 98% rename from integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_foobar.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_foobar.yaml index 9c116549c..ea451b866 100644 --- a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_foobar.yaml +++ b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_foobar.yaml @@ -16,7 +16,6 @@ spec: memory: 2Gi diskSize: 2Gi status: - activeBranch: main clusterName: pg-foobar-main-a4f04c0c configuration: parameters: diff --git a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_foobar_failed.yaml b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_foobar_failed.yaml similarity index 100% rename from integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_foobar_failed.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_foobar_failed.yaml diff --git a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_with_audit.yaml b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_with_audit.yaml similarity index 95% rename from integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_with_audit.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_with_audit.yaml index bd580780a..75fff71dd 100644 --- a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_with_audit.yaml +++ b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_with_audit.yaml @@ -7,7 +7,6 @@ metadata: spec: majorVersion: "16" status: - activeBranch: main clusterName: pg-with-audit-main-cb3cab0a reconcilePhase: Completed conditions: diff --git a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_without_audit.yaml b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_without_audit.yaml similarity index 95% rename from integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_without_audit.yaml rename to integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_without_audit.yaml index 1cb565837..d89b7f0d0 100644 --- a/integration_tests/k8s_resources/postgres_branches/dev/someteamname/postgres_without_audit.yaml +++ b/integration_tests/k8s_resources/postgres_databases/dev/someteamname/postgres_without_audit.yaml @@ -7,7 +7,6 @@ metadata: spec: majorVersion: "15" status: - activeBranch: main clusterName: pg-without-audit-main-d2111831 reconcilePhase: Completed conditions: diff --git a/integration_tests/k8s_resources/postgres_branches/staging/someteamname/resources.yaml b/integration_tests/k8s_resources/postgres_databases/staging/someteamname/resources.yaml similarity index 94% rename from integration_tests/k8s_resources/postgres_branches/staging/someteamname/resources.yaml rename to integration_tests/k8s_resources/postgres_databases/staging/someteamname/resources.yaml index 4cddc5f1e..285d1f547 100644 --- a/integration_tests/k8s_resources/postgres_branches/staging/someteamname/resources.yaml +++ b/integration_tests/k8s_resources/postgres_databases/staging/someteamname/resources.yaml @@ -5,7 +5,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-foobar-main-a4f04c0c configuration: parameters: diff --git a/integration_tests/k8s_resources/postgres_dual_read/dev/pg-dual-read-team/resources.yaml b/integration_tests/k8s_resources/postgres_dual_read/dev/pg-dual-read-team/resources.yaml index fdcc0cd35..a0c05c260 100644 --- a/integration_tests/k8s_resources/postgres_dual_read/dev/pg-dual-read-team/resources.yaml +++ b/integration_tests/k8s_resources/postgres_dual_read/dev/pg-dual-read-team/resources.yaml @@ -28,7 +28,6 @@ metadata: spec: majorVersion: "18" status: - activeBranch: main clusterName: pg-foobar-main-a4f04c0c configuration: parameters: diff --git a/integration_tests/k8s_resources/postgres_branch_selection/dev/pg-selection-team/resources.yaml b/integration_tests/k8s_resources/postgres_relations/dev/pg-selection-team/resources.yaml similarity index 55% rename from integration_tests/k8s_resources/postgres_branch_selection/dev/pg-selection-team/resources.yaml rename to integration_tests/k8s_resources/postgres_relations/dev/pg-selection-team/resources.yaml index 8d799876a..b8d069029 100644 --- a/integration_tests/k8s_resources/postgres_branch_selection/dev/pg-selection-team/resources.yaml +++ b/integration_tests/k8s_resources/postgres_relations/dev/pg-selection-team/resources.yaml @@ -5,63 +5,24 @@ metadata: namespace: pg-selection-team spec: majorVersion: "18" - activeBranch: pending status: clusterName: pg-orders-main-65648812 - activeBranch: green ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: orders-main-65648812 - namespace: pg-selection-team -spec: - postgres: orders - branchName: main ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: orders-green-d77a35b4 - namespace: pg-selection-team -spec: - postgres: orders - branchName: green ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: orders-pr-123-99e54251 - namespace: pg-selection-team -spec: - postgres: orders - branchName: pr-123 ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: orders-pending-ef1f4700 - namespace: pg-selection-team -spec: - postgres: orders - branchName: pending --- apiVersion: nais.io/v1alpha1 kind: Application metadata: - name: pinned-app + name: first-app namespace: pg-selection-team spec: image: ghcr.io/nais/testapp:latest uses: postgres: - name: orders - branch: main --- apiVersion: nais.io/v1alpha1 kind: Application metadata: - name: following-app + name: second-app namespace: pg-selection-team spec: image: ghcr.io/nais/testapp:latest @@ -72,7 +33,7 @@ spec: apiVersion: nais.io/v1 kind: Naisjob metadata: - name: pinned-job + name: scheduled-reader namespace: pg-selection-team spec: image: ghcr.io/nais/testapp:latest @@ -80,7 +41,6 @@ spec: uses: postgres: - name: orders - branch: main --- apiVersion: nais.io/v1 kind: Naisjob @@ -94,21 +54,18 @@ spec: apiVersion: nais.io/v1 kind: Postgres metadata: - name: missing-branch + name: provisioning namespace: pg-selection-team spec: majorVersion: "18" -status: - activeBranch: restored --- apiVersion: nais.io/v1alpha1 kind: Application metadata: - name: missing-branch-app + name: provisioning-app namespace: pg-selection-team spec: image: ghcr.io/nais/testapp:latest uses: postgres: - - name: missing-branch - branch: main + - name: provisioning diff --git a/integration_tests/k8s_resources/postgres_search/dev/pg-search-team/resources.yaml b/integration_tests/k8s_resources/postgres_search/dev/pg-search-team/resources.yaml index 5b6aea908..4d4320e7d 100644 --- a/integration_tests/k8s_resources/postgres_search/dev/pg-search-team/resources.yaml +++ b/integration_tests/k8s_resources/postgres_search/dev/pg-search-team/resources.yaml @@ -4,11 +4,3 @@ metadata: name: orders spec: majorVersion: "17" ---- -apiVersion: nais.io/v1 -kind: PostgresBranch -metadata: - name: orders-green-d77a35b4 -spec: - postgres: orders - branchName: green diff --git a/integration_tests/k8s_resources/postgres_workloads/dev/postgres-workload-team/resources.yaml b/integration_tests/k8s_resources/postgres_workloads/dev/postgres-workload-team/resources.yaml index 00d5c1524..6a555f88f 100644 --- a/integration_tests/k8s_resources/postgres_workloads/dev/postgres-workload-team/resources.yaml +++ b/integration_tests/k8s_resources/postgres_workloads/dev/postgres-workload-team/resources.yaml @@ -7,7 +7,6 @@ spec: majorVersion: "17" status: clusterName: pg-orders-main-65648812 - activeBranch: main --- apiVersion: nais.io/v1 kind: Postgres @@ -18,7 +17,6 @@ spec: majorVersion: "17" status: clusterName: pg-reports-main-preserved - activeBranch: main --- apiVersion: nais.io/v1 kind: Postgres @@ -27,7 +25,6 @@ metadata: namespace: postgres-workload-team spec: majorVersion: "18" - activeBranch: pending --- apiVersion: nais.io/v1alpha1 kind: Application @@ -56,7 +53,6 @@ spec: uses: postgres: - name: orders - branch: main - name: reports envPrefix: REPORTS_ - name: archive diff --git a/integration_tests/postgres_audit_log.lua b/integration_tests/postgres_audit_log.lua index 6e66ec1c0..4c03bd252 100644 --- a/integration_tests/postgres_audit_log.lua +++ b/integration_tests/postgres_audit_log.lua @@ -1,5 +1,5 @@ --- The old per-instance audit flag and Cloud SQL Logs URL are not part of --- nais.io/v1 PostgresBranch. Verify logical configuration instead. +-- Cloud SQL-specific audit flags and log URLs do not apply to Postgres. +-- Verify the database configuration instead. Helper.readK8sResources("k8s_resources/postgres_audit_log") local user = User.new("authenticated", "postgres-audit-user@example.com", "postgres-audit-user-id") local team = Team.new("audit-postgres-team", "Testing logical Postgres", "#audit-postgres") diff --git a/integration_tests/postgres_branches.lua b/integration_tests/postgres_databases.lua similarity index 98% rename from integration_tests/postgres_branches.lua rename to integration_tests/postgres_databases.lua index 7e91a446a..e30bb63e2 100644 --- a/integration_tests/postgres_branches.lua +++ b/integration_tests/postgres_databases.lua @@ -3,7 +3,7 @@ local team = Team.new("someteamname", "purpose", "#slack_channel") team:addMember(user) local otherTeam = Team.new("postgres-other-team", "Isolation", "#postgres") otherTeam:addMember(user) -Helper.readK8sResources("k8s_resources/postgres_branches") +Helper.readK8sResources("k8s_resources/postgres_databases") local workloadFields = [[fragment PostgresWorkloadFields on PostgresWorkload { workload { @@ -208,7 +208,7 @@ Test.gql("Postgres configuration exposes explicitly configured parameters in nam } } } } } end) -Test.gql("Postgres configuration is scoped to branch, database, team and environment", function(t) +Test.gql("Postgres configuration is scoped to database, team and environment", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "someteamname") { diff --git a/integration_tests/postgres_dual_read.lua b/integration_tests/postgres_dual_read.lua index 3d51a306b..bbc14a11e 100644 --- a/integration_tests/postgres_dual_read.lua +++ b/integration_tests/postgres_dual_read.lua @@ -3,7 +3,7 @@ local team = Team.new("pg-dual-read-team", "Postgres transition compatibility", team:addMember(user) Helper.readK8sResources("k8s_resources/postgres_dual_read") -Test.gql("Direct Postgres fields read both legacy and directly owned databases", function(t) +Test.gql("Postgres fields read database-owned status", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "pg-dual-read-team") { postgreses { nodes { name state configuration { parameters { name value } } @@ -14,7 +14,7 @@ Test.gql("Direct Postgres fields read both legacy and directly owned databases", } } } } } end) -Test.gql("Direct Postgres metadata works without a Kubernetes branch", function(t) +Test.gql("Postgres metadata is read from the database", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "pg-dual-read-team") { environment(name: "dev") { postgres(name: "orders") { id name state createdAt earliestRestoreTime issues { pageInfo { totalCount } } @@ -36,7 +36,7 @@ Test.gql("The Postgres node keeps its identity and GraphQL type", function(t) } } } end) -Test.gql("Workload queries resolve a virtual main without omitting the database", function(t) +Test.gql("Workload queries resolve their database", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "pg-dual-read-team") { environment(name: "dev") { application(name: "consumer") { postgreses { nodes { postgres { name state } } } @@ -57,18 +57,18 @@ Test.gql("Workload nodes reuse the already resolved parent Postgres", function(t } } } } } end) -Test.gql("Personal access can omit branch before and after direct ownership", function(t) +Test.gql("Personal access is scoped to its database and reused", function(t) t.addHeader("x-user-email", user:email()) for _, postgresName in ipairs({ "foobar", "orders" }) do t.query(string.format([[mutation { createPostgresAccess(input: { postgres: "%s", teamSlug: "pg-dual-read-team", environmentName: "dev", - accessLevel: READ, reason: "Testing branchless personal database access", ttl: "30m" + accessLevel: READ, reason: "Testing personal database access", ttl: "30m" }) { name expiresAt } }]], postgresName)) t.check { data = { createPostgresAccess = { name = Save("personalAccessName"), expiresAt = Save("personalAccessExpiry") } } } - -- Explicit legacy main and omitted branch refer to the same live grant. + -- Repeating the request returns the same live grant. t.query(string.format([[mutation { createPostgresAccess(input: { postgres: "%s", teamSlug: "pg-dual-read-team", environmentName: "dev", - accessLevel: READ, reason: "Testing branchless personal database access" + accessLevel: READ, reason: "Testing personal database access" }) { name expiresAt } }]], postgresName)) t.check { data = { createPostgresAccess = { name = State.personalAccessName, expiresAt = State.personalAccessExpiry } } } t.query(string.format([[{ team(slug: "pg-dual-read-team") { environment(name: "dev") { diff --git a/integration_tests/postgres_issues.lua b/integration_tests/postgres_issues.lua index 892e30851..8fc4b87ef 100644 --- a/integration_tests/postgres_issues.lua +++ b/integration_tests/postgres_issues.lua @@ -2,7 +2,7 @@ local user = User.new("user", "user@usersen.com") local team = Team.new("someteamname", "purpose", "#slack_channel") team:addMember(user) Team.new("postgres-other-team", "Isolation", "#postgres") -Helper.readK8sResources("k8s_resources/postgres_branches") +Helper.readK8sResources("k8s_resources/postgres_databases") local checker = IssueChecker.new() checker:runChecks() @@ -91,14 +91,7 @@ Test.gql("Postgres issues are scoped to the logical database", function(t) } } end) --- Emulate an API rollout before the new checker has refreshed the old snapshot. -Helper.SQLExec([[ - UPDATE issues SET issue_type = 'POSTGRES_BRANCH', resource_type = 'POSTGRES_BRANCH', - resource_name = 'broken-main-69d0ff6e' - WHERE issue_type = 'POSTGRES' AND resource_name = 'broken' AND team = 'someteamname' AND env = 'dev' -]]) - -Test.gql("Old stored rows are exposed as PostgresIssue with the same Node ID", function(t) +Test.gql("PostgresIssue retains its Node ID and database relation", function(t) t.addHeader("x-user-email", user:email()) t.query(string.format([[{ node(id: "%s") { @@ -106,7 +99,7 @@ Test.gql("Old stored rows are exposed as PostgresIssue with the same Node ID", f ... on PostgresIssue { id postgres { name teamEnvironment { name team { slug } } } } } team(slug: "someteamname") { - issues(filter: { resourceName: "broken-main-69d0ff6e" }) { pageInfo { totalCount } nodes { __typename ... on PostgresIssue { postgres { name } } } } + issues(filter: { resourceName: "broken" }) { pageInfo { totalCount } nodes { __typename ... on PostgresIssue { postgres { name } } } } } }]], State.postgres_issue_id)) t.check { data = { @@ -127,7 +120,7 @@ local function teamPostgresFacets(count) end for _, filter in ipairs({ "resourceType: POSTGRES", "issueType: POSTGRES", "resourceType: POSTGRES, issueType: POSTGRES" }) do - Test.gql("Legacy rows match canonical issue filters before refresh: " .. filter, function(t) + Test.gql("Postgres rows match issue filters: " .. filter, function(t) t.addHeader("x-user-email", user:email()) t.query([[{ team(slug: "someteamname") { issues(filter: { ]] .. filter .. [[ }) { @@ -144,7 +137,7 @@ for _, filter in ipairs({ "resourceType: POSTGRES", "issueType: POSTGRES", "reso end) end -Test.gql("Legacy rows retain logical resource filters and database scopes before refresh", function(t) +Test.gql("Postgres rows retain logical resource filters and database scopes", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "someteamname") { issues(filter: { resourceType: POSTGRES, issueType: POSTGRES, resourceName: "broken", environments: ["dev"] }) { @@ -184,13 +177,13 @@ Test.gql("Legacy rows retain logical resource filters and database scopes before } } } end) --- Mixed snapshots are also possible while old and new checker versions overlap. +-- Multiple databases aggregate into a single resource-type facet. Helper.SQLExec([[ INSERT INTO issues (issue_type, resource_type, resource_name, team, env, severity, message) VALUES ('POSTGRES', 'POSTGRES', 'another-db', 'someteamname', 'dev', 'CRITICAL', 'Database failure') ]]) -Test.gql("Mixed legacy and canonical rows aggregate into a single Postgres facet", function(t) +Test.gql("Database rows aggregate into a single Postgres facet", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "someteamname") { issues(filter: { resourceType: POSTGRES, issueType: POSTGRES }) { @@ -208,7 +201,7 @@ end) checker:runChecks() -Test.sql("Checker replaces the legacy snapshot rather than duplicating issues", function(t) - t.query [[SELECT issue_type, resource_type, resource_name FROM issues WHERE team = 'someteamname' AND issue_type IN ('POSTGRES', 'POSTGRES_BRANCH')]] +Test.sql("Checker replaces its snapshot rather than duplicating issues", function(t) + t.query [[SELECT issue_type, resource_type, resource_name FROM issues WHERE team = 'someteamname' AND issue_type = 'POSTGRES']] t.check { { issue_type = "POSTGRES", resource_type = "POSTGRES", resource_name = "broken" } } end) diff --git a/integration_tests/postgres_branch_operations.lua b/integration_tests/postgres_listing.lua similarity index 80% rename from integration_tests/postgres_branch_operations.lua rename to integration_tests/postgres_listing.lua index 79d7fd605..3516aa91e 100644 --- a/integration_tests/postgres_branch_operations.lua +++ b/integration_tests/postgres_listing.lua @@ -1,9 +1,9 @@ -local member = User.new("pg-branch-user", "pg-branch-user@usersen.com") +local member = User.new("pg-listing-user", "pg-listing-user@usersen.com") local team = Team.new("pg-crud-team", "Testing Postgres listing", "#postgres-crud") team:addMember(member) Helper.readK8sResources("k8s_resources/postgres_crud") -Test.gql("Team Postgres list includes databases without branches and paginates", function(t) +Test.gql("Team Postgres list includes provisioning databases and paginates", function(t) t.addHeader("x-user-email", member:email()) t.query [[{ team(slug: "pg-crud-team") { postgreses(first: 1) { nodes { name majorVersion teamEnvironment { environment { name } } } @@ -11,7 +11,7 @@ Test.gql("Team Postgres list includes databases without branches and paginates", facets { labels { key value count } } } } }]] t.check { data = { team = { postgreses = { - nodes = { { name = "branchless", majorVersion = "17", teamEnvironment = { environment = { name = "dev" } } } }, + nodes = { { name = "awaiting-cluster", majorVersion = "17", teamEnvironment = { environment = { name = "dev" } } } }, pageInfo = { totalCount = 2, hasNextPage = true, endCursor = Save("postgresNextPage") }, facets = { labels = { { key = "usecase", value = "reporting", count = 1 } } }, } } } } @@ -28,5 +28,5 @@ Test.gql("Team Postgres list filters instances by label and environment", functi t.query [[{ team(slug: "pg-crud-team") { postgreses(filter: { environments: ["dev"], labels: [{ key: "usecase", value: "reporting" }] }) { nodes { name } pageInfo { totalCount } } } }]] - t.check { data = { team = { postgreses = { nodes = { { name = "branchless" } }, pageInfo = { totalCount = 1 } } } } } + t.check { data = { team = { postgreses = { nodes = { { name = "awaiting-cluster" } }, pageInfo = { totalCount = 1 } } } } } end) diff --git a/integration_tests/postgres_pitr.lua b/integration_tests/postgres_pitr.lua index ff0b13679..c082f7aa7 100644 --- a/integration_tests/postgres_pitr.lua +++ b/integration_tests/postgres_pitr.lua @@ -53,11 +53,11 @@ Test.k8s("PITR pins source UID and physical archive identity", function(t) end) for _, case in ipairs({ - { name = "before archive", source = "pitr-source", time = "2026-09-28T12:00:00Z", message = "earliest recoverable" }, - { name = "missing source", source = "unknown", time = "2026-09-30T12:00:00Z", message = "not found in this team and environment" }, - { name = "missing physical source", source = "branchless", time = "2026-09-30T12:00:00Z", message = "no recoverable cluster" }, - { name = "smaller disk", source = "pitr-source", time = "2026-09-30T12:00:00Z", extra = 'diskSize: "10Gi"', message = "must not be smaller" }, - { name = "missing source extension", source = "pitr-source", time = "2026-09-30T12:00:00Z", extra = "extensions: []", message = "must include source extension" }, + { name = "before archive", source = "pitr-source", time = "2026-09-28T12:00:00Z", message = "earliest recoverable" }, + { name = "missing source", source = "unknown", time = "2026-09-30T12:00:00Z", message = "not found in this team and environment" }, + { name = "missing physical source", source = "awaiting-cluster", time = "2026-09-30T12:00:00Z", message = "no recoverable cluster" }, + { name = "smaller disk", source = "pitr-source", time = "2026-09-30T12:00:00Z", extra = 'diskSize: "10Gi"', message = "must not be smaller" }, + { name = "missing source extension", source = "pitr-source", time = "2026-09-30T12:00:00Z", extra = "extensions: []", message = "must include source extension" }, }) do Test.gql("PITR rejects " .. case.name, function(t) t.addHeader("x-user-email", member:email()) diff --git a/integration_tests/postgres_branch_selection.lua b/integration_tests/postgres_relations.lua similarity index 68% rename from integration_tests/postgres_branch_selection.lua rename to integration_tests/postgres_relations.lua index 0b22e0ecb..6d70c5fa0 100644 --- a/integration_tests/postgres_branch_selection.lua +++ b/integration_tests/postgres_relations.lua @@ -1,25 +1,25 @@ local user = User.new("pg-selection-user", "pg-selection-user@usersen.com") -local team = Team.new("pg-selection-team", "Testing the retired branch facade", "#postgres") +local team = Team.new("pg-selection-team", "Testing Postgres workload relations", "#postgres") team:addMember(user) -Helper.readK8sResources("k8s_resources/postgres_branch_selection") +Helper.readK8sResources("k8s_resources/postgres_relations") -Test.gql("The main facade includes omitted and explicit main consumers", function(t) +Test.gql("Postgres includes all application and job consumers", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "pg-selection-team") { environment(name: "dev") { postgres(name: "orders") { workloads { nodes { workload { __typename ... on Application { name } ... on Job { name } } } } } } } }]] t.check { data = { team = { environment = { postgres = { workloads = { nodes = { - { workload = { __typename = "Application", name = "following-app" } }, - { workload = { __typename = "Application", name = "pinned-app" } }, - { workload = { __typename = "Job", name = "pinned-job" } }, + { workload = { __typename = "Application", name = "first-app" } }, + { workload = { __typename = "Job", name = "scheduled-reader" } }, + { workload = { __typename = "Application", name = "second-app" } }, } } } } } } } end) -Test.gql("Stale active branch metadata never selects a physical target", function(t) +Test.gql("An incomplete physical status remains provisioning", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "pg-selection-team") { environment(name: "dev") { postgres(name: "orders") { name state } - application(name: "following-app") { postgreses { nodes { postgres { name } } } } + application(name: "first-app") { postgreses { nodes { postgres { name } } } } } } }]] t.check { data = { team = { environment = { postgres = { name = "orders", state = "PROGRESSING" }, @@ -35,16 +35,16 @@ Test.gql("Postgres pagination is validated when a workload has no uses", functio t.check { data = Null, errors = { { locations = NotNull(), message = Contains("first must be greater than or equal to 1"), path = { "team", "environment", "job", "postgreses" } } } } end) -Test.gql("A provisioning database retains workload relations without branch objects", function(t) +Test.gql("A provisioning database retains workload relations", function(t) t.addHeader("x-user-email", user:email()) t.query [[{ team(slug: "pg-selection-team") { environment(name: "dev") { - postgres(name: "missing-branch") { + postgres(name: "provisioning") { state workloads { pageInfo { totalCount } nodes { workload { ... on Application { name } } } } } } } }]] t.check { data = { team = { environment = { postgres = { state = "PROGRESSING", - workloads = { pageInfo = { totalCount = 1 }, nodes = { { workload = { name = "missing-branch-app" } } } }, + workloads = { pageInfo = { totalCount = 1 }, nodes = { { workload = { name = "provisioning-app" } } } }, } } } } } end) diff --git a/integration_tests/postgres_search.lua b/integration_tests/postgres_search.lua index 6ab9fb544..5326ac67b 100644 --- a/integration_tests/postgres_search.lua +++ b/integration_tests/postgres_search.lua @@ -5,7 +5,7 @@ team:addMember(member) other:addMember(member) Helper.readK8sResources("k8s_resources/postgres_search") -Test.gql("Search returns logical Postgres databases rather than branches", function(t) +Test.gql("Search returns Postgres databases", function(t) t.addHeader("x-user-email", member:email()) t.query [[{ search(first: 10, filter: { query: "orders", types: [POSTGRES], teams: ["pg-search-team"] }) { @@ -56,13 +56,3 @@ Test.gql("Postgres search scopes matching names to the requested team", function }, } end) - -Test.gql("Postgres search does not return branch names", function(t) - t.addHeader("x-user-email", member:email()) - t.query [[{ - search(first: 10, filter: { query: "green", types: [POSTGRES], teams: ["pg-search-team"] }) { - nodes { __typename } - } - }]] - t.check { data = { search = { nodes = {} } } } -end) diff --git a/integration_tests/postgres_workloads.lua b/integration_tests/postgres_workloads.lua index 875ba21a2..05f534381 100644 --- a/integration_tests/postgres_workloads.lua +++ b/integration_tests/postgres_workloads.lua @@ -10,7 +10,7 @@ local workloadFields = [[fragment PostgresWorkloadFields on PostgresWorkload { } }]] -local function workloadNode(workloadType, name, branch) +local function workloadNode(workloadType, name) return { workload = { __typename = workloadType, @@ -60,7 +60,7 @@ Test.gql("Postgres workloads reference their database through uses.postgres", fu } } } } end) -Test.gql("Postgres workloads include inactive branch references and databases without an active branch", function(t) +Test.gql("Postgres workload relations include provisioning databases and paginate", function(t) t.addHeader("x-user-email", user:email()) t.query([[{ team(slug: "postgres-workload-team") { environment(name: "dev") { postgres(name: "orders") { workloads(first: 1) { pageInfo { totalCount hasNextPage endCursor } nodes { ...PostgresWorkloadFields } } } @@ -69,15 +69,15 @@ Test.gql("Postgres workloads include inactive branch references and databases wi } } }]] .. workloadFields) t.check { data = { team = { environment = { postgres = { workloads = { pageInfo = { totalCount = 2, hasNextPage = true, endCursor = Save("ordersCursor") }, nodes = { - workloadNode("Application", "consumer", "main"), + workloadNode("Application", "consumer"), } } }, reports = { workloads = { pageInfo = { totalCount = 2 }, nodes = { - workloadNode("Application", "consumer", "main"), - workloadNode("Job", "scheduled-reader", "main"), + workloadNode("Application", "consumer"), + workloadNode("Job", "scheduled-reader"), } } }, archive = { workloads = { pageInfo = { totalCount = 2 }, nodes = { - workloadNode("Application", "consumer", "main"), - workloadNode("Job", "scheduled-reader", "main"), + workloadNode("Application", "consumer"), + workloadNode("Job", "scheduled-reader"), } } }, } } } } t.query([[{ team(slug: "postgres-workload-team") { environment(name: "dev") { @@ -88,6 +88,6 @@ Test.gql("Postgres workloads include inactive branch references and databases wi } } }]] .. workloadFields) t.check { data = { team = { environment = { postgres = { workloads = { pageInfo = { totalCount = 2, hasNextPage = false, hasPreviousPage = true }, - nodes = { workloadNode("Job", "scheduled-reader", "main") }, + nodes = { workloadNode("Job", "scheduled-reader") }, } } } } } } end) diff --git a/internal/database/migrations/0084_retire_postgres_branches.sql b/internal/database/migrations/0084_retire_postgres_branches.sql new file mode 100644 index 000000000..54aa5577d --- /dev/null +++ b/internal/database/migrations/0084_retire_postgres_branches.sql @@ -0,0 +1,21 @@ +-- +goose Up +-- Remove retired branch events, including the legacy branch-deletion action. +-- Current database creation, updates, access and deletion requests are retained. +DELETE FROM activity_log_entries +WHERE + resource_type = 'POSTGRES' + AND action IN ( + 'BRANCH_CREATED', + 'BRANCH_ACTIVATED', + 'BRANCH_DELETED', + 'DELETED' + ) +; + +-- Issues are derived state. The checker recreates current Postgres issues using +-- the logical database identity; obsolete physical-resource issues must not leak. +DELETE FROM issues +WHERE + issue_type = 'POSTGRES_BRANCH' + OR resource_type = 'POSTGRES_BRANCH' +; diff --git a/internal/graph/gengql/activitylog.generated.go b/internal/graph/gengql/activitylog.generated.go index 014b7c720..5ce17d621 100644 --- a/internal/graph/gengql/activitylog.generated.go +++ b/internal/graph/gengql/activitylog.generated.go @@ -918,27 +918,6 @@ func (ec *executionContext) _ActivityLogEntry(ctx context.Context, sel ast.Selec return graphql.Null } return ec._PostgresCreatedActivityLogEntry(ctx, sel, obj) - case postgres.PostgresBranchDeletedActivityLogEntry: - return ec._PostgresBranchDeletedActivityLogEntry(ctx, sel, &obj) - case *postgres.PostgresBranchDeletedActivityLogEntry: - if obj == nil { - return graphql.Null - } - return ec._PostgresBranchDeletedActivityLogEntry(ctx, sel, obj) - case postgres.PostgresBranchCreatedActivityLogEntry: - return ec._PostgresBranchCreatedActivityLogEntry(ctx, sel, &obj) - case *postgres.PostgresBranchCreatedActivityLogEntry: - if obj == nil { - return graphql.Null - } - return ec._PostgresBranchCreatedActivityLogEntry(ctx, sel, obj) - case postgres.PostgresBranchActivatedActivityLogEntry: - return ec._PostgresBranchActivatedActivityLogEntry(ctx, sel, &obj) - case *postgres.PostgresBranchActivatedActivityLogEntry: - if obj == nil { - return graphql.Null - } - return ec._PostgresBranchActivatedActivityLogEntry(ctx, sel, obj) case opensearch.OpenSearchUpdatedActivityLogEntry: return ec._OpenSearchUpdatedActivityLogEntry(ctx, sel, &obj) case *opensearch.OpenSearchUpdatedActivityLogEntry: diff --git a/internal/graph/gengql/postgres.generated.go b/internal/graph/gengql/postgres.generated.go index 6fc27362c..f7af09181 100644 --- a/internal/graph/gengql/postgres.generated.go +++ b/internal/graph/gengql/postgres.generated.go @@ -31,7 +31,7 @@ type PostgresResolver interface { Team(ctx context.Context, obj *postgres.Postgres) (*team.Team, error) TeamEnvironment(ctx context.Context, obj *postgres.Postgres) (*team.TeamEnvironment, error) - State(ctx context.Context, obj *postgres.Postgres) (postgres.PostgresBranchState, error) + State(ctx context.Context, obj *postgres.Postgres) (postgres.PostgresState, error) Configuration(ctx context.Context, obj *postgres.Postgres) (*postgres.PostgresConfiguration, error) EarliestRestoreTime(ctx context.Context, obj *postgres.Postgres) (*time.Time, error) @@ -449,8 +449,8 @@ func (ec *executionContext) _Postgres_state(ctx context.Context, field graphql.C return ec.Resolvers.Postgres().State(ctx, obj) }, nil, - func(ctx context.Context, selections ast.SelectionSet, v postgres.PostgresBranchState) graphql.Marshaler { - return ec.marshalNPostgresState2githubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchState(ctx, selections, v) + func(ctx context.Context, selections ast.SelectionSet, v postgres.PostgresState) graphql.Marshaler { + return ec.marshalNPostgresState2githubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresState(ctx, selections, v) }, true, true, @@ -1294,819 +1294,6 @@ func (ec *executionContext) fieldContext_PostgresAccessConnectionDetails_relayTo return graphql.NewScalarFieldContext("PostgresAccessConnectionDetails", field, false, false, errors.New("field of type String does not have child fields")) } -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_id(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_id(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ID(), nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v ident.Ident) graphql.Marshaler { - return ec.marshalNID2githubᚗcomᚋnaisᚋapiᚋinternalᚋgraphᚋidentᚐIdent(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, true, false, errors.New("field of type ID does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_actor(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_actor(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Actor, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_actor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_gitHubActorClaims(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_gitHubActorClaims(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.GitHubActorClaims, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *github.GitHubActorClaims) graphql.Marshaler { - return ec.marshalOGitHubActorClaims2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋauthᚋmiddlewareᚋgithubᚐGitHubActorClaims(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_gitHubActorClaims(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "PostgresBranchActivatedActivityLogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.childFields_GitHubActorClaims(ctx, field) - }, - } - return fc, nil -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_createdAt(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_createdAt(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.CreatedAt, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v time.Time) graphql.Marshaler { - return ec.marshalNTime2timeᚐTime(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_createdAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type Time does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_message(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_message(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Message, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_resourceType(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_resourceType(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ResourceType, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v activitylog.ActivityLogEntryResourceType) graphql.Marshaler { - return ec.marshalNActivityLogEntryResourceType2githubᚗcomᚋnaisᚋapiᚋinternalᚋactivitylogᚐActivityLogEntryResourceType(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_resourceType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type ActivityLogEntryResourceType does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_resourceName(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_resourceName(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ResourceName, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_resourceName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_teamSlug(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_teamSlug(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.TeamSlug, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *slug.Slug) graphql.Marshaler { - return ec.marshalNSlug2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋslugᚐSlug(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_teamSlug(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type Slug does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_environmentName(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_environmentName(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.EnvironmentName, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *string) graphql.Marshaler { - return ec.marshalOString2ᚖstring(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_environmentName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry_data(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivatedActivityLogEntry_data(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Data, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *postgres.PostgresBranchActivityLogEntryData) graphql.Marshaler { - return ec.marshalNPostgresBranchActivityLogEntryData2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchActivityLogEntryData(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivatedActivityLogEntry_data(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "PostgresBranchActivatedActivityLogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.childFields_PostgresBranchActivityLogEntryData(ctx, field) - }, - } - return fc, nil -} - -func (ec *executionContext) _PostgresBranchActivityLogEntryData_branch(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivityLogEntryData) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivityLogEntryData_branch(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Branch, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivityLogEntryData_branch(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivityLogEntryData", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivityLogEntryData_sourceBranch(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivityLogEntryData) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivityLogEntryData_sourceBranch(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.SourceBranch, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *string) graphql.Marshaler { - return ec.marshalOString2ᚖstring(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivityLogEntryData_sourceBranch(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivityLogEntryData", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchActivityLogEntryData_targetTime(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchActivityLogEntryData) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchActivityLogEntryData_targetTime(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.TargetTime, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *time.Time) graphql.Marshaler { - return ec.marshalOTime2ᚖtimeᚐTime(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchActivityLogEntryData_targetTime(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchActivityLogEntryData", field, false, false, errors.New("field of type Time does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_id(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_id(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ID(), nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v ident.Ident) graphql.Marshaler { - return ec.marshalNID2githubᚗcomᚋnaisᚋapiᚋinternalᚋgraphᚋidentᚐIdent(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, true, false, errors.New("field of type ID does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_actor(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_actor(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Actor, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_actor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_gitHubActorClaims(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_gitHubActorClaims(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.GitHubActorClaims, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *github.GitHubActorClaims) graphql.Marshaler { - return ec.marshalOGitHubActorClaims2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋauthᚋmiddlewareᚋgithubᚐGitHubActorClaims(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_gitHubActorClaims(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "PostgresBranchCreatedActivityLogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.childFields_GitHubActorClaims(ctx, field) - }, - } - return fc, nil -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_createdAt(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_createdAt(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.CreatedAt, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v time.Time) graphql.Marshaler { - return ec.marshalNTime2timeᚐTime(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_createdAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type Time does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_message(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_message(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Message, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_resourceType(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_resourceType(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ResourceType, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v activitylog.ActivityLogEntryResourceType) graphql.Marshaler { - return ec.marshalNActivityLogEntryResourceType2githubᚗcomᚋnaisᚋapiᚋinternalᚋactivitylogᚐActivityLogEntryResourceType(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_resourceType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type ActivityLogEntryResourceType does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_resourceName(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_resourceName(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ResourceName, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_resourceName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_teamSlug(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_teamSlug(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.TeamSlug, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *slug.Slug) graphql.Marshaler { - return ec.marshalNSlug2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋslugᚐSlug(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_teamSlug(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type Slug does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_environmentName(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_environmentName(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.EnvironmentName, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *string) graphql.Marshaler { - return ec.marshalOString2ᚖstring(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_environmentName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchCreatedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry_data(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchCreatedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchCreatedActivityLogEntry_data(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Data, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *postgres.PostgresBranchActivityLogEntryData) graphql.Marshaler { - return ec.marshalNPostgresBranchActivityLogEntryData2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchActivityLogEntryData(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchCreatedActivityLogEntry_data(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "PostgresBranchCreatedActivityLogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.childFields_PostgresBranchActivityLogEntryData(ctx, field) - }, - } - return fc, nil -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_id(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_id(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ID(), nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v ident.Ident) graphql.Marshaler { - return ec.marshalNID2githubᚗcomᚋnaisᚋapiᚋinternalᚋgraphᚋidentᚐIdent(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, true, false, errors.New("field of type ID does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_actor(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_actor(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Actor, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_actor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_gitHubActorClaims(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_gitHubActorClaims(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.GitHubActorClaims, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *github.GitHubActorClaims) graphql.Marshaler { - return ec.marshalOGitHubActorClaims2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋauthᚋmiddlewareᚋgithubᚐGitHubActorClaims(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_gitHubActorClaims(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "PostgresBranchDeletedActivityLogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.childFields_GitHubActorClaims(ctx, field) - }, - } - return fc, nil -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_createdAt(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_createdAt(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.CreatedAt, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v time.Time) graphql.Marshaler { - return ec.marshalNTime2timeᚐTime(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_createdAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type Time does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_message(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_message(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Message, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_message(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_resourceType(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_resourceType(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ResourceType, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v activitylog.ActivityLogEntryResourceType) graphql.Marshaler { - return ec.marshalNActivityLogEntryResourceType2githubᚗcomᚋnaisᚋapiᚋinternalᚋactivitylogᚐActivityLogEntryResourceType(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_resourceType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type ActivityLogEntryResourceType does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_resourceName(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_resourceName(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.ResourceName, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v string) graphql.Marshaler { - return ec.marshalNString2string(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_resourceName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_teamSlug(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_teamSlug(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.TeamSlug, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *slug.Slug) graphql.Marshaler { - return ec.marshalNSlug2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋslugᚐSlug(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_teamSlug(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type Slug does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_environmentName(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_environmentName(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.EnvironmentName, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *string) graphql.Marshaler { - return ec.marshalOString2ᚖstring(ctx, selections, v) - }, - true, - false, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_environmentName(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - return graphql.NewScalarFieldContext("PostgresBranchDeletedActivityLogEntry", field, false, false, errors.New("field of type String does not have child fields")) -} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry_data(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresBranchDeletedActivityLogEntry) (ret graphql.Marshaler) { - return graphql.ResolveField( - ctx, - ec.OperationContext, - field, - func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.fieldContext_PostgresBranchDeletedActivityLogEntry_data(ctx, field) - }, - func(ctx context.Context) (any, error) { - return obj.Data, nil - }, - nil, - func(ctx context.Context, selections ast.SelectionSet, v *postgres.PostgresBranchActivityLogEntryData) graphql.Marshaler { - return ec.marshalNPostgresBranchActivityLogEntryData2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchActivityLogEntryData(ctx, selections, v) - }, - true, - true, - ) -} -func (ec *executionContext) fieldContext_PostgresBranchDeletedActivityLogEntry_data(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { - fc = &graphql.FieldContext{ - Object: "PostgresBranchDeletedActivityLogEntry", - Field: field, - IsMethod: false, - IsResolver: false, - Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - return ec.childFields_PostgresBranchActivityLogEntryData(ctx, field) - }, - } - return fc, nil -} - func (ec *executionContext) _PostgresConfiguration_parameters(ctx context.Context, field graphql.CollectedField, obj *postgres.PostgresConfiguration) (ret graphql.Marshaler) { return graphql.ResolveField( ctx, @@ -5838,283 +5025,6 @@ func (ec *executionContext) _PostgresAccessConnectionDetails(ctx context.Context return out } -var postgresBranchActivatedActivityLogEntryImplementors = []string{"PostgresBranchActivatedActivityLogEntry", "ActivityLogEntry", "Node"} - -func (ec *executionContext) _PostgresBranchActivatedActivityLogEntry(ctx context.Context, sel ast.SelectionSet, obj *postgres.PostgresBranchActivatedActivityLogEntry) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, postgresBranchActivatedActivityLogEntryImplementors) - - out := graphql.NewFieldSet(fields) - deferred := make(map[string]*graphql.FieldSet) - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("PostgresBranchActivatedActivityLogEntry") - case "id": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "actor": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_actor(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "gitHubActorClaims": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_gitHubActorClaims(ctx, field, obj) - case "createdAt": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_createdAt(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "message": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_message(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "resourceType": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_resourceType(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "resourceName": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_resourceName(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "teamSlug": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_teamSlug(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "environmentName": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_environmentName(ctx, field, obj) - case "data": - out.Values[i] = ec._PostgresBranchActivatedActivityLogEntry_data(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch(ctx) - if out.Invalids > 0 { - return graphql.Null - } - - atomic.AddInt32(&ec.Deferred, int32(min(len(deferred), math.MaxInt32))) - - for label, dfs := range deferred { - ec.ProcessDeferredGroup(graphql.DeferredGroup{ - Label: label, - Path: graphql.GetPath(ctx), - FieldSet: dfs, - Context: ctx, - }) - } - - return out -} - -var postgresBranchActivityLogEntryDataImplementors = []string{"PostgresBranchActivityLogEntryData"} - -func (ec *executionContext) _PostgresBranchActivityLogEntryData(ctx context.Context, sel ast.SelectionSet, obj *postgres.PostgresBranchActivityLogEntryData) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, postgresBranchActivityLogEntryDataImplementors) - - out := graphql.NewFieldSet(fields) - deferred := make(map[string]*graphql.FieldSet) - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("PostgresBranchActivityLogEntryData") - case "branch": - out.Values[i] = ec._PostgresBranchActivityLogEntryData_branch(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "sourceBranch": - out.Values[i] = ec._PostgresBranchActivityLogEntryData_sourceBranch(ctx, field, obj) - case "targetTime": - out.Values[i] = ec._PostgresBranchActivityLogEntryData_targetTime(ctx, field, obj) - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch(ctx) - if out.Invalids > 0 { - return graphql.Null - } - - atomic.AddInt32(&ec.Deferred, int32(min(len(deferred), math.MaxInt32))) - - for label, dfs := range deferred { - ec.ProcessDeferredGroup(graphql.DeferredGroup{ - Label: label, - Path: graphql.GetPath(ctx), - FieldSet: dfs, - Context: ctx, - }) - } - - return out -} - -var postgresBranchCreatedActivityLogEntryImplementors = []string{"PostgresBranchCreatedActivityLogEntry", "ActivityLogEntry", "Node"} - -func (ec *executionContext) _PostgresBranchCreatedActivityLogEntry(ctx context.Context, sel ast.SelectionSet, obj *postgres.PostgresBranchCreatedActivityLogEntry) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, postgresBranchCreatedActivityLogEntryImplementors) - - out := graphql.NewFieldSet(fields) - deferred := make(map[string]*graphql.FieldSet) - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("PostgresBranchCreatedActivityLogEntry") - case "id": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "actor": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_actor(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "gitHubActorClaims": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_gitHubActorClaims(ctx, field, obj) - case "createdAt": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_createdAt(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "message": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_message(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "resourceType": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_resourceType(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "resourceName": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_resourceName(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "teamSlug": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_teamSlug(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "environmentName": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_environmentName(ctx, field, obj) - case "data": - out.Values[i] = ec._PostgresBranchCreatedActivityLogEntry_data(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch(ctx) - if out.Invalids > 0 { - return graphql.Null - } - - atomic.AddInt32(&ec.Deferred, int32(min(len(deferred), math.MaxInt32))) - - for label, dfs := range deferred { - ec.ProcessDeferredGroup(graphql.DeferredGroup{ - Label: label, - Path: graphql.GetPath(ctx), - FieldSet: dfs, - Context: ctx, - }) - } - - return out -} - -var postgresBranchDeletedActivityLogEntryImplementors = []string{"PostgresBranchDeletedActivityLogEntry", "ActivityLogEntry", "Node"} - -func (ec *executionContext) _PostgresBranchDeletedActivityLogEntry(ctx context.Context, sel ast.SelectionSet, obj *postgres.PostgresBranchDeletedActivityLogEntry) graphql.Marshaler { - fields := graphql.CollectFields(ec.OperationContext, sel, postgresBranchDeletedActivityLogEntryImplementors) - - out := graphql.NewFieldSet(fields) - deferred := make(map[string]*graphql.FieldSet) - for i, field := range fields { - switch field.Name { - case "__typename": - out.Values[i] = graphql.MarshalString("PostgresBranchDeletedActivityLogEntry") - case "id": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_id(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "actor": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_actor(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "gitHubActorClaims": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_gitHubActorClaims(ctx, field, obj) - case "createdAt": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_createdAt(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "message": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_message(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "resourceType": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_resourceType(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "resourceName": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_resourceName(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "teamSlug": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_teamSlug(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - case "environmentName": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_environmentName(ctx, field, obj) - case "data": - out.Values[i] = ec._PostgresBranchDeletedActivityLogEntry_data(ctx, field, obj) - if out.Values[i] == graphql.Null { - out.Invalids++ - } - default: - panic("unknown field " + strconv.Quote(field.Name)) - } - } - out.Dispatch(ctx) - if out.Invalids > 0 { - return graphql.Null - } - - atomic.AddInt32(&ec.Deferred, int32(min(len(deferred), math.MaxInt32))) - - for label, dfs := range deferred { - ec.ProcessDeferredGroup(graphql.DeferredGroup{ - Label: label, - Path: graphql.GetPath(ctx), - FieldSet: dfs, - Context: ctx, - }) - } - - return out -} - var postgresConfigurationImplementors = []string{"PostgresConfiguration"} func (ec *executionContext) _PostgresConfiguration(ctx context.Context, sel ast.SelectionSet, obj *postgres.PostgresConfiguration) graphql.Marshaler { @@ -7558,16 +6468,6 @@ func (ec *executionContext) marshalNPostgresAccessState2githubᚗcomᚋnaisᚋap return v } -func (ec *executionContext) marshalNPostgresBranchActivityLogEntryData2ᚖgithubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchActivityLogEntryData(ctx context.Context, sel ast.SelectionSet, v *postgres.PostgresBranchActivityLogEntryData) graphql.Marshaler { - if v == nil { - if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { - graphql.AddErrorf(ctx, "the requested element is null which the schema does not allow") - } - return graphql.Null - } - return ec._PostgresBranchActivityLogEntryData(ctx, sel, v) -} - func (ec *executionContext) marshalNPostgresConnection2githubᚗcomᚋnaisᚋapiᚋinternalᚋgraphᚋpaginationᚐFacetableConnection(ctx context.Context, sel ast.SelectionSet, v pagination.FacetableConnection[*postgres.Postgres, *postgres.TeamPostgresFilter]) graphql.Marshaler { return ec._PostgresConnection(ctx, sel, &v) } @@ -7666,13 +6566,13 @@ func (ec *executionContext) marshalNPostgresResources2githubᚗcomᚋnaisᚋapi return ec._PostgresResources(ctx, sel, &v) } -func (ec *executionContext) unmarshalNPostgresState2githubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchState(ctx context.Context, v any) (postgres.PostgresBranchState, error) { - var res postgres.PostgresBranchState +func (ec *executionContext) unmarshalNPostgresState2githubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresState(ctx context.Context, v any) (postgres.PostgresState, error) { + var res postgres.PostgresState err := res.UnmarshalGQL(v) return res, graphql.ErrorOnPath(ctx, err) } -func (ec *executionContext) marshalNPostgresState2githubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresBranchState(ctx context.Context, sel ast.SelectionSet, v postgres.PostgresBranchState) graphql.Marshaler { +func (ec *executionContext) marshalNPostgresState2githubᚗcomᚋnaisᚋapiᚋinternalᚋpersistenceᚋpostgresᚐPostgresState(ctx context.Context, sel ast.SelectionSet, v postgres.PostgresState) graphql.Marshaler { return v } diff --git a/internal/graph/gengql/root_.generated.go b/internal/graph/gengql/root_.generated.go index 4afd394a6..79d80dabb 100644 --- a/internal/graph/gengql/root_.generated.go +++ b/internal/graph/gengql/root_.generated.go @@ -2017,51 +2017,6 @@ type ComplexityRoot struct { Username func(childComplexity int) int } - PostgresBranchActivatedActivityLogEntry struct { - Actor func(childComplexity int) int - CreatedAt func(childComplexity int) int - Data func(childComplexity int) int - EnvironmentName func(childComplexity int) int - GitHubActorClaims func(childComplexity int) int - ID func(childComplexity int) int - Message func(childComplexity int) int - ResourceName func(childComplexity int) int - ResourceType func(childComplexity int) int - TeamSlug func(childComplexity int) int - } - - PostgresBranchActivityLogEntryData struct { - Branch func(childComplexity int) int - SourceBranch func(childComplexity int) int - TargetTime func(childComplexity int) int - } - - PostgresBranchCreatedActivityLogEntry struct { - Actor func(childComplexity int) int - CreatedAt func(childComplexity int) int - Data func(childComplexity int) int - EnvironmentName func(childComplexity int) int - GitHubActorClaims func(childComplexity int) int - ID func(childComplexity int) int - Message func(childComplexity int) int - ResourceName func(childComplexity int) int - ResourceType func(childComplexity int) int - TeamSlug func(childComplexity int) int - } - - PostgresBranchDeletedActivityLogEntry struct { - Actor func(childComplexity int) int - CreatedAt func(childComplexity int) int - Data func(childComplexity int) int - EnvironmentName func(childComplexity int) int - GitHubActorClaims func(childComplexity int) int - ID func(childComplexity int) int - Message func(childComplexity int) int - ResourceName func(childComplexity int) int - ResourceType func(childComplexity int) int - TeamSlug func(childComplexity int) int - } - PostgresConfiguration struct { Parameters func(childComplexity int) int } @@ -12660,237 +12615,6 @@ func (e *executableSchema) Complexity(ctx context.Context, typeName, field strin return e.ComplexityRoot.PostgresAccessConnectionDetails.Username(childComplexity), true - case "PostgresBranchActivatedActivityLogEntry.actor": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.Actor == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.Actor(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.createdAt": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.CreatedAt == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.CreatedAt(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.data": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.Data == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.Data(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.environmentName": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.EnvironmentName == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.EnvironmentName(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.gitHubActorClaims": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.GitHubActorClaims == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.GitHubActorClaims(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.id": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.ID == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.ID(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.message": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.Message == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.Message(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.resourceName": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.ResourceName == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.ResourceName(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.resourceType": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.ResourceType == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.ResourceType(childComplexity), true - - case "PostgresBranchActivatedActivityLogEntry.teamSlug": - if e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.TeamSlug == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivatedActivityLogEntry.TeamSlug(childComplexity), true - - case "PostgresBranchActivityLogEntryData.branch": - if e.ComplexityRoot.PostgresBranchActivityLogEntryData.Branch == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivityLogEntryData.Branch(childComplexity), true - - case "PostgresBranchActivityLogEntryData.sourceBranch": - if e.ComplexityRoot.PostgresBranchActivityLogEntryData.SourceBranch == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivityLogEntryData.SourceBranch(childComplexity), true - - case "PostgresBranchActivityLogEntryData.targetTime": - if e.ComplexityRoot.PostgresBranchActivityLogEntryData.TargetTime == nil { - break - } - - return e.ComplexityRoot.PostgresBranchActivityLogEntryData.TargetTime(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.actor": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.Actor == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.Actor(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.createdAt": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.CreatedAt == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.CreatedAt(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.data": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.Data == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.Data(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.environmentName": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.EnvironmentName == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.EnvironmentName(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.gitHubActorClaims": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.GitHubActorClaims == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.GitHubActorClaims(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.id": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.ID == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.ID(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.message": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.Message == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.Message(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.resourceName": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.ResourceName == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.ResourceName(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.resourceType": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.ResourceType == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.ResourceType(childComplexity), true - - case "PostgresBranchCreatedActivityLogEntry.teamSlug": - if e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.TeamSlug == nil { - break - } - - return e.ComplexityRoot.PostgresBranchCreatedActivityLogEntry.TeamSlug(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.actor": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.Actor == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.Actor(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.createdAt": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.CreatedAt == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.CreatedAt(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.data": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.Data == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.Data(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.environmentName": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.EnvironmentName == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.EnvironmentName(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.gitHubActorClaims": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.GitHubActorClaims == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.GitHubActorClaims(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.id": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.ID == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.ID(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.message": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.Message == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.Message(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.resourceName": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.ResourceName == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.ResourceName(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.resourceType": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.ResourceType == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.ResourceType(childComplexity), true - - case "PostgresBranchDeletedActivityLogEntry.teamSlug": - if e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.TeamSlug == nil { - break - } - - return e.ComplexityRoot.PostgresBranchDeletedActivityLogEntry.TeamSlug(childComplexity), true - case "PostgresConfiguration.parameters": if e.ComplexityRoot.PostgresConfiguration.Parameters == nil { break @@ -30345,7 +30069,7 @@ type PostgresPersonalAccessCreatedActivityLogEntry implements ActivityLogEntry & message: String! "Type of the affected resource." resourceType: ActivityLogEntryResourceType! - "Name of the affected Postgres branch." + "Name of the affected Postgres." resourceName: String! "The team slug that the entry belongs to." teamSlug: Slug! @@ -30389,59 +30113,6 @@ type PostgresPersonalAccessConnectionActivityLogEntry implements ActivityLogEntr environmentName: String } -"A Postgres branch was created." -type PostgresBranchCreatedActivityLogEntry implements ActivityLogEntry & Node { - id: ID! - actor: String! - gitHubActorClaims: GitHubActorClaims - createdAt: Time! - message: String! - resourceType: ActivityLogEntryResourceType! - "Name of the Postgres containing the branch." - resourceName: String! - teamSlug: Slug! - environmentName: String - data: PostgresBranchActivityLogEntryData! -} - -"A request to activate a Postgres branch was accepted; the switchover may still be pending." -type PostgresBranchActivatedActivityLogEntry implements ActivityLogEntry & Node { - id: ID! - actor: String! - gitHubActorClaims: GitHubActorClaims - createdAt: Time! - message: String! - resourceType: ActivityLogEntryResourceType! - "Name of the Postgres containing the branch." - resourceName: String! - teamSlug: Slug! - environmentName: String - data: PostgresBranchActivityLogEntryData! -} - -"A Postgres branch was deleted." -type PostgresBranchDeletedActivityLogEntry implements ActivityLogEntry & Node { - id: ID! - actor: String! - gitHubActorClaims: GitHubActorClaims - createdAt: Time! - message: String! - resourceType: ActivityLogEntryResourceType! - "Name of the Postgres containing the branch." - resourceName: String! - teamSlug: Slug! - environmentName: String - data: PostgresBranchActivityLogEntryData! -} - -type PostgresBranchActivityLogEntryData { - branch: String! - "Source branch, populated for branch creation." - sourceBranch: String - "Recovery instant, populated for branch creation." - targetTime: Time -} - type PostgresDeletedActivityLogEntry implements ActivityLogEntry & Node { "ID of the entry." id: ID! @@ -30574,17 +30245,11 @@ extend enum ActivityLogActivityType { """ POSTGRES_PERSONAL_ACCESS_CONNECTION """ - A Postgres branch was deleted (historical entries without branch name) + A Postgres was deleted """ POSTGRES_DELETED "A request to delete a whole Postgres was accepted; cleanup continues asynchronously." POSTGRES_DELETION_REQUESTED - "A Postgres branch was created." - POSTGRES_BRANCH_CREATED - "A Postgres branch was activated." - POSTGRES_BRANCH_ACTIVATED - "A Postgres branch was deleted." - POSTGRES_BRANCH_DELETED } extend type Mutation { @@ -41767,18 +41432,6 @@ func (ec *executionContext) childFields_PostgresAccessConnectionDetails(ctx cont return nil, fmt.Errorf("no field named %q was found under type PostgresAccessConnectionDetails", field.Name) } -func (ec *executionContext) childFields_PostgresBranchActivityLogEntryData(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { - switch field.Name { - case "branch": - return ec.fieldContext_PostgresBranchActivityLogEntryData_branch(ctx, field) - case "sourceBranch": - return ec.fieldContext_PostgresBranchActivityLogEntryData_sourceBranch(ctx, field) - case "targetTime": - return ec.fieldContext_PostgresBranchActivityLogEntryData_targetTime(ctx, field) - } - return nil, fmt.Errorf("no field named %q was found under type PostgresBranchActivityLogEntryData", field.Name) -} - func (ec *executionContext) childFields_PostgresConfiguration(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { switch field.Name { case "parameters": diff --git a/internal/graph/gengql/schema.generated.go b/internal/graph/gengql/schema.generated.go index d0f144c5e..760e5e8dd 100644 --- a/internal/graph/gengql/schema.generated.go +++ b/internal/graph/gengql/schema.generated.go @@ -7327,27 +7327,6 @@ func (ec *executionContext) _Node(ctx context.Context, sel ast.SelectionSet, obj return graphql.Null } return ec._PostgresCreatedActivityLogEntry(ctx, sel, obj) - case postgres.PostgresBranchDeletedActivityLogEntry: - return ec._PostgresBranchDeletedActivityLogEntry(ctx, sel, &obj) - case *postgres.PostgresBranchDeletedActivityLogEntry: - if obj == nil { - return graphql.Null - } - return ec._PostgresBranchDeletedActivityLogEntry(ctx, sel, obj) - case postgres.PostgresBranchCreatedActivityLogEntry: - return ec._PostgresBranchCreatedActivityLogEntry(ctx, sel, &obj) - case *postgres.PostgresBranchCreatedActivityLogEntry: - if obj == nil { - return graphql.Null - } - return ec._PostgresBranchCreatedActivityLogEntry(ctx, sel, obj) - case postgres.PostgresBranchActivatedActivityLogEntry: - return ec._PostgresBranchActivatedActivityLogEntry(ctx, sel, &obj) - case *postgres.PostgresBranchActivatedActivityLogEntry: - if obj == nil { - return graphql.Null - } - return ec._PostgresBranchActivatedActivityLogEntry(ctx, sel, obj) case postgres.Postgres: return ec._Postgres(ctx, sel, &obj) case *postgres.Postgres: diff --git a/internal/graph/issues.resolvers.go b/internal/graph/issues.resolvers.go index 7c7a64151..19d2b0262 100644 --- a/internal/graph/issues.resolvers.go +++ b/internal/graph/issues.resolvers.go @@ -122,9 +122,6 @@ func (r *postgresIssueResolver) TeamEnvironment(ctx context.Context, obj *issue. } func (r *postgresIssueResolver) Postgres(ctx context.Context, obj *issue.PostgresIssue) (*postgres.Postgres, error) { - if obj.LegacyPhysicalName != "" { - return postgres.GetPostgresByPhysicalName(ctx, obj.TeamSlug, obj.EnvironmentName, obj.LegacyPhysicalName) - } return postgres.GetPostgres(ctx, obj.TeamSlug, obj.EnvironmentName, obj.ResourceName) } diff --git a/internal/graph/postgres.resolvers.go b/internal/graph/postgres.resolvers.go index 1c81c52c0..27ed21f5a 100644 --- a/internal/graph/postgres.resolvers.go +++ b/internal/graph/postgres.resolvers.go @@ -77,7 +77,7 @@ func (r *postgresResolver) TeamEnvironment(ctx context.Context, obj *postgres.Po return team.GetTeamEnvironment(ctx, obj.TeamSlug, obj.EnvironmentName) } -func (r *postgresResolver) State(ctx context.Context, obj *postgres.Postgres) (postgres.PostgresBranchState, error) { +func (r *postgresResolver) State(ctx context.Context, obj *postgres.Postgres) (postgres.PostgresState, error) { state, _, err := postgres.PhysicalStatus(ctx, obj) return state, err } @@ -126,10 +126,7 @@ func (r *postgresAccessResolver) TeamEnvironment(ctx context.Context, obj *postg } func (r *postgresAccessResolver) Postgres(ctx context.Context, obj *postgres.PostgresAccess) (*postgres.Postgres, error) { - if obj.PostgresName != "" { - return postgres.GetPostgres(ctx, obj.TeamSlug, obj.EnvironmentName, obj.PostgresName) - } - return postgres.GetPostgresByPhysicalName(ctx, obj.TeamSlug, obj.EnvironmentName, obj.PostgresBranchName) + return postgres.GetPostgres(ctx, obj.TeamSlug, obj.EnvironmentName, obj.PostgresName) } func (r *postgresAccessResolver) Connection(ctx context.Context, obj *postgres.PostgresAccess) (*postgres.PostgresAccessConnectionDetails, error) { diff --git a/internal/graph/postgres_schema_test.go b/internal/graph/postgres_schema_test.go deleted file mode 100644 index 52302c25c..000000000 --- a/internal/graph/postgres_schema_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package graph - -import ( - "testing" - - "github.com/nais/api/internal/graph/gengql" -) - -func TestPostgresBranchMutationsRemoved(t *testing.T) { - schema := gengql.NewExecutableSchema(gengql.Config{}).Schema() - for _, tt := range []struct { - mutation string - typeName string - }{ - {mutation: "createPostgresBranch", typeName: "CreatePostgresBranch"}, - {mutation: "activatePostgresBranch", typeName: "ActivatePostgresBranch"}, - {mutation: "deletePostgresBranch", typeName: "DeletePostgresBranch"}, - } { - t.Run(tt.mutation, func(t *testing.T) { - if schema.Mutation.Fields.ForName(tt.mutation) != nil { - t.Errorf("removed mutation %s is still exposed", tt.mutation) - } - for _, suffix := range []string{"Input", "Payload"} { - if schema.Types[tt.typeName+suffix] != nil { - t.Errorf("removed type %s%s is still exposed", tt.typeName, suffix) - } - } - }) - } -} - -func TestPostgresSchemaRetainsDatabaseOperationsAndBranchHistory(t *testing.T) { - schema := gengql.NewExecutableSchema(gengql.Config{}).Schema() - for _, name := range []string{"createPostgres", "updatePostgres", "deletePostgres", "createPostgresAccess"} { - if schema.Mutation.Fields.ForName(name) == nil { - t.Errorf("mutation %s must remain available", name) - } - } - for _, name := range []string{ - "Postgres", - "PostgresIssue", - "PostgresBranchCreatedActivityLogEntry", - "PostgresBranchActivatedActivityLogEntry", - "PostgresBranchDeletedActivityLogEntry", - } { - if schema.Types[name] == nil { - t.Errorf("type %s must remain available", name) - } - } -} - -func TestPostgresSchemaRetiresBranchReads(t *testing.T) { - schema := gengql.NewExecutableSchema(gengql.Config{}).Schema() - for _, name := range []string{"PostgresBranch", "PostgresBranchIssue", "PostgresBranchConnection", "PostgresBranchFilter", "PostgresBranchOrder", "PostgresBranchState", "PostgresBranchFacets", "TeamInventoryCountPostgresBranches"} { - if schema.Types[name] != nil { - t.Errorf("retired type %s is still exposed", name) - } - } - for name, fields := range map[string][]string{ - "Postgres": {"activeBranch", "desiredActiveBranch", "branch", "branches"}, - "PostgresAccess": {"postgresBranch"}, - "PostgresWorkload": {"branch"}, - "WorkloadPostgres": {"branch"}, - "TeamInventoryCounts": {"postgresBranches"}, - "CreatePostgresAccessInput": {"branch"}, - } { - for _, field := range fields { - if schema.Types[name].Fields.ForName(field) != nil { - t.Errorf("retired field %s.%s is still exposed", name, field) - } - } - } -} diff --git a/internal/graph/schema/postgres.graphqls b/internal/graph/schema/postgres.graphqls index 1dab192d6..7dd5a9c88 100644 --- a/internal/graph/schema/postgres.graphqls +++ b/internal/graph/schema/postgres.graphqls @@ -331,7 +331,7 @@ type PostgresPersonalAccessCreatedActivityLogEntry implements ActivityLogEntry & message: String! "Type of the affected resource." resourceType: ActivityLogEntryResourceType! - "Name of the affected Postgres branch." + "Name of the affected Postgres." resourceName: String! "The team slug that the entry belongs to." teamSlug: Slug! @@ -375,59 +375,6 @@ type PostgresPersonalAccessConnectionActivityLogEntry implements ActivityLogEntr environmentName: String } -"A Postgres branch was created." -type PostgresBranchCreatedActivityLogEntry implements ActivityLogEntry & Node { - id: ID! - actor: String! - gitHubActorClaims: GitHubActorClaims - createdAt: Time! - message: String! - resourceType: ActivityLogEntryResourceType! - "Name of the Postgres containing the branch." - resourceName: String! - teamSlug: Slug! - environmentName: String - data: PostgresBranchActivityLogEntryData! -} - -"A request to activate a Postgres branch was accepted; the switchover may still be pending." -type PostgresBranchActivatedActivityLogEntry implements ActivityLogEntry & Node { - id: ID! - actor: String! - gitHubActorClaims: GitHubActorClaims - createdAt: Time! - message: String! - resourceType: ActivityLogEntryResourceType! - "Name of the Postgres containing the branch." - resourceName: String! - teamSlug: Slug! - environmentName: String - data: PostgresBranchActivityLogEntryData! -} - -"A Postgres branch was deleted." -type PostgresBranchDeletedActivityLogEntry implements ActivityLogEntry & Node { - id: ID! - actor: String! - gitHubActorClaims: GitHubActorClaims - createdAt: Time! - message: String! - resourceType: ActivityLogEntryResourceType! - "Name of the Postgres containing the branch." - resourceName: String! - teamSlug: Slug! - environmentName: String - data: PostgresBranchActivityLogEntryData! -} - -type PostgresBranchActivityLogEntryData { - branch: String! - "Source branch, populated for branch creation." - sourceBranch: String - "Recovery instant, populated for branch creation." - targetTime: Time -} - type PostgresDeletedActivityLogEntry implements ActivityLogEntry & Node { "ID of the entry." id: ID! @@ -560,17 +507,11 @@ extend enum ActivityLogActivityType { """ POSTGRES_PERSONAL_ACCESS_CONNECTION """ - A Postgres branch was deleted (historical entries without branch name) + A Postgres was deleted """ POSTGRES_DELETED "A request to delete a whole Postgres was accepted; cleanup continues asynchronously." POSTGRES_DELETION_REQUESTED - "A Postgres branch was created." - POSTGRES_BRANCH_CREATED - "A Postgres branch was activated." - POSTGRES_BRANCH_ACTIVATED - "A Postgres branch was deleted." - POSTGRES_BRANCH_DELETED } extend type Mutation { diff --git a/internal/grpc/grpcdatabase/testdata/dev-gcp/myteam/postgres.yaml b/internal/grpc/grpcdatabase/testdata/dev-gcp/myteam/postgres.yaml index ba562760a..19baa2c72 100644 --- a/internal/grpc/grpcdatabase/testdata/dev-gcp/myteam/postgres.yaml +++ b/internal/grpc/grpcdatabase/testdata/dev-gcp/myteam/postgres.yaml @@ -7,7 +7,6 @@ metadata: spec: majorVersion: "17" status: - activeBranch: main clusterName: pg-pg-b-main-4a8c4391 reconcilePhase: Completed conditions: diff --git a/internal/issue/checker/postgres.go b/internal/issue/checker/postgres.go index 60902cd00..fd61c5011 100644 --- a/internal/issue/checker/postgres.go +++ b/internal/issue/checker/postgres.go @@ -25,7 +25,7 @@ func (p Postgres) Run(ctx context.Context) ([]Issue, error) { if err != nil { return nil, err } - if state != postgres.PostgresBranchStateDegraded { + if state != postgres.PostgresStateDegraded { continue } issues = append(issues, Issue{ diff --git a/internal/issue/checker/postgres_direct_test.go b/internal/issue/checker/postgres_direct_test.go index f14269818..a54580306 100644 --- a/internal/issue/checker/postgres_direct_test.go +++ b/internal/issue/checker/postgres_direct_test.go @@ -17,7 +17,7 @@ import ( "k8s.io/apimachinery/pkg/util/wait" ) -func TestPostgresIssuesWithoutBranchObjects(t *testing.T) { +func TestPostgresIssueClearedAfterDeletion(t *testing.T) { scheme, err := kubernetes.NewScheme() if err != nil { t.Fatal(err) diff --git a/internal/issue/checker/postgres_test.go b/internal/issue/checker/postgres_test.go index d8d54968e..037c28d55 100644 --- a/internal/issue/checker/postgres_test.go +++ b/internal/issue/checker/postgres_test.go @@ -35,7 +35,7 @@ func TestPostgresWithoutWatcher(t *testing.T) { } } -func TestPostgresIssuesWithoutBranchWatcher(t *testing.T) { +func TestPostgresIssuesFollowDatabaseState(t *testing.T) { scheme, err := kubernetes.NewScheme() if err != nil { t.Fatal(err) @@ -80,23 +80,23 @@ func TestPostgresIssuesWithoutBranchWatcher(t *testing.T) { for _, tt := range []struct { name string status map[string]any - state postgres.PostgresBranchState + state postgres.PostgresState want []Issue }{ - {name: "not observed", state: postgres.PostgresBranchStateProgressing}, - {name: "recovery failed on an inactive branch", status: map[string]any{ + {name: "not observed", state: postgres.PostgresStateProgressing}, + {name: "database recovery failed", status: map[string]any{ "reconcilePhase": "Failed", "conditions": []any{map[string]any{"type": "RecoveryFailed", "status": "True", "reason": "Unrecoverable"}}, - }, state: postgres.PostgresBranchStateDegraded, want: want}, + }, state: postgres.PostgresStateDegraded, want: want}, {name: "healthy again", status: map[string]any{ "reconcilePhase": "Completed", "observedGeneration": int64(1), "conditions": []any{map[string]any{"type": "cluster.postgresql.cnpg.io/ObservedState", "status": "True", "message": "Cluster is in phase: Cluster in healthy state"}}, - }, state: postgres.PostgresBranchStateAvailable}, - {name: "progressing again", state: postgres.PostgresBranchStateProgressing}, + }, state: postgres.PostgresStateAvailable}, + {name: "progressing again", state: postgres.PostgresStateProgressing}, {name: "cluster failure", status: map[string]any{ "reconcilePhase": "Completed", "observedGeneration": int64(1), "conditions": []any{map[string]any{"type": "cluster.postgresql.cnpg.io/ObservedState", "status": "True", "message": "Cluster is in phase: Cluster is unrecoverable and needs manual intervention"}}, - }, state: postgres.PostgresBranchStateDegraded, want: want}, + }, state: postgres.PostgresStateDegraded, want: want}, } { t.Run(tt.name, func(t *testing.T) { if tt.status != nil { diff --git a/internal/issue/facets.go b/internal/issue/facets.go index cae772183..382518a60 100644 --- a/internal/issue/facets.go +++ b/internal/issue/facets.go @@ -39,8 +39,6 @@ func ComputeFacets(ctx context.Context, connection *IssueConnection) (*IssueFace } } - params.LegacyScopeResourceName = legacyPostgresIssueName(params.ScopeResourceName) - params.LegacyFilterResourceName = legacyPostgresIssueName(params.FilterResourceName) rows, err := db(ctx).FacetsForIssues(ctx, params) if err != nil { return nil, err diff --git a/internal/issue/issuesql/issue.sql.go b/internal/issue/issuesql/issue.sql.go index 129afbc7b..f711dd877 100644 --- a/internal/issue/issuesql/issue.sql.go +++ b/internal/issue/issuesql/issue.sql.go @@ -12,29 +12,6 @@ import ( ) const facetsForIssues = `-- name: FacetsForIssues :many -WITH - issue_rows AS ( - SELECT - team, - severity, - env, - resource_name, - ( - CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END - )::TEXT AS resource_type, - ( - CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END - )::TEXT AS issue_type, - resource_type = 'POSTGRES_BRANCH' AS legacy_postgres - FROM - issues - ) SELECT team, EXISTS ( @@ -70,38 +47,30 @@ SELECT AND ( $5::TEXT IS NULL OR resource_name = $5::TEXT - OR ( - legacy_postgres - AND resource_name = $6::TEXT - ) ) ) AS filtered_count FROM - issue_rows AS issues + issues WHERE ( - $7::TEXT = '' - OR team = $7 + $6::TEXT = '' + OR team = $6 ) AND ( - $8::slug[] IS NULL - OR team = ANY ($8::slug[]) + $7::slug[] IS NULL + OR team = ANY ($7::slug[]) ) AND ( - $9::TEXT IS NULL - OR resource_type = $9::TEXT + $8::TEXT IS NULL + OR resource_type = $8::TEXT ) AND ( - $10::TEXT IS NULL - OR resource_name = $10::TEXT - OR ( - legacy_postgres - AND resource_name = $11::TEXT - ) + $9::TEXT IS NULL + OR resource_name = $9::TEXT ) AND ( - $12::TEXT IS NULL - OR env = $12::TEXT + $10::TEXT IS NULL + OR env = $10::TEXT ) GROUP BY team, @@ -118,18 +87,16 @@ ORDER BY ` type FacetsForIssuesParams struct { - Env []string - IssueType *string - Severity *SeverityLevel - FilterResourceType *string - FilterResourceName *string - LegacyFilterResourceName *string - Team string - TeamSlugs []slug.Slug - ScopeResourceType *string - ScopeResourceName *string - LegacyScopeResourceName *string - ScopeEnv *string + Env []string + IssueType *string + Severity *SeverityLevel + FilterResourceType *string + FilterResourceName *string + Team string + TeamSlugs []slug.Slug + ScopeResourceType *string + ScopeResourceName *string + ScopeEnv *string } type FacetsForIssuesRow struct { @@ -142,8 +109,6 @@ type FacetsForIssuesRow struct { FilteredCount int64 } -// Normalize before grouping, including zero-count facets. Keep ListIssues' stored -// row types intact so legacy physical names still reach the Postgres read adapter. func (q *Queries) FacetsForIssues(ctx context.Context, arg FacetsForIssuesParams) ([]*FacetsForIssuesRow, error) { rows, err := q.db.Query(ctx, facetsForIssues, arg.Env, @@ -151,12 +116,10 @@ func (q *Queries) FacetsForIssues(ctx context.Context, arg FacetsForIssuesParams arg.Severity, arg.FilterResourceType, arg.FilterResourceName, - arg.LegacyFilterResourceName, arg.Team, arg.TeamSlugs, arg.ScopeResourceType, arg.ScopeResourceName, - arg.LegacyScopeResourceName, arg.ScopeEnv, ) if err != nil { @@ -271,10 +234,7 @@ WHERE ) AND ( $4::TEXT IS NULL - OR CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END = $4::TEXT + OR issue_type = $4::TEXT ) AND ( $5::severity_level IS NULL @@ -282,82 +242,62 @@ WHERE ) AND ( $6::TEXT IS NULL - OR CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END = $6::TEXT + OR resource_type = $6::TEXT ) AND ( $7::TEXT IS NULL OR resource_name = $7::TEXT - OR ( - resource_type = 'POSTGRES_BRANCH' - AND resource_name = $8::TEXT - ) ) ORDER BY CASE - WHEN $9::TEXT = 'env:asc' THEN env + WHEN $8::TEXT = 'env:asc' THEN env END ASC, CASE - WHEN $9::TEXT = 'env:desc' THEN env + WHEN $8::TEXT = 'env:desc' THEN env END DESC, CASE - WHEN $9::TEXT = 'issue_type:asc' THEN CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END + WHEN $8::TEXT = 'issue_type:asc' THEN issue_type END ASC, CASE - WHEN $9::TEXT = 'issue_type:desc' THEN CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END + WHEN $8::TEXT = 'issue_type:desc' THEN issue_type END DESC, CASE - WHEN $9::TEXT = 'resource_type:asc' THEN CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END + WHEN $8::TEXT = 'resource_type:asc' THEN resource_type END ASC, CASE - WHEN $9::TEXT = 'resource_type:desc' THEN CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END + WHEN $8::TEXT = 'resource_type:desc' THEN resource_type END DESC, CASE - WHEN $9::TEXT = 'resource_name:asc' THEN resource_name + WHEN $8::TEXT = 'resource_name:asc' THEN resource_name END ASC, CASE - WHEN $9::TEXT = 'resource_name:desc' THEN resource_name + WHEN $8::TEXT = 'resource_name:desc' THEN resource_name END DESC, CASE - WHEN $9::TEXT = 'severity:asc' THEN severity + WHEN $8::TEXT = 'severity:asc' THEN severity END ASC, CASE - WHEN $9::TEXT = 'severity:desc' THEN severity + WHEN $8::TEXT = 'severity:desc' THEN severity END DESC, severity DESC, id OFFSET - $10 + $9 LIMIT - $11 + $10 ` type ListIssuesParams struct { - Team string - TeamSlugs []slug.Slug - Env []string - IssueType *string - Severity *SeverityLevel - ResourceType *string - ResourceName *string - LegacyResourceName *string - OrderBy string - Offset int32 - Limit int32 + Team string + TeamSlugs []slug.Slug + Env []string + IssueType *string + Severity *SeverityLevel + ResourceType *string + ResourceName *string + OrderBy string + Offset int32 + Limit int32 } type ListIssuesRow struct { @@ -383,7 +323,6 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]*List arg.Severity, arg.ResourceType, arg.ResourceName, - arg.LegacyResourceName, arg.OrderBy, arg.Offset, arg.Limit, diff --git a/internal/issue/issuesql/querier.go b/internal/issue/issuesql/querier.go index 4ac99ad8b..96a86d9bb 100644 --- a/internal/issue/issuesql/querier.go +++ b/internal/issue/issuesql/querier.go @@ -9,8 +9,6 @@ import ( ) type Querier interface { - // Normalize before grouping, including zero-count facets. Keep ListIssues' stored - // row types intact so legacy physical names still reach the Postgres read adapter. FacetsForIssues(ctx context.Context, arg FacetsForIssuesParams) ([]*FacetsForIssuesRow, error) GetIssueByID(ctx context.Context, id uuid.UUID) (*Issue, error) GetSeverityScoreForWorkload(ctx context.Context, arg GetSeverityScoreForWorkloadParams) (int64, error) diff --git a/internal/issue/legacy_postgres.go b/internal/issue/legacy_postgres.go deleted file mode 100644 index 0e03e4fde..000000000 --- a/internal/issue/legacy_postgres.go +++ /dev/null @@ -1,13 +0,0 @@ -package issue - -import nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" - -// Old issue snapshots key Postgres by its physical main identity. SQL only uses -// this alternative for stored POSTGRES_BRANCH rows; canonical rows and other -// resource kinds continue to match their logical resource name normally. -func legacyPostgresIssueName(name *string) *string { - if name == nil { - return nil - } - return new(nais_io_v1.PostgresPhysicalName(*name)) -} diff --git a/internal/issue/model.go b/internal/issue/model.go index 5347503b0..fa859de82 100644 --- a/internal/issue/model.go +++ b/internal/issue/model.go @@ -52,9 +52,6 @@ func (ValkeyIssue) IsNode() {} // PostgresIssue reports a failure on a Postgres database. type PostgresIssue struct { Base - // LegacyPhysicalName is only populated for rows written before contraction. - // The checker replaces these rows on its next refresh. - LegacyPhysicalName string `json:"-"` } func (PostgresIssue) IsIssue() {} @@ -133,14 +130,13 @@ func (DeprecatedIngressIssue) IsNode() {} type ResourceType string const ( - ResourceTypeOpensearch ResourceType = "OPENSEARCH" - ResourceTypeValkey ResourceType = "VALKEY" - ResourceTypeSQLInstance ResourceType = "SQLINSTANCE" - ResourceTypeApplication ResourceType = "APPLICATION" - ResourceTypeJob ResourceType = "JOB" - ResourceTypeUnleash ResourceType = "UNLEASH" - ResourceTypePostgres ResourceType = "POSTGRES" - ResourceTypePostgresBranch ResourceType = "POSTGRES_BRANCH" + ResourceTypeOpensearch ResourceType = "OPENSEARCH" + ResourceTypeValkey ResourceType = "VALKEY" + ResourceTypeSQLInstance ResourceType = "SQLINSTANCE" + ResourceTypeApplication ResourceType = "APPLICATION" + ResourceTypeJob ResourceType = "JOB" + ResourceTypeUnleash ResourceType = "UNLEASH" + ResourceTypePostgres ResourceType = "POSTGRES" ) var AllResourceType = []ResourceType{ @@ -151,12 +147,11 @@ var AllResourceType = []ResourceType{ ResourceTypeJob, ResourceTypeUnleash, ResourceTypePostgres, - ResourceTypePostgresBranch, } func (e ResourceType) IsValid() bool { switch e { - case ResourceTypeOpensearch, ResourceTypeValkey, ResourceTypeSQLInstance, ResourceTypeApplication, ResourceTypeJob, ResourceTypeUnleash, ResourceTypePostgres, ResourceTypePostgresBranch: + case ResourceTypeOpensearch, ResourceTypeValkey, ResourceTypeSQLInstance, ResourceTypeApplication, ResourceTypeJob, ResourceTypeUnleash, ResourceTypePostgres: return true } return false @@ -229,7 +224,6 @@ const ( IssueTypeApplicationRestartLoop IssueType = "APPLICATION_RESTART_LOOP" IssueTypeApplicationRolloutStuck IssueType = "APPLICATION_ROLLOUT_STUCK" IssueTypePostgres IssueType = "POSTGRES" - IssueTypePostgresBranch IssueType = "POSTGRES_BRANCH" ) var AllIssueType = []IssueType{ @@ -251,7 +245,6 @@ var AllIssueType = []IssueType{ IssueTypeApplicationRestartLoop, IssueTypeApplicationRolloutStuck, IssueTypePostgres, - IssueTypePostgresBranch, } func (e IssueType) IsValid() bool { @@ -262,7 +255,7 @@ func (e IssueType) IsValid() bool { IssueTypeInvalidSpec, IssueTypeFailedSynchronization, IssueTypeVulnerableImage, IssueTypeMissingSBOM, IssueTypeExternalIngressUrgentVulnerability, IssueTypeUnleashReleaseChannel, - IssueTypeApplicationRestartLoop, IssueTypeApplicationRolloutStuck, IssueTypePostgres, IssueTypePostgresBranch: + IssueTypeApplicationRestartLoop, IssueTypeApplicationRolloutStuck, IssueTypePostgres: return true } return false diff --git a/internal/issue/postgres_test.go b/internal/issue/postgres_test.go index 4f9849f3e..015c70eab 100644 --- a/internal/issue/postgres_test.go +++ b/internal/issue/postgres_test.go @@ -11,10 +11,9 @@ import ( func TestPostgresIssueConversion(t *testing.T) { id := uuid.New() for _, tt := range []struct { - name, issueType, resourceType, resourceName, legacyName string + name, issueType, resourceType, resourceName string }{ {name: "logical Postgres", issueType: "POSTGRES", resourceType: "POSTGRES", resourceName: "orders"}, - {name: "row from previous release", issueType: "POSTGRES_BRANCH", resourceType: "POSTGRES_BRANCH", resourceName: "orders-main-12345678", legacyName: "orders-main-12345678"}, } { t.Run(tt.name, func(t *testing.T) { got, err := convert(&issuesql.Issue{ID: id, IssueType: tt.issueType, ResourceType: tt.resourceType, ResourceName: tt.resourceName, Team: "team", Env: "dev", Severity: "CRITICAL", Message: "database failure"}) @@ -25,7 +24,7 @@ func TestPostgresIssueConversion(t *testing.T) { if !ok { t.Fatalf("got %T, want genuine PostgresIssue", got) } - want := &PostgresIssue{Base: Base{ID: newIdent(id.String()), ResourceType: ResourceTypePostgres, ResourceName: tt.resourceName, TeamSlug: "team", EnvironmentName: "dev", Severity: SeverityCritical, Message: "database failure"}, LegacyPhysicalName: tt.legacyName} + want := &PostgresIssue{Base: Base{ID: newIdent(id.String()), ResourceType: ResourceTypePostgres, ResourceName: tt.resourceName, TeamSlug: "team", EnvironmentName: "dev", Severity: SeverityCritical, Message: "database failure"}} if diff := cmp.Diff(want, pg); diff != "" { t.Errorf("converted issue (-want +got):\n%s", diff) } diff --git a/internal/issue/queries.go b/internal/issue/queries.go index 751b37f73..4416b71c4 100644 --- a/internal/issue/queries.go +++ b/internal/issue/queries.go @@ -92,7 +92,6 @@ func listIssues(ctx context.Context, teamSlug slug.Slug, page *pagination.Pagina } } - params.LegacyResourceName = legacyPostgresIssueName(params.ResourceName) ret, err := db(ctx).ListIssues(ctx, params) if err != nil { return nil, err @@ -148,11 +147,6 @@ func convert(issue *issuesql.Issue) (Issue, error) { switch IssueType(issue.IssueType) { case IssueTypePostgres: return &PostgresIssue{Base: base}, nil - case IssueTypePostgresBranch: - // Old rows can outlive an API rollout until the next checker refresh. - // Preserve their ID, but never expose a branch issue as the domain model. - base.ResourceType = ResourceTypePostgres - return &PostgresIssue{Base: base, LegacyPhysicalName: issue.ResourceName}, nil case IssueTypeOpenSearch: d, err := unmarshal[AivenIssueDetails](issue.IssueDetails) if err != nil { diff --git a/internal/issue/queries/issue.sql b/internal/issue/queries/issue.sql index 766ef04d2..ae91fc45f 100644 --- a/internal/issue/queries/issue.sql +++ b/internal/issue/queries/issue.sql @@ -47,10 +47,7 @@ WHERE ) AND ( sqlc.narg('issue_type')::TEXT IS NULL - OR CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END = sqlc.narg('issue_type')::TEXT + OR issue_type = sqlc.narg('issue_type')::TEXT ) AND ( sqlc.narg('severity')::severity_level IS NULL @@ -58,18 +55,11 @@ WHERE ) AND ( sqlc.narg('resource_type')::TEXT IS NULL - OR CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END = sqlc.narg('resource_type')::TEXT + OR resource_type = sqlc.narg('resource_type')::TEXT ) AND ( sqlc.narg('resource_name')::TEXT IS NULL OR resource_name = sqlc.narg('resource_name')::TEXT - OR ( - resource_type = 'POSTGRES_BRANCH' - AND resource_name = sqlc.narg('legacy_resource_name')::TEXT - ) ) ORDER BY CASE @@ -79,28 +69,16 @@ ORDER BY WHEN @order_by::TEXT = 'env:desc' THEN env END DESC, CASE - WHEN @order_by::TEXT = 'issue_type:asc' THEN CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END + WHEN @order_by::TEXT = 'issue_type:asc' THEN issue_type END ASC, CASE - WHEN @order_by::TEXT = 'issue_type:desc' THEN CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END + WHEN @order_by::TEXT = 'issue_type:desc' THEN issue_type END DESC, CASE - WHEN @order_by::TEXT = 'resource_type:asc' THEN CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END + WHEN @order_by::TEXT = 'resource_type:asc' THEN resource_type END ASC, CASE - WHEN @order_by::TEXT = 'resource_type:desc' THEN CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END + WHEN @order_by::TEXT = 'resource_type:desc' THEN resource_type END DESC, CASE WHEN @order_by::TEXT = 'resource_name:asc' THEN resource_name @@ -123,31 +101,6 @@ LIMIT ; -- name: FacetsForIssues :many --- Normalize before grouping, including zero-count facets. Keep ListIssues' stored --- row types intact so legacy physical names still reach the Postgres read adapter. -WITH - issue_rows AS ( - SELECT - team, - severity, - env, - resource_name, - ( - CASE - WHEN resource_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE resource_type - END - )::TEXT AS resource_type, - ( - CASE - WHEN issue_type = 'POSTGRES_BRANCH' THEN 'POSTGRES' - ELSE issue_type - END - )::TEXT AS issue_type, - resource_type = 'POSTGRES_BRANCH' AS legacy_postgres - FROM - issues - ) SELECT team, EXISTS ( @@ -183,14 +136,10 @@ SELECT AND ( sqlc.narg('filter_resource_name')::TEXT IS NULL OR resource_name = sqlc.narg('filter_resource_name')::TEXT - OR ( - legacy_postgres - AND resource_name = sqlc.narg('legacy_filter_resource_name')::TEXT - ) ) ) AS filtered_count FROM - issue_rows AS issues + issues WHERE ( @team::TEXT = '' @@ -207,10 +156,6 @@ WHERE AND ( sqlc.narg('scope_resource_name')::TEXT IS NULL OR resource_name = sqlc.narg('scope_resource_name')::TEXT - OR ( - legacy_postgres - AND resource_name = sqlc.narg('legacy_scope_resource_name')::TEXT - ) ) AND ( sqlc.narg('scope_env')::TEXT IS NULL diff --git a/internal/kubernetes/fake/fake.go b/internal/kubernetes/fake/fake.go index 2ffac2fd9..13ee97d52 100644 --- a/internal/kubernetes/fake/fake.go +++ b/internal/kubernetes/fake/fake.go @@ -194,8 +194,6 @@ func depluralized(s string) string { return "remoteunleashes" case "postgreses": return "postgres" - case "postgresbranchs": - return "postgresbranches" } return s @@ -221,7 +219,6 @@ func NewDynamicClient(scheme *runtime.Scheme) *dynfake.FakeDynamicClient { unleash_nais_io_v1.GroupVersion.WithResource("unleashes"): "UnleashList", unleash_nais_io_v1.GroupVersion.WithResource("remoteunleashes"): "RemoteUnleashList", mapperatorv1.GroupVersion.WithResource("postgres"): "PostgresList", - mapperatorv1.GroupVersion.WithResource("postgresbranches"): "PostgresBranchList", nais_io_v1.GroupVersion.WithResource("naisjobs"): "NaisjobList", nais_io_v1alpha1.GroupVersion.WithResource("tunnels"): "TunnelList", mapperatorv1.GroupVersion.WithResource("valkeys"): "ValkeyList", diff --git a/internal/kubernetes/fake/postgres_fixtures_test.go b/internal/kubernetes/fake/postgres_fixtures_test.go index 751bba8c4..1da5baf7c 100644 --- a/internal/kubernetes/fake/postgres_fixtures_test.go +++ b/internal/kubernetes/fake/postgres_fixtures_test.go @@ -8,24 +8,10 @@ import ( "github.com/nais/api/internal/kubernetes" "github.com/nais/api/internal/kubernetes/fake" nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" - "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" ) -func TestPostgresBranchKindResolver(t *testing.T) { - _, kinds, _, err := fake.Clients(nil)("dev") - if err != nil { - t.Fatal(err) - } - resolved, err := kinds.KindsFor(schema.GroupVersionResource{Group: "nais.io", Version: "v1", Resource: "postgresbranches"}) - if err != nil || len(resolved) != 1 || resolved[0].Kind != "PostgresBranch" { - guessed, _ := meta.UnsafeGuessKindToResource(schema.GroupVersion{Group: "nais.io", Version: "v1"}.WithKind("PostgresBranch")) - t.Fatalf("resolving PostgresBranch resource: %v, %v (guessed %s)", resolved, err, guessed.Resource) - } -} - func TestPostgresFixturesUseRegisteredV1Kinds(t *testing.T) { scheme, err := kubernetes.NewScheme() if err != nil { @@ -35,7 +21,8 @@ func TestPostgresFixturesUseRegisteredV1Kinds(t *testing.T) { // suites may intentionally describe the same resource. for _, path := range []string{ "../../../integration_tests/k8s_resources/create_postgres_access", - "../../../integration_tests/k8s_resources/postgres_branches", + "../../../integration_tests/k8s_resources/postgres_databases", + "../../../integration_tests/k8s_resources/postgres_relations", "../../../integration_tests/k8s_resources/postgres_workloads", "../../../integration_tests/k8s_resources/postgres_audit_log", "../../../integration_tests/k8s_resources/label_selectors", diff --git a/internal/kubernetes/watchers/postgres_contract_test.go b/internal/kubernetes/watchers/postgres_contract_test.go deleted file mode 100644 index 16e2dca12..000000000 --- a/internal/kubernetes/watchers/postgres_contract_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package watchers_test - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "net/url" - "sync/atomic" - "testing" - "time" - - "github.com/nais/api/internal/kubernetes" - "github.com/nais/api/internal/kubernetes/fake" - "github.com/nais/api/internal/kubernetes/watcher" - "github.com/nais/api/internal/kubernetes/watchers" - "github.com/nais/api/internal/persistence/postgres" - "github.com/nais/api/internal/slug" - v1 "github.com/nais/pgrator/pkg/api/v1" - logtest "github.com/sirupsen/logrus/hooks/test" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/watch" - dynamicfake "k8s.io/client-go/dynamic/fake" - k8stesting "k8s.io/client-go/testing" -) - -func TestPostgresContractsWithoutBranchAPI(t *testing.T) { - scheme, err := kubernetes.NewScheme() - if err != nil { - t.Fatal(err) - } - clusters, err := kubernetes.CreateClusterConfigMap("nav", []string{"dev"}, nil) - if err != nil { - t.Fatal(err) - } - log, _ := logtest.NewNullLogger() - mgr, err := watcher.NewManager(scheme, clusters, log, watcher.WithClientCreator(fake.Clients(nil))) - if err != nil { - t.Fatal(err) - } - t.Cleanup(mgr.Stop) - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - c := mgr.GetDynamicClients()["dev"].(*dynamicfake.FakeDynamicClient) - var branchCalls atomic.Int32 - c.PrependReactor("*", "postgresbranches", func(k8stesting.Action) (bool, runtime.Object, error) { - branchCalls.Add(1) - return true, nil, apierrors.NewNotFound(schema.GroupResource{Group: "nais.io", Resource: "postgresbranches"}, "") - }) - c.PrependWatchReactor("postgresbranches", func(k8stesting.Action) (bool, watch.Interface, error) { - branchCalls.Add(1) - return true, nil, apierrors.NewNotFound(schema.GroupResource{Group: "nais.io", Resource: "postgresbranches"}, "") - }) - clusterName := v1.CNPGClusterName(v1.PostgresPhysicalName("orders")) - pg := &unstructured.Unstructured{Object: map[string]any{"apiVersion": "nais.io/v1", "kind": "Postgres", "metadata": map[string]any{"name": "orders", "namespace": "team", "generation": int64(1)}, "spec": map[string]any{"majorVersion": "18"}, "status": map[string]any{"clusterName": clusterName, "reconcilePhase": "Completed", "observedGeneration": int64(1), "conditions": []any{map[string]any{"type": "cluster.postgresql.cnpg.io/ObservedState", "status": "True", "message": "Cluster is in phase: Cluster in healthy state"}}}}} - if _, err := c.Resource(v1.GroupVersion.WithResource("postgres")).Namespace("team").Create(ctx, pg, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - cnpg := &unstructured.Unstructured{Object: map[string]any{"apiVersion": "postgresql.cnpg.io/v1", "kind": "Cluster", "metadata": map[string]any{"name": clusterName, "namespace": "team"}, "status": map[string]any{"conditions": []any{map[string]any{"type": "Ready", "status": "True"}}}}} - if _, err := c.Resource(schema.GroupVersionResource{Group: "postgresql.cnpg.io", Version: "v1", Resource: "clusters"}).Namespace("team").Create(ctx, cnpg, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - registered := watchers.SetupWatchers(ctx, mgr, nil, false) - ready, cancelReady := context.WithTimeout(ctx, 10*time.Second) - defer cancelReady() - if !mgr.WaitForReady(ready) { - t.Fatal("watchers did not synchronize without branch API") - } - ctx = postgres.NewLoaderContext(ctx, registered.PostgresWatcher, "", "", "nav", mgr.GetDynamicClients()) - views := postgres.ListAllForTeam(ctx, "team", nil) - if len(views) != 1 || views[0].Name != "main" || views[0].State != postgres.PostgresBranchStateAvailable { - t.Fatalf("main facade = %+v", views) - } - if _, err := postgres.GetPostgresBranchByObjectName(ctx, "team", "dev", v1.PostgresPhysicalName("orders")); err != nil { - t.Fatal(err) - } - if parent, err := postgres.GetPostgresByPhysicalName(ctx, "team", "dev", v1.PostgresPhysicalName("orders")); err != nil || parent.Name != "orders" { - t.Fatalf("direct issue relation: %+v, %v", parent, err) - } - for _, scope := range []struct{ team, env string }{{"other-team", "dev"}, {"team", "prod"}} { - if _, err := postgres.GetPostgresByPhysicalName(ctx, slug.Slug(scope.team), scope.env, v1.PostgresPhysicalName("orders")); !errors.Is(err, &watcher.ErrorNotFound{}) { - t.Errorf("legacy issue lookup escaped scope %+v: %v", scope, err) - } - } - if selected, err := postgres.GetReadyPostgresBranch(ctx, "team", "dev", "orders", ""); err != nil || selected.State != postgres.PostgresBranchStateAvailable { - t.Fatalf("access target = %+v, %v", selected, err) - } - proxy := postgres.WithLogScope(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })) - parent, err := postgres.GetPostgres(ctx, "team", "dev", "orders") - if err != nil { - t.Fatal(err) - } - parameters := url.Values{"postgres": {parent.ID().String()}, "query": {`{service_name="orders"}`}} - response := httptest.NewRecorder() - proxy.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/loki/api/v1/query_range?"+parameters.Encode(), nil).WithContext(ctx)) - if response.Code != http.StatusNoContent { - t.Fatalf("log request failed: %d %s", response.Code, response.Body.String()) - } - if got := branchCalls.Load(); got != 0 { - t.Fatalf("used retired branch API %d times", got) - } -} diff --git a/internal/persistence/postgres/access_level_test.go b/internal/persistence/postgres/access_level_test.go index abf4ec0f2..79f9e066c 100644 --- a/internal/persistence/postgres/access_level_test.go +++ b/internal/persistence/postgres/access_level_test.go @@ -35,7 +35,7 @@ func TestPostgresAccessLevels(t *testing.T) { } expiresAt := time.Now().Add(time.Hour).Truncate(time.Second) resource := newPostgresAccessResource(CreatePostgresAccessInput{ - Postgres: "orders", Branch: "main", TeamSlug: slug.Slug("team-a"), AccessLevel: level, + Postgres: "orders", TeamSlug: slug.Slug("team-a"), AccessLevel: level, }, "user@example.com", "personal-access", expiresAt) wantSpec := map[string]any{ "postgres": "orders", diff --git a/internal/persistence/postgres/access_reference_test.go b/internal/persistence/postgres/access_reference_test.go index e5eb8dcf0..f7d3b333d 100644 --- a/internal/persistence/postgres/access_reference_test.go +++ b/internal/persistence/postgres/access_reference_test.go @@ -3,30 +3,19 @@ package postgres import ( "testing" "time" - - nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" ) -func TestPostgresAccessReadsBothReferenceShapes(t *testing.T) { - for _, direct := range []bool{false, true} { - resource := newPostgresAccessResource(CreatePostgresAccessInput{Postgres: "orders", Branch: "main", TeamSlug: "team", AccessLevel: PostgresAccessLevelRead}, "user@example.com", "existing-access", time.Now().Add(time.Hour)) - if direct { - spec := resource.Object["spec"].(map[string]any) - delete(spec, "postgresBranch") - spec["postgres"] = "orders" - } - access, err := toPostgresAccess(resource, "team", "dev") - if err != nil { - t.Fatal(err) - } - if access.PostgresBranchName != nais_io_v1.PostgresPhysicalName("orders") { - t.Error("legacy main relationship changed its physical identity") - } - if direct && access.PostgresName != "orders" { - t.Error("direct Postgres reference was lost") - } - if access.Username != "user@example.com" || access.AccessLevel != PostgresAccessLevelRead { - t.Error("access identity or privileges changed") - } +func TestPostgresAccessReference(t *testing.T) { + resource := newPostgresAccessResource(CreatePostgresAccessInput{Postgres: "orders", TeamSlug: "team", AccessLevel: PostgresAccessLevelRead}, "user@example.com", "existing-access", time.Now().Add(time.Hour)) + access, err := toPostgresAccess(resource, "team", "dev") + if err != nil { + t.Fatal(err) + } + if access.PostgresName != "orders" || access.Username != "user@example.com" || access.AccessLevel != PostgresAccessLevelRead { + t.Fatalf("access identity or privileges changed: %+v", access) + } + delete(resource.Object["spec"].(map[string]any), "postgres") + if _, err := toPostgresAccess(resource, "team", "dev"); err == nil { + t.Fatal("accepted access without a database reference") } } diff --git a/internal/persistence/postgres/access_selection_test.go b/internal/persistence/postgres/access_selection_test.go index 209d3af21..1cac6f2d6 100644 --- a/internal/persistence/postgres/access_selection_test.go +++ b/internal/persistence/postgres/access_selection_test.go @@ -8,7 +8,6 @@ import ( "github.com/nais/api/internal/kubernetes" "github.com/nais/api/internal/kubernetes/fake" "github.com/nais/api/internal/kubernetes/watcher" - nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" logrustest "github.com/sirupsen/logrus/hooks/test" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -18,19 +17,8 @@ import ( ) func TestAccessSelectionUsesFreshObservedParent(t *testing.T) { - for _, tc := range []struct { - name, requested, observed, explicit, want string - direct bool - wantError bool - }{ - {name: "omitted ignores stale active", observed: "recovered", direct: true, want: "main"}, - {name: "desired activation does not select target", requested: "main", observed: "recovered", direct: true, want: "main"}, - {name: "explicit main remains explicit", observed: "recovered", explicit: "main", direct: true, want: "main"}, - {name: "explicit retired branch is rejected", observed: "main", explicit: "recovered", direct: true, wantError: true}, - {name: "no observed direct status is unavailable", requested: "recovered", wantError: true}, - {name: "direct ownership uses virtual main", observed: "recovered", direct: true, want: "main"}, - } { - t.Run(tc.name, func(t *testing.T) { + for _, available := range []bool{false, true} { + t.Run(map[bool]string{false: "provisioning", true: "available"}[available], func(t *testing.T) { scheme, err := kubernetes.NewScheme() if err != nil { t.Fatal(err) @@ -49,80 +37,48 @@ func TestAccessSelectionUsesFreshObservedParent(t *testing.T) { t.Cleanup(cancel) client := mgr.GetDynamicClients()["dev"] pgClient := client.Resource(postgresGVR()).Namespace("team") - // Synchronize a different parent first. The access decision must use - // the fresh API-server value written below, not this cached selection. - parent := physicalPostgresObject("orders", map[string]any{"activeBranch": "main"}) - parent.Object["spec"].(map[string]any)["activeBranch"] = tc.requested - parent, err = pgClient.Create(ctx, parent, metav1.CreateOptions{}) + parent, err := pgClient.Create(ctx, physicalPostgresObject("orders", nil), metav1.CreateOptions{}) if err != nil { t.Fatal(err) } - for _, name := range []string{"main", "recovered"} { - branch := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresBranchObjectName("orders", name), "namespace": "team", "generation": int64(2)}, - "spec": map[string]any{"postgres": "orders", "branchName": name}, - "status": healthyPhysicalStatus("unused"), - }} - if _, err := client.Resource(nais_io_v1.GroupVersion.WithResource("postgresbranches")).Namespace("team").Create(ctx, branch, metav1.CreateOptions{}); err != nil { + postgreses := NewPostgresWatcher(ctx, mgr) + ready, cancelReady := context.WithTimeout(ctx, 5*time.Second) + defer cancelReady() + if !mgr.WaitForReady(ready) { + t.Fatal("watchers did not synchronize") + } + if available { + parent.Object["status"] = healthyPhysicalStatus("pg-observed") + if _, err := pgClient.UpdateStatus(ctx, parent, metav1.UpdateOptions{}); err != nil { t.Fatal(err) } cluster := &unstructured.Unstructured{Object: map[string]any{ "apiVersion": "postgresql.cnpg.io/v1", "kind": "Cluster", - "metadata": map[string]any{"name": nais_io_v1.CNPGClusterName(branch.GetName()), "namespace": "team"}, + "metadata": map[string]any{"name": "pg-observed", "namespace": "team"}, "status": map[string]any{"conditions": []any{map[string]any{"type": "Ready", "status": "True"}}}, }} if _, err := client.Resource(cnpgClusterGVR).Namespace("team").Create(ctx, cluster, metav1.CreateOptions{}); err != nil { t.Fatal(err) } } - postgreses := NewPostgresWatcher(ctx, mgr) - ready, cancelReady := context.WithTimeout(ctx, 5*time.Second) - defer cancelReady() - if !mgr.WaitForReady(ready) { - t.Fatal("watchers did not synchronize") - } - status := map[string]any{} - if tc.observed != "" { - status["activeBranch"] = tc.observed - } - if tc.direct { - status = healthyPhysicalStatus(nais_io_v1.CNPGClusterName(nais_io_v1.PostgresPhysicalName("orders"))) - status["activeBranch"] = tc.observed - } - parent.Object["status"] = status - if _, err := pgClient.UpdateStatus(ctx, parent, metav1.UpdateOptions{}); err != nil { - t.Fatal(err) - } ctx = NewLoaderContext(ctx, postgreses, "", "", "nav", mgr.GetDynamicClients()) parentGets := 0 client.(*dynamicfake.FakeDynamicClient).PrependReactor("get", "postgres", func(k8stesting.Action) (bool, runtime.Object, error) { parentGets++ return false, nil, nil }) - input := CreatePostgresAccessInput{Postgres: "orders", Branch: tc.explicit, TeamSlug: "team", EnvironmentName: "dev", AccessLevel: PostgresAccessLevelRead, Reason: "Investigating access selection"} + input := CreatePostgresAccessInput{Postgres: "orders", TeamSlug: "team", EnvironmentName: "dev", AccessLevel: PostgresAccessLevelRead, Reason: "Investigating access selection"} err = input.Validate(ctx) - if tc.wantError { - if err == nil { - t.Fatal("accepted retired or unready target") - } - return - } - if err != nil { - t.Fatal(err) + if (err == nil) != available { + t.Fatalf("available=%t: validation = %v", available, err) } if parentGets != 1 { - t.Fatalf("access selection used %d fresh parent reads, want exactly one", parentGets) - } - if input.Branch != tc.want { - t.Fatalf("selected %q, want %q", input.Branch, tc.want) + t.Fatalf("access selection used %d parent reads, want 1", parentGets) } - // The resolved choice is also the immutable creation identity; do not - // resolve it again or replace an explicit request during creation. resource := newPostgresAccessResource(input, "user@example.com", "access", time.Now().Add(time.Hour)) got, _, err := unstructured.NestedString(resource.Object, "spec", "postgres") if err != nil || got != "orders" { - t.Fatalf("created access target = %q, error = %v", got, err) + t.Fatalf("access target = %q, %v", got, err) } }) } diff --git a/internal/persistence/postgres/active_branch_test.go b/internal/persistence/postgres/active_branch_test.go deleted file mode 100644 index 2bbd6524b..000000000 --- a/internal/persistence/postgres/active_branch_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package postgres - -import ( - "errors" - "testing" - - "github.com/nais/api/internal/kubernetes/watcher" -) - -func TestImplicitActiveBranchNormalizesStaleMetadataWithoutCluster(t *testing.T) { - for _, observed := range []string{"main", "restored"} { - t.Run(observed, func(t *testing.T) { - pg, err := toPostgres(physicalPostgresObject("orders", map[string]any{"activeBranch": observed}), "dev") - if err != nil { - t.Fatal(err) - } - if pg.ActiveBranch == nil || *pg.ActiveBranch != "main" { - t.Fatalf("implicit active branch = %v, want main", pg.ActiveBranch) - } - view, err := BranchForPostgres(t.Context(), pg, *pg.ActiveBranch) - if err != nil || view.Name != "main" || view.State != PostgresBranchStateProgressing { - t.Fatalf("provisioning main = %+v, %v", view, err) - } - if _, err := BranchForPostgres(t.Context(), pg, "restored"); !errors.Is(err, &watcher.ErrorNotFound{}) { - t.Fatalf("explicit retired lookup must not fall back: %v", err) - } - }) - } -} diff --git a/internal/persistence/postgres/activitylog.go b/internal/persistence/postgres/activitylog.go index fe4336225..97ee83081 100644 --- a/internal/persistence/postgres/activitylog.go +++ b/internal/persistence/postgres/activitylog.go @@ -12,9 +12,6 @@ const ( activityLogEntryActionGrantAccess activitylog.ActivityLogEntryAction = "GRANT_ACCESS" activityLogEntryActionCreatePersonalAccess activitylog.ActivityLogEntryAction = "CREATE_PERSONAL_ACCESS" activityLogEntryActionGetPersonalAccessConnection activitylog.ActivityLogEntryAction = "GET_PERSONAL_ACCESS_CONNECTION" - activityLogEntryActionBranchCreated activitylog.ActivityLogEntryAction = "BRANCH_CREATED" - activityLogEntryActionBranchActivated activitylog.ActivityLogEntryAction = "BRANCH_ACTIVATED" - activityLogEntryActionBranchDeleted activitylog.ActivityLogEntryAction = "BRANCH_DELETED" ActivityLogEntryResourceTypePostgres activitylog.ActivityLogEntryResourceType = "POSTGRES" ) @@ -32,7 +29,7 @@ func init() { "POSTGRES_PERSONAL_ACCESS_CREATED", activityLogEntryActionCreatePersonalAccess, ActivityLogEntryResourceTypePostgres, - "Triggered when personal access to a Postgres branch is requested.", + "Triggered when personal access to Postgres is requested.", ) activitylog.RegisterActivityType( "POSTGRES_PERSONAL_ACCESS_CONNECTION", @@ -56,7 +53,7 @@ func init() { "POSTGRES_DELETED", activitylog.ActivityLogEntryActionDeleted, ActivityLogEntryResourceTypePostgres, - "Triggered when a Postgres branch is deleted (legacy event without a branch name).", + "Triggered when a Postgres is deleted.", ) activitylog.RegisterActivityType( "POSTGRES_DELETION_REQUESTED", @@ -64,24 +61,6 @@ func init() { ActivityLogEntryResourceTypePostgres, "Triggered when deletion of a Postgres instance is requested; cleanup is pending.", ) - activitylog.RegisterActivityType( - "POSTGRES_BRANCH_CREATED", - activityLogEntryActionBranchCreated, - ActivityLogEntryResourceTypePostgres, - "Triggered when a Postgres branch is created.", - ) - activitylog.RegisterActivityType( - "POSTGRES_BRANCH_ACTIVATED", - activityLogEntryActionBranchActivated, - ActivityLogEntryResourceTypePostgres, - "Triggered when a Postgres branch is activated.", - ) - activitylog.RegisterActivityType( - "POSTGRES_BRANCH_DELETED", - activityLogEntryActionBranchDeleted, - ActivityLogEntryResourceTypePostgres, - "Triggered when a Postgres branch is deleted.", - ) } func transformPostgresActivityLogEntry(entry activitylog.GenericActivityLogEntry) (activitylog.ActivityLogEntry, error) { @@ -111,7 +90,7 @@ func transformPostgresActivityLogEntry(entry activitylog.GenericActivityLogEntry }, nil case activitylog.ActivityLogEntryActionDeleted: return PostgresDeletedActivityLogEntry{ - GenericActivityLogEntry: entry.WithMessage("Deleted Postgres branch (name unavailable)"), + GenericActivityLogEntry: entry.WithMessage("Deleted Postgres"), }, nil case activityLogEntryActionDeletionRequested: return PostgresDeletedActivityLogEntry{ @@ -149,54 +128,11 @@ func transformPostgresActivityLogEntry(entry activitylog.GenericActivityLogEntry return PostgresPersonalAccessConnectionActivityLogEntry{ GenericActivityLogEntry: entry.WithMessage("Retrieved personal Postgres connection materials"), }, nil - case activityLogEntryActionBranchCreated, activityLogEntryActionBranchActivated, activityLogEntryActionBranchDeleted: - data, err := activitylog.UnmarshalData[PostgresBranchActivityLogEntryData](entry) - if err != nil { - return nil, fmt.Errorf("transforming postgres branch activity log entry data: %w", err) - } - switch entry.Action { - case activityLogEntryActionBranchCreated: - return PostgresBranchCreatedActivityLogEntry{ - GenericActivityLogEntry: entry.WithMessage(fmt.Sprintf("Postgres branch created: %s", data.Branch)), - Data: data, - }, nil - case activityLogEntryActionBranchActivated: - return PostgresBranchActivatedActivityLogEntry{ - GenericActivityLogEntry: entry.WithMessage(fmt.Sprintf("Postgres branch activated: %s", data.Branch)), - Data: data, - }, nil - default: - return PostgresBranchDeletedActivityLogEntry{ - GenericActivityLogEntry: entry.WithMessage(fmt.Sprintf("Postgres branch deleted: %s", data.Branch)), - Data: data, - }, nil - } default: return nil, fmt.Errorf("unsupported postgres activity log entry action: %q", entry.Action) } } -type PostgresBranchCreatedActivityLogEntry struct { - activitylog.GenericActivityLogEntry - Data *PostgresBranchActivityLogEntryData `json:"data"` -} - -type PostgresBranchActivatedActivityLogEntry struct { - activitylog.GenericActivityLogEntry - Data *PostgresBranchActivityLogEntryData `json:"data"` -} - -type PostgresBranchDeletedActivityLogEntry struct { - activitylog.GenericActivityLogEntry - Data *PostgresBranchActivityLogEntryData `json:"data"` -} - -type PostgresBranchActivityLogEntryData struct { - Branch string `json:"branch"` - SourceBranch *string `json:"sourceBranch,omitempty"` - TargetTime *time.Time `json:"targetTime,omitempty"` -} - type PostgresDeletedActivityLogEntry struct { activitylog.GenericActivityLogEntry } diff --git a/internal/persistence/postgres/configuration_test.go b/internal/persistence/postgres/configuration_test.go index 31a479bea..e82c23e8b 100644 --- a/internal/persistence/postgres/configuration_test.go +++ b/internal/persistence/postgres/configuration_test.go @@ -16,7 +16,7 @@ import ( "k8s.io/apimachinery/pkg/util/wait" ) -func TestPostgresBranchConfigurationFromStatus(t *testing.T) { +func TestPostgresConfigurationFromStatus(t *testing.T) { for _, tt := range []struct { name string status map[string]any @@ -55,22 +55,18 @@ func TestPostgresBranchConfigurationFromStatus(t *testing.T) { }, } { t.Run(tt.name, func(t *testing.T) { - obj := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresBranchObjectName("orders", "main"), "namespace": "team"}, - "spec": map[string]any{"postgres": "orders", "branchName": "main"}, - }} if tt.status != nil { - obj.Object["status"] = tt.status + tt.status["clusterName"] = "pg-orders" } - branch, err := toPostgresBranch(obj, "dev") + obj := physicalPostgresObject("orders", tt.status) + pg, err := toPostgres(obj, "dev") if (err != nil) != tt.wantErr { - t.Fatalf("toPostgresBranch error = %v, want error %t", err, tt.wantErr) + t.Fatalf("toPostgres error = %v, want error %t", err, tt.wantErr) } if tt.wantErr { return } - if diff := cmp.Diff(tt.want, branch.Configuration); diff != "" { + if diff := cmp.Diff(tt.want, pg.configuration); diff != "" { t.Errorf("configuration mismatch (-want +got):\n%s", diff) } }) @@ -107,7 +103,7 @@ func TestPostgresWatcherConfigurationUpdates(t *testing.T) { ready, cancelReady := context.WithTimeout(ctx, 5*time.Second) defer cancelReady() if !mgr.WaitForReady(ready) { - t.Fatal("PostgresBranch watcher did not synchronize") + t.Fatal("Postgres watcher did not synchronize") } for _, tt := range []struct { parameters map[string]any @@ -126,8 +122,8 @@ func TestPostgresWatcherConfigurationUpdates(t *testing.T) { t.Fatal(err) } if err := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - branch, err := w.Get("dev", "team", obj.GetName()) - return err == nil && cmp.Equal(tt.want, branch.configuration), err + pg, err := w.Get("dev", "team", obj.GetName()) + return err == nil && cmp.Equal(tt.want, pg.configuration), err }); err != nil { t.Fatalf("watcher did not observe configuration %#v: %v", tt.want, err) } diff --git a/internal/persistence/postgres/delete_postgres_test.go b/internal/persistence/postgres/delete_postgres_test.go index 1b43d595f..1e367d8a4 100644 --- a/internal/persistence/postgres/delete_postgres_test.go +++ b/internal/persistence/postgres/delete_postgres_test.go @@ -33,7 +33,7 @@ func TestPostgresDeletionActivityMessages(t *testing.T) { action activitylog.ActivityLogEntryAction want string }{ - {"historical branch deletion", activitylog.ActivityLogEntryActionDeleted, "Deleted Postgres branch (name unavailable)"}, + {"Postgres deletion", activitylog.ActivityLogEntryActionDeleted, "Deleted Postgres"}, {"whole Postgres deletion request", activityLogEntryActionDeletionRequested, "Requested deletion of Postgres; cleanup is pending"}, } { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/persistence/postgres/delete_test.go b/internal/persistence/postgres/delete_test.go index 26d16ad65..68a0deefd 100644 --- a/internal/persistence/postgres/delete_test.go +++ b/internal/persistence/postgres/delete_test.go @@ -2,7 +2,6 @@ package postgres import ( "context" - "errors" "os" "strings" "testing" @@ -52,7 +51,7 @@ func TestWorkloadUsesMultiplePostgresResources(t *testing.T) { t.Fatalf("application uses not loaded: %+v", apps) } instances, err := ListPostgresForWorkload(ctx, team, "dev", apps[0].Spec.Uses.Postgres) - if err != nil || len(instances) != 3 || instances[0].Name != "archive" || instances[0].ActiveBranch != nil || instances[1].Name != "orders" || instances[2].Name != "reports" { + if err != nil || len(instances) != 3 || instances[0].Name != "archive" || instances[1].Name != "orders" || instances[2].Name != "reports" { t.Fatalf("referenced Postgres = %+v, error = %v", instances, err) } jobs := job.ListAllForTeamInEnvironment(ctx, team, "dev") @@ -60,50 +59,36 @@ func TestWorkloadUsesMultiplePostgresResources(t *testing.T) { t.Fatalf("job uses not loaded: %+v", jobs) } instances, err = ListPostgresForWorkload(ctx, team, "dev", jobs[0].Spec.Uses.Postgres) - if err != nil || len(instances) != 3 || instances[0].Name != "archive" || instances[0].ActiveBranch != nil || instances[1].Name != "orders" || instances[2].Name != "reports" { + if err != nil || len(instances) != 3 || instances[0].Name != "archive" || instances[1].Name != "orders" || instances[2].Name != "reports" { t.Fatalf("job referenced Postgres = %+v, error = %v", instances, err) } page, err := pagination.ParsePage(new(3), nil, nil, nil) if err != nil { t.Fatal(err) } - for _, test := range []struct { - name string - uses []liberatorv1.PostgresUse - branch map[string]string - }{ - {name: "application", uses: apps[0].Spec.Uses.Postgres, branch: map[string]string{"archive": "main", "orders": "main", "reports": "main"}}, - {name: "job", uses: jobs[0].Spec.Uses.Postgres, branch: map[string]string{"archive": "main", "orders": "main", "reports": "main"}}, - } { - usages, totalCount, err := WorkloadPostgresesForWorkload(ctx, team, "dev", test.uses, page) - if err != nil { - t.Fatalf("%s Postgres uses: %v", test.name, err) - } - if totalCount != len(test.branch) || len(usages) != len(test.branch) { - t.Fatalf("%s Postgres uses = (%d, %d), want %d", test.name, len(usages), totalCount, len(test.branch)) + for _, uses := range [][]liberatorv1.PostgresUse{apps[0].Spec.Uses.Postgres, jobs[0].Spec.Uses.Postgres} { + usages, totalCount, err := WorkloadPostgresesForWorkload(ctx, team, "dev", uses, page) + if err != nil || totalCount != 3 || len(usages) != 3 { + t.Fatalf("Postgres uses = %+v, %d, %v", usages, totalCount, err) } - for _, usage := range usages { - if want := test.branch[usage.Postgres.Name]; usage.Branch.Name != want { - t.Errorf("%s Postgres %q branch = %q, want %q", test.name, usage.Postgres.Name, usage.Branch.Name, want) + for i, name := range []string{"archive", "orders", "reports"} { + if usages[i].Postgres.Name != name { + t.Errorf("Postgres use %d = %q, want %q", i, usages[i].Postgres.Name, name) } - delete(test.branch, usage.Postgres.Name) - } - if len(test.branch) != 0 { - t.Errorf("%s Postgres uses missing references: %v", test.name, test.branch) } } - usesWithMissingOffPageBranch := append([]liberatorv1.PostgresUse(nil), apps[0].Spec.Uses.Postgres...) - for index := range usesWithMissingOffPageBranch { - if usesWithMissingOffPageBranch[index].Name == "reports" { - usesWithMissingOffPageBranch[index].Branch = "missing" + usesWithMissingOffPage := append([]liberatorv1.PostgresUse(nil), apps[0].Spec.Uses.Postgres...) + for index := range usesWithMissingOffPage { + if usesWithMissingOffPage[index].Name == "reports" { + usesWithMissingOffPage[index].Name = "missing" } } firstPage, err := pagination.ParsePage(new(1), nil, nil, nil) if err != nil { t.Fatal(err) } - pageUses, totalCount, err := WorkloadPostgresesForWorkload(ctx, team, "dev", usesWithMissingOffPageBranch, firstPage) + pageUses, totalCount, err := WorkloadPostgresesForWorkload(ctx, team, "dev", usesWithMissingOffPage, firstPage) if err != nil || totalCount != 3 || len(pageUses) != 1 || pageUses[0].Postgres.Name != "archive" { t.Fatalf("first Postgres use page = (%+v, %d), error = %v", pageUses, totalCount, err) } @@ -111,17 +96,10 @@ func TestWorkloadUsesMultiplePostgresResources(t *testing.T) { if err != nil { t.Fatal(err) } - if _, _, err := WorkloadPostgresesForWorkload(ctx, team, "dev", usesWithMissingOffPageBranch, reportsPage); err == nil { - t.Fatal("expected an error for a missing branch on the requested page") + if _, _, err := WorkloadPostgresesForWorkload(ctx, team, "dev", usesWithMissingOffPage, reportsPage); err == nil { + t.Fatal("expected an error for a missing Postgres on the requested page") } - for _, entry := range []struct{ postgres, branch string }{{"orders", "main"}, {"reports", "main"}} { - workloads := WorkloadsForInstance(ctx, team, "dev", entry.postgres, entry.branch) - wantCount := 2 - if len(workloads) != wantCount || workloads[0].GetName() != "consumer" || wantCount == 2 && workloads[1].GetName() != "scheduled-reader" { - t.Errorf("workloads for %q = %+v", entry.branch, workloads) - } - } for _, name := range []string{"orders", "reports", "archive"} { pg, err := GetPostgres(ctx, team, "dev", name) if err != nil { @@ -150,7 +128,7 @@ func TestWorkloadUsesMultiplePostgresResources(t *testing.T) { } } -func TestReadyPostgresBranchUsesConcreteName(t *testing.T) { +func TestReadyPostgresUsesObservedCluster(t *testing.T) { scheme, err := kubernetes.NewScheme() if err != nil { t.Fatal(err) @@ -170,36 +148,20 @@ func TestReadyPostgresBranchUsesConcreteName(t *testing.T) { wait, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() if !mgr.WaitForReady(wait) { - t.Fatal("PostgresBranch watcher did not synchronize") + t.Fatal("Postgres watcher did not synchronize") } ctx = NewLoaderContext(ctx, postgresWatcher, "", "", "nav", mgr.GetDynamicClients()) team := slug.Slug("someteamname") - for _, name := range []string{"main"} { - instance, err := GetReadyPostgresBranch(ctx, team, "dev", "foobar", name) - if err != nil || instance.State != PostgresBranchStateAvailable || instance.Name != name || instance.PostgresName != "foobar" { - t.Errorf("%s: got instance %+v, error %v", name, instance, err) - } - } - instance, err := GetReadyPostgresBranch(ctx, team, "dev", "progressing", "main") - if err != nil || instance.State == PostgresBranchStateAvailable { - t.Errorf("progressing instance = %+v, error %v", instance, err) - } - _, err = GetReadyPostgresBranch(ctx, team, "dev", "foobar", "missing") - if !errors.Is(err, &watcher.ErrorNotFound{}) || strings.Contains(err.Error(), "foobar-missing-") { - t.Errorf("missing instance error = %v; want local branch name only", err) + state, err := readyPostgresState(ctx, team, "dev", "foobar") + if err != nil || state != PostgresStateAvailable { + t.Errorf("ready database = %q, %v", state, err) } - _, err = GetPostgresBranch(ctx, team, "dev", "progressing", "recovered") - if !errors.Is(err, &watcher.ErrorNotFound{}) { - t.Errorf("branch in wrong Postgres error = %v", err) - } - pg, err := GetPostgres(ctx, team, "dev", "foobar") - if err != nil { - t.Fatal(err) + state, err = readyPostgresState(ctx, team, "dev", "progressing") + if err != nil || state == PostgresStateAvailable { + t.Errorf("provisioning database = %q, %v", state, err) } - branches := ListForPostgres(ctx, pg, nil, nil) - nodes := branches.Nodes() - if len(nodes) != 1 || nodes[0].Name != "main" { - t.Errorf("Postgres branches = %+v", nodes) + if _, err := readyPostgresState(ctx, team, "dev", "missing"); err == nil { + t.Error("accepted missing database") } } @@ -222,17 +184,17 @@ func TestCreatePostgresAccessRejectsMissingInstance(t *testing.T) { wait, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() if !mgr.WaitForReady(wait) { - t.Fatal("PostgresBranch watcher did not synchronize") + t.Fatal("Postgres watcher did not synchronize") } postgresWatcher := NewPostgresWatcher(ctx, mgr) ctx = NewLoaderContext(ctx, postgresWatcher, "", "", "nav", mgr.GetDynamicClients()) input := CreatePostgresAccessInput{ - Postgres: "foobar", Branch: "missing", TeamSlug: slug.Slug("myteam"), + Postgres: "foobar", TeamSlug: slug.Slug("myteam"), EnvironmentName: "dev", AccessLevel: PostgresAccessLevelRead, Reason: "Investigating missing instance", } err = input.Validate(ctx) - if err == nil || !strings.Contains(err.Error(), `Could not find PostgresBranch "missing"`) { + if err == nil || !strings.Contains(err.Error(), `Could not find Postgres "foobar"`) { t.Errorf("validation error = %v, want named missing instance", err) } } diff --git a/internal/persistence/postgres/facets.go b/internal/persistence/postgres/facets.go index 2c8687330..9c0f54ef0 100644 --- a/internal/persistence/postgres/facets.go +++ b/internal/persistence/postgres/facets.go @@ -2,8 +2,6 @@ package postgres import ( "context" - "slices" - "strings" "github.com/nais/api/internal/graph/model" ) @@ -13,53 +11,3 @@ func (f *PostgresFacets) Labels(ctx context.Context) []model.LabelFacetItem { return pg.Labels }) } - -// Filtered returns the filtered Postgres instances, computing it exactly once per request. -func (f *PostgresBranchFacets) Filtered(ctx context.Context) []*PostgresBranch { - f.filteredOnce.Do(func() { - f.filteredInstances = SortFilterPostgresBranch.Filter(ctx, f.AllInstances, f.Filter) - }) - return f.filteredInstances -} - -// Environments computes environments facets for a Postgres query. -func (f *PostgresBranchFacets) Environments(ctx context.Context) []model.StringFacetItem { - filtered := f.Filtered(ctx) - return model.ComputeEnvironmentsFacet(f.AllInstances, filtered, func(inst *PostgresBranch) string { - return inst.EnvironmentName - }) -} - -// States computes states facets for a Postgres query. -func (f *PostgresBranchFacets) States(ctx context.Context) []PostgresBranchStateFacetItem { - stateCounts := map[PostgresBranchState]int{} - for _, inst := range f.AllInstances { - stateCounts[inst.State] = 0 - } - - filtered := f.Filtered(ctx) - for _, inst := range filtered { - stateCounts[inst.State]++ - } - - states := make([]PostgresBranchStateFacetItem, 0, len(stateCounts)) - for state, count := range stateCounts { - states = append(states, PostgresBranchStateFacetItem{ - State: state, - Count: count, - }) - } - slices.SortFunc(states, func(a, b PostgresBranchStateFacetItem) int { - return strings.Compare(a.State.String(), b.State.String()) - }) - - return states -} - -// Labels computes labels facets for a Postgres query. -func (f *PostgresBranchFacets) Labels(ctx context.Context) []model.LabelFacetItem { - filtered := f.Filtered(ctx) - return model.ComputeLabelsFacet(f.AllInstances, filtered, func(inst *PostgresBranch) []*model.ResourceLabel { - return inst.Labels - }) -} diff --git a/internal/persistence/postgres/facets_test.go b/internal/persistence/postgres/facets_test.go index 5db7cd727..1280ee443 100644 --- a/internal/persistence/postgres/facets_test.go +++ b/internal/persistence/postgres/facets_test.go @@ -1,38 +1,30 @@ package postgres import ( - "context" - "reflect" "testing" + "github.com/google/go-cmp/cmp" "github.com/nais/api/internal/graph/model" ) -func TestComputeFacets(t *testing.T) { - all := []*PostgresBranch{ - {Name: "first", EnvironmentName: "dev", State: PostgresBranchStateAvailable}, - {Name: "second", EnvironmentName: "dev", State: PostgresBranchStateProgressing}, - {Name: "third", EnvironmentName: "prod", State: PostgresBranchStateDegraded}, +func TestPostgresFacets(t *testing.T) { + all := []*Postgres{ + {Name: "first", EnvironmentName: "dev", Labels: []*model.ResourceLabel{{Key: "purpose", Value: "test"}}}, + {Name: "second", EnvironmentName: "prod", Labels: []*model.ResourceLabel{{Key: "purpose", Value: "live"}}}, } - tests := []struct { - name string - filter *PostgresBranchFilter - wantEnvironments []model.StringFacetItem - wantStates []PostgresBranchStateFacetItem - }{ - {"all", nil, []model.StringFacetItem{{Value: "dev", Count: 2}, {Value: "prod", Count: 1}}, []PostgresBranchStateFacetItem{{State: PostgresBranchStateAvailable, Count: 1}, {State: PostgresBranchStateDegraded, Count: 1}, {State: PostgresBranchStateProgressing, Count: 1}}}, - {"filter by environment", &PostgresBranchFilter{Environments: []string{"dev"}}, []model.StringFacetItem{{Value: "dev", Count: 2}, {Value: "prod", Count: 0}}, []PostgresBranchStateFacetItem{{State: PostgresBranchStateAvailable, Count: 1}, {State: PostgresBranchStateDegraded, Count: 0}, {State: PostgresBranchStateProgressing, Count: 1}}}, - {"filter by state", &PostgresBranchFilter{States: []PostgresBranchState{PostgresBranchStateAvailable}}, []model.StringFacetItem{{Value: "dev", Count: 1}, {Value: "prod", Count: 0}}, []PostgresBranchStateFacetItem{{State: PostgresBranchStateAvailable, Count: 1}, {State: PostgresBranchStateDegraded, Count: 0}, {State: PostgresBranchStateProgressing, Count: 0}}}, + filter := &TeamPostgresFilter{Environments: []string{"dev"}} + var filtered []*Postgres + for _, pg := range all { + if filter.Matches(pg) { + filtered = append(filtered, pg) + } } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - f := &PostgresBranchFacets{AllInstances: all, Filter: tt.filter} - if got := f.Environments(context.Background()); !reflect.DeepEqual(got, tt.wantEnvironments) { - t.Errorf("environments=%v want %v", got, tt.wantEnvironments) - } - if got := f.States(context.Background()); !reflect.DeepEqual(got, tt.wantStates) { - t.Errorf("states=%v want %v", got, tt.wantStates) - } - }) + if len(filtered) != 1 || filtered[0] != all[0] { + t.Fatalf("filtered = %+v", filtered) + } + facets := (&PostgresFacets{AllInstances: all, FilteredInstances: filtered}).Labels(t.Context()) + want := model.ComputeLabelsFacet(all, filtered, func(pg *Postgres) []*model.ResourceLabel { return pg.Labels }) + if diff := cmp.Diff(want, facets); diff != "" { + t.Errorf("facets (-want +got):\n%s", diff) } } diff --git a/internal/persistence/postgres/logs_test.go b/internal/persistence/postgres/logs_test.go index 995aac9cf..3ffb21c0c 100644 --- a/internal/persistence/postgres/logs_test.go +++ b/internal/persistence/postgres/logs_test.go @@ -16,7 +16,6 @@ import ( "github.com/nais/api/internal/kubernetes/fake" "github.com/nais/api/internal/kubernetes/watcher" "github.com/nais/api/internal/loki" - nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" logrustest "github.com/sirupsen/logrus/hooks/test" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -222,20 +221,6 @@ func postgresLogTestContext(t *testing.T) context.Context { t.Fatal(err) } } - for _, database := range []string{"legacy", "incomplete"} { - cluster := "pg-stale" - if database == "legacy" { - cluster = "pg-legacy-main-a4f04c0c" - } - branch := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresPhysicalName(database), "namespace": "team", "generation": int64(2)}, - "spec": map[string]any{"postgres": database, "branchName": "main"}, "status": healthyPhysicalStatus(cluster), - }} - if _, err := client.Resource(nais_io_v1.GroupVersion.WithResource("postgresbranches")).Namespace("team").Create(ctx, branch, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } - } postgreses := NewPostgresWatcher(ctx, mgr) ready, cancelReady := context.WithTimeout(ctx, 5*time.Second) defer cancelReady() diff --git a/internal/persistence/postgres/models.go b/internal/persistence/postgres/models.go index e2ca10c1e..7dfa52ec2 100644 --- a/internal/persistence/postgres/models.go +++ b/internal/persistence/postgres/models.go @@ -9,7 +9,6 @@ import ( "slices" "strconv" "strings" - "sync" "time" "github.com/nais/api/internal/graph/ident" @@ -29,42 +28,6 @@ import ( "k8s.io/apimachinery/pkg/util/validation" ) -type PostgresBranchEdge = pagination.Edge[*PostgresBranch] - -type PostgresBranchFilter struct { - Name string `json:"name"` - Environments []string `json:"environments"` - States []PostgresBranchState `json:"states"` - Labels model.LabelFilters `json:"labels,omitempty"` -} - -type PostgresBranchConnection = pagination.FacetableConnection[*PostgresBranch, *PostgresBranchFilter] - -type PostgresBranchFacets struct { - AllInstances []*PostgresBranch - Filter *PostgresBranchFilter - filteredOnce sync.Once - filteredInstances []*PostgresBranch -} - -type PostgresBranchStateFacetItem struct { - State PostgresBranchState `json:"state"` - Count int `json:"count"` -} - -// PostgresBranch represents an independently running database instance. -type PostgresBranch struct { - Name string `json:"name"` - CreatedAt time.Time `json:"createdAt"` - EnvironmentName string `json:"-"` - TeamSlug slug.Slug `json:"-"` - PostgresName string `json:"postgres"` - State PostgresBranchState `json:"state"` - Labels []*model.ResourceLabel `json:"labels"` - Configuration *PostgresConfiguration `json:"configuration,omitempty"` - ClusterName string `json:"-"` -} - type TeamPostgresFilter struct { Environments []string `json:"environments"` Labels model.LabelFilters `json:"labels,omitempty"` @@ -80,9 +43,8 @@ type ( ) type PostgresWorkload struct { - Workload workload.Workload `json:"workload"` - Postgres *Postgres `json:"postgres"` - BranchName string `json:"-"` + Workload workload.Workload `json:"workload"` + Postgres *Postgres `json:"postgres"` } type PostgresUserRole string @@ -96,7 +58,6 @@ const ( type WorkloadPostgres struct { EnvPrefix *string `json:"envPrefix,omitempty"` Role PostgresUserRole `json:"role"` - Branch *PostgresBranch `json:"branch"` Postgres *Postgres `json:"postgres"` } @@ -105,27 +66,22 @@ type PostgresFacets struct { FilteredInstances []*Postgres } -// Postgres selects the instance that workloads use. +// Postgres represents a database used by workloads. type Postgres struct { - Name string `json:"name"` - EnvironmentName string `json:"-"` - TeamSlug slug.Slug `json:"-"` - ActiveBranch *string `json:"activeBranch,omitempty"` - DesiredActiveBranch *string `json:"desiredActiveBranch,omitempty"` - MajorVersion string `json:"majorVersion"` - Extensions []string `json:"extensions"` - HighAvailability bool `json:"highAvailability"` - Resources PostgresResources `json:"resources"` - Labels []*model.ResourceLabel `json:"labels"` - CreatedAt time.Time `json:"createdAt"` - Recovery *PostgresRecovery `json:"recovery,omitempty"` - directClusterName *string - physicalState PostgresBranchState - configuration *PostgresConfiguration -} - -// PostgresState shares the established database-state semantics with legacy branches. -type PostgresState = PostgresBranchState + Name string `json:"name"` + EnvironmentName string `json:"-"` + TeamSlug slug.Slug `json:"-"` + MajorVersion string `json:"majorVersion"` + Extensions []string `json:"extensions"` + HighAvailability bool `json:"highAvailability"` + Resources PostgresResources `json:"resources"` + Labels []*model.ResourceLabel `json:"labels"` + CreatedAt time.Time `json:"createdAt"` + Recovery *PostgresRecovery `json:"recovery,omitempty"` + directClusterName *string + physicalState PostgresState + configuration *PostgresConfiguration +} // PostgresResources contains only resource requests observed on the Postgres CR. type PostgresResources struct { @@ -145,50 +101,41 @@ func (p *Postgres) GetName() string { return p.Name } func (p *Postgres) GetNamespace() string { return p.TeamSlug.String() } func (p *Postgres) GetLabels() map[string]string { return nil } -type PostgresBranchState string +type PostgresState string const ( - PostgresBranchStateAvailable PostgresBranchState = "AVAILABLE" - PostgresBranchStateProgressing PostgresBranchState = "PROGRESSING" - PostgresBranchStateDegraded PostgresBranchState = "DEGRADED" + PostgresStateAvailable PostgresState = "AVAILABLE" + PostgresStateProgressing PostgresState = "PROGRESSING" + PostgresStateDegraded PostgresState = "DEGRADED" ) -var AllPostgresBranchState = []PostgresBranchState{ - PostgresBranchStateAvailable, - PostgresBranchStateProgressing, - PostgresBranchStateDegraded, -} +var AllPostgresState = []PostgresState{PostgresStateAvailable, PostgresStateProgressing, PostgresStateDegraded} -func (e PostgresBranchState) IsValid() bool { +func (e PostgresState) IsValid() bool { switch e { - case PostgresBranchStateAvailable, PostgresBranchStateProgressing, PostgresBranchStateDegraded: + case PostgresStateAvailable, PostgresStateProgressing, PostgresStateDegraded: return true } return false } -func (e PostgresBranchState) String() string { - return string(e) -} +func (e PostgresState) String() string { return string(e) } -func (e *PostgresBranchState) UnmarshalGQL(v any) error { +func (e *PostgresState) UnmarshalGQL(v any) error { str, ok := v.(string) if !ok { return fmt.Errorf("enums must be strings") } - - *e = PostgresBranchState(str) + *e = PostgresState(str) if !e.IsValid() { - return fmt.Errorf("%s is not a valid PostgresBranchState", str) + return fmt.Errorf("%s is not a valid PostgresState", str) } return nil } -func (e PostgresBranchState) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} +func (e PostgresState) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } -func (e *PostgresBranchState) UnmarshalJSON(b []byte) error { +func (e *PostgresState) UnmarshalJSON(b []byte) error { s, err := strconv.Unquote(string(b)) if err != nil { return err @@ -196,7 +143,7 @@ func (e *PostgresBranchState) UnmarshalJSON(b []byte) error { return e.UnmarshalGQL(s) } -func (e PostgresBranchState) MarshalJSON() ([]byte, error) { +func (e PostgresState) MarshalJSON() ([]byte, error) { var buf bytes.Buffer e.MarshalGQL(&buf) return buf.Bytes(), nil @@ -232,7 +179,6 @@ type DeletePostgresPayload struct { // The authenticated actor and final expiry are server-controlled. type CreatePostgresAccessInput struct { Postgres string `json:"postgres"` - Branch string `json:"branch"` TeamSlug slug.Slug `json:"teamSlug"` EnvironmentName string `json:"environmentName"` AccessLevel PostgresAccessLevel `json:"accessLevel"` @@ -247,7 +193,6 @@ func (i *CreatePostgresAccessInput) Validate(ctx context.Context) error { func (i *CreatePostgresAccessInput) ValidationErrors(ctx context.Context) *validate.ValidationErrors { verr := validate.New() i.Postgres = strings.TrimSpace(i.Postgres) - i.Branch = strings.TrimSpace(i.Branch) i.EnvironmentName = strings.TrimSpace(i.EnvironmentName) i.Reason = strings.TrimSpace(i.Reason) i.TTL = strings.TrimSpace(i.TTL) @@ -275,20 +220,15 @@ func (i *CreatePostgresAccessInput) ValidationErrors(ctx context.Context) *valid return verr } - instance, err := GetReadyPostgresBranch(ctx, i.TeamSlug, i.EnvironmentName, i.Postgres, i.Branch) + state, err := readyPostgresState(ctx, i.TeamSlug, i.EnvironmentName, i.Postgres) if err != nil { if k8serrors.IsNotFound(err) || errors.Is(err, &watcher.ErrorNotFound{}) { - verr.Add("branch", "Could not find PostgresBranch %q in Postgres %q", i.Branch, i.Postgres) + verr.Add("postgres", "Could not find Postgres %q", i.Postgres) } else { - verr.Add("branch", "%s", err) - } - } else { - // Keep the choice made from the fresh parent for readiness and the - // eventual immutable access resource, rather than resolving it again. - i.Branch = instance.Name - if instance.State != PostgresBranchStateAvailable { - verr.Add("branch", "Postgres branch %q is not available.", i.Branch) + verr.Add("postgres", "%s", err) } + } else if state != PostgresStateAvailable { + verr.Add("postgres", "Postgres %q is not available.", i.Postgres) } return verr @@ -337,63 +277,19 @@ func (e PostgresAccessLevel) MarshalGQL(w io.Writer) { fmt.Fprint(w, strconv.Quote(e.String())) } -func (p *PostgresBranch) GetObjectKind() schema.ObjectKind { - return schema.EmptyObjectKind -} - -func (p *PostgresBranch) DeepCopyObject() runtime.Object { - return p -} - -func (p *PostgresBranch) GetName() string { - return nais_io_v1.PostgresBranchObjectName(p.PostgresName, p.Name) -} - -func (p *PostgresBranch) GetNamespace() string { - return p.TeamSlug.String() -} - -func (p *PostgresBranch) GetLabels() map[string]string { - return nil -} - -func toPostgresBranch(u *unstructured.Unstructured, environmentName string) (*PostgresBranch, error) { - obj := &nais_io_v1.PostgresBranch{} - if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, obj); err != nil { - return nil, fmt.Errorf("converting PostgresBranch: %w", err) - } - if obj.Spec.Postgres == "" || obj.Spec.BranchName == "" || obj.Name != nais_io_v1.PostgresBranchObjectName(obj.Spec.Postgres, obj.Spec.BranchName) { - return nil, fmt.Errorf("PostgresBranch %q has invalid postgres or branchName", obj.Name) - } - state := PostgresBranchStateProgressing - var configuration *PostgresConfiguration - if obj.Status != nil { - state = postgresStateFromConditions(obj.Status.Conditions, obj.Status.ReconcilePhase == "Completed" && obj.Status.ObservedGeneration >= obj.Generation) - configuration = toPostgresConfiguration(obj.Status.Configuration) - } - return &PostgresBranch{Name: obj.Spec.BranchName, CreatedAt: obj.CreationTimestamp.Time, EnvironmentName: environmentName, TeamSlug: slug.Slug(obj.Namespace), PostgresName: obj.Spec.Postgres, State: state, Labels: model.UserLabels(obj.Labels), Configuration: configuration}, nil -} - func toPostgres(u *unstructured.Unstructured, environmentName string) (*Postgres, error) { obj := &nais_io_v1.Postgres{} if err := runtime.DefaultUnstructuredConverter.FromUnstructured(u.Object, obj); err != nil { return nil, fmt.Errorf("converting Postgres: %w", err) } - var active *string var clusterName *string - state := PostgresBranchStateProgressing + state := PostgresStateProgressing var configuration *PostgresConfiguration - if obj.Status != nil && obj.Status.ActiveBranch != "" { - // The implicit compatibility relation is always virtual main. Stale - // legacy metadata must not turn a provisioning read into a non-main lookup. - active = new(nais_io_v1.DefaultBranchName) - } if obj.Status != nil && obj.Status.ClusterName != "" { if len(validation.IsDNS1123Label(obj.Status.ClusterName)) > 0 { return nil, fmt.Errorf("Postgres %q has invalid clusterName %q", obj.Name, obj.Status.ClusterName) } clusterName = new(obj.Status.ClusterName) - active = new(nais_io_v1.DefaultBranchName) state = postgresStateFromConditions(obj.Status.Conditions, obj.Status.ReconcilePhase == "Completed" && obj.Status.ObservedGeneration >= obj.Generation) configuration = toPostgresConfiguration(obj.Status.Configuration) } @@ -424,7 +320,7 @@ func toPostgres(u *unstructured.Unstructured, environmentName string) (*Postgres } return &Postgres{ Name: obj.Name, EnvironmentName: environmentName, TeamSlug: slug.Slug(obj.Namespace), - ActiveBranch: active, DesiredActiveBranch: strPtr(obj.Spec.ActiveBranch), MajorVersion: obj.Spec.MajorVersion, Extensions: extensions, HighAvailability: obj.Spec.HighAvailability, + MajorVersion: obj.Spec.MajorVersion, Extensions: extensions, HighAvailability: obj.Spec.HighAvailability, Resources: PostgresResources{ CPU: quantity(obj.Spec.Resources.Cpu), Memory: quantity(obj.Spec.Resources.Memory), DiskSize: quantity(obj.Spec.Resources.DiskSize), @@ -437,14 +333,14 @@ func toPostgres(u *unstructured.Unstructured, environmentName string) (*Postgres // postgresStateFromConditions interprets pgrator and CNPG status conditions. // ObservedState=False means no phase has been observed, not a failed cluster. -func postgresStateFromConditions(conditions []metav1.Condition, reconciled bool) PostgresBranchState { +func postgresStateFromConditions(conditions []metav1.Condition, reconciled bool) PostgresState { for _, condition := range conditions { if condition.Type == "RecoveryFailed" && condition.Status == metav1.ConditionTrue && condition.Reason == "Unrecoverable" { - return PostgresBranchStateDegraded + return PostgresStateDegraded } } if !reconciled { - return PostgresBranchStateProgressing + return PostgresStateProgressing } for _, condition := range conditions { if condition.Type != "cluster.postgresql.cnpg.io/ObservedState" || condition.Status != metav1.ConditionTrue { @@ -456,96 +352,31 @@ func postgresStateFromConditions(conditions []metav1.Condition, reconciled bool) } switch phase { case "Cluster in healthy state": - return PostgresBranchStateAvailable + return PostgresStateAvailable case "Cluster is unrecoverable and needs manual intervention", "Cluster cannot proceed to reconciliation due to an unknown plugin being required", "Cluster cannot proceed to reconciliation due to an error while interacting with plugins", "Cluster has incomplete or invalid image catalog": - return PostgresBranchStateDegraded + return PostgresStateDegraded } } - return PostgresBranchStateProgressing -} - -type PostgresBranchOrder struct { - Field PostgresBranchOrderField `json:"field"` - Direction model.OrderDirection `json:"direction"` -} - -type PostgresBranchOrderField string - -const ( - PostgresBranchOrderFieldName PostgresBranchOrderField = "NAME" - PostgresBranchOrderFieldEnvironment PostgresBranchOrderField = "ENVIRONMENT" -) - -var AllPostgresBranchOrderField = []PostgresBranchOrderField{ - PostgresBranchOrderFieldName, - PostgresBranchOrderFieldEnvironment, -} - -func (e PostgresBranchOrderField) IsValid() bool { - switch e { - case PostgresBranchOrderFieldName, PostgresBranchOrderFieldEnvironment: - return true - } - return false -} - -func (e PostgresBranchOrderField) String() string { - return string(e) -} - -func (e *PostgresBranchOrderField) UnmarshalGQL(v any) error { - str, ok := v.(string) - if !ok { - return fmt.Errorf("enums must be strings") - } - - *e = PostgresBranchOrderField(str) - if !e.IsValid() { - return fmt.Errorf("%s is not a valid PostgresBranchOrderField", str) - } - return nil -} - -func (e PostgresBranchOrderField) MarshalGQL(w io.Writer) { - fmt.Fprint(w, strconv.Quote(e.String())) -} - -func (e *PostgresBranchOrderField) UnmarshalJSON(b []byte) error { - s, err := strconv.Unquote(string(b)) - if err != nil { - return err - } - return e.UnmarshalGQL(s) -} - -func (e PostgresBranchOrderField) MarshalJSON() ([]byte, error) { - var buf bytes.Buffer - e.MarshalGQL(&buf) - return buf.Bytes(), nil -} - -type TeamInventoryCountPostgresBranches struct { - Total int `json:"total"` + return PostgresStateProgressing } // PostgresAccess exposes the API/CLI-facing state of a controller-owned personal // database access. Credentials are read from the controller-owned Secret on // demand; they are never cached by the watcher. type PostgresAccess struct { - Name string `json:"name"` - TeamSlug slug.Slug `json:"-"` - EnvironmentName string `json:"-"` - PostgresBranchName string `json:"postgresBranch"` - PostgresName string `json:"-"` - Username string `json:"username"` - AccessLevel PostgresAccessLevel `json:"accessLevel"` - ExpiresAt time.Time `json:"expiresAt"` - State PostgresAccessState `json:"state"` - Message *string `json:"message,omitempty"` - RelayAccess *string `json:"relayAccess,omitempty"` + Name string `json:"name"` + TeamSlug slug.Slug `json:"-"` + EnvironmentName string `json:"-"` + PostgresName string `json:"-"` + Username string `json:"username"` + AccessLevel PostgresAccessLevel `json:"accessLevel"` + ExpiresAt time.Time `json:"expiresAt"` + State PostgresAccessState `json:"state"` + Message *string `json:"message,omitempty"` + RelayAccess *string `json:"relayAccess,omitempty"` } func (PostgresAccess) IsNode() {} diff --git a/internal/persistence/postgres/models_test.go b/internal/persistence/postgres/models_test.go index 5eefe0fce..7bc74ef88 100644 --- a/internal/persistence/postgres/models_test.go +++ b/internal/persistence/postgres/models_test.go @@ -7,57 +7,29 @@ import ( "time" "github.com/nais/api/internal/validate" - nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" ) -func TestToPostgresBranch(t *testing.T) { - createdAt := time.Date(2025, time.December, 31, 12, 0, 0, 0, time.UTC) - obj := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresBranchObjectName("orders", "restored"), "namespace": "my-team", "creationTimestamp": createdAt.Format(time.RFC3339)}, - "spec": map[string]any{"postgres": "orders", "branchName": "restored"}, - "status": map[string]any{"reconcilePhase": "Completed", "conditions": []any{map[string]any{"type": "cluster.postgresql.cnpg.io/ObservedState", "status": "True", "lastTransitionTime": "2026-01-01T00:00:00Z", "reason": "Reconciled", "message": "Cluster is in phase: Cluster in healthy state"}}}, - }} - got, err := toPostgresBranch(obj, "dev") +func TestToPostgresWithoutStatus(t *testing.T) { + obj := physicalPostgresObject("orders", nil) + got, err := toPostgres(obj, "dev") if err != nil { t.Fatal(err) } - if got.Name != "restored" || got.PostgresName != "orders" || got.State != PostgresBranchStateAvailable { - t.Errorf("unexpected PostgresBranch: %+v", got) + if got.Name != "orders" || got.TeamSlug != "team" || got.EnvironmentName != "dev" { + t.Fatalf("unexpected Postgres: %+v", got) } + createdAt := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) if !got.CreatedAt.Equal(createdAt) { t.Errorf("createdAt = %v, want %v", got.CreatedAt, createdAt) } if got.GetName() != obj.GetName() { - t.Errorf("watcher name = %q, want %q", got.GetName(), obj.GetName()) + t.Error("resource name changed") } -} - -func TestToPostgresBranchWithoutStatus(t *testing.T) { - obj := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresBranchObjectName("orders", "main"), "namespace": "my-team"}, - "spec": map[string]any{"postgres": "orders", "branchName": "main"}, - }} - got, err := toPostgresBranch(obj, "dev") - if err != nil { - t.Fatal(err) - } - if got.State != PostgresBranchStateProgressing { - t.Errorf("branch state = %q, want PROGRESSING before status is observed", got.State) - } -} - -func TestToPostgresBranchRejectsMismatchedObjectName(t *testing.T) { - obj := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresBranchObjectName("orders", "main")}, - "spec": map[string]any{"postgres": "orders", "branchName": "other"}, - }} - if _, err := toPostgresBranch(obj, "dev"); err == nil { - t.Fatal("expected a mismatched branch object name to be rejected") + state, config, err := PhysicalStatus(t.Context(), got) + if err != nil || state != PostgresStateProgressing || config != nil { + t.Fatalf("status = %v, %v, %v", state, config, err) } } @@ -66,13 +38,12 @@ func TestToPostgres(t *testing.T) { "apiVersion": "nais.io/v1", "kind": "Postgres", "metadata": map[string]any{"name": "orders", "namespace": "my-team"}, "spec": map[string]any{"majorVersion": "17", "highAvailability": true, "extensions": []any{map[string]any{"name": "pg_trgm"}, map[string]any{"name": "uuid-ossp"}}, "resources": map[string]any{"cpu": "100m", "memory": "2Gi", "diskSize": "10Gi"}}, - "status": map[string]any{"activeBranch": "restored"}, }} got, err := toPostgres(obj, "dev") if err != nil { t.Fatal(err) } - if got.Name != "orders" || got.MajorVersion != "17" || got.ActiveBranch == nil || *got.ActiveBranch != "main" { + if got.Name != "orders" || got.MajorVersion != "17" { t.Errorf("unexpected Postgres: %+v", got) } if !reflect.DeepEqual(got.Extensions, []string{"pg_trgm", "uuid-ossp"}) { @@ -191,18 +162,18 @@ func TestPostgresStateFromConditions(t *testing.T) { name string reconciled bool conditions []metav1.Condition - want PostgresBranchState + want PostgresState }{ - {name: "not reconciled", want: PostgresBranchStateProgressing}, - {name: "unrecoverable recovery failure", conditions: []metav1.Condition{{Type: "RecoveryFailed", Status: metav1.ConditionTrue, Reason: "Unrecoverable"}}, want: PostgresBranchStateDegraded}, - {name: "recovery failure not terminal", conditions: []metav1.Condition{{Type: "RecoveryFailed", Status: metav1.ConditionFalse, Reason: "Recovering"}}, want: PostgresBranchStateProgressing}, - {name: "ready false without recovery failure", reconciled: true, conditions: []metav1.Condition{{Type: "Ready", Status: metav1.ConditionFalse, Reason: "RecoveryFailed"}}, want: PostgresBranchStateProgressing}, - {name: "healthy", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Cluster in healthy state"}}, want: PostgresBranchStateAvailable}, - {name: "still starting", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionFalse, Message: "Cluster is in phase: "}}, want: PostgresBranchStateProgressing}, - {name: "unrecoverable", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Cluster is unrecoverable and needs manual intervention"}}, want: PostgresBranchStateDegraded}, - {name: "plugin failure", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Cluster cannot proceed to reconciliation due to an error while interacting with plugins"}}, want: PostgresBranchStateDegraded}, - {name: "other phase", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Online upgrade in progress"}}, want: PostgresBranchStateProgressing}, - {name: "missing", reconciled: true, want: PostgresBranchStateProgressing}, + {name: "not reconciled", want: PostgresStateProgressing}, + {name: "unrecoverable recovery failure", conditions: []metav1.Condition{{Type: "RecoveryFailed", Status: metav1.ConditionTrue, Reason: "Unrecoverable"}}, want: PostgresStateDegraded}, + {name: "recovery failure not terminal", conditions: []metav1.Condition{{Type: "RecoveryFailed", Status: metav1.ConditionFalse, Reason: "Recovering"}}, want: PostgresStateProgressing}, + {name: "ready false without recovery failure", reconciled: true, conditions: []metav1.Condition{{Type: "Ready", Status: metav1.ConditionFalse, Reason: "RecoveryFailed"}}, want: PostgresStateProgressing}, + {name: "healthy", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Cluster in healthy state"}}, want: PostgresStateAvailable}, + {name: "still starting", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionFalse, Message: "Cluster is in phase: "}}, want: PostgresStateProgressing}, + {name: "unrecoverable", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Cluster is unrecoverable and needs manual intervention"}}, want: PostgresStateDegraded}, + {name: "plugin failure", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Cluster cannot proceed to reconciliation due to an error while interacting with plugins"}}, want: PostgresStateDegraded}, + {name: "other phase", reconciled: true, conditions: []metav1.Condition{{Type: "cluster.postgresql.cnpg.io/ObservedState", Status: metav1.ConditionTrue, Message: "Cluster is in phase: Online upgrade in progress"}}, want: PostgresStateProgressing}, + {name: "missing", reconciled: true, want: PostgresStateProgressing}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/internal/persistence/postgres/physical_status.go b/internal/persistence/postgres/physical_status.go index be83e8bc6..df8a10c5b 100644 --- a/internal/persistence/postgres/physical_status.go +++ b/internal/persistence/postgres/physical_status.go @@ -1,58 +1,16 @@ package postgres -import ( - "context" - - nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" -) +import "context" // PhysicalStatus reads only Postgres status. Missing physical status means the -// database is still provisioning; a retired branch must never supply readiness. +// database is still provisioning. func PhysicalStatus(ctx context.Context, pg *Postgres) (PostgresState, *PostgresConfiguration, error) { if pg.directClusterName != nil { return pg.physicalState, pg.configuration, nil } - return PostgresBranchStateProgressing, nil, nil + return PostgresStateProgressing, nil, nil } -// physicalClusterName selects the same internal target before and after direct ownership. func physicalClusterName(ctx context.Context, pg *Postgres) (*string, error) { return pg.directClusterName, nil } - -func observedBranchName(pg *Postgres) string { - return nais_io_v1.DefaultBranchName -} - -func mainBranchView(pg *Postgres) *PostgresBranch { - clusterName := "" - state := PostgresBranchStateProgressing - if pg.directClusterName != nil { - clusterName = *pg.directClusterName - state = pg.physicalState - } - return &PostgresBranch{ - Name: nais_io_v1.DefaultBranchName, PostgresName: pg.Name, - TeamSlug: pg.TeamSlug, EnvironmentName: pg.EnvironmentName, - CreatedAt: pg.CreatedAt, Labels: pg.Labels, - State: state, Configuration: pg.configuration, - ClusterName: clusterName, - } -} - -func (branch *PostgresBranch) clusterName() string { - if branch.ClusterName != "" { - return branch.ClusterName - } - return nais_io_v1.CNPGClusterName(branch.GetName()) -} - -// MainViews retains the deprecated main view, including its stable node ID, -// using logical Postgres resources only. -func MainViews(postgreses []*Postgres) []*PostgresBranch { - views := make([]*PostgresBranch, 0, len(postgreses)) - for _, pg := range postgreses { - views = append(views, mainBranchView(pg)) - } - return views -} diff --git a/internal/persistence/postgres/physical_status_test.go b/internal/persistence/postgres/physical_status_test.go index a5b36703f..0873127ea 100644 --- a/internal/persistence/postgres/physical_status_test.go +++ b/internal/persistence/postgres/physical_status_test.go @@ -2,7 +2,6 @@ package postgres import ( "context" - "errors" "testing" "time" @@ -10,12 +9,9 @@ import ( "github.com/nais/api/internal/kubernetes" "github.com/nais/api/internal/kubernetes/fake" "github.com/nais/api/internal/kubernetes/watcher" - "github.com/nais/api/internal/slug" - nais_io_v1 "github.com/nais/pgrator/pkg/api/v1" logrustest "github.com/sirupsen/logrus/hooks/test" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/util/wait" ) func physicalPostgresObject(name string, status map[string]any) *unstructured.Unstructured { @@ -47,16 +43,16 @@ func TestDirectPostgresPhysicalStatus(t *testing.T) { change func(map[string]any) want PostgresState }{ - {name: "healthy", want: PostgresBranchStateAvailable}, - {name: "old observed generation", change: func(s map[string]any) { s["observedGeneration"] = int64(1) }, want: PostgresBranchStateProgressing}, - {name: "not completed", change: func(s map[string]any) { s["reconcilePhase"] = "Preparing" }, want: PostgresBranchStateProgressing}, - {name: "no physical condition", change: func(s map[string]any) { delete(s, "conditions") }, want: PostgresBranchStateProgressing}, + {name: "healthy", want: PostgresStateAvailable}, + {name: "old observed generation", change: func(s map[string]any) { s["observedGeneration"] = int64(1) }, want: PostgresStateProgressing}, + {name: "not completed", change: func(s map[string]any) { s["reconcilePhase"] = "Preparing" }, want: PostgresStateProgressing}, + {name: "no physical condition", change: func(s map[string]any) { delete(s, "conditions") }, want: PostgresStateProgressing}, {name: "degraded", change: func(s map[string]any) { s["conditions"].([]any)[0].(map[string]any)["message"] = "Cluster is in phase: Cluster is unrecoverable and needs manual intervention" - }, want: PostgresBranchStateDegraded}, + }, want: PostgresStateDegraded}, } { t.Run(tt.name, func(t *testing.T) { - status := healthyPhysicalStatus("pg-existing-main-12345678") + status := healthyPhysicalStatus("pg-existing-12345678") if tt.change != nil { tt.change(status) } @@ -64,7 +60,6 @@ func TestDirectPostgresPhysicalStatus(t *testing.T) { if err != nil { t.Fatal(err) } - // No branch watcher or context is needed once direct status is selected. state, config, err := PhysicalStatus(t.Context(), pg) if err != nil || state != tt.want { t.Fatalf("status = %q, error = %v; want %q", state, err, tt.want) @@ -73,13 +68,9 @@ func TestDirectPostgresPhysicalStatus(t *testing.T) { if diff := cmp.Diff(wantConfig, config); diff != "" { t.Errorf("configuration (-want +got):\n%s", diff) } - branch := mainBranchView(pg) - legacy := &PostgresBranch{Name: "main", PostgresName: pg.Name, TeamSlug: pg.TeamSlug, EnvironmentName: pg.EnvironmentName} - if branch.GetName() != legacy.GetName() { - t.Error("physical view changed the legacy resource identity") - } - if branch.clusterName() != *pg.directClusterName { - t.Error("virtual main did not preserve the observed physical target") + cluster, err := physicalClusterName(t.Context(), pg) + if err != nil || cluster == nil || *cluster != "pg-existing-12345678" { + t.Fatalf("physical target = %v, %v", cluster, err) } }) } @@ -98,22 +89,7 @@ func TestDirectPostgresInvalidStatus(t *testing.T) { } } -func TestMainViewUsesOnlyDirectStatus(t *testing.T) { - pg := &Postgres{Name: "orders", TeamSlug: "team", EnvironmentName: "dev", directClusterName: new("pg-existing"), physicalState: PostgresBranchStateDegraded} - views := MainViews([]*Postgres{pg}) - if len(views) != 1 { - t.Fatalf("views = %d, want 1", len(views)) - } - for _, branch := range views { - if branch.PostgresName == pg.Name && branch.TeamSlug == pg.TeamSlug && branch.EnvironmentName == pg.EnvironmentName { - if branch.Name != "main" || branch.State != PostgresBranchStateDegraded { - t.Errorf("stale branch won over direct status: %+v", branch) - } - } - } -} - -func TestRetiredBranchCannotSupplyReadiness(t *testing.T) { +func TestPostgresAccessCorroboratesFreshPhysicalStatus(t *testing.T) { scheme, err := kubernetes.NewScheme() if err != nil { t.Fatal(err) @@ -136,16 +112,6 @@ func TestRetiredBranchCannotSupplyReadiness(t *testing.T) { if err != nil { t.Fatal(err) } - branchObj := &unstructured.Unstructured{Object: map[string]any{ - "apiVersion": "nais.io/v1", "kind": "PostgresBranch", - "metadata": map[string]any{"name": nais_io_v1.PostgresPhysicalName("orders"), "namespace": "team", "generation": int64(2)}, - "spec": map[string]any{"postgres": "orders", "branchName": "main"}, - "status": healthyPhysicalStatus("pg-legacy"), - }} - branchClient := client.Resource(nais_io_v1.GroupVersion.WithResource("postgresbranches")).Namespace("team") - if _, err := branchClient.Create(ctx, branchObj, metav1.CreateOptions{}); err != nil { - t.Fatal(err) - } postgreses := NewPostgresWatcher(ctx, mgr) ready, cancelReady := context.WithTimeout(ctx, 5*time.Second) defer cancelReady() @@ -153,72 +119,39 @@ func TestRetiredBranchCannotSupplyReadiness(t *testing.T) { t.Fatal("watchers did not synchronize") } ctx = NewLoaderContext(ctx, postgreses, "", "", "nav", mgr.GetDynamicClients()) - pg, err := GetPostgres(ctx, slug.Slug("team"), "dev", "orders") - if err != nil { - t.Fatal(err) - } - state, config, err := PhysicalStatus(ctx, pg) - if err != nil || state != PostgresBranchStateProgressing || config != nil { - t.Fatalf("retired branch supplied status = %q, %v, %v", state, config, err) + state, err := readyPostgresState(ctx, "team", "dev", "orders") + if err != nil || state != PostgresStateProgressing { + t.Fatalf("provisioning = %q, %v", state, err) } - // Direct status is intentionally incomplete: stale healthy main must not win. - obj.Object["status"] = map[string]any{"clusterName": "pg-preserved-main-12345678"} + // Access reads must use fresh status, even before the informer catches up. + obj.Object["status"] = healthyPhysicalStatus("pg-preserved-12345678") if _, err := pgClient.UpdateStatus(ctx, obj, metav1.UpdateOptions{}); err != nil { t.Fatal(err) } - if err := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - pg, err := postgreses.Get("dev", "team", "orders") - return err == nil && pg.directClusterName != nil, err - }); err != nil { - t.Fatal("Postgres watcher did not observe direct status:", err) - } - main, err := GetPostgresBranch(ctx, "team", "dev", "orders", "main") - if err != nil || main.State != PostgresBranchStateProgressing || main.Configuration != nil { - t.Fatalf("direct main = %+v, error = %v", main, err) - } - if _, err := GetPostgresBranch(ctx, "team", "dev", "orders", "restore"); !errors.Is(err, &watcher.ErrorNotFound{}) { - t.Errorf("non-main unexpectedly resolved: %v", err) - } - if err := branchClient.Delete(ctx, branchObj.GetName(), metav1.DeleteOptions{}); err != nil { - t.Fatal(err) - } - if err := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - views := ListAllForTeam(ctx, "team", nil) - return len(views) == 1 && views[0].ClusterName == "pg-preserved-main-12345678" && views[0].State == PostgresBranchStateProgressing, nil - }); err != nil { - t.Fatal("listing did not switch to direct status:", err) - } - main, err = GetPostgresBranchByObjectName(ctx, "team", "dev", branchObj.GetName()) - if err != nil || main.clusterName() != "pg-preserved-main-12345678" { - t.Fatalf("legacy access reference after detach = %+v, error = %v", main, err) - } - - // The access check must use the freshly observed direct target, not a - // branch-name reconstruction or stale parent from the list informer. - obj.Object["status"] = healthyPhysicalStatus("pg-preserved-main-12345678") - if _, err := pgClient.UpdateStatus(ctx, obj, metav1.UpdateOptions{}); err != nil { - t.Fatal(err) + state, err = readyPostgresState(ctx, "team", "dev", "orders") + if err != nil || state != PostgresStateProgressing { + t.Fatalf("missing cluster = %q, %v", state, err) } cluster := &unstructured.Unstructured{Object: map[string]any{ "apiVersion": "postgresql.cnpg.io/v1", "kind": "Cluster", - "metadata": map[string]any{"name": "pg-preserved-main-12345678", "namespace": "team"}, + "metadata": map[string]any{"name": "pg-preserved-12345678", "namespace": "team"}, "status": map[string]any{"conditions": []any{map[string]any{"type": "Ready", "status": "True"}}}, }} clustersClient := client.Resource(cnpgClusterGVR).Namespace("team") if _, err := clustersClient.Create(ctx, cluster, metav1.CreateOptions{}); err != nil { t.Fatal(err) } - main, err = GetReadyPostgresBranch(ctx, "team", "dev", "orders", "main") - if err != nil || main.State != PostgresBranchStateAvailable { - t.Fatalf("direct ready access target = %+v, error = %v", main, err) + state, err = readyPostgresState(ctx, "team", "dev", "orders") + if err != nil || state != PostgresStateAvailable { + t.Fatalf("ready = %q, %v", state, err) } cluster.Object["status"] = map[string]any{"conditions": []any{map[string]any{"type": "Ready", "status": "False"}}} if _, err := clustersClient.UpdateStatus(ctx, cluster, metav1.UpdateOptions{}); err != nil { t.Fatal(err) } - main, err = GetReadyPostgresBranch(ctx, "team", "dev", "orders", "main") - if err != nil || main.State != PostgresBranchStateProgressing { - t.Fatalf("access must not trust healthy parent over CNPG readiness: %+v, error = %v", main, err) + state, err = readyPostgresState(ctx, "team", "dev", "orders") + if err != nil || state != PostgresStateProgressing { + t.Fatalf("unready cluster = %q, %v", state, err) } } diff --git a/internal/persistence/postgres/queries.go b/internal/persistence/postgres/queries.go index 71cd2b46f..60564dc67 100644 --- a/internal/persistence/postgres/queries.go +++ b/internal/persistence/postgres/queries.go @@ -37,8 +37,7 @@ import ( "k8s.io/client-go/dynamic" ) -// ListPostgresForWorkload resolves the Postgres databases referenced by a workload, -// including databases without an active branch. +// ListPostgresForWorkload resolves the Postgres databases referenced by a workload. func ListPostgresForWorkload(ctx context.Context, teamSlug slug.Slug, environmentName string, uses []liberatorv1.PostgresUse) ([]*Postgres, error) { instances := make([]*Postgres, 0, len(uses)) for _, use := range uses { @@ -77,11 +76,6 @@ func WorkloadPostgresesForWorkload(ctx context.Context, teamSlug slug.Slug, envi workloadPostgreses := make([]*WorkloadPostgres, 0, len(instances)) for _, instance := range instances { use := usesByName[instance.Name] - branchName := selectedBranchName(instance, use) - branch, err := BranchForPostgres(ctx, instance, branchName) - if err != nil { - return nil, 0, err - } role, err := workloadPostgresRole(use.Role) if err != nil { return nil, 0, err @@ -89,7 +83,6 @@ func WorkloadPostgresesForWorkload(ctx context.Context, teamSlug slug.Slug, envi workloadPostgreses = append(workloadPostgreses, &WorkloadPostgres{ EnvPrefix: optionalPostgresUseString(use.EnvPrefix), Role: role, - Branch: branch, Postgres: instance, }) } @@ -120,10 +113,7 @@ func uniquePostgresUses(uses []liberatorv1.PostgresUse) ([]liberatorv1.PostgresU unique := make([]liberatorv1.PostgresUse, 0, len(uses)) byName := make(map[string]liberatorv1.PostgresUse, len(uses)) for _, use := range uses { - if existing, ok := byName[use.Name]; ok { - if existing.Branch != use.Branch { - return nil, fmt.Errorf("workload references multiple branches for Postgres %q", use.Name) - } + if _, ok := byName[use.Name]; ok { continue } byName[use.Name] = use @@ -132,13 +122,6 @@ func uniquePostgresUses(uses []liberatorv1.PostgresUse) ([]liberatorv1.PostgresU return unique, nil } -func selectedBranchName(instance *Postgres, use liberatorv1.PostgresUse) string { - if use.Branch != "" { - return use.Branch - } - return observedBranchName(instance) -} - func ListPostgresForTeam(ctx context.Context, teamSlug slug.Slug, page *pagination.Pagination, filter *TeamPostgresFilter) *PostgresConnection { all := watcher.Objects(fromContext(ctx).postgresWatcher.GetByNamespace(teamSlug.String(), watcher.WithoutDeleted())) instances := make([]*Postgres, 0, len(all)) @@ -157,13 +140,8 @@ func ListPostgresForTeam(ctx context.Context, teamSlug slug.Slug, page *paginati return pagination.NewFacetableConnection(conn, all, filter) } -func ListAllForTeam(ctx context.Context, teamSlug slug.Slug, filter *PostgresBranchFilter) []*PostgresBranch { - postgreses := watcher.Objects(fromContext(ctx).postgresWatcher.GetByNamespace(teamSlug.String(), watcher.WithoutDeleted())) - return MainViews(postgreses) -} - func CountForTeam(ctx context.Context, teamSlug slug.Slug) int { - return len(ListAllForTeam(ctx, teamSlug, nil)) + return len(watcher.Objects(fromContext(ctx).postgresWatcher.GetByNamespace(teamSlug.String(), watcher.WithoutDeleted()))) } func GetPostgresByIdent(ctx context.Context, id ident.Ident) (*Postgres, error) { @@ -305,8 +283,8 @@ func toPostgresAccess(u *unstructured.Unstructured, teamSlug slug.Slug, environm if err != nil { return nil, fmt.Errorf("converting PostgresAccess %q: %w", name, err) } - if (obj.Spec.Postgres == "") == (obj.Spec.PostgresBranch == "") { - return nil, fmt.Errorf("PostgresAccess %q must have exactly one Postgres reference", name) + if obj.Spec.Postgres == "" { + return nil, fmt.Errorf("PostgresAccess %q must have a Postgres reference", name) } expiresAt := obj.Spec.ExpiresAt.Time levelStr := obj.Spec.AccessLevel @@ -323,17 +301,16 @@ func toPostgresAccess(u *unstructured.Unstructured, teamSlug slug.Slug, environm } return &PostgresAccess{ - Name: name, - TeamSlug: teamSlug, - EnvironmentName: environmentName, - PostgresBranchName: obj.Spec.PhysicalName(), - PostgresName: obj.Spec.Postgres, - Username: obj.Spec.Username, - AccessLevel: level, - ExpiresAt: expiresAt, - State: state, - Message: strPtr(message), - RelayAccess: strPtr(relayName), + Name: name, + TeamSlug: teamSlug, + EnvironmentName: environmentName, + PostgresName: obj.Spec.Postgres, + Username: obj.Spec.Username, + AccessLevel: level, + ExpiresAt: expiresAt, + State: state, + Message: strPtr(message), + RelayAccess: strPtr(relayName), }, nil } @@ -366,102 +343,46 @@ func postgresAccessState(obj *nais_io_v1.PostgresAccess, expiresAt time.Time) (P return PostgresAccessStatePending, "waiting for controller" } -func GetReadyPostgresBranch(ctx context.Context, teamSlug slug.Slug, environmentName, postgresName, branchName string) (*PostgresBranch, error) { - // Access is a write decision: select the model and target from a fresh parent - // rather than relying on the informer's potentially older ownership status. +// readyPostgresState reads the parent fresh and corroborates its status with +// CNPG's own Ready condition before personal access can be issued. +func readyPostgresState(ctx context.Context, teamSlug slug.Slug, environmentName, postgresName string) (PostgresState, error) { pg, err := GetPostgres(ctx, teamSlug, environmentName, postgresName) if err != nil { - return nil, err + return "", err } - if branchName == "" { - branchName = observedBranchName(pg) - } - instance, err := BranchForPostgres(ctx, pg, branchName) + return corroboratedPostgresState(ctx, pg) +} + +func corroboratedPostgresState(ctx context.Context, pg *Postgres) (PostgresState, error) { + state, _, err := PhysicalStatus(ctx, pg) if err != nil { - return nil, err + return "", err } - if instance.State != PostgresBranchStateAvailable { - return instance, nil + if state != PostgresStateAvailable { + return state, nil } - // The pgrator reconciliation condition reflects the CNPG phase, but must be - // corroborated with CNPG's own Ready condition before issuing access. - client, err := fromContext(ctx).postgresWatcher.SystemAuthenticatedClient(ctx, environmentName, watcher.WithImpersonatedClientGVR(schema.GroupVersionResource{Group: "postgresql.cnpg.io", Version: "v1", Resource: "clusters"})) + client, err := fromContext(ctx).postgresWatcher.SystemAuthenticatedClient(ctx, pg.EnvironmentName, watcher.WithImpersonatedClientGVR(schema.GroupVersionResource{Group: "postgresql.cnpg.io", Version: "v1", Resource: "clusters"})) if err != nil { - return nil, err + return "", err } - cluster, err := client.Namespace(teamSlug.String()).Get(ctx, instance.clusterName(), metav1.GetOptions{}) + cluster, err := client.Namespace(pg.TeamSlug.String()).Get(ctx, *pg.directClusterName, metav1.GetOptions{}) if k8serrors.IsNotFound(err) { - instance.State = PostgresBranchStateProgressing - return instance, nil + return PostgresStateProgressing, nil } if err != nil { - return nil, fmt.Errorf("getting CNPG Cluster for PostgresBranch %q: %w", branchName, err) + return "", fmt.Errorf("getting CNPG Cluster for Postgres %q: %w", pg.Name, err) } - conditions, found, err := unstructured.NestedSlice(cluster.Object, "status", "conditions") + conditions, _, err := unstructured.NestedSlice(cluster.Object, "status", "conditions") if err != nil { - return nil, err - } - if !found { - instance.State = PostgresBranchStateProgressing - return instance, nil + return "", err } for _, raw := range conditions { condition, ok := raw.(map[string]any) if ok && condition["type"] == "Ready" && condition["status"] == "True" { - return instance, nil + return PostgresStateAvailable, nil } } - instance.State = PostgresBranchStateProgressing - return instance, nil -} - -func GetPostgresBranch(ctx context.Context, teamSlug slug.Slug, environmentName, postgresName, branchName string) (*PostgresBranch, error) { - pg, err := fromContext(ctx).postgresWatcher.Get(environmentName, teamSlug.String(), postgresName) - if err != nil { - return nil, err - } - return BranchForPostgres(ctx, pg, branchName) -} - -// BranchForPostgres implements the legacy branch view for an already resolved -// Postgres. It avoids extra Kubernetes requests and uses the parent's snapshot. -func BranchForPostgres(ctx context.Context, pg *Postgres, branchName string) (*PostgresBranch, error) { - if branchName != nais_io_v1.DefaultBranchName { - return nil, &watcher.ErrorNotFound{Cluster: pg.EnvironmentName, Namespace: pg.TeamSlug.String(), Name: pg.Name + "/" + branchName} - } - return mainBranchView(pg), nil -} - -// GetPostgresBranchByObjectName resolves the internal object name from PostgresAccess. -func GetPostgresBranchByObjectName(ctx context.Context, teamSlug slug.Slug, environmentName, objectName string) (*PostgresBranch, error) { - pg, err := GetPostgresByPhysicalName(ctx, teamSlug, environmentName, objectName) - if errors.Is(err, &watcher.ErrorNotFound{}) { - return nil, &watcher.ErrorNotFound{Cluster: environmentName, Namespace: teamSlug.String(), Name: "Postgres branch"} - } - if err != nil { - return nil, err - } - return mainBranchView(pg), nil -} - -// GetPostgresByPhysicalName adapts historical issue/access identities to their -// logical parent without querying the retired branch API or exposing its naming -// convention to clients. Namespace and environment are part of the lookup. -func GetPostgresByPhysicalName(ctx context.Context, teamSlug slug.Slug, environmentName, objectName string) (*Postgres, error) { - for _, pg := range watcher.Objects(fromContext(ctx).postgresWatcher.GetByNamespace(teamSlug.String())) { - if pg.EnvironmentName == environmentName && nais_io_v1.PostgresPhysicalName(pg.Name) == objectName { - return pg, nil - } - } - return nil, &watcher.ErrorNotFound{Cluster: environmentName, Namespace: teamSlug.String(), Name: "Postgres"} -} - -func ListForPostgres(ctx context.Context, pg *Postgres, page *pagination.Pagination, orderBy *PostgresBranchOrder) *PostgresBranchConnection { - all := []*PostgresBranch{mainBranchView(pg)} - if orderBy == nil { - orderBy = &PostgresBranchOrder{Field: PostgresBranchOrderFieldName, Direction: model.OrderDirectionAsc} - } - return SortFilterPostgresBranch.PaginatedList(ctx, all, page, orderBy.Field, orderBy.Direction, nil) + return PostgresStateProgressing, nil } func GetPostgres(ctx context.Context, teamSlug slug.Slug, environmentName, name string) (*Postgres, error) { @@ -509,11 +430,11 @@ func CreatePostgresAccess(ctx context.Context, input CreatePostgresAccessInput) if err != nil { return nil, err } - selected, err := BranchForPostgres(ctx, pg, input.Branch) + state, err := corroboratedPostgresState(ctx, pg) if err != nil { return nil, err } - if selected.State != PostgresBranchStateAvailable { + if state != PostgresStateAvailable { return nil, apierror.Errorf("Postgres %q is not available", pg.Name) } @@ -524,12 +445,10 @@ func CreatePostgresAccess(ctx context.Context, input CreatePostgresAccessInput) expiresAt := time.Now().Add(accessTTL).Truncate(time.Second) username := authz.ActorFromContext(ctx).User.Identity() - branchObjectName := nais_io_v1.PostgresBranchObjectName(input.Postgres, input.Branch) - - // One access per user and branch: pgrator derives a single personal database role from - // them, so a second access could never become ready. The name is derived from the pair, so - // the API server enforces this atomically through AlreadyExists. - name := postgresAccessName(username, branchObjectName) + // Keep the physical access identity stable so existing accesses cannot be + // duplicated during rollout. It is an opaque controller-owned identifier. + physicalName := nais_io_v1.PostgresPhysicalName(input.Postgres) + name := postgresAccessName(username, physicalName) accesses := client.Namespace(input.TeamSlug.String()) res := newPostgresAccessResource(input, username, name, expiresAt) @@ -546,7 +465,7 @@ func CreatePostgresAccess(ctx context.Context, input CreatePostgresAccessInput) if attempt == 0 { continue // Deleted between Create and Get; retry once. } - return nil, apierror.Errorf("Your previous access to this branch is still being cleaned up. Try again later.") + return nil, apierror.Errorf("Your previous access to this Postgres is still being cleaned up. Try again later.") } if getErr != nil { return nil, getErr @@ -555,7 +474,7 @@ func CreatePostgresAccess(ctx context.Context, input CreatePostgresAccessInput) if err != nil { return nil, fmt.Errorf("reading existing PostgresAccess %q: %w", name, err) } - if oldAccess.Spec.Username != username || oldAccess.Spec.PhysicalName() != branchObjectName || (oldAccess.Spec.Postgres == "") == (oldAccess.Spec.PostgresBranch == "") { + if oldAccess.Spec.Username != username || oldAccess.Spec.Postgres != input.Postgres { return nil, apierror.Errorf("Existing PostgresAccess %q has a conflicting identity", name) } if existing.GetDeletionTimestamp() == nil && existingExpiry(existing).After(time.Now()) { @@ -565,7 +484,7 @@ func CreatePostgresAccess(ctx context.Context, input CreatePostgresAccessInput) } } if attempt > 0 { - return nil, apierror.Errorf("Your previous access to this branch is still being cleaned up. Try again later.") + return nil, apierror.Errorf("Your previous access to this Postgres is still being cleaned up. Try again later.") } // The immutable access must disappear before it can be replaced after // expiry or a change in access level. @@ -615,7 +534,7 @@ func waitForPostgresAccessDeletion(ctx context.Context, accesses dynamic.Resourc return current.GetUID() != uid, nil }) if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil { - return apierror.Errorf("Your previous access to this branch is still being cleaned up after 10 seconds (access %s). Try again later.", name) + return apierror.Errorf("Your previous access to this Postgres is still being cleaned up after 10 seconds (access %s). Try again later.", name) } return err } @@ -626,11 +545,10 @@ func existingExpiry(access *unstructured.Unstructured) time.Time { return t } -// postgresAccessName derives the access name from user and branch, so the Kubernetes API -// server rejects a second concurrent access for the same pair. The NUL separator keeps -// different (user, branch) pairs from producing the same input. -func postgresAccessName(username, branchObjectName string) string { - sum := sha256.Sum256([]byte(username + "\x00" + branchObjectName)) +// postgresAccessName derives a stable access name from user and physical database +// identity. The NUL separator avoids ambiguous pairs; Kubernetes enforces uniqueness. +func postgresAccessName(username, physicalName string) string { + sum := sha256.Sum256([]byte(username + "\x00" + physicalName)) return "postgres-access-" + hex.EncodeToString(sum[:])[:16] } @@ -669,42 +587,13 @@ func newPostgresAccessResource(input CreatePostgresAccessInput, username, name s return res } -func WorkloadsForInstance(ctx context.Context, teamSlug slug.Slug, environmentName, postgresName, branchName string) []workload.Workload { - instance, err := GetPostgresBranch(ctx, teamSlug, environmentName, postgresName, branchName) - if err != nil { - return nil - } - postgres, err := GetPostgres(ctx, teamSlug, environmentName, instance.PostgresName) - if err != nil { - return nil - } - usesBranch := func(use liberatorv1.PostgresUse) bool { - return use.Name == instance.PostgresName && selectedBranchName(postgres, use) == branchName - } - return workloadsMatchingPostgresUse(ctx, teamSlug, environmentName, usesBranch) -} - func WorkloadsForPostgres(ctx context.Context, postgres *Postgres) []*PostgresWorkload { workloads := workloadsMatchingPostgresUse(ctx, postgres.TeamSlug, postgres.EnvironmentName, func(use liberatorv1.PostgresUse) bool { return use.Name == postgres.Name }) ret := make([]*PostgresWorkload, 0, len(workloads)) for _, current := range workloads { - var uses []liberatorv1.PostgresUse - switch current := current.(type) { - case *application.Application: - uses = current.Spec.Uses.Postgres - case *job.Job: - uses = current.Spec.Uses.Postgres - } - branchName := nais_io_v1.DefaultBranchName - for _, use := range uses { - if use.Name == postgres.Name { - branchName = selectedBranchName(postgres, use) - break - } - } - ret = append(ret, &PostgresWorkload{Workload: current, Postgres: postgres, BranchName: branchName}) + ret = append(ret, &PostgresWorkload{Workload: current, Postgres: postgres}) } return ret } diff --git a/internal/persistence/postgres/queries_test.go b/internal/persistence/postgres/queries_test.go index 36aadbd2f..cbe04b378 100644 --- a/internal/persistence/postgres/queries_test.go +++ b/internal/persistence/postgres/queries_test.go @@ -265,14 +265,14 @@ func TestUniquePostgresUses(t *testing.T) { wantErr string }{ { - name: "duplicate references to the same branch collapse", - uses: []liberatorv1.PostgresUse{{Name: "orders", Branch: "main"}, {Name: "orders", Branch: "main"}}, - want: []liberatorv1.PostgresUse{{Name: "orders", Branch: "main"}}, + name: "duplicate references collapse", + uses: []liberatorv1.PostgresUse{{Name: "orders"}, {Name: "orders"}}, + want: []liberatorv1.PostgresUse{{Name: "orders"}}, }, { - name: "one Postgres cannot reference multiple branches", - uses: []liberatorv1.PostgresUse{{Name: "orders", Branch: "main"}, {Name: "orders", Branch: "green"}}, - wantErr: "multiple branches for Postgres \"orders\"", + name: "distinct databases remain separate", + uses: []liberatorv1.PostgresUse{{Name: "orders"}, {Name: "archive"}}, + want: []liberatorv1.PostgresUse{{Name: "orders"}, {Name: "archive"}}, }, } for _, tt := range tests { @@ -297,7 +297,7 @@ func TestUniquePostgresUses(t *testing.T) { func TestNewPostgresAccessResource(t *testing.T) { expiresAt := time.Date(2026, time.September, 17, 12, 0, 0, 0, time.UTC) resource := newPostgresAccessResource(CreatePostgresAccessInput{ - Postgres: "orders", Branch: "main", + Postgres: "orders", TeamSlug: slug.Slug("team-a"), EnvironmentName: "dev", AccessLevel: PostgresAccessLevelReadWrite, @@ -523,7 +523,7 @@ func TestPostgresAccessConnectionDetails(t *testing.T) { } } -func TestPostgresAccessNameIsStablePerUserAndBranch(t *testing.T) { +func TestPostgresAccessNameIsStablePerUserAndDatabase(t *testing.T) { name := postgresAccessName("user@example.com", "orders-main-abc") if name != postgresAccessName("user@example.com", "orders-main-abc") { t.Error("name must be stable, so a second request for the same pair conflicts") @@ -531,11 +531,11 @@ func TestPostgresAccessNameIsStablePerUserAndBranch(t *testing.T) { for _, other := range []string{ postgresAccessName("other@example.com", "orders-main-abc"), postgresAccessName("user@example.com", "orders-recovered-abc"), - // Shifting the boundary between user and branch must not collide. + // Shifting the boundary between user and database must not collide. postgresAccessName("user@example.comorders", "-main-abc"), } { if other == name { - t.Errorf("different user/branch produced the same name %q", name) + t.Errorf("different user/database produced the same name %q", name) } } if errs := validation.IsDNS1123Subdomain(name); len(errs) > 0 { diff --git a/internal/persistence/postgres/sortfilter.go b/internal/persistence/postgres/sortfilter.go index d112e15dd..5047f9189 100644 --- a/internal/persistence/postgres/sortfilter.go +++ b/internal/persistence/postgres/sortfilter.go @@ -1,54 +1,11 @@ package postgres import ( - "context" "slices" - "strings" "github.com/nais/api/internal/graph/model" - "github.com/nais/api/internal/graph/sortfilter" ) func (f *TeamPostgresFilter) Matches(pg *Postgres) bool { return f == nil || (len(f.Environments) == 0 || slices.Contains(f.Environments, pg.EnvironmentName)) && model.MatchesLabelFilters(pg.Labels, f.Labels) } - -var SortFilterPostgresBranch = sortfilter.New[*PostgresBranch, PostgresBranchOrderField, *PostgresBranchFilter]() - -func init() { - SortFilterPostgresBranch.RegisterSort("NAME", func(ctx context.Context, a, b *PostgresBranch) int { - if a.Name != b.Name { - return strings.Compare(a.Name, b.Name) - } - return strings.Compare(a.PostgresName, b.PostgresName) - }, "ENVIRONMENT") - SortFilterPostgresBranch.RegisterSort("ENVIRONMENT", func(ctx context.Context, a, b *PostgresBranch) int { - return strings.Compare(a.EnvironmentName, b.EnvironmentName) - }, "NAME") - - SortFilterPostgresBranch.RegisterFilter(func(ctx context.Context, v *PostgresBranch, filter *PostgresBranchFilter) bool { - if filter.Name != "" { - if !strings.Contains(strings.ToLower(v.Name), strings.ToLower(filter.Name)) { - return false - } - } - - if len(filter.Environments) > 0 { - if !slices.Contains(filter.Environments, v.EnvironmentName) { - return false - } - } - - if len(filter.States) > 0 { - if !slices.Contains(filter.States, v.State) { - return false - } - } - - if !model.MatchesLabelFilters(v.Labels, filter.Labels) { - return false - } - - return true - }) -}