go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/app/pubsub.go (about)

     1  // Copyright 2022 The LUCI Authors.
     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  //      http://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  // limitations under the License.
    14  
    15  package app
    16  
    17  import (
    18  	"net/http"
    19  
    20  	"go.chromium.org/luci/common/retry/transient"
    21  	"go.chromium.org/luci/server/router"
    22  )
    23  
    24  // Sent by pubsub.
    25  // This struct is just convenient for unwrapping the json message.
    26  // See https://source.chromium.org/chromium/infra/infra/+/main:luci/appengine/components/components/pubsub.py;l=178;drc=78ce3aa55a2e5f77dc05517ef3ec377b3f36dc6e.
    27  type pubsubMessage struct {
    28  	Message struct {
    29  		Data       []byte
    30  		Attributes map[string]any
    31  	}
    32  }
    33  
    34  func processErr(ctx *router.Context, err error) string {
    35  	if transient.Tag.In(err) {
    36  		// Transient errors are 500 so that PubSub retries them.
    37  		ctx.Writer.WriteHeader(http.StatusInternalServerError)
    38  		return "transient-failure"
    39  	} else {
    40  		// Permanent failures are 202s so that:
    41  		// - PubSub does not retry them, and
    42  		// - the results can be distinguished from success / ignored results
    43  		//   (which are reported as 200 OK / 204 No Content) in logs.
    44  		// See https://cloud.google.com/pubsub/docs/push#receiving_messages.
    45  		ctx.Writer.WriteHeader(http.StatusAccepted)
    46  		return "permanent-failure"
    47  	}
    48  }