Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions dataflow/snippets/streaming_process_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
#!/usr/bin/env python
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START dataflow_streaming_process_storage]
import argparse
from typing import List, Optional, Tuple

import apache_beam as beam
from apache_beam.io import fileio
from apache_beam.io import PubsubMessage
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.transforms import window


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']}"
Comment on lines +27 to +30

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', '')}"



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)
Comment on lines +33 to +36

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 []



def run(argv: Optional[List[str]] = None) -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--subscription",
required=True,
help="Pub/Sub subscription, such as projects/PROJECT/subscriptions/SUB",
)
parser.add_argument(
"--output",
required=True,
help="Folder for output, such as gs://bucket/output/",
)
known_args, pipeline_args = parser.parse_known_args(argv)
options = PipelineOptions(pipeline_args, streaming=True)

with beam.Pipeline(options=options) as pipeline:
(
pipeline
| "ReadNotifications"
>> beam.io.ReadFromPubSub(
subscription=known_args.subscription, with_attributes=True
)
| "KeepNewObjects"
>> beam.Filter(
lambda msg: msg.attributes.get("eventType") == "OBJECT_FINALIZE"
)
Comment on lines +61 to +64

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)

| "Window" >> beam.WindowInto(window.FixedWindows(60))
| "SumByProduct" >> beam.CombinePerKey(sum)
| "Format" >> beam.MapTuple(lambda product, total: f"{product},{total:.2f}")
| "WriteToGCS"
>> fileio.WriteToFiles(
path=known_args.output,
file_naming=fileio.default_file_naming(prefix="sales", suffix=".csv"),
sink=fileio.TextSink,
)
)


if __name__ == "__main__":
run()
# [END dataflow_streaming_process_storage]