Giter Club home page Giter Club logo

Comments (4)

mohllal avatar mohllal commented on May 26, 2024 2

Thank you @AbdullahMakhdoom for your investigation!

Upon further examination of the code, I initially believed that your suggestion would solve the issue concerning describing the target stream using a stream consumer ARN, as you re-assign a valid stream_arn post retrieval from the stream consumer ARN.

However, upon closer inspection, I've discovered that the current implementation of the _monitor_stream_event_sources method still retrieves data from the stream shards using the standard interator method, rather than subscribing to shards using the stream consumer, as outlined in here.

try:
stream_description = self._get_stream_description(stream_client, stream_arn)
except Exception as e:
LOG.error(
"Cannot describe target stream %s of event source mapping %s: %s",
stream_arn,
mapping_uuid,
e,
)
continue
if stream_description["StreamStatus"] not in {"ENABLED", "ACTIVE"}:
continue
shard_ids = [shard["ShardId"] for shard in stream_description["Shards"]]
for shard_id in shard_ids:
lock_discriminator = f"{mapping_uuid}/{stream_arn}/{shard_id}"
mapped_shard_ids.add(lock_discriminator)
if lock_discriminator not in self._STREAM_LISTENER_THREADS:
shard_iterator = self._get_shard_iterator(
stream_client,
stream_arn,
shard_id,
source["StartingPosition"],
)
monitor_counter += 1
listener_thread = FuncThread(
self._listen_to_shard_and_invoke_lambda,
{
"function_arn": source["FunctionArn"],
"stream_arn": stream_arn,
"batch_size": batch_size,
"parallelization_factor": source.get(
"ParallelizationFactor", 1
),
"lock_discriminator": lock_discriminator,
"shard_id": shard_id,
"stream_client": stream_client,
"shard_iterator": shard_iterator,
"failure_destination": failure_destination,
"max_num_retries": max_num_retries,
},
name=f"monitor-stream-thread-{monitor_counter}",
)
self._STREAM_LISTENER_THREADS[lock_discriminator] = listener_thread
listener_thread.start()

It seems I misunderstood the problem initially, thinking it was just about describing the event source mapping target stream bug using an ARN that belongs to a stream consumer not a stream itself. However, it's actually more complex than that, involving differences in consuming strategies and their implementation.

from localstack.

localstack-bot avatar localstack-bot commented on May 26, 2024

Welcome to LocalStack! Thanks for reporting your first issue and our team will be working towards fixing the issue for you or reach out for more background information. We recommend joining our Slack Community for real-time help and drop a message to LocalStack Pro Support if you are a Pro user! If you are willing to contribute towards fixing this issue, please have a look at our contributing guidelines and our contributing guide.

from localstack.

AbdullahMakhdoom avatar AbdullahMakhdoom commented on May 26, 2024

I can see there is a function from localstack.services.kinesis.provider import find_stream_for_consumer, which returns stream_name. Maybe we can modify the function to return stream_arn as well.

def find_stream_for_consumer(consumer_arn):
    account_id = extract_account_id_from_arn(consumer_arn)
    region_name = extract_region_from_arn(consumer_arn)
    kinesis = connect_to(aws_access_key_id=account_id, region_name=region_name).kinesis
    for stream_name in kinesis.list_streams()["StreamNames"]:
        stream_arn = arns.kinesis_stream_arn(stream_name, account_id, region_name)
        for cons in kinesis.list_stream_consumers(StreamARN=stream_arn)["Consumers"]:
            if cons["ConsumerARN"] == consumer_arn:
[+]                return stream_name, stream_arn
    raise Exception("Unable to find stream for stream consumer %s" % consumer_arn)

Then use this function in to get stream_arn corresponsing to conusmer arn.

def _monitor_stream_event_sources(self, *args):
    # additional code not directly related to the issue at hand...
    try:
[+]        if len(stream_arn.split("/")[-1].split(":")) > 1:
[+]            consumer_arn = stream_arn
[+]             _, stream_arn = find_stream_for_consumer(consumer_arn)
        stream_description = self._get_stream_description(stream_client, stream_arn)
    except Exception as e:
        LOG.error(
            "Cannot describe target stream %s of event source mapping %s: %s",
            stream_arn,
            mapping_uuid,
            e,
        )
        continue
    # additional code not directly related to the issue at hand...

Let me know your thoughts @viren-nadkarni @mohllal
Would be glad to pursue a PR for this solution if it makes sense.

from localstack.

mohllal avatar mohllal commented on May 26, 2024

I just noticed that the Kinesis mock server utilized by Localstack doesn't support SubscribeToShard operation.

LocalStack is proxying the functionality, as a workaround, using the GetRecords operation. However, this approach differs from AWS functionality, which relies on the HTTP2 server push mechanism between the shard and the consumer.

def subscribe_to_shard(
self,
context: RequestContext,
consumer_arn: ConsumerARN,
shard_id: ShardId,
starting_position: StartingPosition,
**kwargs,
) -> SubscribeToShardOutput:
kinesis = connect_to(
aws_access_key_id=context.account_id, region_name=context.region
).kinesis
stream_name = find_stream_for_consumer(consumer_arn)
iter_type = starting_position["Type"]
kwargs = {}
starting_sequence_number = starting_position.get("SequenceNumber") or "0"
if iter_type in ["AT_SEQUENCE_NUMBER", "AFTER_SEQUENCE_NUMBER"]:
kwargs["StartingSequenceNumber"] = starting_sequence_number
elif iter_type in ["AT_TIMESTAMP"]:
# or value is just an example timestamp from aws docs
timestamp = starting_position.get("Timestamp") or 1459799926.480
kwargs["Timestamp"] = timestamp
initial_shard_iterator = kinesis.get_shard_iterator(
StreamName=stream_name, ShardId=shard_id, ShardIteratorType=iter_type, **kwargs
)["ShardIterator"]
def event_generator():
shard_iterator = initial_shard_iterator
last_sequence_number = starting_sequence_number
maximum_duration_subscription_timestamp = now_utc() + MAX_SUBSCRIPTION_SECONDS
while now_utc() < maximum_duration_subscription_timestamp:
try:
result = kinesis.get_records(ShardIterator=shard_iterator)
except Exception as e:
if "ResourceNotFoundException" in str(e):
LOG.debug(
'Kinesis stream "%s" has been deleted, closing shard subscriber',
stream_name,
)
return
raise
shard_iterator = result.get("NextShardIterator")
records = result.get("Records", [])
if not records:
# On AWS there is *at least* 1 event every 5 seconds
# but this is not possible in this structure.
# In order to avoid a 5-second blocking call, we make the compromise of 3 seconds.
time.sleep(3)
yield SubscribeToShardEventStream(
SubscribeToShardEvent=SubscribeToShardEvent(
Records=records,
ContinuationSequenceNumber=str(last_sequence_number),
MillisBehindLatest=0,
ChildShards=[],
)
)
return SubscribeToShardOutput(EventStream=event_generator())

Based on the above implementation, there's no behaviour difference between utilizing a dedicated fan-out stream consumer and a consumer as a Lambda event source mapping source on LocalStack.

This holds true even if we were able to modify the implementation of the StreamEventSourceListener class to accommodate the proxied subscribe_to_shard method.

from localstack.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.