lostluck commented on code in PR #17955: URL: https://github.com/apache/beam/pull/17955#discussion_r894871945
########## sdks/go/examples/native_wordcap/wordcap.go: ########## @@ -0,0 +1,79 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +// native_wordcap is a toy streaming pipeline that uses PubSub. It +// does the following: +// (1) create a topic and publish a few messages to it +// (2) start a streaming pipeline that converts the messages to +// upper case and logs the result. +// +// This is a portable PubSub option and does not need to be run on Dataflow. +package main + +import ( + "context" + "flag" + "os" + "strings" + + "github.com/apache/beam/sdks/v2/go/examples/native_wordcap/nativepubsubio" + "github.com/apache/beam/sdks/v2/go/pkg/beam" + "github.com/apache/beam/sdks/v2/go/pkg/beam/core/util/stringx" + "github.com/apache/beam/sdks/v2/go/pkg/beam/log" + "github.com/apache/beam/sdks/v2/go/pkg/beam/options/gcpopts" + "github.com/apache/beam/sdks/v2/go/pkg/beam/util/pubsubx" + "github.com/apache/beam/sdks/v2/go/pkg/beam/x/beamx" + "github.com/apache/beam/sdks/v2/go/pkg/beam/x/debug" +) + +var ( + input = flag.String("input", os.ExpandEnv("$USER-wordcap"), "Pubsub input topic.") +) + +var ( + data = []string{ + "foo", + "bar", + "baz", + } +) + +func main() { + flag.Parse() + beam.Init() + + ctx := context.Background() + project := gcpopts.GetProject(ctx) + + defer pubsubx.CleanupTopic(ctx, project, *input) + sub, err := pubsubx.Publish(ctx, project, *input, data...) + if err != nil { + log.Fatal(ctx, err) + } + + log.Infof(ctx, "Running streaming native wordcap with subscription: %v", sub.ID()) + + p := beam.NewPipeline() + s := p.Root() + + col := nativepubsubio.NativeRead(ctx, s, project, *input, sub.ID()) Review Comment: We've got a stutter here. The exposed methods should just be Read and Write, rather than have Native prefixed there. Remember that since users will have to write the package name, information in the package short name shouldn't be repeated if possible. (eg. context.Context stutters on the type, but there's no good alternative name when the package is context.) ########## sdks/go/examples/native_wordcap/nativepubsubio/native.go: ########## @@ -0,0 +1,247 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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. + +// Package nativepubsubio contains a Golang implementation of streaming reads +// and writes to PubSub. This is not as fully featured as the cross-language +// pubsubio package present in the Beam Go repository and should not be used +// in place of it. +package nativepubsubio + +import ( + "context" + "errors" + "fmt" + "time" + + "cloud.google.com/go/pubsub" + "github.com/apache/beam/sdks/v2/go/pkg/beam" + "github.com/apache/beam/sdks/v2/go/pkg/beam/core/sdf" + "github.com/apache/beam/sdks/v2/go/pkg/beam/log" + "github.com/apache/beam/sdks/v2/go/pkg/beam/register" + "github.com/apache/beam/sdks/v2/go/pkg/beam/util/pubsubx" +) + +func init() { + register.DoFn5x2[context.Context, beam.BundleFinalization, *sdf.LockRTracker, []byte, func(beam.EventTime, []byte), sdf.ProcessContinuation, error](&pubSubRead{}) + register.DoFn2x1[context.Context, []byte, error](&pubSubWrite{}) + register.Emitter2[beam.EventTime, []byte]() +} + +// pubSubRead is a structural DoFn representing a read from a given subscription ID. +type pubSubRead struct { + ProjectID string + Subscription string + client *pubsub.Client + processedMessages []*pubsub.Message +} + +// newPubSubRead inserts an unbounded read from a PubSub topic into the pipeline. If an existing subscription +// is provided, the DoFn will read using that subscription; otherwise, a new subscription to the topic +// will be created using the provided subscription name. +func newPubSubRead(ctx context.Context, projectID, topic, subscription string) (*pubSubRead, error) { + if topic == "" { + return nil, errors.New("please provide either a topic to read from") + } + client, err := pubsub.NewClient(ctx, projectID) + if err != nil { + return nil, err + } + + top := client.Topic(topic) + if ok, err := top.Exists(ctx); !ok || err != nil { + return nil, fmt.Errorf("failed to get topic; exists: %v, error: %v", ok, err) + } + sub, err := pubsubx.EnsureSubscription(ctx, client, topic, subscription) + if err != nil { + return nil, err + } + return &pubSubRead{ProjectID: projectID, Subscription: sub.ID()}, nil +} + +// CreateInitialRestriction() establishes the PubSub subscription ID as the +// initial restriction +func (r *pubSubRead) CreateInitialRestriction(_ []byte) string { + return r.Subscription +} + +// CreateTracker wraps the PubSub subscription ID in a StaticRTracker +// and applies a mutex via LockRTracker. +func (r *pubSubRead) CreateTracker(rest string) *sdf.LockRTracker { + return sdf.NewLockRTracker(NewSubscriptionRTracker(rest)) +} + +// RestrictionSize always returns 1.0, as the restriction is always 1 subscription. +func (r *pubSubRead) RestrictionSize(_ []byte, rest string) float64 { + return 1.0 +} + +// SplitRestriction is a no-op as the restriction cannot be split. +func (r *pubSubRead) SplitRestriction(_ []byte, rest string) []string { + return []string{rest} +} + +// Setup initializes a PubSub client if one has not been created already +func (r *pubSubRead) Setup(ctx context.Context) error { + if r.client == nil { + client, err := pubsub.NewClient(ctx, r.ProjectID) + if err != nil { + return err + } + r.client = client + } + return nil +} + +var messageTimeout time.Duration = 5 * time.Second + +// ProcessElement initializes a PubSub client if one has not been created already, reads from the PubSub subscription, +// and emits elements as it reads them. If no messages are available, the DoFn will schedule itself to resume processing +// later. If polling the subscription returns an error, the error will be logged and the DoFn will not reschedule itself. +func (r *pubSubRead) ProcessElement(ctx context.Context, bf beam.BundleFinalization, rt *sdf.LockRTracker, _ []byte, emit func(beam.EventTime, []byte)) (sdf.ProcessContinuation, error) { + // Register finalization callback + bf.RegisterCallback(5*time.Minute, func() error { + for _, m := range r.processedMessages { + m.Ack() + } + r.processedMessages = nil + return nil + }) + + for { + ok := rt.TryClaim(r.Subscription) + if !ok { + return sdf.ResumeProcessingIn(5 * time.Second), nil + } Review Comment: As written, we're sort of prevented from having the runner force a checkpoint (only allowing DoFn checkpoints, but given we don't currently split, this is probably fine for now. The risk is a higher throughput pubsub, which will prevent this code from checkpointing, which will prevent downstream aggregations. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
