-
Notifications
You must be signed in to change notification settings - Fork 12
Publish form count KPI metrics to CloudWatch #2821
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
theseanything
wants to merge
1
commit into
main
Choose a base branch
from
theseanything/publish-form-counts-to-cloudwatch
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| module Metrics | ||
| class FormCountService | ||
| class ExportError < StandardError; end | ||
|
|
||
| METRIC_NAME = "FormCount".freeze | ||
| METER_NAME = "forms-admin".freeze | ||
| METER_VERSION = "1.0".freeze | ||
| UNKNOWN_ORG = "Unknown".freeze | ||
| METRIC_STATES = %w[draft live archived].freeze | ||
|
|
||
| def publish_form_counts | ||
| metric_count = 0 | ||
|
|
||
| form_counts_by_org_and_state.each do |(org, state), count| | ||
| form_count_gauge.record(count, attributes: metric_attributes(org:, state:)) | ||
| metric_count += 1 | ||
| end | ||
|
|
||
| export_metrics! | ||
|
|
||
| Rails.logger.info "Published #{metric_count} form count metrics via OpenTelemetry" | ||
| rescue StandardError => e | ||
| Sentry.capture_exception(e) | ||
| raise | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def form_counts_by_org_and_state | ||
| totals = counted_form_totals | ||
| organisation_names.each { |org_name| ensure_all_metric_states(totals, org_name) } | ||
| ensure_all_metric_states(totals, UNKNOWN_ORG) if totals.keys.any? { |(org, _state)| org == UNKNOWN_ORG } | ||
| totals | ||
| end | ||
|
|
||
| def counted_form_totals | ||
| counts_by_org_and_state = Form | ||
| .where.not(state: :deleted) | ||
| .left_joins(group_form: { group: :organisation }) | ||
| .group(Organisation.arel_table[:name], Form.arel_table[:state], Organisation.arel_table[:internal]) | ||
| .count | ||
|
|
||
| counts_by_org_and_state.each_with_object(Hash.new(0)) do |((org_name, state, internal), count), totals| | ||
| next if internal == true # Skip internal organisations for metrics | ||
|
|
||
| totals[[org_name || UNKNOWN_ORG, metric_state(state)]] += count | ||
| end | ||
| end | ||
|
|
||
| def organisation_names | ||
| Organisation.where(internal: false).pluck(:name) | ||
| end | ||
|
|
||
| def ensure_all_metric_states(totals, org_name) | ||
| METRIC_STATES.each { |state| totals[[org_name, state]] += 0 } | ||
| end | ||
|
|
||
| def metric_state(state) | ||
| case state | ||
| when "live", "live_with_draft" then "live" | ||
| when "archived", "archived_with_draft" then "archived" | ||
| when "draft" then "draft" | ||
| end | ||
| end | ||
|
|
||
| def metric_attributes(org:, state:) | ||
| { | ||
| "Environment" => Settings.forms_env.downcase, | ||
| "Org" => org, | ||
| "State" => state, | ||
| } | ||
| end | ||
|
|
||
| def form_count_gauge | ||
| @form_count_gauge ||= meter.create_gauge( | ||
| METRIC_NAME, | ||
| unit: "1", | ||
| description: "Count of forms grouped by organisation and state", | ||
| ) | ||
| end | ||
|
|
||
| def meter | ||
| OpenTelemetry.meter_provider.meter(METER_NAME, version: METER_VERSION) | ||
| end | ||
|
|
||
| def export_metrics! | ||
| return if OpenTelemetry.meter_provider.metric_readers.empty? | ||
|
|
||
| result = OpenTelemetry.meter_provider.force_flush | ||
| return if result == OpenTelemetry::SDK::Metrics::Export::SUCCESS | ||
|
|
||
| raise ExportError, "OpenTelemetry metrics export failed with result code #{result}" | ||
| end | ||
|
theseanything marked this conversation as resolved.
|
||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| namespace :metrics do | ||
| desc "Export form counts as OpenTelemetry metrics grouped by organisation and state" | ||
| task export_form_counts: :environment do | ||
| Metrics::FormCountService.new.publish_form_counts | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| require "rails_helper" | ||
|
|
||
| RSpec.describe "metrics.rake", type: :task do | ||
| describe "metrics:export_form_counts" do | ||
| subject(:task) do | ||
| Rake::Task["metrics:export_form_counts"] | ||
| end | ||
|
|
||
| it "publishes form counts via Metrics::FormCountService" do | ||
| service = instance_double(Metrics::FormCountService) | ||
| allow(Metrics::FormCountService).to receive(:new).and_return(service) | ||
| expect(service).to receive(:publish_form_counts) | ||
|
|
||
| task.invoke | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| require "rails_helper" | ||
| require "opentelemetry-metrics-sdk" | ||
|
|
||
| describe Metrics::FormCountService do | ||
| subject(:service) { described_class.new } | ||
|
|
||
| let(:forms_env) { "test" } | ||
| let(:metric_exporter) { OpenTelemetry::SDK::Metrics::Export::InMemoryMetricPullExporter.new } | ||
| let(:organisation) { create(:organisation, name: "Department for Testing") } | ||
| let(:group) { create(:group, organisation:) } | ||
| let!(:original_meter_provider) { OpenTelemetry.meter_provider } | ||
|
|
||
| before do | ||
| allow(Settings).to receive(:forms_env).and_return(forms_env) | ||
|
|
||
| provider = OpenTelemetry::SDK::Metrics::MeterProvider.new | ||
| periodic_reader = OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader.new( | ||
| export_interval_millis: 60_000, | ||
| exporter: metric_exporter, | ||
| ) | ||
| provider.add_metric_reader(periodic_reader) | ||
| OpenTelemetry.meter_provider = provider | ||
| end | ||
|
|
||
| after do | ||
| OpenTelemetry.meter_provider.shutdown | ||
| OpenTelemetry.meter_provider = original_meter_provider | ||
| end | ||
|
|
||
| around do |example| | ||
| travel_to(Time.zone.local(2026, 6, 3, 12, 0, 0)) do | ||
| example.run | ||
| end | ||
| end | ||
|
|
||
| describe "#publish_form_counts" do | ||
| before do | ||
| Form.destroy_all | ||
|
|
||
| # Use explicit states instead of :live/:archived traits — those pull in :with_pages, | ||
| # and each page factory creates its own :form, inflating counts. | ||
| create(:form, :with_group, group:, state: :draft) | ||
| create(:form, :with_group, group:, state: :live, pages: []) | ||
| create(:form, :with_group, group:, state: :live_with_draft, pages: []) | ||
| create(:form, :with_group, group:, state: :archived, pages: []) | ||
| create(:form, :with_group, group:, state: :archived_with_draft, pages: []) | ||
| create(:form, state: :draft) | ||
| end | ||
|
|
||
| it "publishes grouped form counts via OpenTelemetry" do | ||
| service.publish_form_counts | ||
|
|
||
| expect(exported_data_points).to contain_exactly( | ||
| metric_data_point(org: organisation.name, state: "draft", count: 1), | ||
| metric_data_point(org: organisation.name, state: "live", count: 2), | ||
| metric_data_point(org: organisation.name, state: "archived", count: 2), | ||
| metric_data_point(org: "Unknown", state: "draft", count: 1), | ||
| metric_data_point(org: "Unknown", state: "live", count: 0), | ||
| metric_data_point(org: "Unknown", state: "archived", count: 0), | ||
| ) | ||
| end | ||
|
|
||
| context "when an organisation has no forms" do | ||
| let(:empty_organisation) { create(:organisation, name: "Empty Org", slug: "empty-org") } | ||
|
|
||
| before { empty_organisation } | ||
|
|
||
| it "publishes zero counts for each state" do | ||
| service.publish_form_counts | ||
|
|
||
| expect(exported_data_points).to contain_exactly( | ||
| metric_data_point(org: organisation.name, state: "draft", count: 1), | ||
| metric_data_point(org: organisation.name, state: "live", count: 2), | ||
| metric_data_point(org: organisation.name, state: "archived", count: 2), | ||
| metric_data_point(org: empty_organisation.name, state: "draft", count: 0), | ||
| metric_data_point(org: empty_organisation.name, state: "live", count: 0), | ||
| metric_data_point(org: empty_organisation.name, state: "archived", count: 0), | ||
| metric_data_point(org: "Unknown", state: "draft", count: 1), | ||
| metric_data_point(org: "Unknown", state: "live", count: 0), | ||
| metric_data_point(org: "Unknown", state: "archived", count: 0), | ||
| ) | ||
| end | ||
| end | ||
|
|
||
| context "when an organisation is internal" do | ||
| let(:internal_organisation) { create(:organisation, name: "Internal Org", slug: "internal-org", internal: true) } | ||
| let(:internal_group) { create(:group, organisation: internal_organisation) } | ||
|
|
||
| before do | ||
| create(:form, :with_group, group: internal_group, state: :draft) | ||
| create(:form, :with_group, group: internal_group, state: :live, pages: []) | ||
| end | ||
|
|
||
| it "excludes forms belonging to internal organisations" do | ||
| service.publish_form_counts | ||
|
|
||
| expect(exported_data_points).to contain_exactly( | ||
| metric_data_point(org: organisation.name, state: "draft", count: 1), | ||
| metric_data_point(org: organisation.name, state: "live", count: 2), | ||
| metric_data_point(org: organisation.name, state: "archived", count: 2), | ||
| metric_data_point(org: "Unknown", state: "draft", count: 1), | ||
| metric_data_point(org: "Unknown", state: "live", count: 0), | ||
| metric_data_point(org: "Unknown", state: "archived", count: 0), | ||
| ) | ||
| end | ||
| end | ||
|
|
||
| context "when OpenTelemetry export fails" do | ||
| before do | ||
| allow(OpenTelemetry.meter_provider).to receive(:force_flush) | ||
| .and_return(OpenTelemetry::SDK::Metrics::Export::FAILURE) | ||
| end | ||
|
|
||
| it "captures the exception and re-raises" do | ||
| expect(Sentry).to receive(:capture_exception).with(instance_of(Metrics::FormCountService::ExportError)) | ||
|
|
||
| expect { service.publish_form_counts }.to raise_error(Metrics::FormCountService::ExportError) | ||
| end | ||
| end | ||
| end | ||
|
|
||
| def exported_data_points | ||
| metric_exporter.metric_snapshots.flat_map(&:data_points) | ||
| end | ||
|
|
||
| def metric_data_point(org:, state:, count:) | ||
| have_attributes( | ||
| attributes: { | ||
| "Environment" => forms_env, | ||
| "Org" => org, | ||
| "State" => state, | ||
| }, | ||
| value: count, | ||
| ) | ||
| end | ||
| end |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.