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: 31 additions & 2 deletions pkgs/sdk/server/src/Integrations/FileDataSourceBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using LaunchDarkly.Sdk.Server.Internal;
using LaunchDarkly.Sdk.Server.Internal.DataSources;
using LaunchDarkly.Sdk.Server.Internal.DataSystem;
using LaunchDarkly.Sdk.Server.Subsystems;

namespace LaunchDarkly.Sdk.Server.Integrations
Expand All @@ -16,13 +17,14 @@ namespace LaunchDarkly.Sdk.Server.Integrations
/// object to <see cref="ConfigurationBuilder.DataSource"/>.
/// </remarks>
/// <seealso cref="FileData"/>
public sealed class FileDataSourceBuilder : IComponentConfigurer<IDataSource>
public sealed class FileDataSourceBuilder : IComponentConfigurer<IDataSource>, IDataSourcePersistence
{
internal readonly List<string> _paths = new List<string>();
internal bool _autoUpdate = false;
internal FileDataTypes.IFileReader _fileReader = FlagFileReader.Instance;
internal Func<string, object> _parser = null;
internal bool _skipMissingPaths = false;
internal bool _shouldPersist = false;
internal FileDataTypes.DuplicateKeysHandling _duplicateKeysHandling = FileDataTypes.DuplicateKeysHandling.Throw;

/// <summary>
Expand Down Expand Up @@ -154,11 +156,38 @@ public FileDataSourceBuilder SkipMissingPaths(bool skipMissingPaths)
return this;
}

/// <summary>
/// Specifies whether the data system may write the file data to a persistent store.
/// </summary>
/// <remarks>
/// <para>
/// This applies when the file data source is an initializer or synchronizer of a data system
/// configured with <see cref="ConfigurationBuilder.DataSystem"/>, and that data system has a
/// persistent store in <see cref="DataSystemConfiguration.DataStoreMode.ReadWrite"/> mode. This option
/// is off by default: file data is not LaunchDarkly data, and writing it to a shared store would replace
/// the LaunchDarkly data that other clients read from it. The client serves file data from memory.
/// Set this to <c>true</c> to write the file data, including reloads, to the store.
/// </para>
/// <para>
/// This does not apply to a data source configured with <see cref="ConfigurationBuilder.DataSource"/>.
/// The data store configured there receives all data.
/// </para>
/// </remarks>
/// <param name="shouldPersist">true if the file data may be written to a persistent store</param>
/// <returns>the same factory object</returns>
public FileDataSourceBuilder ShouldPersist(bool shouldPersist)
{
_shouldPersist = shouldPersist;
return this;
}

bool IDataSourcePersistence.ShouldPersist => _shouldPersist;

/// <inheritdoc/>
public IDataSource Build(LdClientContext context)
{
return new FileDataSource(context.DataSourceUpdates, _fileReader, _paths, _autoUpdate,
_parser, _skipMissingPaths, _duplicateKeysHandling,
_parser, _skipMissingPaths, _duplicateKeysHandling, _shouldPersist,
context.Logger.SubLogger(LogNames.DataSourceSubLog));
}
}
Expand Down
39 changes: 37 additions & 2 deletions pkgs/sdk/server/src/Integrations/TestData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Threading.Tasks;
using LaunchDarkly.Logging;
using LaunchDarkly.Sdk.Server.Interfaces;
using LaunchDarkly.Sdk.Server.Internal.DataSystem;
using LaunchDarkly.Sdk.Server.Internal.Model;
using LaunchDarkly.Sdk.Server.Subsystems;

Expand Down Expand Up @@ -50,7 +51,7 @@ namespace LaunchDarkly.Sdk.Server.Integrations
/// </code>
/// </example>
/// <seealso cref="FileData"/>
public sealed class TestData : IComponentConfigurer<IDataSource>
public sealed class TestData : IComponentConfigurer<IDataSource>, IDataSourcePersistence
{
#region Private fields

Expand All @@ -62,6 +63,7 @@ public sealed class TestData : IComponentConfigurer<IDataSource>
private readonly Dictionary<string, FlagBuilder> _currentBuilders =
new Dictionary<string, FlagBuilder>();
private readonly List<DataSourceImpl> _instances = new List<DataSourceImpl>();
private volatile bool _shouldPersist = true;

#endregion

Expand Down Expand Up @@ -233,6 +235,37 @@ internal TestData UsePreconfiguredSegment(Segment segment)
return this;
}

/// <summary>
/// Specifies whether the data system may write the test data to a persistent store.
/// </summary>
/// <remarks>
/// <para>
/// This applies when the test data source is an initializer or synchronizer of a data system
/// configured with <see cref="ConfigurationBuilder.DataSystem"/>, and that data system has a
/// persistent store in <see cref="DataSystemConfiguration.DataStoreMode.ReadWrite"/> mode. By default,
/// the test data is written to the store. Set this to <c>false</c> to keep the test data, including
/// later updates, out of the store. The client still serves it from memory.
/// </para>
/// <para>
/// This does not apply to a data source configured with <see cref="ConfigurationBuilder.DataSource"/>.
/// The data store configured there receives all data.
/// </para>
/// <para>
/// Set this before creating the client. The data system reads the setting each time it starts the
/// test data source, which can also happen in a running client, for example after the source reports
/// that it is off.
/// </para>
/// </remarks>
/// <param name="shouldPersist">true if the test data may be written to a persistent store</param>
/// <returns>the same <see cref="TestData"/> instance</returns>
public TestData ShouldPersist(bool shouldPersist)
{
_shouldPersist = shouldPersist;
return this;
}

bool IDataSourcePersistence.ShouldPersist => _shouldPersist;

/// <summary>
/// Simulates a change in the data source status.
/// </summary>
Expand Down Expand Up @@ -284,7 +317,9 @@ internal FullDataSet<ItemDescriptor> MakeInitData()
DataModel.Segments,
new KeyedItems<ItemDescriptor>(_currentSegments.ToImmutableDictionary())
));
return new FullDataSet<ItemDescriptor>(b.ToImmutable());
// The data set carries the persistence flag as well as the configurer; see
// DataSourceUpdatesV2ToV1Adapter.
return new FullDataSet<ItemDescriptor>(b.ToImmutable(), _shouldPersist);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,8 @@ private bool ApplyFullChangeSetToLegacyStore(ChangeSet<ItemDescriptor> unsortedC
new[] { unsortedChangeset.EnvironmentId }));
}

return InitWithHeaders(new FullDataSet<ItemDescriptor>(unsortedChangeset.Data), headers);
return InitWithHeaders(new FullDataSet<ItemDescriptor>(unsortedChangeset.Data, unsortedChangeset.ShouldPersist),
headers);
}

private bool ApplyPartialChangeSetToLegacyStore(ChangeSet<ItemDescriptor> changeSet)
Expand Down
10 changes: 9 additions & 1 deletion pkgs/sdk/server/src/Internal/DataSources/FileDataSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ namespace LaunchDarkly.Sdk.Server.Internal.DataSources
internal sealed class FileDataSource : IDataSource
{
private readonly IDataSourceUpdates _dataSourceUpdates;
private readonly bool _shouldPersist;
private readonly List<string> _paths;
private readonly IDisposable _reloader;
private readonly FlagFileParser _parser;
Expand Down Expand Up @@ -53,14 +54,18 @@ internal sealed class FileDataSource : IDataSource
/// null to parse JSON only</param>
/// <param name="skipMissingPaths">true to skip missing files instead of failing the load</param>
/// <param name="duplicateKeysHandling">how to handle a key that appears in more than one file</param>
/// <param name="shouldPersist">whether the FDv2 data system may write the file data to a persistent
/// store</param>
/// <param name="logger">the destination for log output</param>
public FileDataSource(IDataSourceUpdates dataSourceUpdates, FileDataTypes.IFileReader fileReader,
List<string> paths, bool autoUpdate, Func<string, object> alternateParser, bool skipMissingPaths,
FileDataTypes.DuplicateKeysHandling duplicateKeysHandling,
bool shouldPersist,
Logger logger)
{
_logger = logger;
_dataSourceUpdates = dataSourceUpdates;
_shouldPersist = shouldPersist;
_paths = new List<string>(paths);
_parser = new FlagFileParser(alternateParser);
_dataMerger = new FlagFileDataMerger(duplicateKeysHandling);
Expand Down Expand Up @@ -192,10 +197,13 @@ private void LoadAll(bool isRetry)
}
}

// The data set carries the persistence flag as well as the configurer, so that a configurer
// that wraps this data source's builder still keeps file data out of a persistent store.
var allData = new FullDataSet<ItemDescriptor>(
ImmutableDictionary.Create<DataKind, KeyedItems<ItemDescriptor>>()
.SetItem(DataModel.Features, new KeyedItems<ItemDescriptor>(flags))
.SetItem(DataModel.Segments, new KeyedItems<ItemDescriptor>(segments))
.SetItem(DataModel.Segments, new KeyedItems<ItemDescriptor>(segments)),
_shouldPersist
);
_dataSourceUpdates.Init(allData);
_loadedValidData = true;
Expand Down
5 changes: 3 additions & 2 deletions pkgs/sdk/server/src/Internal/DataStores/DataStoreSorter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static FullDataSet<ItemDescriptor> SortAllCollections(FullDataSet<ItemDes
var kind = entry.Key;
dataOut.Add(kind, new KeyedItems<ItemDescriptor>(SortCollection(kind, entry.Value.Items)));
}
return new FullDataSet<ItemDescriptor>(dataOut);
return new FullDataSet<ItemDescriptor>(dataOut, allData.ShouldPersist);
}

/// <summary>
Expand All @@ -49,7 +49,8 @@ public static ChangeSet<ItemDescriptor> SortChangeset(ChangeSet<ItemDescriptor>
dataOut.Add(kind, new KeyedItems<ItemDescriptor>(SortCollection(kind, entry.Value.Items)));
}

return new ChangeSet<ItemDescriptor>(inSet.Type, inSet.Selector, dataOut, inSet.EnvironmentId);
return new ChangeSet<ItemDescriptor>(inSet.Type, inSet.Selector, dataOut, inSet.EnvironmentId,
shouldPersist: inSet.ShouldPersist);
}

private static IEnumerable<KeyValuePair<string, ItemDescriptor>> SortCollection(DataKind kind,
Expand Down
19 changes: 13 additions & 6 deletions pkgs/sdk/server/src/Internal/DataStores/InMemoryDataStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ internal class InMemoryDataStore : IDataStore, IDataStoreMetadata, ITransactiona

private volatile InitMetadata _metadata;

// The persistence indicator of the latest full or partial payload, exported with the data for store
// recovery. Like the data system spec, the store tracks a single, most recent indicator, not one per item.
private volatile bool _shouldPersist = true;

private readonly object _selectorLock = new object();
private Selector _selector;

Expand Down Expand Up @@ -107,10 +111,11 @@ public void Apply(ChangeSet<ItemDescriptor> changeSet)
switch (changeSet.Type)
{
case ChangeSetType.Full:
ApplyFullPayload(changeSet.Data, new InitMetadata(changeSet.EnvironmentId), changeSet.Selector);
ApplyFullPayload(changeSet.Data, new InitMetadata(changeSet.EnvironmentId), changeSet.Selector,
changeSet.ShouldPersist);
break;
case ChangeSetType.Partial:
ApplyPartialData(changeSet.Data, changeSet.Selector);
ApplyPartialData(changeSet.Data, changeSet.Selector, changeSet.ShouldPersist);
break;
case ChangeSetType.None:
break;
Expand All @@ -132,11 +137,11 @@ public void Dispose()

public void InitWithMetadata(FullDataSet<ItemDescriptor> data, InitMetadata metadata)
{
ApplyFullPayload(data.Data, metadata, Selector.Empty);
ApplyFullPayload(data.Data, metadata, Selector.Empty, data.ShouldPersist);
}

private void ApplyPartialData(IEnumerable<KeyValuePair<DataKind, KeyedItems<ItemDescriptor>>> data,
Selector selector)
Selector selector, bool shouldPersist)
{
lock (WriterLock)
{
Expand Down Expand Up @@ -165,11 +170,12 @@ private void ApplyPartialData(IEnumerable<KeyValuePair<DataKind, KeyedItems<Item

Items = itemsBuilder.ToImmutable();
Selector = selector;
_shouldPersist = shouldPersist;
}
}

private void ApplyFullPayload(IEnumerable<KeyValuePair<DataKind, KeyedItems<ItemDescriptor>>> data,
InitMetadata metadata, Selector selector)
InitMetadata metadata, Selector selector, bool shouldPersist)
{
var itemsBuilder =
ImmutableDictionary.CreateBuilder<DataKind, ImmutableDictionary<string, ItemDescriptor>>();
Expand All @@ -193,6 +199,7 @@ private void ApplyFullPayload(IEnumerable<KeyValuePair<DataKind, KeyedItems<Item
_metadata = metadata;
_initialized = true;
Selector = selector;
_shouldPersist = shouldPersist;
}
}

Expand All @@ -215,7 +222,7 @@ public FullDataSet<ItemDescriptor> ExportAll()
));
}

return new FullDataSet<ItemDescriptor>(builder.ToImmutable());
return new FullDataSet<ItemDescriptor>(builder.ToImmutable(), _shouldPersist);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,15 @@ private bool PollAvailabilityAfterOutage()
try
{
var externalData = externalCache.ExportAll();
if (!externalData.ShouldPersist)
{
// The memory store holds data from a source that does not request persistence,
// such as the file data source. That data must not reach the store, so the
// store is left as it is, and it has still recovered.
_log.Info("Not updating persistent store after outage, because the in-memory data is not to be persisted");
return true;
}

var serializedData = PersistentDataStoreConverter.ToSerializedFormat(externalData);
var e = InitCore(serializedData);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,29 @@ namespace LaunchDarkly.Sdk.Server.Internal.DataSystem
/// <summary>
/// Adapts an <see cref="IDataSourceUpdatesV2"/> to work with data sources expecting <see cref="IDataSourceUpdates"/>.
/// </summary>
/// <remarks>
/// <para>
/// The adapter is given the persistence flag of the source it serves, from the source's configurer, and
/// applies it to the change sets it creates from full data sets and upserts alike. A full data set can also
/// carry a flag of its own, which the SDK's file and test data sources set, so that their data stays out of
/// a persistent store even when another configurer wraps theirs. A change set is persisted only if both
/// flags allow it. An FDv1 upsert carries no flag, so it takes the flag of the last full data set, the data
/// it changes.
/// </para>
/// <para>
/// Change sets that an FDv2 source applies directly pass through with their own flag.
/// </para>
/// </remarks>
internal class DataSourceUpdatesV2ToV1Adapter : IDataSourceUpdates, IDataSourceUpdatesV2, IDataSourceUpdatesHeaders
{
private readonly IDataSourceUpdatesV2 _destination;
private readonly bool _shouldPersist;
private volatile bool _dataSetShouldPersist = true;

public DataSourceUpdatesV2ToV1Adapter(IDataSourceUpdatesV2 sink)
public DataSourceUpdatesV2ToV1Adapter(IDataSourceUpdatesV2 sink, bool shouldPersist = true)
{
_destination = sink;
_shouldPersist = shouldPersist;
}

public IDataStoreStatusProvider DataStoreStatusProvider => _destination.DataStoreStatusProvider;
Expand All @@ -42,7 +58,8 @@ public bool Upsert(DataStoreTypes.DataKind kind, string key, DataStoreTypes.Item
DataStoreTypes.ChangeSetType.Partial,
Subsystems.Selector.Empty,
data,
null
null,
shouldPersist: _shouldPersist && _dataSetShouldPersist
);

return _destination.Apply(changeSet);
Expand All @@ -63,12 +80,15 @@ public bool InitWithHeaders(DataStoreTypes.FullDataSet<DataStoreTypes.ItemDescri
?.FirstOrDefault();
}

_dataSetShouldPersist = allData.ShouldPersist;

// Convert FullDataSet to ChangeSet and call Apply
var changeSet = new DataStoreTypes.ChangeSet<DataStoreTypes.ItemDescriptor>(
DataStoreTypes.ChangeSetType.Full,
Subsystems.Selector.Empty,
allData.Data,
environmentId
environmentId,
shouldPersist: _shouldPersist && allData.ShouldPersist
);

return _destination.Apply(changeSet);
Expand Down
9 changes: 8 additions & 1 deletion pkgs/sdk/server/src/Internal/DataSystem/FDv2DataSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,15 @@ private static Func<IComponentConfigurer<IDataSource>, SourceFactory> FactoryWit
private static SourceFactory ToSourceFactory(IComponentConfigurer<IDataSource> dataSourceFactory,
LdClientContext clientContext)
{
// The data of a source whose configurer does not state otherwise is persisted. That includes the FDv1
// fallback synchronizer, whose data comes from LaunchDarkly, and a custom data source.
return (sink) =>
dataSourceFactory.Build(clientContext.WithDataSourceUpdates(new DataSourceUpdatesV2ToV1Adapter(sink)));
{
var shouldPersist = !(dataSourceFactory is IDataSourcePersistence persistence) ||

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.

Is there an obvious argument for doing it this way and not the inverse? The inverse being a sources not implementing the interface defaults to persist and sources must implement and opt out of persist?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This reply was written by an AI agent (Claude Code) working on behalf of @kinyoklion.

The code is that inverse: a configurer that does not implement IDataSourcePersistence is persisted, and a source opts out by implementing it. The file data source and test data implement it and default to ShouldPersist(false).

The reason is in the data system spec. DATASYSTEM v2 Requirement 1.1.7 says initializers MUST indicate whether data persistence is requested via the persist field of a returned Basis, and Requirement 1.2.8 says the same of synchronizers for a Basis or a Delta. The motivation under 1.1.7 is that not all data should be mirrored to a persistent store, only data that is "trusted" or "authoritative", and its examples are a file initializer that sets persist = false and a polling initializer that sets persist = true.

So the sources that carry local, non-authoritative data declare that they do not persist: the file data source, which the spec names, and test data, which is local data of the same kind. Everything else keeps persisting without having to declare anything: the FDv2 streaming and polling sources, the FDv1 fallback synchronizer, whose data also comes from LaunchDarkly, and a custom data source written against the existing IDataSource API, whose data the SDK always wrote to the store before this change. Defaulting the other way would make each of those opt in, and a custom source that predates the interface would silently stop being persisted.

persistence.ShouldPersist;
return dataSourceFactory.Build(
clientContext.WithDataSourceUpdates(new DataSourceUpdatesV2ToV1Adapter(sink, shouldPersist)));
};
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace LaunchDarkly.Sdk.Server.Internal.DataSystem
{
/// <summary>
/// Implemented by a data source configurer that states whether the FDv2 data system may write the
/// source's data to a persistent store.
/// </summary>
/// <remarks>
/// The data system reads this when it builds the source, and applies it to every full data set and
/// every upsert that the source delivers. A configurer that does not implement this interface
/// produces data that is persisted. The FDv1 data system does not use this: there, the data store
/// receives all data.
/// </remarks>
internal interface IDataSourcePersistence
{
/// <summary>
/// True if the data system may write the data from the sources built by this configurer to a
/// persistent store.
/// </summary>
bool ShouldPersist { get; }
}
}
Loading
Loading