-
Notifications
You must be signed in to change notification settings - Fork 504
/
Copy pathItemBatchOperation.cs
416 lines (364 loc) · 15.4 KB
/
ItemBatchOperation.cs
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Serialization.HybridRow;
using Microsoft.Azure.Cosmos.Serialization.HybridRow.IO;
using Microsoft.Azure.Cosmos.Serialization.HybridRow.Layouts;
using Microsoft.Azure.Documents;
/// <summary>
/// Represents an operation on an item which will be executed as part of a batch request
/// on a container.
/// </summary>
internal class ItemBatchOperation : IDisposable
{
#pragma warning disable SA1401 // Fields should be private
protected Memory<byte> body;
#pragma warning restore SA1401 // Fields should be private
private bool isDisposed;
public ItemBatchOperation(
OperationType operationType,
int operationIndex,
PartitionKey partitionKey,
string id = null,
Stream resourceStream = null,
TransactionalBatchItemRequestOptions requestOptions = null,
CosmosDiagnosticsContext diagnosticsContext = null)
{
this.OperationType = operationType;
this.OperationIndex = operationIndex;
this.PartitionKey = partitionKey;
this.Id = id;
this.ResourceStream = resourceStream;
this.RequestOptions = requestOptions;
this.DiagnosticsContext = diagnosticsContext;
}
public ItemBatchOperation(
OperationType operationType,
int operationIndex,
ContainerCore containerCore,
string id = null,
Stream resourceStream = null,
TransactionalBatchItemRequestOptions requestOptions = null)
{
this.OperationType = operationType;
this.OperationIndex = operationIndex;
this.ContainerCore = containerCore;
this.Id = id;
this.ResourceStream = resourceStream;
this.RequestOptions = requestOptions;
this.DiagnosticsContext = null;
}
public PartitionKey? PartitionKey { get; internal set; }
public string Id { get; }
public OperationType OperationType { get; }
public Stream ResourceStream { get; protected set; }
public TransactionalBatchItemRequestOptions RequestOptions { get; }
public int OperationIndex { get; internal set; }
internal ContainerCore ContainerCore { get; }
internal CosmosDiagnosticsContext DiagnosticsContext { get; set; }
internal string PartitionKeyJson { get; set; }
internal Documents.PartitionKey ParsedPartitionKey { get; set; }
internal Memory<byte> ResourceBody
{
get
{
Debug.Assert(
this.ResourceStream == null || !this.body.IsEmpty,
"ResourceBody read without materialization of ResourceStream");
return this.body;
}
set
{
this.body = value;
}
}
/// <summary>
/// Operational context used in stream operations.
/// </summary>
/// <seealso cref="BatchAsyncBatcher"/>
/// <seealso cref="BatchAsyncStreamer"/>
/// <seealso cref="BatchAsyncContainerExecutor"/>
internal ItemBatchOperationContext Context { get; private set; }
/// <summary>
/// Disposes the current <see cref="ItemBatchOperation"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
internal static Result WriteOperation(ref RowWriter writer, TypeArgument typeArg, ItemBatchOperation operation)
{
bool pkWritten = false;
Result r = writer.WriteInt32("operationType", (int)operation.OperationType);
if (r != Result.Success)
{
return r;
}
r = writer.WriteInt32("resourceType", (int)ResourceType.Document);
if (r != Result.Success)
{
return r;
}
if (operation.PartitionKeyJson != null)
{
r = writer.WriteString("partitionKey", operation.PartitionKeyJson);
if (r != Result.Success)
{
return r;
}
pkWritten = true;
}
if (operation.Id != null)
{
r = writer.WriteString("id", operation.Id);
if (r != Result.Success)
{
return r;
}
}
if (!operation.ResourceBody.IsEmpty)
{
r = writer.WriteBinary("resourceBody", operation.ResourceBody.Span);
if (r != Result.Success)
{
return r;
}
}
if (operation.RequestOptions != null)
{
TransactionalBatchItemRequestOptions options = operation.RequestOptions;
if (options.IndexingDirective.HasValue)
{
string indexingDirectiveString = IndexingDirectiveStrings.FromIndexingDirective(options.IndexingDirective.Value);
r = writer.WriteString("indexingDirective", indexingDirectiveString);
if (r != Result.Success)
{
return r;
}
}
if (options.IfMatchEtag != null)
{
r = writer.WriteString("ifMatch", options.IfMatchEtag);
if (r != Result.Success)
{
return r;
}
}
else if (options.IfNoneMatchEtag != null)
{
r = writer.WriteString("ifNoneMatch", options.IfNoneMatchEtag);
if (r != Result.Success)
{
return r;
}
}
if (options.Properties != null)
{
if (options.Properties.TryGetValue(WFConstants.BackendHeaders.BinaryId, out object binaryIdObj))
{
byte[] binaryId = binaryIdObj as byte[];
if (binaryId != null)
{
r = writer.WriteBinary("binaryId", binaryId);
if (r != Result.Success)
{
return r;
}
}
}
if (options.Properties.TryGetValue(WFConstants.BackendHeaders.EffectivePartitionKey, out object epkObj))
{
byte[] epk = epkObj as byte[];
if (epk != null)
{
r = writer.WriteBinary("effectivePartitionKey", epk);
if (r != Result.Success)
{
return r;
}
}
}
if (!pkWritten && options.Properties.TryGetValue(
HttpConstants.HttpHeaders.PartitionKey,
out object pkStrObj))
{
string pkString = pkStrObj as string;
if (pkString != null)
{
r = writer.WriteString("partitionKey", pkString);
if (r != Result.Success)
{
return r;
}
}
}
if (options.Properties.TryGetValue(WFConstants.BackendHeaders.TimeToLiveInSeconds, out object ttlObj))
{
string ttlStr = ttlObj as string;
if (ttlStr != null && int.TryParse(ttlStr, out int ttl))
{
r = writer.WriteInt32("timeToLiveInSeconds", ttl);
if (r != Result.Success)
{
return r;
}
}
}
}
}
return Result.Success;
}
/// <summary>
/// Computes and returns an approximation for the length of this <see cref="ItemBatchOperation"/>.
/// when serialized.
/// </summary>
/// <returns>An under-estimate of the length.</returns>
internal int GetApproximateSerializedLength()
{
int length = 0;
if (this.PartitionKeyJson != null)
{
length += this.PartitionKeyJson.Length;
}
if (this.Id != null)
{
length += this.Id.Length;
}
length += this.body.Length;
if (this.RequestOptions != null)
{
if (this.RequestOptions.IfMatchEtag != null)
{
length += this.RequestOptions.IfMatchEtag.Length;
}
if (this.RequestOptions.IfNoneMatchEtag != null)
{
length += this.RequestOptions.IfNoneMatchEtag.Length;
}
if (this.RequestOptions.IndexingDirective.HasValue)
{
length += 7; // "Default", "Include", "Exclude" are possible values
}
if (this.RequestOptions.Properties != null)
{
if (this.RequestOptions.Properties.TryGetValue(WFConstants.BackendHeaders.BinaryId, out object binaryIdObj))
{
byte[] binaryId = binaryIdObj as byte[];
if (binaryId != null)
{
length += binaryId.Length;
}
}
if (this.RequestOptions.Properties.TryGetValue(WFConstants.BackendHeaders.EffectivePartitionKey, out object epkObj))
{
byte[] epk = epkObj as byte[];
if (epk != null)
{
length += epk.Length;
}
}
}
}
return length;
}
/// <summary>
/// Encrypts (if encryption options are set) and materializes the operation's resource into a Memory{byte} wrapping a byte array.
/// </summary>
/// <param name="serializerCore">Serializer to serialize user provided objects to JSON.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> for cancellation.</param>
internal virtual async Task EncryptAndMaterializeResourceAsync(CosmosSerializerCore serializerCore, CancellationToken cancellationToken)
{
if (this.body.IsEmpty && this.ResourceStream != null)
{
Stream stream = this.ResourceStream;
if (this.ContainerCore != null && this.RequestOptions?.EncryptionOptions != null)
{
stream = await this.ContainerCore.ClientContext.EncryptItemAsync(
stream,
this.RequestOptions.EncryptionOptions,
(DatabaseCore)this.ContainerCore.Database,
this.DiagnosticsContext,
cancellationToken);
}
this.body = await BatchExecUtils.StreamToMemoryAsync(stream, cancellationToken);
}
}
/// <summary>
/// Attached a context to the current operation to track resolution.
/// </summary>
/// <exception cref="InvalidOperationException">If the operation already had an attached context.</exception>
internal void AttachContext(ItemBatchOperationContext context)
{
if (this.Context != null)
{
throw new InvalidOperationException("Cannot modify the current context of an operation.");
}
this.Context = context;
}
/// <summary>
/// Disposes the disposable members held by this class.
/// </summary>
/// <param name="disposing">Indicates whether to dispose managed resources or not.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing && !this.isDisposed)
{
this.isDisposed = true;
if (this.ResourceStream != null)
{
this.ResourceStream.Dispose();
this.ResourceStream = null;
}
}
}
}
#pragma warning disable SA1402 // File may only contain a single type
internal class ItemBatchOperation<T> : ItemBatchOperation
#pragma warning restore SA1402 // File may only contain a single type
{
public ItemBatchOperation(
OperationType operationType,
int operationIndex,
PartitionKey partitionKey,
T resource,
string id = null,
TransactionalBatchItemRequestOptions requestOptions = null)
: base(operationType, operationIndex, partitionKey: partitionKey, id: id, requestOptions: requestOptions)
{
this.Resource = resource;
}
public ItemBatchOperation(
OperationType operationType,
int operationIndex,
T resource,
ContainerCore containerCore,
string id = null,
TransactionalBatchItemRequestOptions requestOptions = null)
: base(operationType, operationIndex, containerCore: containerCore, id: id, requestOptions: requestOptions)
{
this.Resource = resource;
}
public T Resource { get; private set; }
/// <summary>
/// Materializes the operation's resource into a Memory{byte} wrapping a byte array.
/// </summary>
/// <param name="serializerCore">Serializer to serialize user provided objects to JSON.</param>
/// <param name="cancellationToken"><see cref="CancellationToken"/> for cancellation.</param>
internal override Task EncryptAndMaterializeResourceAsync(CosmosSerializerCore serializerCore, CancellationToken cancellationToken)
{
if (this.body.IsEmpty && this.Resource != null)
{
this.ResourceStream = serializerCore.ToStream(this.Resource);
return base.EncryptAndMaterializeResourceAsync(serializerCore, cancellationToken);
}
return Task.CompletedTask;
}
}
}