go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/buildbucket/appengine/model/requestid.go (about)

     1  // Copyright 2021 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 model
    16  
    17  import (
    18  	"context"
    19  	"crypto/sha256"
    20  	"fmt"
    21  	"time"
    22  
    23  	"go.chromium.org/luci/auth/identity"
    24  	"go.chromium.org/luci/gae/service/datastore"
    25  	"go.chromium.org/luci/server/auth"
    26  )
    27  
    28  // RequestID stores request IDs for request deduplication.
    29  type RequestID struct {
    30  	_     datastore.PropertyMap `gae:"-,extra"`
    31  	_kind string                `gae:"$kind,RequestID"`
    32  	// ID is a string of the form "<auth.Identity>:<request ID string>" encoded
    33  	// as a hex string using SHA-256 for a well-distributed key space.
    34  	ID string `gae:"$id"`
    35  
    36  	// BuildID is the ID of the Build entity this entity refers to.
    37  	BuildID    int64             `gae:"build_id,noindex"`
    38  	CreatedBy  identity.Identity `gae:"created_by,noindex"`
    39  	CreateTime time.Time         `gae:"create_time,noindex"`
    40  	// RequestID is the original request ID string this entity was created from.
    41  	RequestID string `gae:"request_id,noindex"`
    42  }
    43  
    44  // NewRequestID returns a request ID with the entity ID filled in.
    45  func NewRequestID(ctx context.Context, buildID int64, now time.Time, requestID string) *RequestID {
    46  	u := auth.CurrentIdentity(ctx)
    47  	return &RequestID{
    48  		ID:         fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s:%s", u, requestID)))),
    49  		BuildID:    buildID,
    50  		CreatedBy:  u,
    51  		CreateTime: now,
    52  		RequestID:  requestID,
    53  	}
    54  }