Skip to content

Commit

Permalink
Add prometheus collector for oldest OS Places postcode
Browse files Browse the repository at this point in the history
  • Loading branch information
KludgeKML committed Oct 2, 2023
1 parent 01b02f6 commit 7bad3f2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 18 deletions.
27 changes: 9 additions & 18 deletions lib/collectors/global_prometheus_collector.rb
Original file line number Diff line number Diff line change
@@ -1,37 +1,28 @@
require "prometheus_exporter"
require "prometheus_exporter/server"

# Load Rails models as not automatically included for Prometheus Exporter
require File.expand_path("../../config/environment", __dir__) unless defined? Rails

module Collectors
class GlobalPrometheusCollector < PrometheusExporter::Server::TypeCollector
SECONDS_PER_DAY = 86_400

def type
"locations_api_global"
end

def metrics
oldest_postcode = PrometheusExporter::Metric::Gauge.new("locations_api_postcode_oldest_timestamp_seconds", "Timestamp of update of oldest postcode served")
oldest_postcode.observe(get_oldest_postcode_served)
oldest_os_places_postcode = PrometheusExporter::Metric::Gauge.new("locations_api_oldest_os_places_postcode_age_days", "Days since last update of oldest postcode OS Places postcode")
oldest_os_places_postcode.observe(get_oldest_postcode / SECONDS_PER_DAY)

[oldest_postcode]
[oldest_os_places_postcode]
end

private

def token_expiry_info
def get_oldest_postcode
# Cache metric to prevent needless expensive calls to the database
Rails.cache.fetch("token_expiry_info", expires_in: 1.hour) do
ApiUser.all.flat_map do |user|
user.authorisations.where(revoked_at: nil).map do |token|
{
expires_at: token.expires_at.to_i,
api_user: user.email,
application_name: token.application.name.parameterize,
}
end
end
Rails.cache.fetch("metrics:oldest_postcode", expires_in: 1.hour) do
(Time.zone.now.to_i - Postcode.os_places.order(updated_at: :asc).first.updated_at.to_i)
end
end
end
end
end
26 changes: 26 additions & 0 deletions spec/lib/collectors/global_prometheus_collector_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require "spec_helper"

RSpec.describe Collectors::GlobalPrometheusCollector do
before do
@collector = Collectors::GlobalPrometheusCollector.new
Rails.cache.delete("metrics:oldest_postcode")
end

describe "#type" do
it "has the correct value" do
expect(@collector.type).to eq("locations_api_global")
end
end

describe "#metrics" do
before do
@postcode = Postcode.create!(postcode: "E18QS", updated_at: Time.zone.now - 2.days)
end

it "records the time in days since the oldest postcode's update timestamp" do
metrics = @collector.metrics

expect(metrics.first.data.first.last).to eq(2)
end
end
end

0 comments on commit 7bad3f2

Please sign in to comment.