func newReceiver()

in lib/notifiers/notifiers.go [513:563]


func newReceiver(notifier Notifier, params *receiverParams) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		var pspw pubSubPushWrapper
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Errorf("failed to read request message: %v", err)
			http.Error(w, "Bad request body", http.StatusBadRequest)
			return
		}

		if err := json.Unmarshal(body, &pspw); err != nil {
			log.Errorf("failed to unmarshal body %q: %v", body, err)
			http.Error(w, "Bad pubsub.Message JSON", http.StatusBadRequest)
			return
		}

		log.V(2).Infof("got PubSub message with ID %q from subscription %q", pspw.Message.ID, pspw.Subscription)

		build := new(cbpb.Build)
		// Be as lenient as possible in unmarshalling.
		// `Unmarshal` will fail if we get a payload with a field that is unknown to the current proto version unless `DiscardUnknown` is set.
		uo := protojson.UnmarshalOptions{
			AllowPartial:   true,
			DiscardUnknown: true,
		}
		bv2 := protoadapt.MessageV2Of(build)
		if err := uo.Unmarshal(pspw.Message.Data, bv2); err != nil {
			if params.ignoreBadMessages {
				log.Warningf("not attempting to handle unmarshal-able Pub/Sub message id=%q data=%q publishTime=%q which gave error: %v",
					pspw.Message.ID, string(pspw.Message.Data), pspw.Message.PublishTime, err)
				return
			}

			log.Errorf("failed to unmarshal PubSub message id=%q data=%q publishTime=%q into a Build: %v",
				pspw.Message.ID, string(pspw.Message.Data), pspw.Message.PublishTime, err)
			http.Error(w, "Bad Cloud Build Pub/Sub data", http.StatusBadRequest)
			return
		}
		build = protoadapt.MessageV1Of(bv2).(*cbpb.Build)

		log.V(2).Infof("got PubSub Build payload:\n%+v\nattempting to send notification", prototext.Format(build))
		if err := notifier.SendNotification(ctx, build); err != nil {
			log.Errorf("failed to run SendNotification: %v", err)
			http.Error(w, "failed to send notification", http.StatusInternalServerError)
			return
		}

		log.V(2).Infof("acking PubSub message %q with Build payload:\n%v", pspw.Message.ID, prototext.Format(build))
	}
}