Skip to content

Commit 6d9c3e8

Browse files
authored
docs(batch): create API docs for the utility (#1621)
* docs: add api docs & review types * chore: updated comment
1 parent 4e6c0d2 commit 6d9c3e8

12 files changed

+510
-277
lines changed

packages/batch/src/AsyncBatchProcessor.ts

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,39 @@
11
import { BasePartialBatchProcessor } from './BasePartialBatchProcessor';
2-
import type { BaseRecord, FailureResponse, SuccessResponse } from './types';
2+
import type {
3+
EventSourceType,
4+
FailureResponse,
5+
SuccessResponse,
6+
} from './types';
37

48
/**
5-
* Process native partial responses from SQS, Kinesis Data Streams, and DynamoDB
9+
* Asynchronously process a batch of records from SQS, Kinesis Data Streams, and DynamoDB and report partial failures
10+
* using native responses.
11+
*
12+
* When processing a batch of records, this processor will handle partial failures and
13+
* return a response object that can be used to report partial failures and avoid reprocessing
14+
* the same records.
15+
*
16+
* @example
17+
* ```typescript
18+
* import {
19+
* AsyncBatchProcessor,
20+
* EventType,
21+
* } from '@aws-lambda-powertools/batch';
22+
*
23+
* const processor = new AsyncBatchProcessor(EventType.SQS);
24+
* ```
625
*/
726
class AsyncBatchProcessor extends BasePartialBatchProcessor {
27+
/**
28+
* Process a record asynchronously using the provided handler.
29+
*
30+
* @param record Record to process within the batch
31+
*/
832
public async asyncProcessRecord(
9-
record: BaseRecord
33+
record: EventSourceType
1034
): Promise<SuccessResponse | FailureResponse> {
1135
try {
12-
const data = this.toBatchType(record, this.eventType);
13-
const result = await this.handler(data, this.options);
36+
const result = await this.handler(record, this.options?.context);
1437

1538
return this.successHandler(record, result);
1639
} catch (error) {
@@ -19,11 +42,13 @@ class AsyncBatchProcessor extends BasePartialBatchProcessor {
1942
}
2043

2144
/**
22-
* Process a record with instance's handler
23-
* @param record Batch record to be processed
24-
* @returns response of success or failure
45+
* Process a record synchronously using the provided handler.
46+
*
47+
* Throws an error if called on an async processor. Please use `asyncProcessRecord()` instead.
2548
*/
26-
public processRecord(_record: BaseRecord): SuccessResponse | FailureResponse {
49+
public processRecord(
50+
_record: EventSourceType
51+
): SuccessResponse | FailureResponse {
2752
throw new Error('Not implemented. Use asyncProcess() instead.');
2853
}
2954
}

packages/batch/src/BasePartialBatchProcessor.ts

Lines changed: 68 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,22 @@ import type {
44
SQSRecord,
55
} from 'aws-lambda';
66
import { BasePartialProcessor } from './BasePartialProcessor';
7-
import { DATA_CLASS_MAPPING, DEFAULT_RESPONSE, EventType } from './constants';
7+
import { DEFAULT_RESPONSE, EventType } from './constants';
88
import { BatchProcessingError } from './errors';
9-
import type {
10-
EventSourceDataClassTypes,
11-
PartialItemFailureResponse,
12-
PartialItemFailures,
13-
} from './types';
9+
import type { PartialItemFailureResponse, PartialItemFailures } from './types';
1410

1511
/**
16-
* Process batch and partially report failed items
12+
* Abstract class to process a batch of records and report partial failures
1713
*/
1814
abstract class BasePartialBatchProcessor extends BasePartialProcessor {
19-
public COLLECTOR_MAPPING;
20-
21-
public batchResponse: PartialItemFailureResponse;
22-
23-
public eventType: keyof typeof EventType;
15+
/**
16+
* Response object to be used in reporting partial failures
17+
*/
18+
protected batchResponse: PartialItemFailureResponse;
19+
/**
20+
* The type of event that triggered the Lambda function
21+
*/
22+
private eventType: keyof typeof EventType;
2423

2524
/**
2625
* Initializes base batch processing class
@@ -29,128 +28,116 @@ abstract class BasePartialBatchProcessor extends BasePartialProcessor {
2928
public constructor(eventType: keyof typeof EventType) {
3029
super();
3130
this.eventType = eventType;
32-
this.batchResponse = DEFAULT_RESPONSE;
33-
this.COLLECTOR_MAPPING = {
34-
[EventType.SQS]: () => this.collectSqsFailures(),
35-
[EventType.KinesisDataStreams]: () => this.collectKinesisFailures(),
36-
[EventType.DynamoDBStreams]: () => this.collectDynamoDBFailures(),
37-
};
31+
this.batchResponse = { ...DEFAULT_RESPONSE };
32+
}
33+
34+
/**
35+
* Return response object to be used in reporting partial failures
36+
*/
37+
public response(): PartialItemFailureResponse {
38+
return this.batchResponse;
3839
}
3940

4041
/**
41-
* Report messages to be deleted in case of partial failures
42+
* Perfom cleanup after processing a batch of records.
43+
*
44+
* If the entire batch failed, throw an error. Otherwise,
45+
* prepare the response object to be used in reporting partial failures.
4246
*/
43-
public clean(): void {
47+
protected clean(): void {
4448
if (!this.hasMessagesToReport()) {
4549
return;
4650
}
4751

4852
if (this.entireBatchFailed()) {
4953
throw new BatchProcessingError(
5054
'All records failed processing. ' +
51-
this.exceptions.length +
55+
this.errors.length +
5256
' individual errors logged separately below.',
53-
this.exceptions
57+
this.errors
5458
);
5559
}
5660

57-
const messages: PartialItemFailures[] = this.getMessagesToReport();
58-
this.batchResponse = { batchItemFailures: messages };
61+
this.batchResponse = { batchItemFailures: this.getMessagesToReport() };
5962
}
6063

6164
/**
62-
* Collects identifiers of failed items for a DynamoDB stream
63-
* @returns list of identifiers for failed items
65+
* Collect the identifiers of failed items for a DynamoDB stream.
6466
*/
65-
public collectDynamoDBFailures(): PartialItemFailures[] {
67+
protected collectDynamoDBFailures(): PartialItemFailures[] {
6668
const failures: PartialItemFailures[] = [];
6769

68-
for (const msg of this.failureMessages) {
69-
const msgId = (msg as DynamoDBRecord).dynamodb?.SequenceNumber;
70-
if (msgId) {
71-
failures.push({ itemIdentifier: msgId });
70+
for (const message of this.failureMessages) {
71+
const messageId = (message as DynamoDBRecord).dynamodb?.SequenceNumber;
72+
if (messageId) {
73+
failures.push({ itemIdentifier: messageId });
7274
}
7375
}
7476

7577
return failures;
7678
}
7779

7880
/**
79-
* Collects identifiers of failed items for a Kinesis stream
80-
* @returns list of identifiers for failed items
81+
* Collect the identifiers of failed items for a Kinesis data stream.
8182
*/
82-
public collectKinesisFailures(): PartialItemFailures[] {
83-
const failures: PartialItemFailures[] = [];
84-
85-
for (const msg of this.failureMessages) {
86-
const msgId = (msg as KinesisStreamRecord).kinesis.sequenceNumber;
87-
failures.push({ itemIdentifier: msgId });
88-
}
89-
90-
return failures;
83+
protected collectKinesisFailures(): PartialItemFailures[] {
84+
return this.failureMessages.map((message) => {
85+
const {
86+
kinesis: { sequenceNumber },
87+
} = message as KinesisStreamRecord;
88+
89+
return { itemIdentifier: sequenceNumber };
90+
});
9191
}
9292

9393
/**
94-
* Collects identifiers of failed items for an SQS batch
95-
* @returns list of identifiers for failed items
94+
* Collect the identifiers of failed items for a SQS queue.
9695
*/
97-
public collectSqsFailures(): PartialItemFailures[] {
98-
const failures: PartialItemFailures[] = [];
99-
100-
for (const msg of this.failureMessages) {
101-
const msgId = (msg as SQSRecord).messageId;
102-
failures.push({ itemIdentifier: msgId });
103-
}
96+
protected collectSqsFailures(): PartialItemFailures[] {
97+
return this.failureMessages.map((message) => {
98+
const { messageId } = message as SQSRecord;
10499

105-
return failures;
100+
return { itemIdentifier: messageId };
101+
});
106102
}
107103

108104
/**
109-
* Determines whether all records in a batch failed to process
110-
* @returns true if all records resulted in exception results
105+
* Determine whether the entire batch failed to be processed.
111106
*/
112-
public entireBatchFailed(): boolean {
113-
return this.exceptions.length == this.records.length;
107+
protected entireBatchFailed(): boolean {
108+
return this.errors.length === this.records.length;
114109
}
115110

116111
/**
117-
* Collects identifiers for failed batch items
118-
* @returns formatted messages to use in batch deletion
112+
* Collect all failed messages and returns them as a list of partial failures
113+
* according to the event type.
119114
*/
120-
public getMessagesToReport(): PartialItemFailures[] {
121-
return this.COLLECTOR_MAPPING[this.eventType]();
115+
protected getMessagesToReport(): PartialItemFailures[] {
116+
switch (this.eventType) {
117+
case EventType.SQS:
118+
return this.collectSqsFailures();
119+
case EventType.KinesisDataStreams:
120+
return this.collectKinesisFailures();
121+
case EventType.DynamoDBStreams:
122+
return this.collectDynamoDBFailures();
123+
}
122124
}
123125

124126
/**
125-
* Determines if any records failed to process
126-
* @returns true if any records resulted in exception
127+
* Determine whether there are any failed messages to report as partial failures.
127128
*/
128-
public hasMessagesToReport(): boolean {
129+
protected hasMessagesToReport(): boolean {
129130
return this.failureMessages.length != 0;
130131
}
131132

132133
/**
133-
* Remove results from previous execution
134+
* Prepare class instance for processing a new batch of records.
134135
*/
135-
public prepare(): void {
136+
protected prepare(): void {
136137
this.successMessages.length = 0;
137138
this.failureMessages.length = 0;
138-
this.exceptions.length = 0;
139-
this.batchResponse = DEFAULT_RESPONSE;
140-
}
141-
142-
/**
143-
* @returns Batch items that failed processing, if any
144-
*/
145-
public response(): PartialItemFailureResponse {
146-
return this.batchResponse;
147-
}
148-
149-
public toBatchType(
150-
record: EventSourceDataClassTypes,
151-
eventType: keyof typeof EventType
152-
): SQSRecord | KinesisStreamRecord | DynamoDBRecord {
153-
return DATA_CLASS_MAPPING[eventType](record);
139+
this.errors.length = 0;
140+
this.batchResponse = { ...DEFAULT_RESPONSE };
154141
}
155142
}
156143

0 commit comments

Comments
 (0)