• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

localstack / localstack / aa29258c-55e5-4a0d-ab0a-50af00b3a3ed

13 Feb 2025 09:28AM UTC coverage: 86.881% (-0.02%) from 86.901%
aa29258c-55e5-4a0d-ab0a-50af00b3a3ed

push

circleci

web-flow
skip flaky transcribe tests (#12260)

61502 of 70789 relevant lines covered (86.88%)

0.87 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.15
/localstack-core/localstack/services/lambda_/event_source_mapping/pollers/stream_poller.py
1
import json
1✔
2
import logging
1✔
3
from abc import abstractmethod
1✔
4
from datetime import datetime
1✔
5
from typing import Iterator
1✔
6

7
from botocore.client import BaseClient
1✔
8
from botocore.exceptions import ClientError
1✔
9

10
from localstack.aws.api.pipes import (
1✔
11
    OnPartialBatchItemFailureStreams,
12
)
13
from localstack.services.lambda_.event_source_mapping.event_processor import (
1✔
14
    BatchFailureError,
15
    CustomerInvocationError,
16
    EventProcessor,
17
    PartialBatchFailureError,
18
    PipeInternalError,
19
)
20
from localstack.services.lambda_.event_source_mapping.pipe_utils import (
1✔
21
    get_current_time,
22
    get_datetime_from_timestamp,
23
    get_internal_client,
24
)
25
from localstack.services.lambda_.event_source_mapping.pollers.poller import (
1✔
26
    Poller,
27
    get_batch_item_failures,
28
)
29
from localstack.services.lambda_.event_source_mapping.pollers.sqs_poller import get_queue_url
1✔
30
from localstack.utils.aws.arns import parse_arn, s3_bucket_name
1✔
31
from localstack.utils.strings import long_uid
1✔
32

33
LOG = logging.getLogger(__name__)
1✔
34

35

36
# TODO: fix this poller to support resharding
37
#   https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-resharding.html
38
class StreamPoller(Poller):
1✔
39
    # Mapping of shard id => shard iterator
40
    shards: dict[str, str]
1✔
41
    # Iterator for round-robin polling from different shards because a batch cannot contain events from different shards
42
    # This is a workaround for not handling shards in parallel.
43
    iterator_over_shards: Iterator[tuple[str, str]] | None
1✔
44
    # ESM UUID is needed in failure processing to form s3 failure destination object key
45
    esm_uuid: str | None
1✔
46

47
    # The ARN of the processor (e.g., Pipe ARN)
48
    partner_resource_arn: str | None
1✔
49

50
    def __init__(
1✔
51
        self,
52
        source_arn: str,
53
        source_parameters: dict | None = None,
54
        source_client: BaseClient | None = None,
55
        processor: EventProcessor | None = None,
56
        partner_resource_arn: str | None = None,
57
        esm_uuid: str | None = None,
58
    ):
59
        super().__init__(source_arn, source_parameters, source_client, processor)
1✔
60
        self.partner_resource_arn = partner_resource_arn
1✔
61
        self.esm_uuid = esm_uuid
1✔
62
        self.shards = {}
1✔
63
        self.iterator_over_shards = None
1✔
64

65
    @abstractmethod
1✔
66
    def transform_into_events(self, records: list[dict], shard_id) -> list[dict]:
1✔
67
        pass
×
68

69
    @property
1✔
70
    @abstractmethod
1✔
71
    def stream_parameters(self) -> dict:
1✔
72
        pass
×
73

74
    @abstractmethod
1✔
75
    def initialize_shards(self) -> dict[str, str]:
1✔
76
        """Returns a shard dict mapping from shard id -> shard iterator
77
        The implementations for Kinesis and DynamoDB are similar but differ in various ways:
78
        * Kinesis uses "StreamARN" and DynamoDB uses "StreamArn" as source parameter
79
        * Kinesis uses "StreamStatus.ACTIVE" and DynamoDB uses "StreamStatus.ENABLED"
80
        * Only Kinesis supports the additional StartingPosition called "AT_TIMESTAMP" using "StartingPositionTimestamp"
81
        """
82
        pass
×
83

84
    @abstractmethod
1✔
85
    def stream_arn_param(self) -> dict:
1✔
86
        """Returns a dict of the correct key/value pair for the stream arn used in GetRecords.
87
        Either StreamARN for Kinesis or {} for DynamoDB (unsupported)"""
88
        pass
×
89

90
    @abstractmethod
1✔
91
    def failure_payload_details_field_name(self) -> str:
1✔
92
        pass
×
93

94
    @abstractmethod
1✔
95
    def get_approximate_arrival_time(self, record: dict) -> float:
1✔
96
        pass
×
97

98
    @abstractmethod
1✔
99
    def format_datetime(self, time: datetime) -> str:
1✔
100
        """Formats a datetime in the correct format for DynamoDB (with ms) or Kinesis (without ms)"""
101
        pass
×
102

103
    @abstractmethod
1✔
104
    def get_sequence_number(self, record: dict) -> str:
1✔
105
        pass
×
106

107
    def pre_filter(self, events: list[dict]) -> list[dict]:
1✔
108
        return events
1✔
109

110
    def post_filter(self, events: list[dict]) -> list[dict]:
1✔
111
        return events
1✔
112

113
    def poll_events(self):
1✔
114
        """Generalized poller for streams such as Kinesis or DynamoDB
115
        Examples of Kinesis consumers:
116
        * StackOverflow: https://stackoverflow.com/a/22403036/6875981
117
        * AWS Sample: https://github.com/aws-samples/kinesis-poster-worker/blob/master/worker.py
118
        Examples of DynamoDB consumers:
119
        * Blogpost: https://www.tecracer.com/blog/2022/05/getting-a-near-real-time-view-of-a-dynamodb-stream-with-python.html
120
        """
121
        # TODO: consider potential shard iterator timeout after 300 seconds (likely not relevant with short-polling):
122
        #   https://docs.aws.amazon.com/streams/latest/dev/troubleshooting-consumers.html#shard-iterator-expires-unexpectedly
123
        #  Does this happen if no records are received for 300 seconds?
124
        if not self.shards:
1✔
125
            self.shards = self.initialize_shards()
1✔
126

127
        # TODO: improve efficiency because this currently limits the throughput to at most batch size per poll interval
128
        # Handle shards round-robin. Re-initialize current shard iterator once all shards are handled.
129
        if self.iterator_over_shards is None:
1✔
130
            self.iterator_over_shards = iter(self.shards.items())
1✔
131

132
        current_shard_tuple = next(self.iterator_over_shards, None)
1✔
133
        if not current_shard_tuple:
1✔
134
            self.iterator_over_shards = iter(self.shards.items())
1✔
135
            current_shard_tuple = next(self.iterator_over_shards, None)
1✔
136

137
        try:
1✔
138
            self.poll_events_from_shard(*current_shard_tuple)
1✔
139
        # TODO: implement exponential back-off for errors in general
140
        except PipeInternalError:
1✔
141
            # TODO: standardize logging
142
            # Ignore and wait for the next polling interval, which will do retry
143
            pass
×
144

145
    def poll_events_from_shard(self, shard_id: str, shard_iterator: str):
1✔
146
        abort_condition = None
1✔
147
        get_records_response = self.get_records(shard_iterator)
1✔
148
        records = get_records_response["Records"]
1✔
149
        polled_events = self.transform_into_events(records, shard_id)
1✔
150
        # Check MaximumRecordAgeInSeconds
151
        if maximum_record_age_in_seconds := self.stream_parameters.get("MaximumRecordAgeInSeconds"):
1✔
152
            arrival_timestamp_of_last_event = polled_events[-1]["approximateArrivalTimestamp"]
×
153
            now = get_current_time().timestamp()
×
154
            record_age_in_seconds = now - arrival_timestamp_of_last_event
×
155
            if record_age_in_seconds > maximum_record_age_in_seconds:
×
156
                abort_condition = "RecordAgeExpired"
×
157

158
        # TODO: implement format detection behavior (e.g., for JSON body):
159
        #  https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-pipes-event-filtering.html
160
        #  Check whether we need poller-specific filter-preprocessing here without modifying the actual event!
161
        # convert to json for filtering (HACK for fixing parity with v1 and getting regression tests passing)
162
        # localstack.services.lambda_.event_source_listeners.kinesis_event_source_listener.KinesisEventSourceListener._filter_records
163
        # TODO: explore better abstraction for the entire filtering, including the set_data and get_data remapping
164
        #  We need better clarify which transformations happen before and after filtering -> fix missing test coverage
165
        parsed_events = self.pre_filter(polled_events)
1✔
166
        # TODO: advance iterator past matching events!
167
        #  We need to checkpoint the sequence number for each shard and then advance the shard iterator using
168
        #  GetShardIterator with a given sequence number
169
        #  https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html
170
        #  Failing to do so kinda blocks the stream resulting in very high latency.
171
        matching_events = self.filter_events(parsed_events)
1✔
172
        matching_events_post_filter = self.post_filter(matching_events)
1✔
173

174
        # TODO: implement MaximumBatchingWindowInSeconds flush condition (before or after filter?)
175
        # Don't trigger upon empty events
176
        if len(matching_events_post_filter) == 0:
1✔
177
            # Update shard iterator if no records match the filter
178
            self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
179
            return
1✔
180
        events = self.add_source_metadata(matching_events_post_filter)
1✔
181
        LOG.debug("Polled %d events from %s in shard %s", len(events), self.source_arn, shard_id)
1✔
182
        # TODO: A retry should probably re-trigger fetching the record from the stream again?!
183
        #  -> This could be tested by setting a high retry number, using a long pipe execution, and a relatively
184
        #  short record expiration age at the source. Check what happens if the record expires at the source.
185
        #  A potential implementation could use checkpointing based on the iterator position (within shard scope)
186
        # TODO: handle partial batch failure (see poller.py:parse_batch_item_failures)
187
        # TODO: think about how to avoid starvation of other shards if one shard runs into infinite retries
188
        attempts = 0
1✔
189
        error_payload = {}
1✔
190
        while not abort_condition and not self.max_retries_exceeded(attempts):
1✔
191
            try:
1✔
192
                self.processor.process_events_batch(events)
1✔
193
                # Update shard iterator if execution is successful
194
                self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
195
                return
1✔
196
            except PartialBatchFailureError as ex:
1✔
197
                # TODO: add tests for partial batch failure scenarios
198
                if (
1✔
199
                    self.stream_parameters.get("OnPartialBatchItemFailure")
200
                    == OnPartialBatchItemFailureStreams.AUTOMATIC_BISECT
201
                ):
202
                    # TODO: implement and test splitting batches in half until batch size 1
203
                    #  https://docs.aws.amazon.com/eventbridge/latest/pipes-reference/API_PipeSourceKinesisStreamParameters.html
204
                    LOG.warning(
×
205
                        "AUTOMATIC_BISECT upon partial batch item failure is not yet implemented. Retrying the entire batch."
206
                    )
207
                error_payload = ex.error
1✔
208

209
                # Extract all sequence numbers from events in batch. This allows us to fail the whole batch if
210
                # an unknown itemidentifier is returned.
211
                batch_sequence_numbers = {
1✔
212
                    self.get_sequence_number(event) for event in matching_events
213
                }
214

215
                # If the batchItemFailures array contains multiple items, Lambda uses the record with the lowest sequence number as the checkpoint.
216
                # Lambda then retries all records starting from that checkpoint.
217
                failed_sequence_ids: list[int] | None = get_batch_item_failures(
1✔
218
                    ex.partial_failure_payload, batch_sequence_numbers
219
                )
220

221
                # If None is returned, consider the entire batch a failure.
222
                if failed_sequence_ids is None:
1✔
223
                    continue
1✔
224

225
                # This shouldn't be possible since a PartialBatchFailureError was raised
226
                if len(failed_sequence_ids) == 0:
1✔
227
                    assert failed_sequence_ids, (
×
228
                        "Invalid state encountered: PartialBatchFailureError raised but no batch item failures found."
229
                    )
230

231
                lowest_sequence_id: str = min(failed_sequence_ids, key=int)
1✔
232

233
                # Discard all successful events and re-process from sequence number of failed event
234
                _, events = self.bisect_events(lowest_sequence_id, events)
1✔
235
            except (BatchFailureError, Exception) as ex:
1✔
236
                if isinstance(ex, BatchFailureError):
1✔
237
                    error_payload = ex.error
1✔
238

239
                # FIXME partner_resource_arn is not defined in ESM
240
                LOG.debug(
1✔
241
                    "Attempt %d failed while processing %s with events: %s",
242
                    attempts,
243
                    self.partner_resource_arn or self.source_arn,
244
                    events,
245
                )
246
            finally:
247
                # Retry polling until the record expires at the source
248
                attempts += 1
1✔
249

250
        # Send failed events to potential DLQ
251
        abort_condition = abort_condition or "RetryAttemptsExhausted"
1✔
252
        failure_context = self.processor.generate_event_failure_context(
1✔
253
            abort_condition=abort_condition,
254
            error=error_payload,
255
            attempts_count=attempts,
256
            partner_resource_arn=self.partner_resource_arn,
257
        )
258
        self.send_events_to_dlq(shard_id, events, context=failure_context)
1✔
259
        # Update shard iterator if the execution failed but the events are sent to a DLQ
260
        self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
261

262
    def get_records(self, shard_iterator: str) -> dict:
1✔
263
        """Returns a GetRecordsOutput from the GetRecords endpoint of streaming services such as Kinesis or DynamoDB"""
264
        try:
1✔
265
            get_records_response = self.source_client.get_records(
1✔
266
                # TODO: add test for cross-account scenario
267
                # Differs for Kinesis and DynamoDB but required for cross-account scenario
268
                **self.stream_arn_param(),
269
                ShardIterator=shard_iterator,
270
                Limit=self.stream_parameters["BatchSize"],
271
            )
272
            return get_records_response
1✔
273
        # TODO: test iterator expired with conditional error scenario (requires failure destinations)
274
        except self.source_client.exceptions.ExpiredIteratorException as e:
1✔
275
            LOG.debug(
×
276
                "Shard iterator %s expired for stream %s, re-initializing shards",
277
                shard_iterator,
278
                self.source_arn,
279
            )
280
            # TODO: test TRIM_HORIZON and AT_TIMESTAMP scenarios for this case. We don't want to start from scratch and
281
            #  might need to think about checkpointing here.
282
            self.shards = self.initialize_shards()
×
283
            raise PipeInternalError from e
×
284
        except ClientError as e:
1✔
285
            if "AccessDeniedException" in str(e):
1✔
286
                LOG.warning(
×
287
                    "Insufficient permissions to get records from stream %s: %s",
288
                    self.source_arn,
289
                    e,
290
                )
291
                raise CustomerInvocationError from e
×
292
            elif "ResourceNotFoundException" in str(e):
1✔
293
                # FIXME: The 'Invalid ShardId in ShardIterator' error is returned by DynamoDB-local. Unsure when/why this is returned.
294
                if "Invalid ShardId in ShardIterator" in str(e):
1✔
295
                    LOG.warning(
×
296
                        "Invalid ShardId in ShardIterator for %s. Re-initializing shards.",
297
                        self.source_arn,
298
                    )
299
                    self.initialize_shards()
×
300
                else:
301
                    LOG.warning(
1✔
302
                        "Source stream %s does not exist: %s",
303
                        self.source_arn,
304
                        e,
305
                    )
306
                    raise CustomerInvocationError from e
1✔
307
            elif "TrimmedDataAccessException" in str(e):
×
308
                LOG.debug(
×
309
                    "Attempted to iterate over trimmed record or expired shard iterator %s for stream %s, re-initializing shards",
310
                    shard_iterator,
311
                    self.source_arn,
312
                )
313
                self.initialize_shards()
×
314
            else:
315
                LOG.debug("ClientError during get_records for stream %s: %s", self.source_arn, e)
×
316
                raise PipeInternalError from e
×
317

318
    def send_events_to_dlq(self, shard_id, events, context) -> None:
1✔
319
        dlq_arn = self.stream_parameters.get("DeadLetterConfig", {}).get("Arn")
1✔
320
        if dlq_arn:
1✔
321
            failure_timstamp = get_current_time()
1✔
322
            dlq_event = self.create_dlq_event(shard_id, events, context, failure_timstamp)
1✔
323
            # Send DLQ event to DLQ target
324
            parsed_arn = parse_arn(dlq_arn)
1✔
325
            service = parsed_arn["service"]
1✔
326
            # TODO: use a sender instance here, likely inject via DI into poller (what if it updates?)
327
            if service == "sqs":
1✔
328
                # TODO: inject and cache SQS client using proper IAM role (supports cross-account operations)
329
                sqs_client = get_internal_client(dlq_arn)
1✔
330
                # TODO: check if the DLQ exists
331
                dlq_url = get_queue_url(dlq_arn)
1✔
332
                # TODO: validate no FIFO queue because they are unsupported
333
                sqs_client.send_message(QueueUrl=dlq_url, MessageBody=json.dumps(dlq_event))
1✔
334
            elif service == "sns":
1✔
335
                sns_client = get_internal_client(dlq_arn)
1✔
336
                sns_client.publish(TopicArn=dlq_arn, Message=json.dumps(dlq_event))
1✔
337
            elif service == "s3":
1✔
338
                s3_client = get_internal_client(dlq_arn)
1✔
339
                dlq_event_with_payload = {
1✔
340
                    **dlq_event,
341
                    "payload": {
342
                        "Records": events,
343
                    },
344
                }
345
                s3_client.put_object(
1✔
346
                    Bucket=s3_bucket_name(dlq_arn),
347
                    Key=get_failure_s3_object_key(self.esm_uuid, shard_id, failure_timstamp),
348
                    Body=json.dumps(dlq_event_with_payload),
349
                )
350
            else:
351
                LOG.warning("Unsupported DLQ service %s", service)
×
352

353
    def create_dlq_event(
1✔
354
        self, shard_id: str, events: list[dict], context: dict, failure_timestamp: datetime
355
    ) -> dict:
356
        first_record = events[0]
1✔
357
        first_record_arrival = get_datetime_from_timestamp(
1✔
358
            self.get_approximate_arrival_time(first_record)
359
        )
360

361
        last_record = events[-1]
1✔
362
        last_record_arrival = get_datetime_from_timestamp(
1✔
363
            self.get_approximate_arrival_time(last_record)
364
        )
365
        return {
1✔
366
            **context,
367
            self.failure_payload_details_field_name(): {
368
                "approximateArrivalOfFirstRecord": self.format_datetime(first_record_arrival),
369
                "approximateArrivalOfLastRecord": self.format_datetime(last_record_arrival),
370
                "batchSize": len(events),
371
                "endSequenceNumber": self.get_sequence_number(last_record),
372
                "shardId": shard_id,
373
                "startSequenceNumber": self.get_sequence_number(first_record),
374
                "streamArn": self.source_arn,
375
            },
376
            "timestamp": failure_timestamp.isoformat(timespec="milliseconds").replace(
377
                "+00:00", "Z"
378
            ),
379
            "version": "1.0",
380
        }
381

382
    def max_retries_exceeded(self, attempts: int) -> bool:
1✔
383
        maximum_retry_attempts = self.stream_parameters.get("MaximumRetryAttempts", -1)
1✔
384
        # Infinite retries until the source expires
385
        if maximum_retry_attempts == -1:
1✔
386
            return False
1✔
387
        return attempts > maximum_retry_attempts
1✔
388

389
    def bisect_events(
1✔
390
        self, sequence_number: str, events: list[dict]
391
    ) -> tuple[list[dict], list[dict]]:
392
        """Splits list of events in two, where a sequence number equals a passed parameter `sequence_number`.
393
        This is used for:
394
          - `ReportBatchItemFailures`: Discarding events in a batch following a failure when is set.
395
          - `BisectBatchOnFunctionError`: Used to split a failed batch in two when doing a retry (not implemented)."""
396
        for i, event in enumerate(events):
1✔
397
            if self.get_sequence_number(event) == sequence_number:
1✔
398
                return events[:i], events[i:]
1✔
399

400
        return events, []
×
401

402

403
def get_failure_s3_object_key(esm_uuid: str, shard_id: str, failure_datetime: datetime) -> str:
1✔
404
    """
405
    From https://docs.aws.amazon.com/lambda/latest/dg/kinesis-on-failure-destination.html:
406

407
    The S3 object containing the invocation record uses the following naming convention:
408
    aws/lambda/<ESM-UUID>/<shardID>/YYYY/MM/DD/YYYY-MM-DDTHH.MM.SS-<Random UUID>
409

410
    :return: Key for s3 object that invocation failure record will be put to
411
    """
412
    timestamp = failure_datetime.strftime("%Y-%m-%dT%H.%M.%S")
1✔
413
    year_month_day = failure_datetime.strftime("%Y/%m/%d")
1✔
414
    random_uuid = long_uid()
1✔
415
    return f"aws/lambda/{esm_uuid}/{shard_id}/{year_month_day}/{timestamp}-{random_uuid}"
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc