...

Source file src/cloud.google.com/go/internal/pubsub/publish.go

Documentation: cloud.google.com/go/internal/pubsub

     1  // Copyright 2020 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  
    14  package pubsub
    15  
    16  import "context"
    17  
    18  // A PublishResult holds the result from a call to Publish.
    19  type PublishResult struct {
    20  	ready    chan struct{}
    21  	serverID string
    22  	err      error
    23  }
    24  
    25  // Ready returns a channel that is closed when the result is ready.
    26  // When the Ready channel is closed, Get is guaranteed not to block.
    27  func (r *PublishResult) Ready() <-chan struct{} { return r.ready }
    28  
    29  // Get returns the server-generated message ID and/or error result of a Publish call.
    30  // Get blocks until the Publish call completes or the context is done.
    31  func (r *PublishResult) Get(ctx context.Context) (serverID string, err error) {
    32  	// If the result is already ready, return it even if the context is done.
    33  	select {
    34  	case <-r.Ready():
    35  		return r.serverID, r.err
    36  	default:
    37  	}
    38  	select {
    39  	case <-ctx.Done():
    40  		return "", ctx.Err()
    41  	case <-r.Ready():
    42  		return r.serverID, r.err
    43  	}
    44  }
    45  
    46  // NewPublishResult creates a PublishResult.
    47  func NewPublishResult() *PublishResult {
    48  	return &PublishResult{ready: make(chan struct{})}
    49  }
    50  
    51  // SetPublishResult sets the server ID and error for a publish result and closes
    52  // the Ready channel.
    53  func SetPublishResult(r *PublishResult, sid string, err error) {
    54  	r.serverID = sid
    55  	r.err = err
    56  	close(r.ready)
    57  }
    58  

View as plain text