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

localstack / localstack / 287d2d5f-77c6-4688-a935-5247d99c1a92

18 Mar 2025 09:15PM UTC coverage: 86.828% (-0.09%) from 86.915%
287d2d5f-77c6-4688-a935-5247d99c1a92

push

circleci

web-flow
APIGW: migrate to new Counter type for REST API analytics (#12383)

8 of 8 new or added lines in 1 file covered. (100.0%)

129 existing lines in 10 files now uncovered.

62766 of 72288 relevant lines covered (86.83%)

0.87 hits per line

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

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

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

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

36
LOG = logging.getLogger(__name__)
1✔
37

38

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

50
    # The ARN of the processor (e.g., Pipe ARN)
51
    partner_resource_arn: str | None
1✔
52

53
    # Used for backing-off between retries and breaking the retry loop
54
    _is_shutdown: threading.Event
1✔
55

56
    def __init__(
1✔
57
        self,
58
        source_arn: str,
59
        source_parameters: dict | None = None,
60
        source_client: BaseClient | None = None,
61
        processor: EventProcessor | None = None,
62
        partner_resource_arn: str | None = None,
63
        esm_uuid: str | None = None,
64
    ):
65
        super().__init__(source_arn, source_parameters, source_client, processor)
1✔
66
        self.partner_resource_arn = partner_resource_arn
1✔
67
        self.esm_uuid = esm_uuid
1✔
68
        self.shards = {}
1✔
69
        self.iterator_over_shards = None
1✔
70

71
        self._is_shutdown = threading.Event()
1✔
72

73
    @abstractmethod
1✔
74
    def transform_into_events(self, records: list[dict], shard_id) -> list[dict]:
1✔
75
        pass
×
76

77
    @property
1✔
78
    @abstractmethod
1✔
79
    def stream_parameters(self) -> dict:
1✔
80
        pass
×
81

82
    @abstractmethod
1✔
83
    def initialize_shards(self) -> dict[str, str]:
1✔
84
        """Returns a shard dict mapping from shard id -> shard iterator
85
        The implementations for Kinesis and DynamoDB are similar but differ in various ways:
86
        * Kinesis uses "StreamARN" and DynamoDB uses "StreamArn" as source parameter
87
        * Kinesis uses "StreamStatus.ACTIVE" and DynamoDB uses "StreamStatus.ENABLED"
88
        * Only Kinesis supports the additional StartingPosition called "AT_TIMESTAMP" using "StartingPositionTimestamp"
89
        """
90
        pass
×
91

92
    @abstractmethod
1✔
93
    def stream_arn_param(self) -> dict:
1✔
94
        """Returns a dict of the correct key/value pair for the stream arn used in GetRecords.
95
        Either StreamARN for Kinesis or {} for DynamoDB (unsupported)"""
96
        pass
×
97

98
    @abstractmethod
1✔
99
    def failure_payload_details_field_name(self) -> str:
1✔
100
        pass
×
101

102
    @abstractmethod
1✔
103
    def get_approximate_arrival_time(self, record: dict) -> float:
1✔
104
        pass
×
105

106
    @abstractmethod
1✔
107
    def format_datetime(self, time: datetime) -> str:
1✔
108
        """Formats a datetime in the correct format for DynamoDB (with ms) or Kinesis (without ms)"""
109
        pass
×
110

111
    @abstractmethod
1✔
112
    def get_sequence_number(self, record: dict) -> str:
1✔
113
        pass
×
114

115
    def close(self):
1✔
116
        self._is_shutdown.set()
1✔
117

118
    def pre_filter(self, events: list[dict]) -> list[dict]:
1✔
119
        return events
1✔
120

121
    def post_filter(self, events: list[dict]) -> list[dict]:
1✔
122
        return events
1✔
123

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

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

143
        current_shard_tuple = next(self.iterator_over_shards, None)
1✔
144
        if not current_shard_tuple:
1✔
145
            self.iterator_over_shards = iter(self.shards.items())
1✔
146
            current_shard_tuple = next(self.iterator_over_shards, None)
1✔
147

148
        # TODO Better handling when shards are initialised and the iterator returns nothing
149
        if not current_shard_tuple:
1✔
150
            raise PipeInternalError(
1✔
151
                "Failed to retrieve any shards for stream polling despite initialization."
152
            )
153

154
        try:
1✔
155
            self.poll_events_from_shard(*current_shard_tuple)
1✔
156
        except PipeInternalError:
1✔
157
            # TODO: standardize logging
158
            # Ignore and wait for the next polling interval, which will do retry
UNCOV
159
            pass
×
160

161
    def poll_events_from_shard(self, shard_id: str, shard_iterator: str):
1✔
162
        abort_condition = None
1✔
163
        get_records_response = self.get_records(shard_iterator)
1✔
164
        records = get_records_response.get("Records", [])
1✔
165
        if not records:
1✔
166
            self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
167
            raise EmptyPollResultsException(service=self.event_source(), source_arn=self.source_arn)
1✔
168

169
        polled_events = self.transform_into_events(records, shard_id)
1✔
170

171
        # Check MaximumRecordAgeInSeconds
172
        if maximum_record_age_in_seconds := self.stream_parameters.get("MaximumRecordAgeInSeconds"):
1✔
173
            arrival_timestamp_of_last_event = polled_events[-1]["approximateArrivalTimestamp"]
×
174
            now = get_current_time().timestamp()
×
175
            record_age_in_seconds = now - arrival_timestamp_of_last_event
×
176
            if record_age_in_seconds > maximum_record_age_in_seconds:
×
177
                abort_condition = "RecordAgeExpired"
×
178

179
        # TODO: implement format detection behavior (e.g., for JSON body):
180
        #  https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-pipes-event-filtering.html
181
        #  Check whether we need poller-specific filter-preprocessing here without modifying the actual event!
182
        # convert to json for filtering (HACK for fixing parity with v1 and getting regression tests passing)
183
        # localstack.services.lambda_.event_source_listeners.kinesis_event_source_listener.KinesisEventSourceListener._filter_records
184
        # TODO: explore better abstraction for the entire filtering, including the set_data and get_data remapping
185
        #  We need better clarify which transformations happen before and after filtering -> fix missing test coverage
186
        parsed_events = self.pre_filter(polled_events)
1✔
187
        # TODO: advance iterator past matching events!
188
        #  We need to checkpoint the sequence number for each shard and then advance the shard iterator using
189
        #  GetShardIterator with a given sequence number
190
        #  https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html
191
        #  Failing to do so kinda blocks the stream resulting in very high latency.
192
        matching_events = self.filter_events(parsed_events)
1✔
193
        matching_events_post_filter = self.post_filter(matching_events)
1✔
194

195
        # TODO: implement MaximumBatchingWindowInSeconds flush condition (before or after filter?)
196
        # Don't trigger upon empty events
197
        if len(matching_events_post_filter) == 0:
1✔
198
            # Update shard iterator if no records match the filter
199
            self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
200
            return
1✔
201
        events = self.add_source_metadata(matching_events_post_filter)
1✔
202
        LOG.debug("Polled %d events from %s in shard %s", len(events), self.source_arn, shard_id)
1✔
203
        # TODO: A retry should probably re-trigger fetching the record from the stream again?!
204
        #  -> This could be tested by setting a high retry number, using a long pipe execution, and a relatively
205
        #  short record expiration age at the source. Check what happens if the record expires at the source.
206
        #  A potential implementation could use checkpointing based on the iterator position (within shard scope)
207
        # TODO: handle partial batch failure (see poller.py:parse_batch_item_failures)
208
        # TODO: think about how to avoid starvation of other shards if one shard runs into infinite retries
209
        attempts = 0
1✔
210
        error_payload = {}
1✔
211

212
        max_retries = self.stream_parameters.get("MaximumRetryAttempts", -1)
1✔
213
        # NOTE: max_retries == 0 means exponential backoff is disabled
214
        boff = ExponentialBackoff(max_retries=max_retries)
1✔
215
        while (
1✔
216
            not abort_condition
217
            and not self.max_retries_exceeded(attempts)
218
            and not self._is_shutdown.is_set()
219
        ):
220
            try:
1✔
221
                if attempts > 0:
1✔
222
                    # TODO: Should we always backoff (with jitter) before processing since we may not want multiple pollers
223
                    # all starting up and polling simultaneously
224
                    # For example: 500 persisted ESMs starting up and requesting concurrently could flood gateway
225
                    self._is_shutdown.wait(boff.next_backoff())
1✔
226

227
                self.processor.process_events_batch(events)
1✔
228
                boff.reset()
1✔
229

230
                # Update shard iterator if execution is successful
231
                self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
232
                return
1✔
233
            except PartialBatchFailureError as ex:
1✔
234
                # TODO: add tests for partial batch failure scenarios
235
                if (
1✔
236
                    self.stream_parameters.get("OnPartialBatchItemFailure")
237
                    == OnPartialBatchItemFailureStreams.AUTOMATIC_BISECT
238
                ):
239
                    # TODO: implement and test splitting batches in half until batch size 1
240
                    #  https://docs.aws.amazon.com/eventbridge/latest/pipes-reference/API_PipeSourceKinesisStreamParameters.html
241
                    LOG.warning(
×
242
                        "AUTOMATIC_BISECT upon partial batch item failure is not yet implemented. Retrying the entire batch."
243
                    )
244
                error_payload = ex.error
1✔
245

246
                # Extract all sequence numbers from events in batch. This allows us to fail the whole batch if
247
                # an unknown itemidentifier is returned.
248
                batch_sequence_numbers = {
1✔
249
                    self.get_sequence_number(event) for event in matching_events
250
                }
251

252
                # If the batchItemFailures array contains multiple items, Lambda uses the record with the lowest sequence number as the checkpoint.
253
                # Lambda then retries all records starting from that checkpoint.
254
                failed_sequence_ids: list[int] | None = get_batch_item_failures(
1✔
255
                    ex.partial_failure_payload, batch_sequence_numbers
256
                )
257

258
                # If None is returned, consider the entire batch a failure.
259
                if failed_sequence_ids is None:
1✔
260
                    continue
1✔
261

262
                # This shouldn't be possible since a PartialBatchFailureError was raised
263
                if len(failed_sequence_ids) == 0:
1✔
264
                    assert failed_sequence_ids, (
×
265
                        "Invalid state encountered: PartialBatchFailureError raised but no batch item failures found."
266
                    )
267

268
                lowest_sequence_id: str = min(failed_sequence_ids, key=int)
1✔
269

270
                # Discard all successful events and re-process from sequence number of failed event
271
                _, events = self.bisect_events(lowest_sequence_id, events)
1✔
272
            except (BatchFailureError, Exception) as ex:
1✔
273
                if isinstance(ex, BatchFailureError):
1✔
274
                    error_payload = ex.error
1✔
275

276
                # FIXME partner_resource_arn is not defined in ESM
277
                LOG.debug(
1✔
278
                    "Attempt %d failed while processing %s with events: %s",
279
                    attempts,
280
                    self.partner_resource_arn or self.source_arn,
281
                    events,
282
                )
283
            finally:
284
                # Retry polling until the record expires at the source
285
                attempts += 1
1✔
286

287
        # Send failed events to potential DLQ
288
        abort_condition = abort_condition or "RetryAttemptsExhausted"
1✔
289
        failure_context = self.processor.generate_event_failure_context(
1✔
290
            abort_condition=abort_condition,
291
            error=error_payload,
292
            attempts_count=attempts,
293
            partner_resource_arn=self.partner_resource_arn,
294
        )
295
        self.send_events_to_dlq(shard_id, events, context=failure_context)
1✔
296
        # Update shard iterator if the execution failed but the events are sent to a DLQ
297
        self.shards[shard_id] = get_records_response["NextShardIterator"]
1✔
298

299
    def get_records(self, shard_iterator: str) -> dict:
1✔
300
        """Returns a GetRecordsOutput from the GetRecords endpoint of streaming services such as Kinesis or DynamoDB"""
301
        try:
1✔
302
            get_records_response = self.source_client.get_records(
1✔
303
                # TODO: add test for cross-account scenario
304
                # Differs for Kinesis and DynamoDB but required for cross-account scenario
305
                **self.stream_arn_param(),
306
                ShardIterator=shard_iterator,
307
                Limit=self.stream_parameters["BatchSize"],
308
            )
309
            return get_records_response
1✔
310
        # TODO: test iterator expired with conditional error scenario (requires failure destinations)
311
        except self.source_client.exceptions.ExpiredIteratorException as e:
1✔
312
            LOG.debug(
×
313
                "Shard iterator %s expired for stream %s, re-initializing shards",
314
                shard_iterator,
315
                self.source_arn,
316
            )
317
            # TODO: test TRIM_HORIZON and AT_TIMESTAMP scenarios for this case. We don't want to start from scratch and
318
            #  might need to think about checkpointing here.
319
            self.shards = self.initialize_shards()
×
320
            raise PipeInternalError from e
×
321
        except ClientError as e:
1✔
322
            if "AccessDeniedException" in str(e):
1✔
323
                LOG.warning(
×
324
                    "Insufficient permissions to get records from stream %s: %s",
325
                    self.source_arn,
326
                    e,
327
                )
328
                raise CustomerInvocationError from e
×
329
            elif "ResourceNotFoundException" in str(e):
1✔
330
                # FIXME: The 'Invalid ShardId in ShardIterator' error is returned by DynamoDB-local. Unsure when/why this is returned.
331
                if "Invalid ShardId in ShardIterator" in str(e):
1✔
332
                    LOG.warning(
×
333
                        "Invalid ShardId in ShardIterator for %s. Re-initializing shards.",
334
                        self.source_arn,
335
                    )
336
                    self.shards = self.initialize_shards()
×
337
                else:
338
                    LOG.warning(
1✔
339
                        "Source stream %s does not exist: %s",
340
                        self.source_arn,
341
                        e,
342
                    )
343
                    raise CustomerInvocationError from e
1✔
UNCOV
344
            elif "TrimmedDataAccessException" in str(e):
×
345
                LOG.debug(
×
346
                    "Attempted to iterate over trimmed record or expired shard iterator %s for stream %s, re-initializing shards",
347
                    shard_iterator,
348
                    self.source_arn,
349
                )
350
                self.shards = self.initialize_shards()
×
351
            else:
UNCOV
352
                LOG.debug("ClientError during get_records for stream %s: %s", self.source_arn, e)
×
UNCOV
353
            raise PipeInternalError from e
×
354

355
    def send_events_to_dlq(self, shard_id, events, context) -> None:
1✔
356
        dlq_arn = self.stream_parameters.get("DeadLetterConfig", {}).get("Arn")
1✔
357
        if dlq_arn:
1✔
358
            failure_timstamp = get_current_time()
1✔
359
            dlq_event = self.create_dlq_event(shard_id, events, context, failure_timstamp)
1✔
360
            # Send DLQ event to DLQ target
361
            parsed_arn = parse_arn(dlq_arn)
1✔
362
            service = parsed_arn["service"]
1✔
363
            # TODO: use a sender instance here, likely inject via DI into poller (what if it updates?)
364
            if service == "sqs":
1✔
365
                # TODO: inject and cache SQS client using proper IAM role (supports cross-account operations)
366
                sqs_client = get_internal_client(dlq_arn)
1✔
367
                # TODO: check if the DLQ exists
368
                dlq_url = get_queue_url(dlq_arn)
1✔
369
                # TODO: validate no FIFO queue because they are unsupported
370
                sqs_client.send_message(QueueUrl=dlq_url, MessageBody=json.dumps(dlq_event))
1✔
371
            elif service == "sns":
1✔
372
                sns_client = get_internal_client(dlq_arn)
1✔
373
                sns_client.publish(TopicArn=dlq_arn, Message=json.dumps(dlq_event))
1✔
374
            elif service == "s3":
1✔
375
                s3_client = get_internal_client(dlq_arn)
1✔
376
                dlq_event_with_payload = {
1✔
377
                    **dlq_event,
378
                    "payload": {
379
                        "Records": events,
380
                    },
381
                }
382
                s3_client.put_object(
1✔
383
                    Bucket=s3_bucket_name(dlq_arn),
384
                    Key=get_failure_s3_object_key(self.esm_uuid, shard_id, failure_timstamp),
385
                    Body=json.dumps(dlq_event_with_payload),
386
                )
387
            else:
388
                LOG.warning("Unsupported DLQ service %s", service)
×
389

390
    def create_dlq_event(
1✔
391
        self, shard_id: str, events: list[dict], context: dict, failure_timestamp: datetime
392
    ) -> dict:
393
        first_record = events[0]
1✔
394
        first_record_arrival = get_datetime_from_timestamp(
1✔
395
            self.get_approximate_arrival_time(first_record)
396
        )
397

398
        last_record = events[-1]
1✔
399
        last_record_arrival = get_datetime_from_timestamp(
1✔
400
            self.get_approximate_arrival_time(last_record)
401
        )
402
        return {
1✔
403
            **context,
404
            self.failure_payload_details_field_name(): {
405
                "approximateArrivalOfFirstRecord": self.format_datetime(first_record_arrival),
406
                "approximateArrivalOfLastRecord": self.format_datetime(last_record_arrival),
407
                "batchSize": len(events),
408
                "endSequenceNumber": self.get_sequence_number(last_record),
409
                "shardId": shard_id,
410
                "startSequenceNumber": self.get_sequence_number(first_record),
411
                "streamArn": self.source_arn,
412
            },
413
            "timestamp": failure_timestamp.isoformat(timespec="milliseconds").replace(
414
                "+00:00", "Z"
415
            ),
416
            "version": "1.0",
417
        }
418

419
    def max_retries_exceeded(self, attempts: int) -> bool:
1✔
420
        maximum_retry_attempts = self.stream_parameters.get("MaximumRetryAttempts", -1)
1✔
421
        # Infinite retries until the source expires
422
        if maximum_retry_attempts == -1:
1✔
423
            return False
1✔
424
        return attempts > maximum_retry_attempts
1✔
425

426
    def bisect_events(
1✔
427
        self, sequence_number: str, events: list[dict]
428
    ) -> tuple[list[dict], list[dict]]:
429
        """Splits list of events in two, where a sequence number equals a passed parameter `sequence_number`.
430
        This is used for:
431
          - `ReportBatchItemFailures`: Discarding events in a batch following a failure when is set.
432
          - `BisectBatchOnFunctionError`: Used to split a failed batch in two when doing a retry (not implemented)."""
433
        for i, event in enumerate(events):
1✔
434
            if self.get_sequence_number(event) == sequence_number:
1✔
435
                return events[:i], events[i:]
1✔
436

437
        return events, []
×
438

439

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

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

447
    :return: Key for s3 object that invocation failure record will be put to
448
    """
449
    timestamp = failure_datetime.strftime("%Y-%m-%dT%H.%M.%S")
1✔
450
    year_month_day = failure_datetime.strftime("%Y/%m/%d")
1✔
451
    random_uuid = long_uid()
1✔
452
    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 · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc