Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 additions & 13 deletions config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1009,19 +1009,26 @@ if geonames_source_file do
config :location, :geonames_source_file, geonames_source_file
end

if otlp_endpoint do
config :opentelemetry,
resource: Plausible.OpenTelemetry.resource_attributes(runtime_metadata),
span_processor: :batch,
traces_exporter: :otlp

config :opentelemetry_exporter,
otlp_protocol: :grpc,
otlp_endpoint: otlp_endpoint
else
config :opentelemetry,
sampler: :always_off,
traces_exporter: :none
cond do
otlp_endpoint ->
config :opentelemetry,
resource: Plausible.OpenTelemetry.resource_attributes(runtime_metadata),
span_processor: :batch,
traces_exporter: :otlp

config :opentelemetry_exporter,
otlp_protocol: :grpc,
otlp_endpoint: otlp_endpoint

config_env() in [:test, :ce_test] ->
config :opentelemetry,
traces_exporter: :none,
processors: [{:otel_simple_processor, %{}}]

true ->
config :opentelemetry,
sampler: :always_off,
traces_exporter: :none
end

beam_metrics_enabled? = get_bool_from_path_or_env(config_dir, "BEAM_METRICS_ENABLED", false)
Expand Down
22 changes: 22 additions & 0 deletions lib/plausible/open_telemetry.ex
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ defmodule Plausible.OpenTelemetry do
end
end

def add_site_attributes(site, credential) do
add_site_attributes(site)

if is_nil(credential.team_id), do: Tracer.set_attribute("plausible.team.id", site.team_id)
end

def add_user_attributes(user) do
case user do
%Plausible.Auth.User{} = user ->
Expand All @@ -52,6 +58,22 @@ defmodule Plausible.OpenTelemetry do
end
end

def add_credential_attributes(credential) do
{type, label} = credential_type_and_label(credential)

Tracer.set_attributes([
{"plausible.user.id", credential.user_id},
{"plausible.credential.type", type},
{"plausible.credential.id", credential.id},
{"plausible.credential.label", label}
])

if credential.team_id, do: Tracer.set_attribute("plausible.team.id", credential.team_id)
end

defp credential_type_and_label(%Plausible.Auth.ApiKey{} = api_key),
do: {"api_key", api_key.key_prefix}

# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/README.md#service
def resource_attributes(runtime_metadata) do
[
Expand Down
4 changes: 3 additions & 1 deletion lib/plausible_web/plugs/authorize_public_api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ defmodule PlausibleWeb.Plugs.AuthorizePublicAPI do

with {:ok, token} <- get_bearer_token(conn),
{:ok, api_key, limit_key, hourly_limit} <- find_api_key(conn, token, context),
Plausible.OpenTelemetry.add_credential_attributes(api_key),
:ok <- RateLimit.check_rate_limit(limit_key, hourly_limit) do
conn
|> assign(:current_credential, api_key)
Expand Down Expand Up @@ -144,7 +145,7 @@ defmodule PlausibleWeb.Plugs.AuthorizePublicAPI do
feature: Plausible.Billing.Feature.StatsAPI,
allow_consolidated_views: conn.private[:allow_consolidated_views]
) do
Plausible.OpenTelemetry.add_site_attributes(site)
Plausible.OpenTelemetry.add_site_attributes(site, api_key)
site = Plausible.Repo.preload(site, :completed_imports)
{:ok, assign(conn, :site, site)}
end
Expand Down Expand Up @@ -214,6 +215,7 @@ defmodule PlausibleWeb.Plugs.AuthorizePublicAPI do
feature: feature,
allow_consolidated_views: conn.private[:allow_consolidated_views]
) do
Plausible.OpenTelemetry.add_site_attributes(site, api_key)
{:ok, assign(conn, :site, site)}
end

Expand Down
109 changes: 109 additions & 0 deletions test/plausible_web/api_trace_attributes_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
defmodule PlausibleWeb.APITraceAttributesTest do
use PlausibleWeb.ConnCase, async: false

require Record

Record.defrecordp(:span, Record.extract(:span, from_lib: "opentelemetry/include/otel_span.hrl"))

require OpenTelemetry.Tracer, as: Tracer

setup do
:otel_simple_processor.set_exporter(:otel_exporter_pid, self())
:ok
end

describe "Stats API" do
test "traces the credential and site" do
user = new_user()
site = new_site(owner: user)
api_key = insert(:api_key, user: user, team: team_of(user))

attributes = trace_query(api_key, site, 200)

assert attributes["plausible.user.id"] == user.id
assert attributes["plausible.team.id"] == api_key.team_id
assert attributes["plausible.credential.type"] == "api_key"
assert attributes["plausible.credential.id"] == api_key.id
assert attributes["plausible.credential.label"] == api_key.key_prefix
assert attributes["plausible.site.id"] == site.id
end

test "traces the team of the site for a legacy API key" do
user = new_user()
site = new_site(owner: user)
api_key = insert(:api_key, user: user)

attributes = trace_query(api_key, site, 200)

assert attributes["plausible.team.id"] == site.team_id
end

test "does not trace the team of a site a legacy API key cannot access" do
api_key = insert(:api_key, user: new_user())
site = new_site()

attributes = trace_query(api_key, site, 401)

refute Map.has_key?(attributes, "plausible.team.id")
end

@tag :capture_log
test "traces the credential on rate-limited requests" do
user = new_user(team: [hourly_api_request_limit: 0])
site = new_site(owner: user)
api_key = insert(:api_key, user: user, team: team_of(user))

attributes = trace_query(api_key, site, 429)

assert attributes["plausible.user.id"] == user.id
assert attributes["plausible.credential.id"] == api_key.id
end
end

on_ee do
describe "Sites API" do
test "traces the credential on the sites list" do
user = new_user()
api_key = insert(:api_key, user: user, team: team_of(user), scopes: ["sites:read:*"])

attributes =
trace(fn ->
build_conn()
|> put_req_header("authorization", "Bearer #{api_key.key}")
|> get("/api/v1/sites")
|> json_response(200)
end)

assert attributes["plausible.user.id"] == user.id
assert attributes["plausible.team.id"] == api_key.team_id
assert attributes["plausible.credential.type"] == "api_key"
assert attributes["plausible.credential.id"] == api_key.id
assert attributes["plausible.credential.label"] == api_key.key_prefix
end
end
end

defp trace_query(api_key, site, status) do
trace(fn ->
build_conn()
|> put_req_header("authorization", "Bearer #{api_key.key}")
|> post("/api/v2/query", %{
"site_id" => site.domain,
"metrics" => ["visitors"],
"date_range" => "all"
})
|> json_response(status)
end)
end

defp trace(request) do
span_id =
Tracer.with_span "test request" do
request.()
OpenTelemetry.Span.span_id(Tracer.current_span_ctx())
end

assert_receive {:span, span(span_id: ^span_id, attributes: attributes)}
:otel_attributes.map(attributes)
end
end
2 changes: 2 additions & 0 deletions test/test_helper.exs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ if Mix.env() != :e2e_test do
FunWithFlags.enable(:annotations)

Ecto.Adapters.SQL.Sandbox.mode(Plausible.Repo, :manual)

:ok = :telemetry.detach({OpentelemetryPhoenix, :endpoint_start})
end

# warn about minio if it's included in tests but not running
Expand Down
Loading