Files
Tim Deeb-SwihartandGitHub 95169a53c3 Replace gogo/protobuf with google/protobuf (#5032)
**What changed?**

gogo/protobuf has been replaced with Google's official go compiler. 

**Why?**

gogo/protobuf has been deprecated for some time and the community is
moving on, building new tools (like vtproto) atop google's v2 compiler.

**How did you test it?**

`make test`

**Potential risks**

1. The change from embedded gogo-generated-structs to
google-generated-pointers-to-structs created a risk of nil pointer
exceptions. I've fixed all the ones our tests found but it's possible
there are more lurking in the new code.
2. This change may cause our performance to decrease. Certainly
encoding/deconding of proto objects will become slower, but the overuse
of pointers by the google compiler may negatively affect our overall
performance. We'll need to keep an eye on the GC stats
3. This breaks the HTTP API. We will not support [shortand payload
encoding](https://github.com/temporalio/proposals/blob/master/api/http-api.md#payload-formatting)
in this first pass; that will come once this initial work is in testing.

**Breaking changes for developers**

- `*time.Time` in proto structs will now be
[timestamppb.Timestamp](https://pkg.go.dev/google.golang.org/[email protected]/types/known/timestamppb#section-documentation)
- `*time.Duration` will now be
[durationpb.Duration](https://pkg.go.dev/google.golang.org/protobuf/types/known/durationpb)
- V2-generated structs embed locks, so you cannot dereference them. `go
vet` will scream at you about this. If you need a copy, use
`proto.Clone`.
- If the performance of this sucks then I will either update our code
generator to add shallow-clone methods or hand-roll the ones we need
- Proto enums will, when formatted to JSON, now be in
`SCREAMING_SNAKE_CASE` rather than `PascalCase`. We decided (in
discussion with the SDK team) that now was as good a time as any to rip
the bandage off.
- Proto objects, or objects embedding protos, cannot be compared using
`reflect.DeepEqual` or _anything_ that uses it. This includes `testify`
and `mock` equality testers!
- You will need to use the `common/testing/protorequire`,
`common/testing/protoassert`, or `common/testing/protomock` packages
instead. I've implemented proto-compatible matchers and assertions there
for all cases I've encountered
- If you need `reflect.DeepEqual` for any reason you can use
`go.temporal.io/api/temporalproto.DeepEqual` instead

Note that history loading will not be impacted by the JSON changes: I
rewrote history loading to dynamically fix incoming history JSON data
(like all our other sdks); you can find this code in [my fork of our go
API](https://github.com/tdeebswihart/temporal-api-go/blob/master/internal/temporalhistoryv1/load.go)
alongside its tests.

**🚨Sharp Edges Introduced🚨**

Beware `*timestamppb.Timestamp.AsTime()`. If you need to extract a time
value from a proto time (timestamppb) **always** make sure to check
whether it's nil first. When the proto object is `nil` `AsTime()` will
return a non-zero time at the proto epoch: UTC midnight on January 1,
1970.

I've made this mistake multiple times during this transition and each
time it's been a pain to debug

**Is hotfix candidate?**

No.
2023-11-21 15:19:37 -08:00

303 lines
8.8 KiB
Go

// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package s3store
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
commonpb "go.temporal.io/api/common/v1"
historypb "go.temporal.io/api/history/v1"
"go.temporal.io/api/serviceerror"
workflowpb "go.temporal.io/api/workflow/v1"
"go.uber.org/multierr"
"google.golang.org/protobuf/proto"
archiverspb "go.temporal.io/server/api/archiver/v1"
"go.temporal.io/server/common/archiver"
"go.temporal.io/server/common/codec"
"go.temporal.io/server/common/searchattribute"
)
// encoding & decoding util
func Encode(message proto.Message) ([]byte, error) {
encoder := codec.NewJSONPBEncoder()
return encoder.Encode(message)
}
func decodeVisibilityRecord(data []byte) (*archiverspb.VisibilityRecord, error) {
record := &archiverspb.VisibilityRecord{}
encoder := codec.NewJSONPBEncoder()
err := encoder.Decode(data, record)
if err != nil {
return nil, err
}
return record, nil
}
func SerializeToken(token interface{}) ([]byte, error) {
if token == nil {
return nil, nil
}
return json.Marshal(token)
}
func deserializeGetHistoryToken(bytes []byte) (*getHistoryToken, error) {
token := &getHistoryToken{}
err := json.Unmarshal(bytes, token)
return token, err
}
func deserializeQueryVisibilityToken(bytes []byte) *string {
var ret = string(bytes)
return &ret
}
func serializeQueryVisibilityToken(token string) []byte {
return []byte(token)
}
// Only validates the scheme and buckets are passed
func SoftValidateURI(URI archiver.URI) error {
if URI.Scheme() != URIScheme {
return archiver.ErrURISchemeMismatch
}
if len(URI.Hostname()) == 0 {
return errNoBucketSpecified
}
return nil
}
func BucketExists(ctx context.Context, s3cli s3iface.S3API, URI archiver.URI) error {
ctx, cancel := ensureContextTimeout(ctx)
defer cancel()
_, err := s3cli.HeadBucketWithContext(ctx, &s3.HeadBucketInput{
Bucket: aws.String(URI.Hostname()),
})
if err == nil {
return nil
}
if IsNotFoundError(err) {
return errBucketNotExists
}
return err
}
func KeyExists(ctx context.Context, s3cli s3iface.S3API, URI archiver.URI, key string) (bool, error) {
ctx, cancel := ensureContextTimeout(ctx)
defer cancel()
_, err := s3cli.HeadObjectWithContext(ctx, &s3.HeadObjectInput{
Bucket: aws.String(URI.Hostname()),
Key: aws.String(key),
})
if err != nil {
if IsNotFoundError(err) {
return false, nil
}
return false, err
}
return true, nil
}
func IsNotFoundError(err error) bool {
aerr, ok := err.(awserr.Error)
return ok && (aerr.Code() == "NotFound")
}
// Key construction
func constructHistoryKey(path, namespaceID, workflowID, runID string, version int64, batchIdx int) string {
prefix := constructHistoryKeyPrefixWithVersion(path, namespaceID, workflowID, runID, version)
return fmt.Sprintf("%s%d", prefix, batchIdx)
}
func constructHistoryKeyPrefixWithVersion(path, namespaceID, workflowID, runID string, version int64) string {
prefix := constructHistoryKeyPrefix(path, namespaceID, workflowID, runID)
return fmt.Sprintf("%s/%v/", prefix, version)
}
func constructHistoryKeyPrefix(path, namespaceID, workflowID, runID string) string {
return strings.TrimLeft(strings.Join([]string{path, namespaceID, "history", workflowID, runID}, "/"), "/")
}
func constructTimeBasedSearchKey(path, namespaceID, primaryIndexKey, primaryIndexValue, secondaryIndexKey string, t time.Time, precision string) string {
var timeFormat = ""
switch precision {
case PrecisionSecond:
timeFormat = ":05"
fallthrough
case PrecisionMinute:
timeFormat = ":04" + timeFormat
fallthrough
case PrecisionHour:
timeFormat = "15" + timeFormat
fallthrough
case PrecisionDay:
timeFormat = "2006-01-02T" + timeFormat
}
return fmt.Sprintf(
"%s/%s",
constructIndexedVisibilitySearchPrefix(path, namespaceID, primaryIndexKey, primaryIndexValue, secondaryIndexKey),
t.Format(timeFormat),
)
}
func constructTimestampIndex(path, namespaceID, primaryIndexKey, primaryIndexValue, secondaryIndexKey string, secondaryIndexValue time.Time, runID string) string {
return fmt.Sprintf(
"%s/%s/%s",
constructIndexedVisibilitySearchPrefix(path, namespaceID, primaryIndexKey, primaryIndexValue, secondaryIndexKey),
secondaryIndexValue.Format(time.RFC3339),
runID,
)
}
func constructIndexedVisibilitySearchPrefix(
path string,
namespaceID string,
primaryIndexKey string,
primaryIndexValue string,
secondaryIndexType string,
) string {
return strings.TrimLeft(
strings.Join(
[]string{path, namespaceID, "visibility", primaryIndexKey, primaryIndexValue, secondaryIndexType},
"/",
),
"/",
)
}
func constructVisibilitySearchPrefix(path, namespaceID string) string {
return strings.TrimLeft(strings.Join([]string{path, namespaceID, "visibility"}, "/"), "/")
}
func ensureContextTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
if _, ok := ctx.Deadline(); ok {
return ctx, func() {}
}
return context.WithTimeout(ctx, defaultBlobstoreTimeout)
}
func Upload(ctx context.Context, s3cli s3iface.S3API, URI archiver.URI, key string, data []byte) error {
ctx, cancel := ensureContextTimeout(ctx)
defer cancel()
_, err := s3cli.PutObjectWithContext(ctx, &s3.PutObjectInput{
Bucket: aws.String(URI.Hostname()),
Key: aws.String(key),
Body: bytes.NewReader(data),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == s3.ErrCodeNoSuchBucket {
return serviceerror.NewInvalidArgument(errBucketNotExists.Error())
}
}
return err
}
return nil
}
func Download(ctx context.Context, s3cli s3iface.S3API, URI archiver.URI, key string) ([]byte, error) {
ctx, cancel := ensureContextTimeout(ctx)
defer cancel()
result, err := s3cli.GetObjectWithContext(ctx, &s3.GetObjectInput{
Bucket: aws.String(URI.Hostname()),
Key: aws.String(key),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == s3.ErrCodeNoSuchBucket {
return nil, serviceerror.NewInvalidArgument(errBucketNotExists.Error())
}
if aerr.Code() == s3.ErrCodeNoSuchKey {
return nil, serviceerror.NewNotFound(archiver.ErrHistoryNotExist.Error())
}
}
return nil, err
}
defer func() {
if ierr := result.Body.Close(); ierr != nil {
err = multierr.Append(err, ierr)
}
}()
body, err := io.ReadAll(result.Body)
if err != nil {
return nil, err
}
return body, nil
}
func historyMutated(request *archiver.ArchiveHistoryRequest, historyBatches []*historypb.History, isLast bool) bool {
lastBatch := historyBatches[len(historyBatches)-1].Events
lastEvent := lastBatch[len(lastBatch)-1]
lastFailoverVersion := lastEvent.GetVersion()
if lastFailoverVersion > request.CloseFailoverVersion {
return true
}
if !isLast {
return false
}
lastEventID := lastEvent.GetEventId()
return lastFailoverVersion != request.CloseFailoverVersion || lastEventID+1 != request.NextEventID
}
func convertToExecutionInfo(record *archiverspb.VisibilityRecord, saTypeMap searchattribute.NameTypeMap) (*workflowpb.WorkflowExecutionInfo, error) {
searchAttributes, err := searchattribute.Parse(record.SearchAttributes, &saTypeMap)
if err != nil {
return nil, err
}
return &workflowpb.WorkflowExecutionInfo{
Execution: &commonpb.WorkflowExecution{
WorkflowId: record.GetWorkflowId(),
RunId: record.GetRunId(),
},
Type: &commonpb.WorkflowType{
Name: record.WorkflowTypeName,
},
StartTime: record.StartTime,
ExecutionTime: record.ExecutionTime,
CloseTime: record.CloseTime,
Status: record.Status,
HistoryLength: record.HistoryLength,
Memo: record.Memo,
SearchAttributes: searchAttributes,
}, nil
}