From 332d19b815f21575e96bfb80733aec869a53329a Mon Sep 17 00:00:00 2001
From: Bojan Marjanovic <bmarjanovic@gitlab.com>
Date: Wed, 16 Oct 2024 16:45:23 +0000
Subject: [PATCH] Add OrphanedNamespacesMetric

---
 .../20241014113429_orphaned_namespaces.yml    | 19 +++++++++++++++++++
 .../orphaned_namespaces_metric.rb             | 18 ++++++++++++++++++
 .../orphaned_namespaces_metric_spec.rb        |  9 +++++++++
 3 files changed, 46 insertions(+)
 create mode 100644 config/metrics/counts_all/20241014113429_orphaned_namespaces.yml
 create mode 100644 lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric.rb
 create mode 100644 spec/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric_spec.rb

diff --git a/config/metrics/counts_all/20241014113429_orphaned_namespaces.yml b/config/metrics/counts_all/20241014113429_orphaned_namespaces.yml
new file mode 100644
index 0000000000000..f1073eab007e6
--- /dev/null
+++ b/config/metrics/counts_all/20241014113429_orphaned_namespaces.yml
@@ -0,0 +1,19 @@
+---
+key_path: counts.orphaned_namespaces
+description: Whether orphaned namespaces are present
+product_group: tenant_scale
+value_type: number
+status: active
+milestone: "17.6"
+instrumentation_class: OrphanedNamespacesMetric
+introduced_by_url: https://gitlab.com/gitlab-org/gitlab/-/merge_requests/168983
+time_frame: all
+data_source: database
+data_category: optional
+distribution:
+- ce
+- ee
+tier:
+- free
+- premium
+- ultimate
diff --git a/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric.rb b/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric.rb
new file mode 100644
index 0000000000000..f8dd70b440c86
--- /dev/null
+++ b/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module Gitlab
+  module Usage
+    module Metrics
+      module Instrumentations
+        class OrphanedNamespacesMetric < GenericMetric
+          value do
+            ::Namespace
+              .where.not(parent_id: nil)
+              .where('NOT EXISTS(SELECT 1 FROM namespaces p WHERE p.id = namespaces.parent_id)')
+              .exists?
+          end
+        end
+      end
+    end
+  end
+end
diff --git a/spec/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric_spec.rb b/spec/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric_spec.rb
new file mode 100644
index 0000000000000..5c8d8d858014d
--- /dev/null
+++ b/spec/lib/gitlab/usage/metrics/instrumentations/orphaned_namespaces_metric_spec.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+require 'spec_helper'
+
+RSpec.describe Gitlab::Usage::Metrics::Instrumentations::OrphanedNamespacesMetric, feature_category: :service_ping do
+  let(:expected_value) { false }
+
+  it_behaves_like 'a correct instrumented metric value', { time_frame: 'all', data_source: 'database' }
+end
-- 
GitLab