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

142 lines
5.7 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 taskqueue
import (
"strings"
"sync/atomic"
"time"
"go.temporal.io/server/common/log/tag"
p "go.temporal.io/server/common/persistence"
"go.temporal.io/server/service/matching"
"go.temporal.io/server/service/worker/scanner/executor"
)
type handlerStatus = executor.TaskStatus
const (
handlerStatusDone = executor.TaskStatusDone
handlerStatusErr = executor.TaskStatusErr
handlerStatusDefer = executor.TaskStatusDefer
)
const scannerTaskQueuePrefix = "temporal-sys-tl-scanner"
// deleteHandler handles deletions for a given task queue
// this handler limits the amount of tasks deleted to maxTasksPerJob
// for fairness among all the task queue in the system - when there
// is more work to do subsequently, this handler will return StatusDefer
// with the assumption that the executor will schedule this task later
//
// Each loop of the handler proceeds as follows
// - Retrieve the next batch of tasks sorted by task_id for this task queue from persistence
// - If there are 0 tasks for this task queue, try deleting the task queue if its idle
// - If any of the tasks in the batch isn't expired, we are done. Since tasks are retrieved
// in sorted order, if one of the tasks isn't expired, chances are, none of the tasks above
// it are expired as well - so, we give up and wait for the next run
// - Delete the entire batch of tasks
// - If the number of tasks retrieved is less than batchSize, there are no more tasks in the task queue
// Try deleting the task queue if its idle
func (s *Scavenger) deleteHandler(key *p.TaskQueueKey, state *taskQueueState) handlerStatus {
var err error
var nProcessed, nDeleted int
defer func() { s.deleteHandlerLog(key, state, nProcessed, nDeleted, err) }()
for nProcessed < maxTasksPerJob {
resp, err1 := s.getTasks(s.lifecycleCtx, key, taskBatchSize)
if err1 != nil {
err = err1
return handlerStatusErr
}
nTasks := len(resp.Tasks)
if nTasks == 0 {
s.tryDeleteTaskQueue(key, state)
return handlerStatusDone
}
for _, task := range resp.Tasks {
nProcessed++
if !matching.IsTaskExpired(task) {
return handlerStatusDone
}
}
lastTaskID := resp.Tasks[nTasks-1].GetTaskId()
if _, err = s.completeTasks(s.lifecycleCtx, key, lastTaskID+1, nTasks); err != nil {
return handlerStatusErr
}
nDeleted += nTasks
if nTasks < taskBatchSize {
s.tryDeleteTaskQueue(key, state)
return handlerStatusDone
}
}
return handlerStatusDefer
}
func (s *Scavenger) tryDeleteTaskQueue(key *p.TaskQueueKey, state *taskQueueState) {
if strings.HasPrefix(key.TaskQueueName, scannerTaskQueuePrefix) {
return // avoid deleting our own task queue
}
delta := time.Now().UTC().Sub(state.lastUpdated)
if delta < taskQueueGracePeriod {
return
}
// usually, matching engine is the authoritative owner of a taskqueue
// and its incorrect for any other entity to mutate executorTask queues (including deleting it)
// the delete here is safe because of two reasons:
// - we delete the executorTask queue only if the lastUpdated is > 48H. If a executorTask queue is idle for
// this amount of time, it will no longer be owned by any host in matching engine (because
// of idle timeout). If any new host has to take ownership of this at this time, it can only
// do so by updating the rangeID
// - deleteTaskQueue is a conditional delete where condition is the rangeID
if err := s.deleteTaskQueue(s.lifecycleCtx, key, state.rangeID); err != nil {
s.logger.Error("deleteTaskQueue error", tag.Error(err))
return
}
atomic.AddInt64(&s.stats.taskqueue.nDeleted, 1)
s.logger.Info("taskqueue deleted", tag.WorkflowNamespaceID(key.NamespaceID), tag.WorkflowTaskQueueName(key.TaskQueueName), tag.WorkflowTaskQueueType(key.TaskQueueType))
}
func (s *Scavenger) deleteHandlerLog(key *p.TaskQueueKey, state *taskQueueState, nProcessed int, nDeleted int, err error) {
atomic.AddInt64(&s.stats.task.nDeleted, int64(nDeleted))
atomic.AddInt64(&s.stats.task.nProcessed, int64(nProcessed))
if err != nil {
s.logger.Error("scavenger.deleteHandler processed.",
tag.Error(err), tag.WorkflowNamespaceID(key.NamespaceID), tag.WorkflowTaskQueueName(key.TaskQueueName), tag.WorkflowTaskQueueType(key.TaskQueueType), tag.NumberProcessed(nProcessed), tag.NumberDeleted(nDeleted))
return
}
if nProcessed > 0 {
s.logger.Info("scavenger.deleteHandler processed.",
tag.WorkflowNamespaceID(key.NamespaceID), tag.WorkflowTaskQueueName(key.TaskQueueName), tag.WorkflowTaskQueueType(key.TaskQueueType), tag.NumberProcessed(nProcessed), tag.NumberDeleted(nDeleted))
}
}