-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathTable.cs
More file actions
300 lines (257 loc) · 13.3 KB
/
Table.cs
File metadata and controls
300 lines (257 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
#nullable enable
namespace DurableTask.AzureStorage.Storage
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Data.Tables;
using Azure.Data.Tables.Models;
using DurableTask.AzureStorage.Monitoring;
class Table
{
readonly AzureStorageClient azureStorageClient;
readonly AzureStorageOrchestrationServiceStats stats;
readonly TableServiceClient tableServiceClient;
readonly TableClient tableClient;
public Table(AzureStorageClient azureStorageClient, TableServiceClient tableServiceClient, string tableName)
{
this.azureStorageClient = azureStorageClient;
this.stats = this.azureStorageClient.Stats;
this.tableServiceClient = tableServiceClient;
this.tableClient = tableServiceClient.GetTableClient(tableName);
}
public string Name => this.tableClient.Name;
internal Uri Uri => this.tableClient.Uri;
public async Task<bool> CreateIfNotExistsAsync(CancellationToken cancellationToken = default)
{
// If we received null, then the response must have been a 409 (Conflict) and the table must already exist
Response<TableItem> response = await this.tableClient.CreateIfNotExistsAsync(cancellationToken).DecorateFailure();
return response != null;
}
public async Task<bool> DeleteIfExistsAsync(CancellationToken cancellationToken = default)
{
// If we received null, then the response must have been a 404 (NotFound) and the table must not exist
Response response = await this.tableClient.DeleteAsync(cancellationToken).DecorateFailure();
return response != null;
}
public async Task<bool> ExistsAsync(CancellationToken cancellationToken = default)
{
// TODO: Re-evaluate the use of an "Exists" method as it was intentional omitted from the client API
List<TableItem> tables = await this.tableServiceClient
.QueryAsync(filter: $"TableName eq '{this.tableClient.Name}'", cancellationToken: cancellationToken)
.DecorateFailure()
.ToListAsync(cancellationToken);
return tables.Count > 0;
}
public async Task DeleteAsync(CancellationToken cancellationToken = default)
{
await this.tableClient.DeleteAsync(cancellationToken).DecorateFailure();
}
public async Task ReplaceEntityAsync<T>(T tableEntity, ETag ifMatch, CancellationToken cancellationToken = default) where T : ITableEntity
{
await this.tableClient.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Replace, cancellationToken).DecorateFailure();
this.stats.TableEntitiesWritten.Increment();
}
public async Task DeleteEntityAsync<T>(T tableEntity, ETag ifMatch = default, CancellationToken cancellationToken = default) where T : ITableEntity
{
await this.tableClient.DeleteEntityAsync(tableEntity.PartitionKey, tableEntity.RowKey, ifMatch, cancellationToken).DecorateFailure();
this.stats.TableEntitiesWritten.Increment();
}
public async Task<Response> InsertEntityAsync<T>(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity
{
Response result = await this.tableClient.AddEntityAsync(tableEntity, cancellationToken).DecorateFailure();
this.stats.TableEntitiesWritten.Increment();
return result;
}
public async Task<Response> MergeEntityAsync<T>(T tableEntity, ETag ifMatch, CancellationToken cancellationToken = default) where T : ITableEntity
{
Response result = await this.tableClient.UpdateEntityAsync(tableEntity, ifMatch, TableUpdateMode.Merge, cancellationToken).DecorateFailure();
this.stats.TableEntitiesWritten.Increment();
return result;
}
public async Task InsertOrMergeEntityAsync<T>(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity
{
await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Merge, cancellationToken).DecorateFailure();
this.stats.TableEntitiesWritten.Increment();
}
public async Task InsertOrReplaceEntityAsync<T>(T tableEntity, CancellationToken cancellationToken = default) where T : ITableEntity
{
await this.tableClient.UpsertEntityAsync(tableEntity, TableUpdateMode.Replace, cancellationToken).DecorateFailure();
this.stats.TableEntitiesWritten.Increment();
}
public async Task<TableTransactionResults> DeleteBatchAsync<T>(IEnumerable<T> entityBatch, CancellationToken cancellationToken = default) where T : ITableEntity
{
return await this.ExecuteBatchAsync(entityBatch, item => new TableTransactionAction(TableTransactionActionType.Delete, item), cancellationToken: cancellationToken);
}
/// <summary>
/// Deletes entities in parallel batches of up to 100. Each batch is an atomic transaction,
/// but multiple batches are submitted concurrently for improved throughput.
/// Concurrency is controlled by the global <see cref="Http.ThrottlingHttpPipelinePolicy"/>.
/// If a batch fails because an entity was already deleted (404/EntityNotFound),
/// it falls back to individual deletes for that batch, skipping already-deleted entities.
/// </summary>
public async Task<TableTransactionResults> DeleteBatchParallelAsync<T>(
IReadOnlyList<T> entityBatch,
CancellationToken cancellationToken = default) where T : ITableEntity
{
if (entityBatch.Count == 0)
{
return new TableTransactionResults(Array.Empty<Response>(), TimeSpan.Zero, 0);
}
const int batchSize = 100;
int chunkCount = (entityBatch.Count + batchSize - 1) / batchSize;
var chunks = new List<List<TableTransactionAction>>(chunkCount);
var currentChunk = new List<TableTransactionAction>(batchSize);
foreach (T entity in entityBatch)
{
currentChunk.Add(new TableTransactionAction(TableTransactionActionType.Delete, entity));
if (currentChunk.Count == batchSize)
{
chunks.Add(currentChunk);
currentChunk = new List<TableTransactionAction>(batchSize);
}
}
if (currentChunk.Count > 0)
{
chunks.Add(currentChunk);
}
var resultsBuilder = new TableTransactionResultsBuilder();
var stopwatch = Stopwatch.StartNew();
TableTransactionResults[] allResults = await Task.WhenAll(
chunks.Select(chunk => this.ExecuteBatchWithFallbackAsync(chunk, cancellationToken)));
stopwatch.Stop();
foreach (TableTransactionResults result in allResults)
{
resultsBuilder.Add(result);
}
TableTransactionResults aggregatedResults = resultsBuilder.ToResults();
return new TableTransactionResults(aggregatedResults.Responses, stopwatch.Elapsed, aggregatedResults.RequestCount);
}
/// <summary>
/// Executes a batch transaction. If it fails due to an entity not found (404),
/// falls back to individual delete operations, skipping entities that are already gone.
/// </summary>
async Task<TableTransactionResults> ExecuteBatchWithFallbackAsync(
List<TableTransactionAction> batch,
CancellationToken cancellationToken)
{
try
{
return await this.ExecuteBatchAsync(batch, cancellationToken);
}
catch (DurableTaskStorageException ex) when (ex.HttpStatusCode == 404)
{
// One or more entities in the batch were already deleted.
// Fall back to individual deletes, skipping 404s.
return await this.DeleteEntitiesIndividuallyAsync(batch, cancellationToken);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
return await this.DeleteEntitiesIndividuallyAsync(batch, cancellationToken);
}
}
async Task<TableTransactionResults> DeleteEntitiesIndividuallyAsync(
List<TableTransactionAction> batch,
CancellationToken cancellationToken)
{
var responses = new List<Response>();
var stopwatch = Stopwatch.StartNew();
int requestCount = 0;
foreach (TableTransactionAction action in batch)
{
requestCount++;
try
{
Response response = await this.tableClient.DeleteEntityAsync(
action.Entity.PartitionKey,
action.Entity.RowKey,
ETag.All,
cancellationToken).DecorateFailure();
responses.Add(response);
this.stats.TableEntitiesWritten.Increment();
}
catch (DurableTaskStorageException ex) when (ex.HttpStatusCode == 404)
{
// Entity already deleted; skip.
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
// Entity already deleted; skip.
}
}
stopwatch.Stop();
return new TableTransactionResults(responses, stopwatch.Elapsed, requestCount);
}
public async Task<TableTransactionResults> InsertOrMergeBatchAsync<T>(IEnumerable<T> entityBatch, CancellationToken cancellationToken = default) where T : ITableEntity
{
TableTransactionResults results = await this.ExecuteBatchAsync(entityBatch, item => new TableTransactionAction(TableTransactionActionType.UpsertMerge, item), cancellationToken: cancellationToken);
if (results.Responses.Count > 0)
{
this.stats.TableEntitiesWritten.Increment(results.Responses.Count);
}
return results;
}
async Task<TableTransactionResults> ExecuteBatchAsync<T>(
IEnumerable<T> entityBatch,
Func<T, TableTransactionAction> batchOperation,
int batchSize = 100,
CancellationToken cancellationToken = default) where T : ITableEntity
{
if (batchSize > 100)
{
throw new ArgumentOutOfRangeException(nameof(batchSize), "Table storage does not support batch sizes greater than 100.");
}
var resultsBuilder = new TableTransactionResultsBuilder();
var batch = new List<TableTransactionAction>(batchSize);
foreach (T entity in entityBatch)
{
batch.Add(batchOperation(entity));
if (batch.Count == batchSize)
{
resultsBuilder.Add(await this.ExecuteBatchAsync(batch, cancellationToken));
batch.Clear();
}
}
if (batch.Count > 0)
{
resultsBuilder.Add(await this.ExecuteBatchAsync(batch, cancellationToken));
}
return resultsBuilder.ToResults();
}
public async Task<TableTransactionResults> ExecuteBatchAsync(IEnumerable<TableTransactionAction> batchOperation, CancellationToken cancellationToken = default)
{
var stopwatch = new Stopwatch();
Response<IReadOnlyList<Response>> response = await this.tableClient.SubmitTransactionAsync(batchOperation, cancellationToken).DecorateFailure();
IReadOnlyList<Response> batchResults = response.Value;
stopwatch.Stop();
this.stats.TableEntitiesWritten.Increment(batchResults.Count);
return new TableTransactionResults(batchResults, stopwatch.Elapsed);
}
public TableQueryResponse<T> ExecuteQueryAsync<T>(
string? filter = null,
int? maxPerPage = null,
IEnumerable<string>? select = null,
CancellationToken cancellationToken = default) where T : class, ITableEntity, new()
{
return new TableQueryResponse<T>(
this.tableClient.QueryAsync<T>(filter, maxPerPage, select, cancellationToken).DecorateFailure(),
this.stats);
}
}
}