Repository navigation
Conversation
Add a new code sample for a streaming pipeline using Cloud Storage and DataFlow.
|
Here is the summary of changes. You are about to add 1 region tag.
This comment is generated by snippet-bot.
|
There was a problem hiding this comment.
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.
| 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']}" |
There was a problem hiding this comment.
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.
| 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', '')}" |
| 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) |
There was a problem hiding this comment.
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 []| | "KeepNewObjects" | ||
| >> beam.Filter( | ||
| lambda msg: msg.attributes.get("eventType") == "OBJECT_FINALIZE" | ||
| ) |
There was a problem hiding this comment.
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.
| | "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) |
Add a new code sample for a streaming pipeline using Cloud Storage and DataFlow.
Test: #15025
Description
Bug # http://b/589715201
Checklist
Testing
Compliance & Style
Post-Approval Actions