Module: LaunchDarkly::Integrations::FileData

Defined in:
lib/ldclient-rb/integrations/file_data.rb

Overview

Provides a way to use local files as a source of feature flag state. This allows using a predetermined feature flag state without an actual LaunchDarkly connection.

Reading flags from a file is only intended for pre-production environments. Production environments should always be configured to receive flag updates from LaunchDarkly.

To use this component, call FileData.data_source, and store its return value in the Config#data_source property of your LaunchDarkly client configuration. In the options to data_source, set paths to the file path(s) of your data file(s):

file_source = LaunchDarkly::Integrations::FileData.data_source(paths: [ myFilePath ])
config = LaunchDarkly::Config.new(data_source: file_source)

This will cause the client not to connect to LaunchDarkly to get feature flags. The client may still make network connections to send analytics events, unless you have disabled this with Config#send_events or Config#offline?.

Flag data files can be either JSON or YAML. They contain an object with three possible properties:

  • flags: Feature flag definitions.
  • flagValues: Simplified feature flags that contain only a value.
  • segments: Context segment definitions.

The format of the data in flags and segments is defined by the LaunchDarkly application and is subject to change. Rather than trying to construct these objects yourself, it is simpler to request existing flags directly from the LaunchDarkly server in JSON format, and use this output as the starting point for your file. In Linux you would do this:

    curl -H "Authorization: YOUR_SDK_KEY" https://sdk.launchdarkly.com/sdk/latest-all

The output will look something like this (but with many more properties):

{
  "flags": {
    "flag-key-1": {
      "key": "flag-key-1",
      "on": true,
      "variations": [ "a", "b" ]
    }
  },
  "segments": {
    "segment-key-1": {
      "key": "segment-key-1",
      "included": [ "user-key-1" ]
    }
  }
}

Data in this format allows the SDK to exactly duplicate all the kinds of flag behavior supported by LaunchDarkly. However, in many cases you will not need this complexity, but will just want to set specific flag keys to specific values. For that, you can use a much simpler format:

{
  "flagValues": {
    "my-string-flag-key": "value-1",
    "my-boolean-flag-key": true,
    "my-integer-flag-key": 3
  }
}

Or, in YAML:

flagValues:
  my-string-flag-key: "value-1"
  my-boolean-flag-key: true
  my-integer-flag-key: 1

It is also possible to specify both "flags" and "flagValues", if you want some flags to have simple values and others to have complex behavior. However, it is an error to use the same flag key or segment key more than once, either in a single file or across multiple files.

If the data source encounters any error in any file-- malformed content, a missing file, or a duplicate key-- it will not load flags from any of the files.

The same file format serves the file-based override source, FileData.override_source, which supplies flag and segment overrides that take precedence over LaunchDarkly data instead of replacing the connection to LaunchDarkly. Flag overrides are currently experimental and subject to change.

Class Method Summary collapse

Class Method Details

.data_source(options = {}) ⇒ Object

Returns a factory for the file data source component.

Parameters:

  • options (Hash) (defaults to: {}) —

    the configuration options

Options Hash (options):

  • :paths (Array) —

    The paths of the source files for loading flag data. These may be absolute paths or relative to the current working directory.

  • :auto_update (Boolean) —

    True if the data source should watch for changes to the source file(s) and reload flags whenever there is a change. Auto-updating will only work if all of the files you specified have valid directory paths at startup time. Note that the default implementation of this feature is based on polling the filesystem, which may not perform well. If you install the 'listen' gem (not included by default, to avoid adding unwanted dependencies to the SDK), its native file watching mechanism will be used instead.

  • :poll_interval (Float) —

    The minimum interval, in seconds, between checks for file modifications - used only if auto_update is true, and if the native file-watching mechanism from 'listen' is not being used. The default value is 1 second.

Returns:



110
111
112
113
# File 'lib/ldclient-rb/integrations/file_data.rb', line 110

def self.data_source(options={})
  lambda { |sdk_key, config|
    Impl::Integrations::FileDataSourceImpl.new(config.feature_store, config.data_source_update_sink, config.logger, options) }
end

.data_source_v2(options = {}) ⇒ FileDataSourceV2Builder

Returns a builder for the FDv2-compatible file data source.

This method returns a builder proc that can be used with the FDv2 data system configuration as both an Initializer and a Synchronizer. When used as an Initializer (via fetch), it reads files once. When used as a Synchronizer (via sync), it watches for file changes and automatically updates when files are modified.

Examples:

Using as an initializer

file_source = LaunchDarkly::Integrations::FileData.data_source_v2(paths: ['flags.json'])
data_system_config = LaunchDarkly::DataSystemConfig.new(
  initializers: [file_source]
)
config = LaunchDarkly::Config.new(data_system_config: data_system_config)

Using as a synchronizer

file_source = LaunchDarkly::Integrations::FileData.data_source_v2(paths: ['flags.json'])
data_system_config = LaunchDarkly::DataSystemConfig.new(
  synchronizers: [file_source]
)
config = LaunchDarkly::Config.new(data_system_config: data_system_config)

Using as both initializer and synchronizer

file_source = LaunchDarkly::Integrations::FileData.data_source_v2(paths: ['flags.json'])
data_system_config = LaunchDarkly::DataSystemConfig.new(
  initializers: [file_source],
  synchronizers: [file_source]
)
config = LaunchDarkly::Config.new(data_system_config: data_system_config)

Parameters:

  • options (Hash) (defaults to: {}) —

    the configuration options

Options Hash (options):

  • :paths (Array<String>, String) —

    The paths of the source files for loading flag data. These may be absolute paths or relative to the current working directory. (Required)

  • :poll_interval (Float) —

    The minimum interval, in seconds, between checks for file modifications - used only if the native file-watching mechanism from 'listen' is not being used. The default value is 1 second.

Returns:



153
154
155
156
157
158
# File 'lib/ldclient-rb/integrations/file_data.rb', line 153

def self.data_source_v2(options = {})
  paths = options[:paths] || []
  poll_interval = options[:poll_interval] || 1

  FileDataSourceV2Builder.new(paths, poll_interval)
end

.override_source(options = {}) ⇒ FileOverrideSourceBuilder

Returns a builder for a file-based override source. Flag overrides are currently experimental and subject to change.

Overrides are flag and segment definitions that take precedence over data received from LaunchDarkly at evaluation time, on a per-key basis. They exist for resilience during an incident. An operator can force one or more flags to a known state on a running application, whether or not the application can reach LaunchDarkly, by writing them to a file. The override stays in effect until it is removed from the file. Flags not present in the files are completely unaffected.

The files use the same document format as the file data source: a JSON or YAML document with optional flags, flagValues, and segments members. A flagValues entry expands into a flag that is on and serves the given value as its fallthrough for every context. Such a flag is not available to client-side SDKs, so all_flags_state with client_side_only: true leaves it out, even when the flag it overrides is available to them. To override such a flag, define it in flags with "clientSide": true. When several files are configured, their entries are combined in the configured order, and the duplicate keys handling decides what happens when the same key appears in more than one file.

A file whose name ends in .yaml or .yml, in any case, is read as YAML, and any other file is read as JSON. Files must be UTF-8. Whether a JSON file may contain comments or repeated keys depends on the application's version of the json gem.

A reload replaces the entire set of overrides, so removing an entry from a file removes the override. A configured file that does not exist contributes no overrides. It can be created later, and deleting a file removes its overrides. A file that exists but cannot be read or parsed fails that whole reload. The previously loaded overrides stay in effect, the failure is logged, and the source retries after a short delay and recovers on its own once the file is readable. A file that contains an entry marked as deleted fails to load, and the overrides in effect stay; to remove an override, remove its entry or delete the file. Whenever the set of overrides in effect changes, including at startup, the source logs the overrides in effect and what each file supplied, at Info level.

Files can be rewritten in place: if the source finds a file empty while it is being rewritten, it keeps the overrides in effect until the new content is written. To remove a file's overrides, delete the file or write a document with no entries, such as {}. An empty JSON file is not a valid document. For a YAML file, replacing its contents in one operation, such as by renaming a fully written temporary file over it, avoids briefly applying a partly written file.

An evaluation that an override affects, directly or through a prerequisite or segment, is marked: its reason reports EvaluationReason#override_affected, it produces no individual analytics event, and it is counted under a separate summary counter.

Pass the returned builder to DataSystem::ConfigBuilder#overrides. The configuration is validated when the client is created, and an invalid configuration raises ArgumentError from LDClient.new.

Examples:

overrides = LaunchDarkly::Integrations::FileData.override_source(paths: ["/etc/launchdarkly/overrides.json"])
config = LaunchDarkly::Config.new(data_system_config: LaunchDarkly::DataSystem.default.overrides(overrides).build)
client = LaunchDarkly::LDClient.new(sdk_key, config)

Parameters:

  • options (Hash) (defaults to: {}) —

    the configuration options

Options Hash (options):

  • :paths (Array<String>, String) —

    One or more files, in precedence order. Required. Each path must be a non-empty String, absolute or relative to the current working directory.

  • :duplicate_keys_handling (Symbol) —

    What to do when the same key appears in more than one file. :fail (the default) treats the reload as failed and keeps the previous overrides. :ignore keeps the entry from the first configured file that defines the key.

  • :change_detection (Symbol) —

    How the source detects file changes. :polling (the default) examines the files on an interval and works on every file system, including network mounts and directories whose contents are swapped through symbolic links. :watching uses file system change notifications through the listen gem, which the host application must provide. Watching follows edits to the configured files and to the targets of configured symbolic links, including the update of a mounted Kubernetes ConfigMap. It does not follow a deployment that points a link further along the path, or a configured directory, at another location, such as a current link to a release directory, or that replaces a configured directory. Use polling for such deployments.

  • :poll_interval (Numeric) —

    Seconds between examinations of the files in polling mode. The default is 1. An interval below 1 is raised to 1 with a warning.

Returns:



233
234
235
# File 'lib/ldclient-rb/integrations/file_data.rb', line 233

def self.override_source(options = {})
  FileOverrideSourceBuilder.new(options)
end