Skip to content
Open
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
12 changes: 11 additions & 1 deletion docs/GettingStarted.md
Original file line number Diff line number Diff line change
Expand Up @@ -2905,10 +2905,20 @@ Configure Feature Flags with environment variables or inside a `Datadog.configur

`DD_EXPERIMENTAL_FLAGGING_PROVIDER_ENABLED` and `c.open_feature.enabled` are deprecated. When neither stable setting is explicitly configured, the legacy value `true` selects `remote_config` and `false` disables Feature Flags.

The API key is sent only to the managed Datadog endpoint. A custom agentless URL is treated as opaque, and its query string is preserved without automatically adding `dd_env`.
Configuration polling sends the API key only to the managed Datadog endpoint. A custom agentless configuration URL is treated as opaque, and its query string is preserved without automatically adding `dd_env`.

Comment thread
leoromanovsky marked this conversation as resolved.
Resolved
Feature Flags respects `DD_TRACE_DEBUG` and outputs debugging diagnostics when it is enabled.

#### Event delivery with agentless configuration

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a blocker or anything - but is it maybe time to extract FFE documentation into a separate .md file?


When `c.feature_flags.configuration_source` is `agentless`, exposures and flag evaluations share one delivery route. The library prefers a local Agent or serverless relay that forwards EVP origin metadata; Datadog Agent 7.84.0 and later support this metadata. Otherwise, the library sends events directly to `https://event-platform-intake.<DD_SITE>`, authenticated with `DD_API_KEY`. Allow outbound HTTPS access to this host for direct delivery. If direct delivery is not configured, the library can still use an older Agent's advertised EVP endpoint. When `c.feature_flags.configuration_source` is `remote_config`, events are delivered only through the Agent.

Direct event delivery supports `https_proxy` or `HTTPS_PROXY` and `no_proxy` or `NO_PROXY`; lowercase variables take precedence. Proxy URLs must use `http://` or a bare `host:port`, including for HTTPS intake requests. An explicitly empty HTTPS proxy variable disables proxying. When neither HTTPS proxy variable is set, Ruby's standard HTTP proxy settings apply; prefer `http_proxy` because Ruby warns when using uppercase `HTTP_PROXY`. These HTTPS proxy settings apply to event delivery; agentless configuration polling uses Ruby's standard HTTP proxy settings. Event delivery does not follow redirects.

If the local route returns a 404 or 405 response, or a request fails before it is sent, the library resends that batch directly to Datadog one time, provided direct delivery is configured. If the local route encounters an ambiguous transport error, the library sends only later batches directly, so events the local route may have accepted are not duplicated. A 403, 429, or 5xx response keeps the local route and does not replay the batch.

After switching to direct delivery, the library keeps using it in that process until you reconfigure the library with `Datadog.configure`. If no usable local route is available and direct delivery is not configured, the library logs a warning once until reconfiguration, drops the batch, and retries local discovery on the next batch after a 30-second cooldown.

The provider requires `openfeature-sdk` 0.5.1 or later. It sends exposures, evaluation counts, and evaluation metrics from provider hooks, and earlier `openfeature-sdk` releases run no hooks. With an earlier release, flags still evaluate, Datadog receives no exposures or evaluation counts, and the provider logs one warning at initialization.

Exposures are sent only for evaluations that run the provider's hooks, which happens when the application evaluates through an OpenFeature client with the Datadog provider registered directly:
Expand Down
6 changes: 2 additions & 4 deletions lib/datadog/open_feature/agentless/transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,8 @@ def apply_custom_authentication(request)
username = uri.user
return unless username

request.basic_auth(
URI::RFC2396_PARSER.unescape(username),
URI::RFC2396_PARSER.unescape(uri.password.to_s),
)
parser = defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::DEFAULT_PARSER
request.basic_auth(parser.unescape(username), parser.unescape(uri.password.to_s))
end

def headers(etag)
Expand Down
17 changes: 14 additions & 3 deletions lib/datadog/open_feature/component.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require_relative "transport"
require_relative "transport/agentless"
require_relative "evaluation_engine"
require_relative "../core/utils/time"
require_relative "configuration/source"
Expand Down Expand Up @@ -51,14 +52,21 @@ def self.build(settings, agent_settings, resolution:, on_configuration_change:,
new(
settings,
agent_settings,
resolution: resolution,
on_configuration_change: on_configuration_change,
logger: logger,
telemetry: telemetry,
)
end

def initialize(settings, agent_settings, logger:, telemetry:, on_configuration_change: nil)
transport = Transport::HTTP.build(agent_settings: agent_settings, logger: logger)
def initialize(settings, agent_settings, logger:, telemetry:, on_configuration_change: nil,
resolution: Configuration::Source.resolve(settings))
if resolution.source == Configuration::Source::AGENTLESS
@event_transport = Transport::Agentless.new(
agent_settings: agent_settings, site: settings.site, api_key: settings.api_key, logger: logger,
)
end
transport = @event_transport || Transport::HTTP.build(agent_settings: agent_settings, logger: logger)
@worker = Exposures::Worker.new(settings: settings, transport: transport, telemetry: telemetry, logger: logger)

@engine = EvaluationEngine.new(telemetry: telemetry, logger: logger)
Expand Down Expand Up @@ -159,8 +167,11 @@ def shutdown!
@configuration_condition.broadcast
end

@event_transport&.shutdown!(timeout: 5)
Comment thread
leoromanovsky marked this conversation as resolved.
Resolved
@flag_eval_evp_writer&.request_stop
@worker.graceful_shutdown
@flag_eval_evp_writer&.stop
@event_transport&.close
# Symmetric teardown: drop any accumulated span-enrichment state and
# subscriptions (Ruby CLAUDE.md mandates closing resources).
@span_enrichment_hook&.shutdown
Expand Down Expand Up @@ -196,7 +207,7 @@ def create_flag_eval_evp_hook
return unless @settings.open_feature.evaluation_counts_enabled
return unless Hooks::FlagEvalEVPHook.available?

evp_transport = Transport::HTTP.build_flagevaluations(
evp_transport = @event_transport || Transport::HTTP.build_flagevaluations(
agent_settings: @agent_settings,
logger: @logger,
)
Expand Down
46 changes: 29 additions & 17 deletions lib/datadog/open_feature/exposures/worker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ class Worker
include Core::Workers::Queue
include Core::Workers::Polling

# Let the five-second agentless request timeout close sockets before forced termination.
GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS = 6
GRACEFUL_SHUTDOWN_EXTRA_SECONDS = 5
GRACEFUL_SHUTDOWN_WAIT_INTERVAL_SECONDS = 0.5

DEFAULT_FLUSH_INTERVAL_SECONDS = 30
DEFAULT_BUFFER_LIMIT = Buffer::DEFAULT_LIMIT
Expand Down Expand Up @@ -54,6 +55,9 @@ def stop(force_stop = false, timeout = Core::Workers::Polling::DEFAULT_SHUTDOWN_
end

def enqueue(event)
return false unless enabled?

start if forked?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Codex working with @sameerank:

[P2] Wake the restarted poller after the first child enqueue

This starts the restarted poller before the first child event is pushed. The poller can observe the new buffer while it is empty and enter its 30-second interval wait; the later buffer.push(event) does not signal that wait. A deterministic barrier around this ordering left the child event undelivered after 200 ms, and the existing shutdown path can hide the delay by waking the poller.

Please remember whether this enqueue performed the fork restart and, after its push succeeds, signal that restarted poller. Limiting the signal to this first post-fork path preserves ordinary batching behavior.

Executed validation

The baseline regression failed with 1,492 examples and one timeout. The candidate wakeup, together with the shutdown-race fix and a normal post-fork positive control, passed both OpenFeature dependency appraisals: 2,984 aggregate examples and zero failures.

unless buffer.push(event)
@logger.debug { "Feature Flags: exposure not queued: buffer closed" }
return false
Expand All @@ -74,24 +78,32 @@ def perform(*args)
end

def graceful_shutdown
return false unless enabled? || !run_loop?

self.enabled = false

started = Core::Utils::Time.get_time
wait_time = loop_base_interval + GRACEFUL_SHUTDOWN_EXTRA_SECONDS

loop do
break if buffer.empty? && !in_iteration?

sleep(GRACEFUL_SHUTDOWN_WAIT_INTERVAL_SECONDS)
break if Core::Utils::Time.get_time - started > wait_time
buffer.close
wait_time = if @transport.is_a?(Transport::HTTP)
loop_base_interval + GRACEFUL_SHUTDOWN_EXTRA_SECONDS
else
GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS
end

@logger.debug do
"Feature Flags: exposure worker stopping; queued=#{buffer.length}, " \
"upload_in_progress=#{!!in_iteration?}, wait_budget=#{wait_time}s"
end
stopped = stop(true, wait_time)
log_shutdown_outcome(wait_time)
stopped = stop(true)
@logger.debug("Feature Flags: exposure worker stopped") unless running?
stopped
ensure
self.enabled = false
end

def work_pending?
!buffer.empty?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: buffer.any?

end

protected

def after_fork
self.buffer = Buffer.new(@buffer_limit)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Comment from Codex working with @sameerank:

[P2] Keep teardown terminal across this fork reset

graceful_shutdown closes the buffer, but it does not set enabled = false until the blocking stop returns. If the first enqueue in a child races with teardown in that child, start if forked? can reach this after_fork, replace the closed buffer with an open one, and start another worker. A deterministic fork/thread regression returned true from that enqueue, sent one exposure after shutdown had returned, and left the replacement worker running.

Please record a terminal stop-requested state before closing or waiting, re-check it around the fork restart, and keep any replacement child buffer closed when teardown has begun. If restart creates a thread during the race, stop it after leaving the async lifecycle lock.

Executed validation

The baseline regression failed with 1,491 examples and one failure. A candidate fix with the lifecycle checks above, an ordinary post-fork positive control, and the separate first-delivery regression passed both OpenFeature dependency appraisals: 2,984 aggregate examples and zero failures.

end

private
Expand All @@ -106,11 +118,11 @@ def send_events(events, dropped)
end

payload = @batch_builder.payload_for(events)
@logger.debug { "Feature Flags: flushing #{events.size} exposure event(s) to the Datadog Agent" }
@logger.debug { "Feature Flags: flushing #{events.size} exposure event(s) to Datadog" }
response = @transport.send_exposures(payload)

if response&.ok?
@logger.debug { "Feature Flags: sent #{events.size} exposure event(s) to the Datadog Agent" }
@logger.debug { "Feature Flags: sent #{events.size} exposure event(s) to Datadog" }
else
@logger.debug do
"Feature Flags: exposure upload response was not OK; dropping #{events.size} exposure event(s) " \
Expand Down
24 changes: 16 additions & 8 deletions lib/datadog/open_feature/flag_evaluation/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ def enqueue(
runtime_default: nil, targeting_key: nil, attrs: nil, observe_full_evaluation_data: false,
features: Aggregator::NO_FEATURES, **_event
)
return if @stopped

start_background_thread if forked?

# Avoid snapshot work when the queue is already full.
Expand All @@ -109,8 +111,12 @@ def enqueue(
observe_full_evaluation_data: observe_full_evaluation_data,
features: features,
}
@queue.push(bounded_event, true)
@stop_mutex.synchronize { @stop_cond.signal }
@stop_mutex.synchronize do
return if @stopped
Comment thread
leoromanovsky marked this conversation as resolved.
Resolved

@queue.push(bounded_event, true)
@stop_cond.signal
end
start_background_thread unless running?
rescue ThreadError
# Report queue backpressure on the next flush.
Expand All @@ -120,25 +126,27 @@ def enqueue(
# Stop the background thread and flush remaining events. Wakes the worker out of its
# interruptible wait so the drain + final flush happen immediately (no up-to-10s delay).
def stop
@stop_mutex.synchronize do
@stopped = true
@stop_cond.broadcast
end

request_stop
return true if join(SHUTDOWN_TIMEOUT_SECONDS)

@logger.debug { "OpenFeature EVP: writer did not stop gracefully; terminating worker thread" }
terminate
end

def request_stop
@stop_mutex.synchronize do
@stopped = true
@stop_cond.broadcast
end
end

protected

def after_fork
@aggregator = Aggregator.new
@queue = SizedQueue.new(QUEUE_SIZE)
@stop_mutex = Mutex.new
@stop_cond = ConditionVariable.new
@stopped = false
@dropped_queue_overflow = 0
@dropped_pre_queue_overflow = 0
@context_truncated_counts = Hash.new(0)
Expand Down
156 changes: 156 additions & 0 deletions lib/datadog/open_feature/transport/agentless.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# frozen_string_literal: true

require_relative "../../core/encoding"
require_relative "../../core/evp"
require_relative "../../core/utils/time"
require_relative "http_client"

module Datadog
module OpenFeature
module Transport
# Component-owned route selection shared by both event writers.
Comment thread
leoromanovsky marked this conversation as resolved.
Resolved
class Agentless
DISCOVERY_TIMEOUT_SECONDS = 5
REQUEST_TIMEOUT_SECONDS = 5
RECOVERY_INTERVAL_SECONDS = 30
LOCAL_ROUTES = ["/evp_proxy/v4", "/evp_proxy/v2"].freeze

def initialize(agent_settings:, site:, api_key:, logger:)
@client = HTTPClient.new(agent_settings: agent_settings, site: site, api_key: api_key)
@logger = logger
@mutex = Mutex.new
@fork_mutex = Mutex.new
@route = nil
@recover_at = 0.0
@unavailable_warning_logged = false
@pid = Process.pid
@closed = false
@shutdown_deadline = nil
end

def send_exposures(payload)
send_batch("/api/v2/exposures", payload)
end

def send_flag_evaluations(payload)
send_batch("/api/v2/flagevaluation", payload)
end

def shutdown!(timeout:)
reset_after_fork
@shutdown_deadline = Core::Utils::Time.get_time + timeout
end

def close
@closed = true
end

private

def send_batch(path, payload)
encoded = Core::Encoding::JSONEncoder.encode(payload)
route = select_route
return Response.new unless route

response = send_once(route, path, encoded)
if route != :direct && (response.internal_error? || [404, 405].include?(response.code))
fallback = leave_local(route)
if fallback && (response.pre_send? || [404, 405].include?(response.code))
response = send_once(:direct, path, encoded)
end
end
@logger.debug { "OpenFeature EVP: batch dropped after delivery failure" } unless response.ok?
response
# Serialization and delivery failures must never interrupt flag evaluation or reveal event data.
rescue
@logger.debug { "OpenFeature EVP: batch dropped after internal delivery failure" }
Response.new
end

def send_once(route, path, encoded)
direct = route == :direct
@client.request(direct ? path : route.to_s + path,
payload: encoded, direct: direct, timeout: remaining(REQUEST_TIMEOUT_SECONDS))
end

def select_route
reset_after_fork
@mutex.synchronize do
return if @closed || remaining(REQUEST_TIMEOUT_SECONDS) <= 0
return @route if @route || Core::Utils::Time.get_time < @recover_at

info = @client.request("/info", timeout: remaining(DISCOVERY_TIMEOUT_SECONDS)).info
@route = compatible_route(info)
@route = :direct if !@route && @client.direct?
@route ||= local_route(info)
warn_unavailable unless @route
@recover_at = Core::Utils::Time.get_time + RECOVERY_INTERVAL_SECONDS unless @route
Comment thread
leoromanovsky marked this conversation as resolved.
Resolved
@route
end
end

def compatible_route(info)
return unless info

headers = info["evp_proxy_allowed_headers"]
return unless headers.is_a?(Array)

headers = headers.grep(String).map { |header| header.strip.downcase }
return unless HTTPClient::IDENTITY_HEADERS.keys.all? { |name| headers.include?(name.downcase) }
Comment thread
leoromanovsky marked this conversation as resolved.
Resolved

local_route(info)
end

def local_route(info)
endpoints = info && info["endpoints"]
return unless endpoints.is_a?(Array)

LOCAL_ROUTES.find { |path| endpoints.include?(path) || endpoints.include?(path + "/") }
end

def leave_local(route)
@mutex.synchronize do
return false if @closed

if @route == route
@route = @client.direct? ? :direct : nil
warn_unavailable unless @route
@recover_at = Core::Utils::Time.get_time + RECOVERY_INTERVAL_SECONDS unless @route
end
@route == :direct
end
end

def warn_unavailable
return if @unavailable_warning_logged || remaining(REQUEST_TIMEOUT_SECONDS) <= 0

@unavailable_warning_logged = true
@logger.warn("Feature Flags exposures and flag evaluations are being dropped: " \
"no usable local Agent EVP route is available, and direct delivery requires DD_API_KEY and a valid DD_SITE.")
end

def remaining(limit)
return 0 if @closed

deadline = @shutdown_deadline
deadline ? [limit, deadline - Core::Utils::Time.get_time].min : limit
end

def reset_after_fork
return if @pid == Process.pid

@fork_mutex.synchronize do
return if @pid == Process.pid

@mutex = Mutex.new
@route = nil
@recover_at = 0.0
@unavailable_warning_logged = false
@shutdown_deadline = nil
@pid = Process.pid
end
end
end
end
end
end
Loading
Loading