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

localstack / localstack / 794fa40c-fa5b-47bd-a3c8-c37dc8063c77

16 May 2025 04:26PM UTC coverage: 86.636% (+0.01%) from 86.622%
794fa40c-fa5b-47bd-a3c8-c37dc8063c77

push

circleci

web-flow
Apigw/add support for response override in request (#12628)

22 of 22 new or added lines in 7 files covered. (100.0%)

64 existing lines in 9 files now uncovered.

64433 of 74372 relevant lines covered (86.64%)

0.87 hits per line

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

88.84
/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 bisect import bisect_left
1✔
6
from collections import defaultdict
1✔
7
from datetime import datetime
1✔
8
from typing import Iterator
1✔
9

10
from botocore.client import BaseClient
1✔
11
from botocore.exceptions import ClientError
1✔
12

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

42
LOG = logging.getLogger(__name__)
1✔
43

44

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

56
    # The ARN of the processor (e.g., Pipe ARN)
57
    partner_resource_arn: str | None
1✔
58

59
    # Used for backing-off between retries and breaking the retry loop
60
    _is_shutdown: threading.Event
1✔
61

62
    # Collects and flushes a batch of records based on a batching policy
63
    shard_batcher: dict[str, Batcher[dict]]
1✔
64

65
    def __init__(
1✔
66
        self,
67
        source_arn: str,
68
        source_parameters: dict | None = None,
69
        source_client: BaseClient | None = None,
70
        processor: EventProcessor | None = None,
71
        partner_resource_arn: str | None = None,
72
        esm_uuid: str | None = None,
73
    ):
74
        super().__init__(source_arn, source_parameters, source_client, processor)
1✔
75
        self.partner_resource_arn = partner_resource_arn
1✔
76
        self.esm_uuid = esm_uuid
1✔
77
        self.shards = {}
1✔
78
        self.iterator_over_shards = None
1✔
79

80
        self._is_shutdown = threading.Event()
1✔
81

82
        self.shard_batcher = defaultdict(
1✔
83
            lambda: Batcher(
84
                max_count=self.stream_parameters.get("BatchSize", 100),
85
                max_window=self.stream_parameters.get("MaximumBatchingWindowInSeconds", 0),
86
            )
87
        )
88

89
    @abstractmethod
1✔
90
    def transform_into_events(self, records: list[dict], shard_id) -> list[dict]:
1✔
91
        pass
×
92

93
    @property
1✔
94
    @abstractmethod
1✔
95
    def stream_parameters(self) -> dict:
1✔
96
        pass
×
97

98
    @abstractmethod
1✔
99
    def initialize_shards(self) -> dict[str, str]:
1✔
100
        """Returns a shard dict mapping from shard id -> shard iterator
101
        The implementations for Kinesis and DynamoDB are similar but differ in various ways:
102
        * Kinesis uses "StreamARN" and DynamoDB uses "StreamArn" as source parameter
103
        * Kinesis uses "StreamStatus.ACTIVE" and DynamoDB uses "StreamStatus.ENABLED"
104
        * Only Kinesis supports the additional StartingPosition called "AT_TIMESTAMP" using "StartingPositionTimestamp"
105
        """
106
        pass
×
107

108
    @abstractmethod
1✔
109
    def stream_arn_param(self) -> dict:
1✔
110
        """Returns a dict of the correct key/value pair for the stream arn used in GetRecords.
111
        Either StreamARN for Kinesis or {} for DynamoDB (unsupported)"""
112
        pass
×
113

114
    @abstractmethod
1✔
115
    def failure_payload_details_field_name(self) -> str:
1✔
116
        pass
×
117

118
    @abstractmethod
1✔
119
    def get_approximate_arrival_time(self, record: dict) -> float:
1✔
120
        pass
×
121

122
    @abstractmethod
1✔
123
    def format_datetime(self, time: datetime) -> str:
1✔
124
        """Formats a datetime in the correct format for DynamoDB (with ms) or Kinesis (without ms)"""
125
        pass
×
126

127
    @abstractmethod
1✔
128
    def get_sequence_number(self, record: dict) -> str:
1✔
129
        pass
×
130

131
    def close(self):
1✔
132
        self._is_shutdown.set()
1✔
133

134
    def pre_filter(self, events: list[dict]) -> list[dict]:
1✔
135
        return events
1✔
136

137
    def post_filter(self, events: list[dict]) -> list[dict]:
1✔
138
        return events
1✔
139

140
    def poll_events(self):
1✔
141
        """Generalized poller for streams such as Kinesis or DynamoDB
142
        Examples of Kinesis consumers:
143
        * StackOverflow: https://stackoverflow.com/a/22403036/6875981
144
        * AWS Sample: https://github.com/aws-samples/kinesis-poster-worker/blob/master/worker.py
145
        Examples of DynamoDB consumers:
146
        * Blogpost: https://www.tecracer.com/blog/2022/05/getting-a-near-real-time-view-of-a-dynamodb-stream-with-python.html
147
        """
148
        # TODO: consider potential shard iterator timeout after 300 seconds (likely not relevant with short-polling):
149
        #   https://docs.aws.amazon.com/streams/latest/dev/troubleshooting-consumers.html#shard-iterator-expires-unexpectedly
150
        #  Does this happen if no records are received for 300 seconds?
151
        if not self.shards:
1✔
152
            self.shards = self.initialize_shards()
1✔
153

154
        if not self.shards:
1✔
155
            LOG.debug("No shards found for %s.", self.source_arn)
1✔
156
            raise EmptyPollResultsException(service=self.event_source(), source_arn=self.source_arn)
1✔
157
        else:
158
            # Remove all shard batchers without corresponding shards
159
            for shard_id in self.shard_batcher.keys() - self.shards.keys():
1✔
160
                self.shard_batcher.pop(shard_id, None)
×
161

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

167
        current_shard_tuple = next(self.iterator_over_shards, None)
1✔
168
        if not current_shard_tuple:
1✔
169
            self.iterator_over_shards = iter(self.shards.items())
1✔
170
            current_shard_tuple = next(self.iterator_over_shards, None)
1✔
171

172
        # TODO Better handling when shards are initialised and the iterator returns nothing
173
        if not current_shard_tuple:
1✔
174
            raise PipeInternalError(
×
175
                "Failed to retrieve any shards for stream polling despite initialization."
176
            )
177

178
        try:
1✔
179
            self.poll_events_from_shard(*current_shard_tuple)
1✔
180
        except PipeInternalError:
1✔
181
            # TODO: standardize logging
182
            # Ignore and wait for the next polling interval, which will do retry
183
            pass
1✔
184

185
    def poll_events_from_shard(self, shard_id: str, shard_iterator: str):
1✔
186
        get_records_response = self.get_records(shard_iterator)
1✔
187
        records: list[dict] = get_records_response.get("Records", [])
1✔
188
        if not (next_shard_iterator := get_records_response.get("NextShardIterator")):
1✔
189
            # If the next shard iterator is None, we can assume the shard is closed or
190
            # has expired on the DynamoDB Local server, hence we should re-initialize.
191
            self.shards = self.initialize_shards()
1✔
192

193
        # We cannot reliably back-off when no records found since an iterator
194
        # may have to move multiple times until records are returned.
195
        # See https://docs.aws.amazon.com/streams/latest/dev/troubleshooting-consumers.html#getrecords-returns-empty
196
        # However, we still need to check if batcher should be triggered due to time-based batching.
197
        should_flush = self.shard_batcher[shard_id].add(records)
1✔
198
        if not should_flush:
1✔
199
            self.shards[shard_id] = next_shard_iterator
1✔
200
            return
1✔
201

202
        # Retrieve and drain all events in batcher
203
        collected_records = self.shard_batcher[shard_id].flush()
1✔
204
        # If there is overflow (i.e 1k BatchSize and 1.2K returned in flush), further split up the batch.
205
        for batch in batched(collected_records, self.stream_parameters.get("BatchSize")):
1✔
206
            # This could potentially lead to data loss if forward_events_to_target raises an exception after a flush
207
            # which would otherwise be solved with checkpointing.
208
            # TODO: Implement checkpointing, leasing, etc. from https://docs.aws.amazon.com/streams/latest/dev/kcl-concepts.html
209
            self.forward_events_to_target(shard_id, next_shard_iterator, batch)
1✔
210

211
    def forward_events_to_target(self, shard_id, next_shard_iterator, records):
1✔
212
        polled_events = self.transform_into_events(records, shard_id)
1✔
213
        abort_condition = None
1✔
214
        # TODO: implement format detection behavior (e.g., for JSON body):
215
        #  https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-pipes-event-filtering.html
216
        #  Check whether we need poller-specific filter-preprocessing here without modifying the actual event!
217
        # convert to json for filtering (HACK for fixing parity with v1 and getting regression tests passing)
218
        # localstack.services.lambda_.event_source_listeners.kinesis_event_source_listener.KinesisEventSourceListener._filter_records
219
        # TODO: explore better abstraction for the entire filtering, including the set_data and get_data remapping
220
        #  We need better clarify which transformations happen before and after filtering -> fix missing test coverage
221
        parsed_events = self.pre_filter(polled_events)
1✔
222
        # TODO: advance iterator past matching events!
223
        #  We need to checkpoint the sequence number for each shard and then advance the shard iterator using
224
        #  GetShardIterator with a given sequence number
225
        #  https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html
226
        #  Failing to do so kinda blocks the stream resulting in very high latency.
227
        matching_events = self.filter_events(parsed_events)
1✔
228
        matching_events_post_filter = self.post_filter(matching_events)
1✔
229

230
        # TODO: implement MaximumBatchingWindowInSeconds flush condition (before or after filter?)
231
        # Don't trigger upon empty events
232
        if len(matching_events_post_filter) == 0:
1✔
233
            # Update shard iterator if no records match the filter
234
            self.shards[shard_id] = next_shard_iterator
1✔
235
            return
1✔
236
        events = self.add_source_metadata(matching_events_post_filter)
1✔
237
        LOG.debug("Polled %d events from %s in shard %s", len(events), self.source_arn, shard_id)
1✔
238
        #  -> This could be tested by setting a high retry number, using a long pipe execution, and a relatively
239
        #  short record expiration age at the source. Check what happens if the record expires at the source.
240
        #  A potential implementation could use checkpointing based on the iterator position (within shard scope)
241
        # TODO: handle partial batch failure (see poller.py:parse_batch_item_failures)
242
        # TODO: think about how to avoid starvation of other shards if one shard runs into infinite retries
243
        attempts = 0
1✔
244
        discarded_events_for_dlq = []
1✔
245
        error_payload = {}
1✔
246

247
        max_retries = self.stream_parameters.get("MaximumRetryAttempts", -1)
1✔
248
        max_record_age = max(
1✔
249
            self.stream_parameters.get("MaximumRecordAgeInSeconds", -1), 0
250
        )  # Disable check if -1
251
        # NOTE: max_retries == 0 means exponential backoff is disabled
252
        boff = ExponentialBackoff(max_retries=max_retries)
1✔
253
        while not abort_condition and events and not self._is_shutdown.is_set():
1✔
254
            if self.max_retries_exceeded(attempts):
1✔
255
                abort_condition = "RetryAttemptsExhausted"
1✔
256
                break
1✔
257

258
            if max_record_age:
1✔
259
                events, expired_events = self.bisect_events_by_record_age(max_record_age, events)
1✔
260
                if expired_events:
1✔
261
                    discarded_events_for_dlq.extend(expired_events)
1✔
262
                    continue
1✔
263

264
            try:
1✔
265
                if attempts > 0:
1✔
266
                    # TODO: Should we always backoff (with jitter) before processing since we may not want multiple pollers
267
                    # all starting up and polling simultaneously
268
                    # For example: 500 persisted ESMs starting up and requesting concurrently could flood gateway
269
                    self._is_shutdown.wait(boff.next_backoff())
1✔
270

271
                self.processor.process_events_batch(events)
1✔
272
                boff.reset()
1✔
273
                # We may need to send on data to a DLQ so break the processing loop and proceed if invocation successful.
274
                break
1✔
275
            except PartialBatchFailureError as ex:
1✔
276
                # TODO: add tests for partial batch failure scenarios
277
                if (
1✔
278
                    self.stream_parameters.get("OnPartialBatchItemFailure")
279
                    == OnPartialBatchItemFailureStreams.AUTOMATIC_BISECT
280
                ):
281
                    # TODO: implement and test splitting batches in half until batch size 1
282
                    #  https://docs.aws.amazon.com/eventbridge/latest/pipes-reference/API_PipeSourceKinesisStreamParameters.html
283
                    LOG.warning(
×
284
                        "AUTOMATIC_BISECT upon partial batch item failure is not yet implemented. Retrying the entire batch."
285
                    )
286
                error_payload = ex.error
1✔
287

288
                # Extract all sequence numbers from events in batch. This allows us to fail the whole batch if
289
                # an unknown itemidentifier is returned.
290
                batch_sequence_numbers = {
1✔
291
                    self.get_sequence_number(event) for event in matching_events
292
                }
293

294
                # If the batchItemFailures array contains multiple items, Lambda uses the record with the lowest sequence number as the checkpoint.
295
                # Lambda then retries all records starting from that checkpoint.
296
                failed_sequence_ids: list[int] | None = get_batch_item_failures(
1✔
297
                    ex.partial_failure_payload, batch_sequence_numbers
298
                )
299

300
                # If None is returned, consider the entire batch a failure.
301
                if failed_sequence_ids is None:
1✔
302
                    continue
1✔
303

304
                # This shouldn't be possible since a PartialBatchFailureError was raised
305
                if len(failed_sequence_ids) == 0:
1✔
306
                    assert failed_sequence_ids, (
×
307
                        "Invalid state encountered: PartialBatchFailureError raised but no batch item failures found."
308
                    )
309

310
                lowest_sequence_id: str = min(failed_sequence_ids, key=int)
1✔
311

312
                # Discard all successful events and re-process from sequence number of failed event
313
                _, events = self.bisect_events(lowest_sequence_id, events)
1✔
314
            except BatchFailureError as ex:
1✔
315
                error_payload = ex.error
1✔
316

317
                # FIXME partner_resource_arn is not defined in ESM
318
                LOG.debug(
1✔
319
                    "Attempt %d failed while processing %s with events: %s",
320
                    attempts,
321
                    self.partner_resource_arn or self.source_arn,
322
                    events,
323
                    exc_info=LOG.isEnabledFor(logging.DEBUG),
324
                )
325
            except Exception:
×
326
                # FIXME partner_resource_arn is not defined in ESM
327
                LOG.error(
×
328
                    "Attempt %d failed with unexpected error while processing %s with events: %s",
329
                    attempts,
330
                    self.partner_resource_arn or self.source_arn,
331
                    events,
332
                    exc_info=LOG.isEnabledFor(logging.DEBUG),
333
                )
334
            finally:
335
                # Retry polling until the record expires at the source
336
                attempts += 1
1✔
337

338
        if discarded_events_for_dlq:
1✔
339
            abort_condition = "RecordAgeExceeded"
1✔
340
            error_payload = {}
1✔
341
            events = discarded_events_for_dlq
1✔
342

343
        # Send failed events to potential DLQ
344
        if abort_condition:
1✔
345
            failure_context = self.processor.generate_event_failure_context(
1✔
346
                abort_condition=abort_condition,
347
                error=error_payload,
348
                attempts_count=attempts,
349
                partner_resource_arn=self.partner_resource_arn,
350
            )
351
            self.send_events_to_dlq(shard_id, events, context=failure_context)
1✔
352
        # Update shard iterator if the execution failed but the events are sent to a DLQ
353
        self.shards[shard_id] = next_shard_iterator
1✔
354

355
    def get_records(self, shard_iterator: str) -> dict:
1✔
356
        """Returns a GetRecordsOutput from the GetRecords endpoint of streaming services such as Kinesis or DynamoDB"""
357
        try:
1✔
358
            get_records_response = self.source_client.get_records(
1✔
359
                # TODO: add test for cross-account scenario
360
                # Differs for Kinesis and DynamoDB but required for cross-account scenario
361
                **self.stream_arn_param(),
362
                ShardIterator=shard_iterator,
363
                Limit=self.stream_parameters["BatchSize"],
364
            )
365
            return get_records_response
1✔
366
        # TODO: test iterator expired with conditional error scenario (requires failure destinations)
367
        except self.source_client.exceptions.ExpiredIteratorException as e:
1✔
368
            LOG.debug(
1✔
369
                "Shard iterator %s expired for stream %s, re-initializing shards",
370
                shard_iterator,
371
                self.source_arn,
372
            )
373
            # TODO: test TRIM_HORIZON and AT_TIMESTAMP scenarios for this case. We don't want to start from scratch and
374
            #  might need to think about checkpointing here.
375
            self.shards = self.initialize_shards()
1✔
376
            raise PipeInternalError from e
1✔
377
        except ClientError as e:
1✔
378
            if "AccessDeniedException" in str(e):
1✔
379
                LOG.warning(
×
380
                    "Insufficient permissions to get records from stream %s: %s",
381
                    self.source_arn,
382
                    e,
383
                )
384
                raise CustomerInvocationError from e
×
385
            elif "ResourceNotFoundException" in str(e):
1✔
386
                # FIXME: The 'Invalid ShardId in ShardIterator' error is returned by DynamoDB-local. Unsure when/why this is returned.
UNCOV
387
                if "Invalid ShardId in ShardIterator" in str(e):
×
388
                    LOG.warning(
×
389
                        "Invalid ShardId in ShardIterator for %s. Re-initializing shards.",
390
                        self.source_arn,
391
                    )
392
                    self.shards = self.initialize_shards()
×
393
                else:
UNCOV
394
                    LOG.warning(
×
395
                        "Source stream %s does not exist: %s",
396
                        self.source_arn,
397
                        e,
398
                    )
UNCOV
399
                    raise CustomerInvocationError from e
×
400
            elif "TrimmedDataAccessException" in str(e):
1✔
401
                LOG.debug(
×
402
                    "Attempted to iterate over trimmed record or expired shard iterator %s for stream %s, re-initializing shards",
403
                    shard_iterator,
404
                    self.source_arn,
405
                )
406
                self.shards = self.initialize_shards()
×
407
            else:
408
                LOG.debug("ClientError during get_records for stream %s: %s", self.source_arn, e)
1✔
409
            raise PipeInternalError from e
1✔
410

411
    def send_events_to_dlq(self, shard_id, events, context) -> None:
1✔
412
        dlq_arn = self.stream_parameters.get("DeadLetterConfig", {}).get("Arn")
1✔
413
        if dlq_arn:
1✔
414
            failure_timstamp = get_current_time()
1✔
415
            dlq_event = self.create_dlq_event(shard_id, events, context, failure_timstamp)
1✔
416
            # Send DLQ event to DLQ target
417
            parsed_arn = parse_arn(dlq_arn)
1✔
418
            service = parsed_arn["service"]
1✔
419
            # TODO: use a sender instance here, likely inject via DI into poller (what if it updates?)
420
            if service == "sqs":
1✔
421
                # TODO: inject and cache SQS client using proper IAM role (supports cross-account operations)
422
                sqs_client = get_internal_client(dlq_arn)
1✔
423
                # TODO: check if the DLQ exists
424
                dlq_url = get_queue_url(dlq_arn)
1✔
425
                # TODO: validate no FIFO queue because they are unsupported
426
                sqs_client.send_message(QueueUrl=dlq_url, MessageBody=json.dumps(dlq_event))
1✔
427
            elif service == "sns":
1✔
428
                sns_client = get_internal_client(dlq_arn)
1✔
429
                sns_client.publish(TopicArn=dlq_arn, Message=json.dumps(dlq_event))
1✔
430
            elif service == "s3":
1✔
431
                s3_client = get_internal_client(dlq_arn)
1✔
432
                dlq_event_with_payload = {
1✔
433
                    **dlq_event,
434
                    "payload": {
435
                        "Records": events,
436
                    },
437
                }
438
                s3_client.put_object(
1✔
439
                    Bucket=s3_bucket_name(dlq_arn),
440
                    Key=get_failure_s3_object_key(self.esm_uuid, shard_id, failure_timstamp),
441
                    Body=json.dumps(dlq_event_with_payload),
442
                )
443
            else:
444
                LOG.warning("Unsupported DLQ service %s", service)
×
445

446
    def create_dlq_event(
1✔
447
        self, shard_id: str, events: list[dict], context: dict, failure_timestamp: datetime
448
    ) -> dict:
449
        first_record = events[0]
1✔
450
        first_record_arrival = get_datetime_from_timestamp(
1✔
451
            self.get_approximate_arrival_time(first_record)
452
        )
453

454
        last_record = events[-1]
1✔
455
        last_record_arrival = get_datetime_from_timestamp(
1✔
456
            self.get_approximate_arrival_time(last_record)
457
        )
458
        return {
1✔
459
            **context,
460
            self.failure_payload_details_field_name(): {
461
                "approximateArrivalOfFirstRecord": self.format_datetime(first_record_arrival),
462
                "approximateArrivalOfLastRecord": self.format_datetime(last_record_arrival),
463
                "batchSize": len(events),
464
                "endSequenceNumber": self.get_sequence_number(last_record),
465
                "shardId": shard_id,
466
                "startSequenceNumber": self.get_sequence_number(first_record),
467
                "streamArn": self.source_arn,
468
            },
469
            "timestamp": failure_timestamp.isoformat(timespec="milliseconds").replace(
470
                "+00:00", "Z"
471
            ),
472
            "version": "1.0",
473
        }
474

475
    def max_retries_exceeded(self, attempts: int) -> bool:
1✔
476
        maximum_retry_attempts = self.stream_parameters.get("MaximumRetryAttempts", -1)
1✔
477
        # Infinite retries until the source expires
478
        if maximum_retry_attempts == -1:
1✔
479
            return False
1✔
480
        return attempts > maximum_retry_attempts
1✔
481

482
    def bisect_events(
1✔
483
        self, sequence_number: str, events: list[dict]
484
    ) -> tuple[list[dict], list[dict]]:
485
        """Splits list of events in two, where a sequence number equals a passed parameter `sequence_number`.
486
        This is used for:
487
          - `ReportBatchItemFailures`: Discarding events in a batch following a failure when is set.
488
          - `BisectBatchOnFunctionError`: Used to split a failed batch in two when doing a retry (not implemented)."""
489
        for i, event in enumerate(events):
1✔
490
            if self.get_sequence_number(event) == sequence_number:
1✔
491
                return events[:i], events[i:]
1✔
492

493
        return events, []
×
494

495
    def bisect_events_by_record_age(
1✔
496
        self, maximum_record_age: int, events: list[dict]
497
    ) -> tuple[list[dict], list[dict]]:
498
        """Splits events into [valid_events], [expired_events] based on record age.
499
        Where:
500
          - Events with age < maximum_record_age are valid.
501
          - Events with age >= maximum_record_age are expired."""
502
        cutoff_timestamp = get_current_time().timestamp() - maximum_record_age
1✔
503
        index = bisect_left(events, cutoff_timestamp, key=self.get_approximate_arrival_time)
1✔
504
        return events[index:], events[:index]
1✔
505

506

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

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

514
    :return: Key for s3 object that invocation failure record will be put to
515
    """
516
    timestamp = failure_datetime.strftime("%Y-%m-%dT%H.%M.%S")
1✔
517
    year_month_day = failure_datetime.strftime("%Y/%m/%d")
1✔
518
    random_uuid = long_uid()
1✔
519
    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