| | | 1 | | using System.Data.Common; |
| | | 2 | | using System.Diagnostics; |
| | | 3 | | using System.Text; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.DurableFlows.Internal; |
| | | 7 | | |
| | | 8 | | internal static class DurableFlowStoreShared |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Rows one prune statement deletes. Every relational store deletes in batches of this size: |
| | | 12 | | /// an unbatched DELETE over a large expired backlog holds row locks and bloats one transaction |
| | | 13 | | /// for the unlucky create that triggered the prune. |
| | | 14 | | /// </summary> |
| | | 15 | | public const int PruneBatchSize = 1000; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// The default <c>PruneBudget</c>: wall-clock time one opportunistic prune may spend draining |
| | | 19 | | /// batches after the first. Two seconds at ~1000 rows per batch drains tens of thousands of |
| | | 20 | | /// expired rows per interval on an ordinary database, against the ~3 rows/second a single |
| | | 21 | | /// batch per five-minute interval sustained — which any instance creating more than that fell |
| | | 22 | | /// behind forever. |
| | | 23 | | /// </summary> |
| | 2 | 24 | | public static readonly TimeSpan DefaultPruneBudget = TimeSpan.FromSeconds(2); |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Runs an opportunistic prune so that its failure never fails the primitive it rides on, |
| | | 28 | | /// draining <see cref="PruneBatchSize"/>-row batches until a batch comes back short (the |
| | | 29 | | /// backlog is gone) or <paramref name="budget"/> lapses. The first batch always runs, so a |
| | | 30 | | /// zero budget is the historical single-batch policy. Awaited bare inside |
| | | 31 | | /// <c>TryCreateAsync</c>, a prune chosen as the deadlock victim (1205) or hitting a lock-wait |
| | | 32 | | /// timeout against the store's own live checkpoint traffic failed <c>StartAsync</c> for a flow |
| | | 33 | | /// whose row would have been created without incident — and <see cref="ShouldPrune"/> had |
| | | 34 | | /// already consumed the interval, so it was not retried either. Loads filter on expiry, so a |
| | | 35 | | /// skipped prune costs nothing but disk until the next interval. The outcome is never silent: |
| | | 36 | | /// deleted rows, a lapsed budget with rows remaining, and failures are counted on the |
| | | 37 | | /// <c>AsyncResponse</c> meter and logged when the store has a logger. Cancellation still |
| | | 38 | | /// propagates. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <param name="pruneBatch">Deletes one batch and returns the rows it deleted.</param> |
| | | 41 | | /// <param name="budget">Wall-clock budget for batches after the first.</param> |
| | | 42 | | /// <param name="providerName">Metric/log tag for the store ("PostgreSQL", "SQL Server", …).</param> |
| | | 43 | | /// <param name="logger">The store's logger when DI supplied one.</param> |
| | | 44 | | public static async Task PruneQuietlyAsync(Func<Task<int>> pruneBatch, TimeSpan budget, string providerName, ILogger |
| | | 45 | | { |
| | 8 | 46 | | var started = Stopwatch.GetTimestamp(); |
| | 8 | 47 | | var deleted = 0L; |
| | 8 | 48 | | var batches = 0; |
| | | 49 | | try |
| | | 50 | | { |
| | | 51 | | while (true) |
| | | 52 | | { |
| | 8 | 53 | | var batchDeleted = await pruneBatch().ConfigureAwait(false); |
| | 0 | 54 | | batches++; |
| | 0 | 55 | | deleted += Math.Max(batchDeleted, 0); |
| | 0 | 56 | | if (batchDeleted < PruneBatchSize) |
| | | 57 | | break; |
| | | 58 | | |
| | 0 | 59 | | if (Stopwatch.GetElapsedTime(started) >= budget) |
| | | 60 | | { |
| | 0 | 61 | | AsyncResponseDiagnostics.RecordFlowStatePruneBudgetExhausted(providerName); |
| | 0 | 62 | | logger?.LogWarning( |
| | 0 | 63 | | "{Provider} durable-flow prune deleted {Deleted} expired rows in {Batches} batches and stopped a |
| | 0 | 64 | | providerName, deleted, batches, budget); |
| | | 65 | | break; |
| | | 66 | | } |
| | | 67 | | } |
| | | 68 | | |
| | 0 | 69 | | AsyncResponseDiagnostics.RecordFlowStatePruned(providerName, deleted); |
| | 0 | 70 | | } |
| | 4 | 71 | | catch (OperationCanceledException) |
| | | 72 | | { |
| | 4 | 73 | | AsyncResponseDiagnostics.RecordFlowStatePruned(providerName, deleted); |
| | 4 | 74 | | throw; |
| | | 75 | | } |
| | 4 | 76 | | catch (Exception ex) |
| | | 77 | | { |
| | | 78 | | // Opportunistic maintenance; the next interval retries — but never silently. |
| | 4 | 79 | | AsyncResponseDiagnostics.RecordFlowStatePruned(providerName, deleted); |
| | 4 | 80 | | AsyncResponseDiagnostics.RecordFlowStatePruneFailure(providerName); |
| | 4 | 81 | | logger?.LogWarning( |
| | 4 | 82 | | ex, |
| | 4 | 83 | | "{Provider} durable-flow prune failed after deleting {Deleted} expired rows in {Batches} batches; the fl |
| | 4 | 84 | | providerName, deleted, batches); |
| | 4 | 85 | | } |
| | 4 | 86 | | } |
| | | 87 | | |
| | | 88 | | /// <summary>A <c>PruneBudget</c> is a non-negative duration; zero means a single batch per interval.</summary> |
| | | 89 | | public static void ValidatePruneBudget(TimeSpan budget, string optionsName) |
| | | 90 | | { |
| | 0 | 91 | | if (budget < TimeSpan.Zero) |
| | 0 | 92 | | throw new InvalidOperationException($"{optionsName}.PruneBudget cannot be negative (zero limits each prune t |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | /// <summary> |
| | | 96 | | /// Upper bound for TTL values handed to server-clock date arithmetic (~68 years). SQL Server's |
| | | 97 | | /// <c>DATEADD</c> takes <c>int</c> seconds, and MySQL/Oracle datetime types stop at year 9999, |
| | | 98 | | /// so an absurd <see cref="DurableFlowOptions.StateExpiry"/> (for example |
| | | 99 | | /// <see cref="TimeSpan.MaxValue"/>) would overflow inside the database. Clamping mirrors |
| | | 100 | | /// <see cref="AddSaturating(DateTime, TimeSpan)"/> on the client side: huge expiries saturate |
| | | 101 | | /// to "effectively never" instead of failing every write. |
| | | 102 | | /// </summary> |
| | 2 | 103 | | private static readonly TimeSpan MaxServerClockTtl = TimeSpan.FromSeconds(int.MaxValue); |
| | | 104 | | |
| | | 105 | | public static void ValidateCreate(string flowId, FlowState state, TimeSpan ttl) |
| | | 106 | | { |
| | 455 | 107 | | ValidateWrite(flowId, state, ttl); |
| | 444 | 108 | | if (state.Revision != 0) |
| | 2 | 109 | | throw new ArgumentException("A new flow ledger must start at revision zero.", nameof(state)); |
| | 442 | 110 | | } |
| | | 111 | | |
| | | 112 | | public static void ValidateUpdate(string flowId, FlowState state, long expectedRevision, TimeSpan ttl) |
| | | 113 | | { |
| | 897 | 114 | | ValidateWrite(flowId, state, ttl); |
| | 897 | 115 | | if (expectedRevision < 0) |
| | 2 | 116 | | throw new ArgumentOutOfRangeException(nameof(expectedRevision), "The expected revision cannot be negative.") |
| | 895 | 117 | | if (state.Revision != checked(expectedRevision + 1)) |
| | 2 | 118 | | throw new ArgumentException("The new flow-state revision must increment the expected revision by one.", name |
| | 891 | 119 | | } |
| | | 120 | | |
| | | 121 | | /// <summary> |
| | | 122 | | /// Argument preamble shared by every store's lease acquire/renew path. The stores pass their |
| | | 123 | | /// own parameters straight through, so the thrown <c>ParamName</c>s ("flowId", "leaseId", |
| | | 124 | | /// "leaseDuration") match the public <c>IFlowStateStore</c> signatures exactly. |
| | | 125 | | /// </summary> |
| | | 126 | | public static void ValidateLeaseArgs(string flowId, string leaseId, TimeSpan leaseDuration) |
| | | 127 | | { |
| | 215 | 128 | | ArgumentException.ThrowIfNullOrWhiteSpace(flowId); |
| | 211 | 129 | | ArgumentException.ThrowIfNullOrWhiteSpace(leaseId); |
| | 207 | 130 | | if (leaseDuration <= TimeSpan.Zero) |
| | 6 | 131 | | throw new ArgumentOutOfRangeException(nameof(leaseDuration)); |
| | 201 | 132 | | } |
| | | 133 | | |
| | | 134 | | /// <summary> |
| | | 135 | | /// Shapes one persisted lease pair into the <see cref="IFlowStateStore.ObserveLeaseAsync"/> |
| | | 136 | | /// answer, identically in all nine stores. The pair is reported RAW: nothing here (or in the |
| | | 137 | | /// reads that feed it) compares the expiry with a clock, because the engine's liveness proof |
| | | 138 | | /// is that two observations differ, and an expired lease that nobody took over must keep |
| | | 139 | | /// reading as the same lease until someone acquires or releases it. |
| | | 140 | | /// <para> |
| | | 141 | | /// A <c>null</c> <paramref name="leaseId"/> — never leased, released, or no row at all — is |
| | | 142 | | /// <see cref="FlowLeaseObservation.Unheld"/>, never <c>null</c>: <c>null</c> is reserved for |
| | | 143 | | /// "this store cannot report leases". |
| | | 144 | | /// </para> |
| | | 145 | | /// <para> |
| | | 146 | | /// Every store persists the lease expiry as a UTC instant, but the drivers disagree about the |
| | | 147 | | /// <see cref="DateTimeKind"/> they hand back (zone-less SQL columns read as |
| | | 148 | | /// <see cref="DateTimeKind.Unspecified"/>; a legacy-timestamp Npgsql or a custom Cosmos |
| | | 149 | | /// serializer can produce <see cref="DateTimeKind.Local"/>). The observation always carries |
| | | 150 | | /// <see cref="DateTimeKind.Utc"/> with the ticks the store kept, so two renewals compare |
| | | 151 | | /// strictly increasing whichever driver read them. |
| | | 152 | | /// </para> |
| | | 153 | | /// </summary> |
| | | 154 | | public static FlowLeaseObservation LeaseObservation(string? leaseId, DateTime? leaseExpiresAt) |
| | | 155 | | { |
| | 44 | 156 | | if (leaseId is null) |
| | 12 | 157 | | return FlowLeaseObservation.Unheld; |
| | | 158 | | |
| | 32 | 159 | | return new FlowLeaseObservation( |
| | 32 | 160 | | leaseId, |
| | 32 | 161 | | leaseExpiresAt is { } expiry |
| | 32 | 162 | | ? expiry.Kind == DateTimeKind.Local ? expiry.ToUniversalTime() : DateTime.SpecifyKind(expiry, DateTimeKi |
| | 32 | 163 | | : null); |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | /// <summary> |
| | | 167 | | /// The ledger has exactly ONE wire format: Core's <c>FlowStateJson</c> (source-generated |
| | | 168 | | /// metadata, nulls omitted on write, resolved through the <c>AsyncResponseJson</c> chain so |
| | | 169 | | /// <c>AsyncResponseJsonSerialization.RegisterResolver</c> — the documented trim/AOT seam — |
| | | 170 | | /// reaches every store). Serialize and Deserialize both delegate there, so a ledger written |
| | | 171 | | /// through any provider store always loads through any other, byte for byte. |
| | | 172 | | /// </summary> |
| | 1343 | 173 | | public static string Serialize(FlowState state) => FlowStateJson.Serialize(state); |
| | | 174 | | |
| | | 175 | | /// <summary> |
| | | 176 | | /// Serializes a ledger for a full-state write and enforces the store's <c>MaxStateBytes</c> |
| | | 177 | | /// budget. Without the guard an oversized ledger surfaces as the provider's opaque payload |
| | | 178 | | /// error (DynamoDB 400 KB item cap, Cosmos 2 MB, MongoDB 16 MB) which the executor retries |
| | | 179 | | /// into the dead-letter queue with no hint at the real cause. Throwing here keeps the same |
| | | 180 | | /// at-least-once semantics (run fails → retries → DLQ = operator alarm) but names the cause. |
| | | 181 | | /// </summary> |
| | | 182 | | /// <exception cref="FlowStateTooLargeException">The serialized state exceeds <paramref name="maxStateBytes"/>.</exc |
| | | 183 | | public static string SerializeBounded(string flowId, FlowState state, long? maxStateBytes, string providerName) |
| | | 184 | | { |
| | 1335 | 185 | | var json = Serialize(state); |
| | 1335 | 186 | | if (maxStateBytes is { } limit) |
| | | 187 | | { |
| | 1333 | 188 | | long size = Encoding.UTF8.GetByteCount(json); |
| | 1333 | 189 | | if (size > limit) |
| | 6 | 190 | | throw new FlowStateTooLargeException(flowId, size, limit, providerName); |
| | | 191 | | } |
| | | 192 | | |
| | 1329 | 193 | | return json; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | /// <summary> |
| | | 197 | | /// Materializes a loaded ledger row. |
| | | 198 | | /// <para> |
| | | 199 | | /// The row is never executed as anything but what it consistently says it is: a revision |
| | | 200 | | /// inside the JSON that disagrees with the row's own revision column, or a ledger whose |
| | | 201 | | /// <c>FlowId</c> is not the key it was loaded under (a row copied or restored under the |
| | | 202 | | /// wrong key), is refused — the read-side mirror of the write-side key/identity validation |
| | | 203 | | /// in <see cref="ValidateCreate"/>. |
| | | 204 | | /// </para> |
| | | 205 | | /// <para> |
| | | 206 | | /// Refused means <see cref="FlowStateUnreadableException"/>, never <c>null</c>. Every built-in |
| | | 207 | | /// store reads the JSON and the revision from ONE row or document, so a disagreement inside |
| | | 208 | | /// that snapshot is an inconsistent — corrupt, hand-edited, mis-restored — ledger that is |
| | | 209 | | /// physically present, not proof the run is gone. A <c>null</c> here told the executor to |
| | | 210 | | /// acknowledge the wake-up as belonging to a deleted flow, and the run behind the row lost |
| | | 211 | | /// its only wake-up while its row sat in the table. Unreadable JSON and an unknown schema |
| | | 212 | | /// version throw for the same reason (see the exception's remarks); the delivery rides the |
| | | 213 | | /// transport's retry and dead-letter path, which is the operator alarm. |
| | | 214 | | /// </para> |
| | | 215 | | /// </summary> |
| | | 216 | | /// <exception cref="FlowStateUnreadableException">The row is present but uninterpretable or inconsistent.</exceptio |
| | | 217 | | public static FlowState? ReadState(string flowId, string stateJson, long revision) |
| | | 218 | | { |
| | 687 | 219 | | var state = Deserialize(stateJson, flowId); |
| | 685 | 220 | | if (state.Revision != revision) |
| | | 221 | | { |
| | 4 | 222 | | throw new FlowStateUnreadableException( |
| | 4 | 223 | | flowId, |
| | 4 | 224 | | $"its stored revision is {revision} but the revision inside its JSON is {state.Revision}"); |
| | | 225 | | } |
| | | 226 | | |
| | 681 | 227 | | if (!string.Equals(state.FlowId, flowId, StringComparison.Ordinal)) |
| | 2 | 228 | | throw new FlowStateUnreadableException(flowId, "the flow id inside its JSON is not the id it is stored under |
| | | 229 | | |
| | 679 | 230 | | return state; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary> |
| | | 234 | | /// <paramref name="instant"/> + <paramref name="ttl"/>, saturating at |
| | | 235 | | /// <see cref="DateTime.MaxValue"/> instead of throwing: an absurd |
| | | 236 | | /// <see cref="DurableFlowOptions.StateExpiry"/> then means "effectively never expires" rather |
| | | 237 | | /// than failing every write with an <see cref="ArgumentOutOfRangeException"/>. |
| | | 238 | | /// </summary> |
| | | 239 | | public static DateTime AddSaturating(DateTime instant, TimeSpan ttl) |
| | 1504 | 240 | | => ttl > DateTime.MaxValue - instant ? DateTime.MaxValue : instant + ttl; |
| | | 241 | | |
| | | 242 | | /// <inheritdoc cref="AddSaturating(DateTime, TimeSpan)"/> |
| | | 243 | | public static DateTimeOffset AddSaturating(DateTimeOffset instant, TimeSpan ttl) |
| | 4 | 244 | | => ttl > DateTimeOffset.MaxValue - instant ? DateTimeOffset.MaxValue : instant + ttl; |
| | | 245 | | |
| | | 246 | | /// <summary>TTL clamped for server-clock date arithmetic; see <see cref="MaxServerClockTtl"/>.</summary> |
| | | 247 | | public static TimeSpan ServerClockTtl(TimeSpan ttl) |
| | 8 | 248 | | => ttl > MaxServerClockTtl ? MaxServerClockTtl : ttl; |
| | | 249 | | |
| | | 250 | | /// <summary>Whole milliseconds of <see cref="ServerClockTtl"/>, for stores that bind the TTL as a number.</summary> |
| | | 251 | | public static long ServerClockTtlMilliseconds(TimeSpan ttl) |
| | 4 | 252 | | => (long)ServerClockTtl(ttl).TotalMilliseconds; |
| | | 253 | | |
| | | 254 | | /// <inheritdoc cref="FlowStateJson.Deserialize"/> |
| | 703 | 255 | | public static FlowState Deserialize(string json, string flowId) => FlowStateJson.Deserialize(json, flowId); |
| | | 256 | | |
| | | 257 | | /// <summary> |
| | | 258 | | /// Throttles opportunistic expired-state pruning: returns <c>true</c> at most once per |
| | | 259 | | /// <paramref name="interval"/> (a non-positive interval prunes on every operation, matching the |
| | | 260 | | /// channel packages). Loads already filter on expiry, so throttling never affects correctness. |
| | | 261 | | /// </summary> |
| | | 262 | | public static bool ShouldPrune(ref long lastTicks, TimeSpan interval) |
| | | 263 | | { |
| | 6 | 264 | | if (interval <= TimeSpan.Zero) |
| | 2 | 265 | | return true; |
| | | 266 | | |
| | 4 | 267 | | var now = DateTime.UtcNow.Ticks; |
| | 4 | 268 | | var last = Interlocked.Read(ref lastTicks); |
| | 4 | 269 | | return now - last >= interval.Ticks |
| | 4 | 270 | | && Interlocked.CompareExchange(ref lastTicks, now, last) == last; |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | /// <summary> |
| | | 274 | | /// Advisory-lock key for schema DDL, derived exactly like the channel/transport packages |
| | | 275 | | /// (FNV-1a over <c>asyncresponse:ddl:{schemaName}</c>) so flow-store DDL serializes with any |
| | | 276 | | /// channel/transport DDL running against the same schema. |
| | | 277 | | /// </summary> |
| | | 278 | | public static long SchemaLockKey(string schemaName) |
| | | 279 | | { |
| | | 280 | | const ulong offset = 14695981039346656037UL; |
| | | 281 | | const ulong prime = 1099511628211UL; |
| | 6 | 282 | | var hash = offset; |
| | 380 | 283 | | foreach (var b in Encoding.UTF8.GetBytes(SchemaLockResource(schemaName))) |
| | | 284 | | { |
| | 184 | 285 | | hash ^= b; |
| | 184 | 286 | | hash *= prime; |
| | | 287 | | } |
| | | 288 | | |
| | 6 | 289 | | return unchecked((long)hash); |
| | | 290 | | } |
| | | 291 | | |
| | | 292 | | /// <summary>SQL Server <c>sp_getapplock</c> resource name for schema DDL (shared with the channel/transport package |
| | | 293 | | public static string SchemaLockResource(string schemaName) |
| | 8 | 294 | | => $"asyncresponse:ddl:{schemaName}"; |
| | | 295 | | |
| | | 296 | | /// <summary>Connection-string guard shared by the stores that own their connections.</summary> |
| | | 297 | | public static void ValidateConnectionString(string? connectionString, string optionsTypeName) |
| | | 298 | | { |
| | 0 | 299 | | if (string.IsNullOrWhiteSpace(connectionString)) |
| | 0 | 300 | | throw new InvalidOperationException($"{optionsTypeName}.ConnectionString must be configured."); |
| | 0 | 301 | | } |
| | | 302 | | |
| | | 303 | | /// <summary><c>MaxStateBytes</c> guard shared by all nine stores (null disables the budget).</summary> |
| | | 304 | | public static void ValidateMaxStateBytes(long? maxStateBytes, string optionsTypeName) |
| | | 305 | | { |
| | 274 | 306 | | if (maxStateBytes is <= 0) |
| | 2 | 307 | | throw new InvalidOperationException($"{optionsTypeName}.MaxStateBytes must be positive when configured."); |
| | 272 | 308 | | } |
| | | 309 | | |
| | | 310 | | /// <summary> |
| | | 311 | | /// Opens a fresh provider connection, disposing it when open fails — an ADO.NET connection |
| | | 312 | | /// that failed to open still holds its allocation until disposed, and the caller never |
| | | 313 | | /// receives it. |
| | | 314 | | /// </summary> |
| | | 315 | | public static async Task<TConnection> OpenConnectionAsync<TConnection>( |
| | | 316 | | string? connectionString, |
| | | 317 | | CancellationToken cancellationToken) |
| | | 318 | | where TConnection : DbConnection, new() |
| | | 319 | | { |
| | 0 | 320 | | var connection = new TConnection { ConnectionString = connectionString }; |
| | | 321 | | try |
| | | 322 | | { |
| | 0 | 323 | | await connection.OpenAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 324 | | return connection; |
| | | 325 | | } |
| | 0 | 326 | | catch |
| | | 327 | | { |
| | 0 | 328 | | await connection.DisposeAsync().ConfigureAwait(false); |
| | 0 | 329 | | throw; |
| | | 330 | | } |
| | 0 | 331 | | } |
| | | 332 | | |
| | | 333 | | public static void ValidateIdentifier(string? value, string optionName, string providerName, int identifierCap = 0) |
| | | 334 | | { |
| | 14 | 335 | | if (string.IsNullOrWhiteSpace(value)) |
| | 2 | 336 | | throw new InvalidOperationException($"{optionName} must be configured."); |
| | | 337 | | |
| | 12 | 338 | | if (!(char.IsAsciiLetter(value[0]) || value[0] == '_')) |
| | 2 | 339 | | throw new InvalidOperationException($"{optionName} '{value}' must be a simple {providerName} identifier (let |
| | | 340 | | |
| | 858 | 341 | | foreach (var c in value) |
| | | 342 | | { |
| | 420 | 343 | | if (!(char.IsAsciiLetterOrDigit(c) || c == '_')) |
| | 2 | 344 | | throw new InvalidOperationException($"{optionName} '{value}' must be a simple {providerName} identifier |
| | | 345 | | } |
| | | 346 | | |
| | 8 | 347 | | if (identifierCap > 0 && value.Length > identifierCap) |
| | 2 | 348 | | throw new InvalidOperationException( |
| | 2 | 349 | | $"{optionName} '{value}' is {value.Length} characters; {providerName} identifiers are limited to {identi |
| | 6 | 350 | | } |
| | | 351 | | |
| | | 352 | | /// <summary> |
| | | 353 | | /// Derived object name with suffix space RESERVED before the provider's identifier cap: |
| | | 354 | | /// truncating the whole "{table}{suffix}" lets a maximum-length table name derive its own |
| | | 355 | | /// name — on providers where indexes share the table namespace the DDL is then silently |
| | | 356 | | /// skipped, on the rest it fails outright. |
| | | 357 | | /// <para> |
| | | 358 | | /// Kept in step with <c>AsyncResponse.Internal.RelationalNamePlan.DerivedName</c>, which is |
| | | 359 | | /// the same rule for the channel and transport packages. The two cannot be one method: this |
| | | 360 | | /// file is source-linked into all nine flow stores, and RelationalNamePlan is linked only |
| | | 361 | | /// into the four relational channel/transport packages that need a name plan. |
| | | 362 | | /// </para> |
| | | 363 | | /// </summary> |
| | | 364 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 365 | | /// <paramref name="suffix"/> leaves no room for a stem inside <paramref name="identifierCap"/>. |
| | | 366 | | /// Guarded explicitly: the slice below would otherwise take a negative length and fail schema |
| | | 367 | | /// creation with a bare index-out-of-range naming neither the suffix nor the cap. |
| | | 368 | | /// </exception> |
| | | 369 | | public static string DerivedName(string tableName, string suffix, int identifierCap) |
| | | 370 | | { |
| | 8 | 371 | | if (identifierCap <= 0 || tableName.Length + suffix.Length <= identifierCap) |
| | 4 | 372 | | return tableName + suffix; |
| | | 373 | | |
| | 4 | 374 | | if (suffix.Length >= identifierCap) |
| | | 375 | | { |
| | 2 | 376 | | throw new ArgumentOutOfRangeException( |
| | 2 | 377 | | nameof(suffix), |
| | 2 | 378 | | $"The derived-name suffix '{suffix}' is {suffix.Length} characters, which leaves no room for a table ste |
| | 2 | 379 | | $"the {identifierCap}-character identifier limit. Shorten the suffix."); |
| | | 380 | | } |
| | | 381 | | |
| | 2 | 382 | | return tableName[..(identifierCap - suffix.Length)] + suffix; |
| | | 383 | | } |
| | | 384 | | |
| | | 385 | | private static void ValidateWrite(string flowId, FlowState state, TimeSpan ttl) |
| | | 386 | | { |
| | 1352 | 387 | | ArgumentException.ThrowIfNullOrWhiteSpace(flowId); |
| | 1350 | 388 | | ArgumentNullException.ThrowIfNull(state); |
| | 1348 | 389 | | if (!string.Equals(state.FlowId, flowId, StringComparison.Ordinal)) |
| | 2 | 390 | | throw new ArgumentException("The flow state id must match the store key.", nameof(state)); |
| | 1346 | 391 | | if (state.SchemaVersion != FlowStateSchema.Current) |
| | 3 | 392 | | throw new ArgumentException("The flow state must use the current schema version.", nameof(state)); |
| | 1343 | 393 | | if (ttl <= TimeSpan.Zero) |
| | 2 | 394 | | throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than zero."); |
| | 1341 | 395 | | } |
| | | 396 | | } |