Skip to content

feat(dataflow): Create streaming_process_storage.py - #15023

Open
cbonnie wants to merge 1 commit into
mainfrom
cbonnie-patch-2
Open

cbonnie wants to merge 1 commit into
mainfrom
cbonnie-patch-2

Conversation

@cbonnie

@cbonnie cbonnie commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Add a new code sample for a streaming pipeline using Cloud Storage and DataFlow.

Test: #15025

Description

Bug # http://b/589715201

Checklist

Testing

  • I have tested this change on a live environment and verified it works as intended.

Compliance & Style


Post-Approval Actions

  • Please merge this PR for me once it is approved

Add a new code sample for a streaming pipeline using Cloud Storage and DataFlow.
@cbonnie
cbonnie requested review from a team as code owners December 3, 2026 15:15
@snippet-bot

snippet-bot Bot commented Dec 3, 2026

Copy link
Copy Markdown

Here is the summary of changes.

You are about to add 1 region tag.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label Bot added the samples Issues that are directly related to samples. label Dec 3, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new Apache Beam streaming pipeline snippet (streaming_process_storage.py) that processes GCS notifications from Pub/Sub, reads the corresponding files, aggregates CSV data by product, and writes the results back to GCS. The review feedback highlights several critical improvements for robustness: guarding against None values in Pub/Sub message attributes to prevent runtime and type-checking errors, implementing defensive parsing of CSV lines to avoid crashing the streaming pipeline on malformed input, and utilizing beam.FlatMap to handle safely filtered records.

Comment on lines +27 to +30
def to_gcs_path(message: PubsubMessage) -> str:
"""Builds a gs:// path from a notification's attributes."""
attrs = message.attributes
return f"gs://{attrs['bucketId']}/{attrs['objectId']}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since type hints are enforced in this repository, accessing attrs['bucketId'] directly when message.attributes is Optional[Dict[str, str]] will cause type-checking (mypy) failures. Guard against None and use safe dictionary access to satisfy the type checker and prevent runtime errors.

Suggested change
def to_gcs_path(message: PubsubMessage) -> str:
"""Builds a gs:// path from a notification's attributes."""
attrs = message.attributes
return f"gs://{attrs['bucketId']}/{attrs['objectId']}"
def to_gcs_path(message: PubsubMessage) -> str:
'''Builds a gs:// path from a notification's attributes.'''
attrs = message.attributes or {}
return f"gs://{attrs.get('bucketId', '')}/{attrs.get('objectId', '')}"

Comment on lines +33 to +36
def parse_record(line: str) -> Tuple[str, float]:
"""Parses a CSV line into a (product, amount) tuple."""
_, product, amount = line.split(",")
return product, float(amount)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In a streaming pipeline, any unhandled exception (such as a ValueError from line.split or float(amount)) will crash the worker and stall the pipeline. It is safer to use defensive parsing and return a list of tuples so that malformed lines can be safely ignored using beam.FlatMap.

def parse_record(line: str) -> List[Tuple[str, float]]:
    '''Parses a CSV line into a (product, amount) tuple.'''
    try:
        parts = line.split(',')
        if len(parts) == 3:
            return [(parts[1], float(parts[2]))]
    except ValueError:
        pass
    return []

Comment on lines +61 to +64
| "KeepNewObjects"
>> beam.Filter(
lambda msg: msg.attributes.get("eventType") == "OBJECT_FINALIZE"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If a Pub/Sub message is received without any attributes, msg.attributes will be None, causing an AttributeError when calling .get(). Guard against this by safely handling a None attributes dictionary.

Suggested change
| "KeepNewObjects"
>> beam.Filter(
lambda msg: msg.attributes.get("eventType") == "OBJECT_FINALIZE"
)
| 'KeepNewObjects'
>> beam.Filter(
lambda msg: (msg.attributes or {}).get('eventType') == 'OBJECT_FINALIZE'
)

)
| "ToPath" >> beam.Map(to_gcs_path)
| "ReadNewFiles" >> beam.io.ReadAllFromText(skip_header_lines=1)
| "Parse" >> beam.Map(parse_record)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Use beam.FlatMap instead of beam.Map to handle the list of parsed records and safely ignore any malformed lines that returned an empty list.

Suggested change
| "Parse" >> beam.Map(parse_record)
| 'Parse' >> beam.FlatMap(parse_record)

@iennae iennae changed the title Create streaming_process_storage.py feat(dataflow): Create streaming_process_storage.py Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

samples Issues that are directly related to samples.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant