|
1 | | -// Copyright (c) Microsoft Corporation. All rights reserved. |
2 | | -// Licensed under the MIT License. |
3 | 1 |
|
4 | | -/* |
5 | | - The BulkWriter class is an attempt to provide guidance for creating |
6 | | - a higher level abstraction over the existing low level Java Bulk API |
7 | | - */ |
8 | 2 | package com.azure.cosmos.examples.bulk.sync; |
9 | 3 |
|
10 | 4 | import com.azure.cosmos.CosmosContainer; |
|
16 | 10 | import com.azure.cosmos.models.CosmosItemOperation; |
17 | 11 | import org.slf4j.Logger; |
18 | 12 | import org.slf4j.LoggerFactory; |
19 | | -import reactor.core.publisher.Sinks; |
| 13 | + |
| 14 | +import java.util.ArrayList; |
| 15 | +import java.util.List; |
20 | 16 | import java.util.concurrent.Semaphore; |
21 | 17 |
|
22 | 18 | public class BulkWriter { |
23 | 19 | private static final Logger logger = LoggerFactory.getLogger(BulkWriter.class); |
24 | 20 |
|
25 | | - private final Sinks.Many<CosmosItemOperation> bulkInputEmitter = Sinks.many().unicast().onBackpressureBuffer(); |
| 21 | + private final CosmosContainer cosmosContainer; |
26 | 22 | private final int cpuCount = Runtime.getRuntime().availableProcessors(); |
27 | | - |
28 | | - //Max items to be buffered to avoid out of memory error |
29 | 23 | private final Semaphore semaphore = new Semaphore(1024 * 167 / cpuCount); |
30 | | - |
31 | | - private final Sinks.EmitFailureHandler emitFailureHandler = |
32 | | - (signalType, emitResult) -> { |
33 | | - if (emitResult.equals(Sinks.EmitResult.FAIL_NON_SERIALIZED)) { |
34 | | - logger.debug("emitFailureHandler - Signal: [{}], Result: [{}]", signalType, emitResult); |
35 | | - return true; |
36 | | - } else { |
37 | | - logger.error("emitFailureHandler - Signal: [{}], Result: [{}]", signalType, emitResult); |
38 | | - return false; |
39 | | - } |
40 | | - }; |
41 | | - |
42 | | - private final CosmosContainer cosmosContainer; |
| 24 | + private final List<CosmosItemOperation> bufferedOperations = new ArrayList<>(); |
| 25 | + private final int maxRetries = 5; |
43 | 26 |
|
44 | 27 | public BulkWriter(CosmosContainer cosmosContainer) { |
45 | 28 | this.cosmosContainer = cosmosContainer; |
46 | 29 | } |
47 | 30 |
|
48 | 31 | public void scheduleWrites(CosmosItemOperation cosmosItemOperation) { |
49 | | - while(!semaphore.tryAcquire()) { |
| 32 | + while (!semaphore.tryAcquire()) { |
50 | 33 | logger.info("Unable to acquire permit"); |
51 | 34 | } |
52 | 35 | logger.info("Acquired permit"); |
53 | | - scheduleInternalWrites(cosmosItemOperation); |
54 | | - } |
55 | | - |
56 | | - private void scheduleInternalWrites(CosmosItemOperation cosmosItemOperation) { |
57 | | - bulkInputEmitter.emitNext(cosmosItemOperation, emitFailureHandler); |
| 36 | + bufferedOperations.add(cosmosItemOperation); |
58 | 37 | } |
59 | 38 |
|
60 | 39 | public Iterable<CosmosBulkOperationResponse<Object>> execute() { |
61 | | - return this.execute(null); |
| 40 | + return execute(null); |
62 | 41 | } |
63 | 42 |
|
64 | 43 | public Iterable<CosmosBulkOperationResponse<Object>> execute(CosmosBulkExecutionOptions bulkOptions) { |
65 | 44 | if (bulkOptions == null) { |
66 | 45 | bulkOptions = new CosmosBulkExecutionOptions(); |
67 | 46 | } |
68 | | - bulkInputEmitter.tryEmitComplete(); |
69 | | - Iterable<CosmosBulkOperationResponse<Object>> bulkOperationResponse = cosmosContainer |
70 | | - .executeBulkOperations( |
71 | | - bulkInputEmitter.asFlux().toIterable(), |
72 | | - bulkOptions); |
73 | | - for (CosmosBulkOperationResponse<Object> response : bulkOperationResponse) { |
74 | | - processBulkOperationResponse( |
75 | | - response.getResponse(), |
76 | | - response.getOperation(), |
77 | | - response.getException()); |
78 | | - } |
79 | | - semaphore.release(); |
80 | | - return bulkOperationResponse; |
81 | | - } |
82 | 47 |
|
| 48 | + List<CosmosItemOperation> currentBatch = new ArrayList<>(bufferedOperations); |
| 49 | + bufferedOperations.clear(); |
| 50 | + List<CosmosBulkOperationResponse<Object>> finalResponses = new ArrayList<>(); |
| 51 | + int attempt = 0; |
| 52 | + |
| 53 | + while (!currentBatch.isEmpty() && attempt <= maxRetries) { |
| 54 | + logger.info("Executing bulk attempt {} with {} items", attempt + 1, currentBatch.size()); |
| 55 | + |
| 56 | + Iterable<CosmosBulkOperationResponse<Object>> responses = |
| 57 | + cosmosContainer.executeBulkOperations(currentBatch, bulkOptions); |
| 58 | + |
| 59 | + List<CosmosItemOperation> toRetry = new ArrayList<>(); |
| 60 | + |
| 61 | + for (CosmosBulkOperationResponse<Object> response : responses) { |
| 62 | + processBulkOperationResponse( |
| 63 | + response.getResponse(), |
| 64 | + response.getOperation(), |
| 65 | + response.getException(), |
| 66 | + toRetry |
| 67 | + ); |
| 68 | + finalResponses.add(response); |
| 69 | + } |
| 70 | + |
| 71 | + currentBatch = toRetry; |
| 72 | + attempt++; |
| 73 | + } |
83 | 74 |
|
| 75 | + if (!currentBatch.isEmpty()) { |
| 76 | + logger.error("BulkWriter: {} items failed after {} retries", currentBatch.size(), maxRetries); |
| 77 | + } |
84 | 78 |
|
| 79 | + semaphore.release(); |
| 80 | + return finalResponses; |
| 81 | + } |
85 | 82 |
|
86 | 83 | private void processBulkOperationResponse( |
87 | | - CosmosBulkItemResponse itemResponse, |
88 | | - CosmosItemOperation itemOperation, |
89 | | - Exception exception) { |
| 84 | + CosmosBulkItemResponse itemResponse, |
| 85 | + CosmosItemOperation itemOperation, |
| 86 | + Exception exception, |
| 87 | + List<CosmosItemOperation> retryList) { |
90 | 88 |
|
91 | 89 | if (exception != null) { |
92 | | - handleException(itemOperation, exception); |
| 90 | + handleException(itemOperation, exception, retryList); |
93 | 91 | } else { |
94 | | - processResponseCode(itemResponse, itemOperation); |
| 92 | + processResponseCode(itemResponse, itemOperation, retryList); |
95 | 93 | } |
96 | 94 | } |
97 | 95 |
|
98 | 96 | private void processResponseCode( |
99 | | - CosmosBulkItemResponse itemResponse, |
100 | | - CosmosItemOperation itemOperation) { |
| 97 | + CosmosBulkItemResponse itemResponse, |
| 98 | + CosmosItemOperation itemOperation, |
| 99 | + List<CosmosItemOperation> retryList) { |
101 | 100 |
|
102 | 101 | if (itemResponse.isSuccessStatusCode()) { |
103 | 102 | logger.info( |
104 | | - "The operation for Item ID: [{}] Item PartitionKey Value: [{}] completed successfully " + |
105 | | - "with a response status code: [{}]", |
106 | | - itemOperation.getId(), |
107 | | - itemOperation.getPartitionKeyValue(), |
108 | | - itemResponse.getStatusCode()); |
| 103 | + "Item ID [{}] with PartitionKey [{}] succeeded with status [{}]", |
| 104 | + itemOperation.getId(), |
| 105 | + itemOperation.getPartitionKeyValue(), |
| 106 | + itemResponse.getStatusCode()); |
109 | 107 | } else if (shouldRetry(itemResponse.getStatusCode())) { |
110 | 108 | logger.info( |
111 | | - "The operation for Item ID: [{}] Item PartitionKey Value: [{}] will be retried", |
112 | | - itemOperation.getId(), |
113 | | - itemOperation.getPartitionKeyValue()); |
114 | | - //re-scheduling |
115 | | - scheduleWrites(itemOperation); |
| 109 | + "Item ID [{}] with PartitionKey [{}] will be retried (status [{}])", |
| 110 | + itemOperation.getId(), |
| 111 | + itemOperation.getPartitionKeyValue(), |
| 112 | + itemResponse.getStatusCode()); |
| 113 | + if (itemResponse.getRetryAfterDuration() != null) { |
| 114 | + logger.info( |
| 115 | + "Item ID [{}] with PartitionKey [{}] will be retried after [{}] milliseconds", |
| 116 | + itemOperation.getId(), |
| 117 | + itemOperation.getPartitionKeyValue(), |
| 118 | + itemResponse.getRetryAfterDuration().toMillis()); |
| 119 | + try { |
| 120 | + Thread.sleep(itemResponse.getRetryAfterDuration().toMillis()); |
| 121 | + } catch (InterruptedException e) { |
| 122 | + throw new RuntimeException(e); |
| 123 | + } |
| 124 | + } |
| 125 | + retryList.add(itemOperation); |
116 | 126 | } else { |
117 | 127 | logger.info( |
118 | | - "The operation for Item ID: [{}] Item PartitionKey Value: [{}] did not complete successfully " + |
119 | | - "with a response status code: [{}]", |
120 | | - itemOperation.getId(), |
121 | | - itemOperation.getPartitionKeyValue(), |
122 | | - itemResponse.getStatusCode()); |
| 128 | + "Item ID [{}] with PartitionKey [{}] failed with non-retryable status [{}]", |
| 129 | + itemOperation.getId(), |
| 130 | + itemOperation.getPartitionKeyValue(), |
| 131 | + itemResponse.getStatusCode()); |
123 | 132 | } |
124 | 133 | } |
125 | 134 |
|
126 | | - private void handleException(CosmosItemOperation itemOperation, Exception exception) { |
| 135 | + private void handleException( |
| 136 | + CosmosItemOperation itemOperation, |
| 137 | + Exception exception, |
| 138 | + List<CosmosItemOperation> retryList) { |
| 139 | + |
127 | 140 | if (!(exception instanceof CosmosException)) { |
128 | 141 | logger.info( |
129 | | - "The operation for Item ID: [{}] Item PartitionKey Value: [{}] encountered an unexpected failure", |
130 | | - itemOperation.getId(), |
131 | | - itemOperation.getPartitionKeyValue()); |
132 | | - } else { |
133 | | - if (shouldRetry(((CosmosException) exception).getStatusCode())) { |
134 | | - logger.info( |
135 | | - "The operation for Item ID: [{}] Item PartitionKey Value: [{}] will be retried", |
| 142 | + "Item ID [{}] with PartitionKey [{}] encountered unexpected failure", |
136 | 143 | itemOperation.getId(), |
137 | 144 | itemOperation.getPartitionKeyValue()); |
138 | | - |
139 | | - //re-scheduling |
140 | | - scheduleWrites(itemOperation); |
| 145 | + } else { |
| 146 | + int statusCode = ((CosmosException) exception).getStatusCode(); |
| 147 | + if (shouldRetry(statusCode)) { |
| 148 | + logger.info( |
| 149 | + "Item ID [{}] with PartitionKey [{}] will be retried due to exception status [{}]", |
| 150 | + itemOperation.getId(), |
| 151 | + itemOperation.getPartitionKeyValue(), |
| 152 | + statusCode); |
| 153 | + retryList.add(itemOperation); |
| 154 | + } else { |
| 155 | + logger.error( |
| 156 | + "Item ID [{}] with PartitionKey [{}] failed with non-retryable exception: {}", |
| 157 | + itemOperation.getId(), |
| 158 | + itemOperation.getPartitionKeyValue(), |
| 159 | + exception.getMessage()); |
141 | 160 | } |
142 | 161 | } |
143 | 162 | } |
144 | 163 |
|
145 | 164 | private boolean shouldRetry(int statusCode) { |
146 | 165 | return statusCode == HttpConstants.StatusCodes.REQUEST_TIMEOUT || |
147 | | - statusCode == HttpConstants.StatusCodes.TOO_MANY_REQUESTS; |
| 166 | + statusCode == HttpConstants.StatusCodes.TOO_MANY_REQUESTS; |
148 | 167 | } |
149 | 168 | } |
0 commit comments