using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using RudderSdk.Core.Models.ProjectStorage; namespace RudderSdk.Core; /// Project key-value storage (global, shared across players). public sealed class ProjectStorageService { private readonly RudderClient _client; internal ProjectStorageService(RudderClient client) => _client = client; /// Fetches one page of project storage items, optionally filtered by type. public Task GetAsync(string? type = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) { var query = Url.Query( ("types", type), ("limit", limit > 0 ? limit.ToString() : null), ("cursor", cursor)); return _client.SendAsync("GET", "/sdk/v1/project-storage" + query, cancellationToken); } /// Iterates over all project storage items, following the cursor pagination. public async IAsyncEnumerable ListAllAsync( string? type = null, int limit = 100, [EnumeratorCancellation] CancellationToken cancellationToken = default) { string? cursor = null; do { var page = await GetAsync(type, limit, cursor, cancellationToken).ConfigureAwait(false); if (page?.Items != null) { foreach (var item in page.Items) yield return item; } cursor = page?.NextCursor; } while (!string.IsNullOrEmpty(cursor)); } /// /// Saves (upserts) project storage items. When /// is null, a random one is generated. /// public Task SaveAsync(IEnumerable items, string? idempotencyKey = null, CancellationToken cancellationToken = default) => _client.SendAsync( "PUT", "/sdk/v1/project-storage", new UpdateProjectStorageRequest { IdempotencyKey = idempotencyKey ?? Guid.NewGuid().ToString(), Items = items?.ToList() ?? new List() }, cancellationToken); }