forked from Azure/azure-sdk-for-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TableTransaction.ts
445 lines (402 loc) · 14 KB
/
TableTransaction.ts
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
DeleteTableEntityOptions,
TableEntity,
TableTransactionEntityResponse,
TableTransactionResponse,
TransactionAction,
UpdateMode,
UpdateTableEntityOptions,
} from "./models";
import { NamedKeyCredential, SASCredential, TokenCredential } from "@azure/core-auth";
import {
OperationOptions,
ServiceClient,
serializationPolicy,
serializationPolicyName,
} from "@azure/core-client";
import {
Pipeline,
PipelineRequest,
PipelineResponse,
RestError,
createHttpHeaders,
createPipelineRequest,
} from "@azure/core-rest-pipeline";
import {
getInitialTransactionBody,
getTransactionHttpRequestBody,
} from "./utils/transactionHelpers";
import {
transactionHeaderFilterPolicy,
transactionHeaderFilterPolicyName,
transactionRequestAssemblePolicy,
transactionRequestAssemblePolicyName,
} from "./TablePolicies";
import { TableClientLike } from "./utils/internalModels";
import { TableServiceErrorOdataError } from "./generated";
import { cosmosPatchPolicy } from "./cosmosPathPolicy";
import { getTransactionHeaders } from "./utils/transactionHeaders";
import { isCosmosEndpoint } from "./utils/isCosmosEndpoint";
import { tracingClient } from "./utils/tracing";
/**
* Helper to build a list of transaction actions
*/
export class TableTransaction {
/**
* List of actions to perform in a transaction
*/
public actions: TransactionAction[];
constructor(actions?: TransactionAction[]) {
this.actions = actions ?? [];
}
/**
* Adds a create action to the transaction
* @param entity - entity to create
*/
createEntity<T extends object = Record<string, unknown>>(entity: TableEntity<T>): void {
this.actions.push(["create", entity]);
}
/**
* Adds a delete action to the transaction
* @param partitionKey - partition key of the entity to delete
* @param rowKey - rowKey of the entity to delete
*/
deleteEntity(partitionKey: string, rowKey: string): void {
this.actions.push(["delete", { partitionKey, rowKey }]);
}
/**
* Adds an update action to the transaction
* @param entity - entity to update
* @param updateOptions - options for the update operation
*/
updateEntity<T extends object = Record<string, unknown>>(
entity: TableEntity<T>,
updateOptions?: UpdateTableEntityOptions
): void;
/**
* Adds an update action to the transaction
* @param entity - entity to update
* @param updateMode - update mode
* @param updateOptions - options for the update operation
*/
updateEntity<T extends object = Record<string, unknown>>(
entity: TableEntity<T>,
updateMode: UpdateMode,
updateOptions?: UpdateTableEntityOptions
): void;
/**
* Adds an update action to the transaction
* @param entity - entity to update
* @param updateModeOrOptions - update mode or update options
* @param updateOptions - options for the update operation
*/
updateEntity<T extends object = Record<string, unknown>>(
entity: TableEntity<T>,
updateModeOrOptions: UpdateMode | UpdateTableEntityOptions | undefined,
updateOptions?: UpdateTableEntityOptions
): void {
// UpdateMode is a string union
const realUpdateMode: UpdateMode | undefined =
typeof updateModeOrOptions === "string" ? updateModeOrOptions : undefined;
const realUpdateOptions: UpdateTableEntityOptions | undefined =
typeof updateModeOrOptions === "object" ? updateModeOrOptions : updateOptions;
this.actions.push(["update", entity, realUpdateMode ?? "Merge", realUpdateOptions ?? {}]);
}
/**
* Adds an upsert action to the transaction, which inserts if the entity doesn't exist or updates the existing one
* @param entity - entity to upsert
* @param updateMode - update mode
*/
upsertEntity<T extends object = Record<string, unknown>>(
entity: TableEntity<T>,
updateMode: UpdateMode = "Merge"
): void {
this.actions.push(["upsert", entity, updateMode]);
}
}
/**
* TableTransaction collects sub-operations that can be submitted together via submitTransaction
*/
export class InternalTableTransaction {
/**
* Table Account URL
*/
public url: string;
/**
* This part of the state can be reset by
* calling the reset function. Other parts of the state
* such as the credentials remain the same throughout the life
* of the instance.
*/
private resetableState: {
transactionId: string;
changesetId: string;
pendingOperations: Promise<any>[];
bodyParts: string[];
partitionKey: string;
};
private interceptClient: TableClientLike;
private allowInsecureConnection: boolean;
private client: ServiceClient;
/**
* @param url - Tables account url
* @param partitionKey - partition key
* @param credential - credential to authenticate the transaction request
*/
constructor(
url: string,
partitionKey: string,
transactionId: string,
changesetId: string,
client: ServiceClient,
interceptClient: TableClientLike,
credential?: NamedKeyCredential | SASCredential | TokenCredential,
allowInsecureConnection: boolean = false
) {
this.client = client;
this.url = url;
this.interceptClient = interceptClient;
this.allowInsecureConnection = allowInsecureConnection;
// Initialize Reset-able properties
this.resetableState = this.initializeSharedState(transactionId, changesetId, partitionKey);
// Depending on the auth method used we need to build the url
if (!credential) {
// When the SAS token is provided as part of the URL we need to move it after $batch
const urlParts = url.split("?");
this.url = urlParts[0];
const sas = urlParts.length > 1 ? `?${urlParts[1]}` : "";
this.url = `${this.getUrlWithSlash()}$batch${sas}`;
} else {
// When using a SharedKey credential no SAS token is needed
this.url = `${this.getUrlWithSlash()}$batch`;
}
}
/**
* Resets the state of the Transaction.
*/
reset(transactionId: string, changesetId: string, partitionKey: string): void {
this.resetableState = this.initializeSharedState(transactionId, changesetId, partitionKey);
}
private initializeSharedState(transactionId: string, changesetId: string, partitionKey: string) {
const pendingOperations: Promise<any>[] = [];
const bodyParts = getInitialTransactionBody(transactionId, changesetId);
const isCosmos = isCosmosEndpoint(this.url);
prepateTransactionPipeline(this.interceptClient.pipeline, bodyParts, changesetId, isCosmos);
return {
transactionId,
changesetId,
partitionKey,
pendingOperations,
bodyParts,
};
}
/**
* Adds a createEntity operation to the transaction
* @param entity - Entity to create
*/
public createEntity<T extends object>(entity: TableEntity<T>): void {
this.checkPartitionKey(entity.partitionKey);
this.resetableState.pendingOperations.push(this.interceptClient.createEntity(entity));
}
/**
* Adds a createEntity operation to the transaction per each entity in the entities array
* @param entities - Array of entities to create
*/
public createEntities<T extends object>(entities: TableEntity<T>[]): void {
for (const entity of entities) {
this.checkPartitionKey(entity.partitionKey);
this.resetableState.pendingOperations.push(this.interceptClient.createEntity(entity));
}
}
/**
* Adds a deleteEntity operation to the transaction
* @param partitionKey - Partition key of the entity to delete
* @param rowKey - Row key of the entity to delete
* @param options - Options for the delete operation
*/
public deleteEntity(
partitionKey: string,
rowKey: string,
options?: DeleteTableEntityOptions
): void {
this.checkPartitionKey(partitionKey);
this.resetableState.pendingOperations.push(
this.interceptClient.deleteEntity(partitionKey, rowKey, options)
);
}
/**
* Adds an updateEntity operation to the transaction
* @param entity - Entity to update
* @param mode - Update mode (Merge or Replace)
* @param options - Options for the update operation
*/
public updateEntity<T extends object>(
entity: TableEntity<T>,
mode: UpdateMode,
options?: UpdateTableEntityOptions
): void {
this.checkPartitionKey(entity.partitionKey);
this.resetableState.pendingOperations.push(
this.interceptClient.updateEntity(entity, mode, options)
);
}
/**
* Adds an upsertEntity operation to the transaction
* @param entity - The properties for the table entity.
* @param mode - The different modes for updating the entity:
* - Merge: Updates an entity by updating the entity's properties without replacing the existing entity.
* - Replace: Updates an existing entity by replacing the entire entity.
* @param options - The options parameters.
*/
public upsertEntity<T extends object>(
entity: TableEntity<T>,
mode: UpdateMode,
options?: OperationOptions
): void {
this.checkPartitionKey(entity.partitionKey);
this.resetableState.pendingOperations.push(
this.interceptClient.upsertEntity(entity, mode, options)
);
}
/**
* Submits the operations in the transaction
*/
public async submitTransaction(): Promise<TableTransactionResponse> {
await Promise.all(this.resetableState.pendingOperations);
const body = getTransactionHttpRequestBody(
this.resetableState.bodyParts,
this.resetableState.transactionId,
this.resetableState.changesetId
);
const headers = getTransactionHeaders(this.resetableState.transactionId);
return tracingClient.withSpan(
"TableTransaction.submitTransaction",
{} as OperationOptions,
async (updatedOptions) => {
const request = createPipelineRequest({
url: this.url,
method: "POST",
body,
headers: createHttpHeaders(headers),
tracingOptions: updatedOptions.tracingOptions,
allowInsecureConnection: this.allowInsecureConnection,
});
const rawTransactionResponse = await this.client.sendRequest(request);
return parseTransactionResponse(rawTransactionResponse);
}
);
}
private checkPartitionKey(partitionKey: string): void {
if (this.resetableState.partitionKey !== partitionKey) {
throw new Error("All operations in a transaction must target the same partitionKey");
}
}
private getUrlWithSlash(): string {
return this.url.endsWith("/") ? this.url : `${this.url}/`;
}
}
export function parseTransactionResponse(
transactionResponse: PipelineResponse
): TableTransactionResponse {
const subResponsePrefix = `--changesetresponse_`;
const status = transactionResponse.status;
const rawBody = transactionResponse.bodyAsText || "";
const splitBody = rawBody.split(subResponsePrefix);
const isSuccessByStatus = 200 <= status && status < 300;
if (!isSuccessByStatus) {
handleBodyError(rawBody, status, transactionResponse.request, transactionResponse);
}
// Dropping the first and last elements as they are the boundaries
// we just care about sub request content
const subResponses = splitBody.slice(1, splitBody.length - 1);
const responses: TableTransactionEntityResponse[] = subResponses.map((subResponse) => {
const statusMatch = subResponse.match(/HTTP\/1.1 ([0-9]*)/);
if (statusMatch?.length !== 2) {
throw new Error(`Couldn't extract status from sub-response:\n ${subResponse}`);
}
const subResponseStatus = Number.parseInt(statusMatch[1]);
if (!Number.isInteger(subResponseStatus)) {
throw new Error(`Expected sub-response status to be an integer ${subResponseStatus}`);
}
const bodyMatch = subResponse.match(/\{(.*)\}/);
if (bodyMatch?.length === 2) {
handleBodyError(
bodyMatch[0],
subResponseStatus,
transactionResponse.request,
transactionResponse
);
}
const etagMatch = subResponse.match(/ETag: (.*)/);
const rowKeyMatch = subResponse.match(/RowKey='(.*)'/);
return {
status: subResponseStatus,
...(rowKeyMatch?.length === 2 && { rowKey: rowKeyMatch[1] }),
...(etagMatch?.length === 2 && { etag: etagMatch[1] }),
};
});
return {
status,
subResponses: responses,
getResponseForEntity: (rowKey: string) => responses.find((r) => r.rowKey === rowKey),
};
}
function handleBodyError(
bodyAsText: string,
statusCode: number,
request: PipelineRequest,
response: PipelineResponse
) {
let parsedError;
try {
parsedError = JSON.parse(bodyAsText);
} catch {
parsedError = {};
}
let message = "Transaction Failed";
let code: string | undefined;
// Only transaction sub-responses return body
if (parsedError && parsedError["odata.error"]) {
const error: TableServiceErrorOdataError = parsedError["odata.error"];
message = error.message?.value ?? message;
code = error.code;
}
throw new RestError(message, {
code,
statusCode,
request,
response,
});
}
/**
* Prepares the transaction pipeline to intercept operations
* @param pipeline - Client pipeline
*/
export function prepateTransactionPipeline(
pipeline: Pipeline,
bodyParts: string[],
changesetId: string,
isCosmos: boolean
): void {
// Fist, we need to clear all the existing policies to make sure we start
// with a fresh state.
const policies = pipeline.getOrderedPolicies();
for (const policy of policies) {
pipeline.removePolicy({
name: policy.name,
});
}
// With the clear state we now initialize the pipelines required for intercepting the requests.
// Use transaction assemble policy to assemble request and intercept request from going to wire
pipeline.addPolicy(serializationPolicy(), { phase: "Serialize" });
pipeline.addPolicy(transactionHeaderFilterPolicy());
pipeline.addPolicy(transactionRequestAssemblePolicy(bodyParts, changesetId));
if (isCosmos) {
pipeline.addPolicy(cosmosPatchPolicy(), {
afterPolicies: [transactionHeaderFilterPolicyName],
beforePolicies: [serializationPolicyName, transactionRequestAssemblePolicyName],
});
}
}