go.temporal.io/server/client/matching/client.go
535 LOC · 191 covered · 344 uncovered · 39 ranges · 64 concepts · 8 introducers · 12 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
// Generates all three generated files in this package:
//go:generate go run ../../cmd/tools/genrpcwrappers -service matching
package matching
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
enumspb "go.temporal.io/api/enums/v1"
taskqueuepb "go.temporal.io/api/taskqueue/v1"
"go.temporal.io/server/api/matchingservice/v1"
"go.temporal.io/server/common"
"go.temporal.io/server/common/debug"
"go.temporal.io/server/common/dynamicconfig"
"go.temporal.io/server/common/goro"
"go.temporal.io/server/common/log"
"go.temporal.io/server/common/log/tag"
"go.temporal.io/server/common/membership"
"go.temporal.io/server/common/metrics"
"go.temporal.io/server/common/tqid"
"google.golang.org/grpc"
)
var _ matchingservice.MatchingServiceClient = (*clientImpl)(nil)
const (
// DefaultTimeout is the max timeout for regular calls
DefaultTimeout = time.Minute * debug.TimeoutMultiplier
// DefaultLongPollTimeout is the max timeout for long poll calls
DefaultLongPollTimeout = time.Minute * 5 * debug.TimeoutMultiplier
// evictionCheckInterval is how often departed hosts are reaped from the cache.
evictionCheckInterval = 30 * time.Second
)
type clientImpl struct {
timeout time.Duration
longPollTimeout time.Duration
clients common.ClientCache
resolver membership.ServiceResolver
connectionCloseDelay dynamicconfig.DurationPropertyFn
metricsHandler metrics.Handler
logger log.Logger
loadBalancer LoadBalancer
spreadRouting dynamicconfig.TypedPropertyFn[dynamicconfig.GradualChange[int]]
partitionCache *partitionCache
evictionWatcher *goro.Handle
}
// NewClient creates a new matching service gRPC client
func NewClient(
timeout time.Duration,
longPollTimeout time.Duration,
clients common.ClientCache,
metricsHandler metrics.Handler,
logger log.Logger,
lb LoadBalancer,
spreadRouting dynamicconfig.TypedPropertyFn[dynamicconfig.GradualChange[int]],
resolver membership.ServiceResolver,
connectionCloseDelay dynamicconfig.DurationPropertyFn,
c := &clientImpl{
timeout: timeout,
longPollTimeout: longPollTimeout,
clients: clients,
resolver: resolver,
connectionCloseDelay: connectionCloseDelay,
metricsHandler: metricsHandler,
logger: logger,
loadBalancer: lb,
spreadRouting: spreadRouting,
partitionCache: newPartitionCache(metricsHandler),
}
// Start goroutine to prune partition count cache. Stopped by Stop().
c.partitionCache.Start()
// Evict cached clients whose host leaves the membership ring. Stopped by Stop().
c.evictionWatcher = goro.NewHandle(context.Background()).Go(c.watchMembership)
return c
}
// Stop deterministically releases the resources started by NewClient: it stops
// the eviction watcher and partition-cache rotation goroutines and closes every
// cached gRPC connection. It is safe to call more than once.
c.evictionWatcher.Cancel()
<-c.evictionWatcher.Done()
c.partitionCache.Stop()
c.clients.EvictAll()
}
// watchMembership evicts cached clients whose host leaves the membership ring.
// It runs until ctx is cancelled (by Stop).
listenerName := fmt.Sprintf("matchingClientCache-%s", uuid.New().String())
ch := make(chan *membership.ChangedEvent, 1)
if err := c.resolver.AddListener(listenerName, ch); err != nil {
c.logger.Error("Failed to subscribe matching cache to membership", tag.Error(err))
return err
}
// Reap departed hosts via a per-address deadline checked by a single ticker;
// a re-add resets it to the latest removal.
ticker := time.NewTicker(evictionCheckInterval)
defer ticker.Stop()
for {
select {
return nil
for _, h := range event.HostsRemoved {
}
delete(evictAt, h.GetAddress())
}
case <-ticker.C:
reapEvictableClients(c.resolver, c.clients, evictAt)
}
}
}
func reapEvictableClients(
resolver membership.ServiceResolver,
clients common.ClientCache,
evictAt map[string]time.Time,
) {
if len(evictAt) == 0 {
return
}
members := make(map[string]struct{})
for _, m := range resolver.Members() {
members[m.GetAddress()] = struct{}{}
}
now := time.Now()
for addr, deadline := range evictAt {
if _, ok := members[addr]; ok {
delete(evictAt, addr) // back in the ring; cancel the eviction
continue
}
if now.Before(deadline) {
continue
}
clients.Evict(addr)
delete(evictAt, addr)
}
}
func (c *clientImpl) AddActivityTask(
ctx context.Context,
request *matchingservice.AddActivityTaskRequest,
opts ...grpc.CallOption,
if !isPartitionAwareKind(request.GetTaskQueue().GetKind()) {
return c.addActivityTask(ctx, PartitionCounts{}, request, opts)
}
request.GetNamespaceId(),
request.GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_ACTIVITY,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.addActivityTask)
}
func (c *clientImpl) addActivityTask(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.AddActivityTaskRequest,
opts []grpc.CallOption,
request = common.CloneProto(request)
client, err := c.pickClientForWrite(
request.GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_ACTIVITY,
request.GetForwardInfo().GetSourcePartition(),
pc,
)
if err != nil {
return nil, err
}
defer cancel()
return client.AddActivityTask(ctx, request, opts...)
}
func (c *clientImpl) AddWorkflowTask(
ctx context.Context,
request *matchingservice.AddWorkflowTaskRequest,
if !isPartitionAwareKind(request.GetTaskQueue().GetKind()) {
}
request.GetNamespaceId(),
request.GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_WORKFLOW,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.addWorkflowTask)
}
func (c *clientImpl) addWorkflowTask(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.AddWorkflowTaskRequest,
opts []grpc.CallOption,
request = common.CloneProto(request)
client, err := c.pickClientForWrite(
request.GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_WORKFLOW,
request.GetForwardInfo().GetSourcePartition(),
pc,
)
if err != nil {
return nil, err
}
defer cancel()
return client.AddWorkflowTask(ctx, request, opts...)
}
func (c *clientImpl) PollActivityTaskQueue(
ctx context.Context,
request *matchingservice.PollActivityTaskQueueRequest,
opts ...grpc.CallOption,
if !isPartitionAwareKind(request.GetPollRequest().GetTaskQueue().GetKind()) {
return c.pollActivityTaskQueue(ctx, PartitionCounts{}, request, opts)
}
request.GetNamespaceId(),
request.GetPollRequest().GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_ACTIVITY,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.pollActivityTaskQueue)
}
func (c *clientImpl) pollActivityTaskQueue(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.PollActivityTaskQueueRequest,
opts []grpc.CallOption,
request = common.CloneProto(request)
client, release, err := c.pickClientForRead(
request.GetPollRequest().GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_ACTIVITY,
request.GetForwardedSource(),
pc,
)
if err != nil {
return nil, err
}
defer release()
}
ctx, cancel := c.createLongPollContext(ctx)
defer cancel()
return client.PollActivityTaskQueue(ctx, request, opts...)
}
func (c *clientImpl) PollWorkflowTaskQueue(
ctx context.Context,
request *matchingservice.PollWorkflowTaskQueueRequest,
opts ...grpc.CallOption,
if !isPartitionAwareKind(request.GetPollRequest().GetTaskQueue().GetKind()) {
return c.pollWorkflowTaskQueue(ctx, PartitionCounts{}, request, opts)
}
pkey := c.partitionCache.makeKey(
request.GetNamespaceId(),
request.GetPollRequest().GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_WORKFLOW,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.pollWorkflowTaskQueue)
}
func (c *clientImpl) pollWorkflowTaskQueue(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.PollWorkflowTaskQueueRequest,
opts []grpc.CallOption,
request = common.CloneProto(request)
client, release, err := c.pickClientForRead(
request.GetPollRequest().GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_WORKFLOW,
request.GetForwardedSource(),
pc,
)
if err != nil {
return nil, err
}
defer release()
}
ctx, cancel := c.createLongPollContext(ctx)
defer cancel()
return client.PollWorkflowTaskQueue(ctx, request, opts...)
}
func (c *clientImpl) QueryWorkflow(
ctx context.Context,
request *matchingservice.QueryWorkflowRequest,
opts ...grpc.CallOption,
) (*matchingservice.QueryWorkflowResponse, error) {
if !isPartitionAwareKind(request.GetTaskQueue().GetKind()) {
return c.queryWorkflow(ctx, PartitionCounts{}, request, opts)
}
pkey := c.partitionCache.makeKey(
request.GetNamespaceId(),
request.GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_WORKFLOW,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.queryWorkflow)
}
func (c *clientImpl) queryWorkflow(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.QueryWorkflowRequest,
opts []grpc.CallOption,
) (*matchingservice.QueryWorkflowResponse, error) {
// use shallow copy since QueryRequest may contain a large payload
request = &matchingservice.QueryWorkflowRequest{
NamespaceId: request.NamespaceId,
TaskQueue: common.CloneProto(request.TaskQueue),
QueryRequest: request.QueryRequest,
VersionDirective: request.VersionDirective,
ForwardInfo: request.ForwardInfo,
Priority: request.Priority,
}
client, err := c.pickClientForWrite(
request.GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_WORKFLOW,
request.GetForwardInfo().GetSourcePartition(),
pc,
)
if err != nil {
return nil, err
}
ctx, cancel := c.createContext(ctx)
defer cancel()
return client.QueryWorkflow(ctx, request, opts...)
}
func (c *clientImpl) DispatchNexusTask(
ctx context.Context,
request *matchingservice.DispatchNexusTaskRequest,
opts ...grpc.CallOption,
) (*matchingservice.DispatchNexusTaskResponse, error) {
if !isPartitionAwareKind(request.GetTaskQueue().GetKind()) {
return c.dispatchNexusTask(ctx, PartitionCounts{}, request, opts)
}
pkey := c.partitionCache.makeKey(
request.GetNamespaceId(),
request.GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_NEXUS,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.dispatchNexusTask)
}
func (c *clientImpl) dispatchNexusTask(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.DispatchNexusTaskRequest,
opts []grpc.CallOption,
) (*matchingservice.DispatchNexusTaskResponse, error) {
// use shallow copy since Request may contain a large payload
request = &matchingservice.DispatchNexusTaskRequest{
NamespaceId: request.NamespaceId,
TaskQueue: common.CloneProto(request.TaskQueue),
Request: request.Request,
ForwardInfo: request.ForwardInfo,
}
client, err := c.pickClientForWrite(
request.GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_NEXUS,
request.GetForwardInfo().GetSourcePartition(),
pc,
)
if err != nil {
return nil, err
}
ctx, cancel := c.createContext(ctx)
defer cancel()
return client.DispatchNexusTask(ctx, request, opts...)
}
func (c *clientImpl) PollNexusTaskQueue(
ctx context.Context,
request *matchingservice.PollNexusTaskQueueRequest,
opts ...grpc.CallOption,
) (*matchingservice.PollNexusTaskQueueResponse, error) {
if !isPartitionAwareKind(request.GetRequest().GetTaskQueue().GetKind()) {
return c.pollNexusTaskQueue(ctx, PartitionCounts{}, request, opts)
}
pkey := c.partitionCache.makeKey(
request.GetNamespaceId(),
request.GetRequest().GetTaskQueue().GetName(),
enumspb.TASK_QUEUE_TYPE_NEXUS,
)
return invokeWithPartitionCounts(ctx, c.logger, c.partitionCache, pkey, request, opts, c.pollNexusTaskQueue)
}
func (c *clientImpl) pollNexusTaskQueue(
ctx context.Context,
pc PartitionCounts,
request *matchingservice.PollNexusTaskQueueRequest,
opts []grpc.CallOption,
) (*matchingservice.PollNexusTaskQueueResponse, error) {
request = common.CloneProto(request)
client, release, err := c.pickClientForRead(
request.GetRequest().GetTaskQueue(),
request.GetNamespaceId(),
enumspb.TASK_QUEUE_TYPE_NEXUS,
request.GetForwardedSource(),
pc,
)
if err != nil {
return nil, err
}
if release != nil {
defer release()
}
ctx, cancel := c.createLongPollContext(ctx)
defer cancel()
return client.PollNexusTaskQueue(ctx, request, opts...)
}
// processInputPartition returns a partition in certain cases that load balancer involvement is not necessary,
// otherwise, returns a task queue to pass down to the load balancer.
func (c *clientImpl) processInputPartition(proto *taskqueuepb.TaskQueue, nsid string, taskType enumspb.TaskQueueType, forwardedFrom string) (tqid.Partition, *tqid.TaskQueue) {
service_grpc.pb.go ×20
partition, err := tqid.PartitionFromProto(proto, nsid, taskType)
if err != nil {
// We preserve the old logic (not returning error in case of invalid proto info) until it's verified that
// clients are not sending invalid names.
c.logger.Info("invalid tq partition", tag.Error(err), tag.Stringer("proto", proto))
metrics.MatchingClientInvalidTaskQueuePartition.With(c.metricsHandler).Record(1)
return tqid.UnsafeTaskQueueFamily(nsid, proto.GetName()).TaskQueue(taskType).RootPartition(), nil
}
return partition, nil
}
case *tqid.NormalPartition:
return nil, p.TaskQueue()
default:
return partition, nil
}
}
// pickClientForWrite mutates the given proto. Callers should copy the proto before if necessary.
func (c *clientImpl) pickClientForWrite(
proto *taskqueuepb.TaskQueue,
nsid string,
taskType enumspb.TaskQueueType,
forwardedFrom string,
pc PartitionCounts,
p, tq := c.processInputPartition(proto, nsid, taskType, forwardedFrom)
if tq != nil {
p = c.loadBalancer.PickWritePartition(tq, pc)
}
proto.Name = p.RpcName()
return c.getClientForTaskQueuePartition(p)
}
// pickClientForRead mutates the given proto. Callers should copy the proto before if necessary.
func (c *clientImpl) pickClientForRead(
proto *taskqueuepb.TaskQueue,
nsid string,
taskType enumspb.TaskQueueType,
forwardedFrom string,
pc PartitionCounts,
) (client matchingservice.MatchingServiceClient, release func(), err error) {
service_grpc.pb.go ×20
p, tq := c.processInputPartition(proto, nsid, taskType, forwardedFrom)
if tq != nil {
token := c.loadBalancer.PickReadPartition(tq, pc)
p = token.TQPartition
release = token.Release
}
client, err = c.getClientForTaskQueuePartition(p)
return client, release, err
}
func (c *clientImpl) createContext(parent context.Context) (context.Context, context.CancelFunc) {
service_grpc.pb.go ×20
return context.WithTimeout(parent, c.timeout)
}
func (c *clientImpl) createLongPollContext(parent context.Context) (context.Context, context.CancelFunc) {
service_grpc.pb.go ×20
return context.WithTimeout(parent, c.longPollTimeout)
}
spreadChange := c.spreadRouting()
spread := spreadChange.Value(p.GradualChangeKey(), time.Now())
return c.clients.Lookup(p.RoutingKey(spread))
}
func (c *clientImpl) getClientForTaskQueuePartition(
partition tqid.Partition,
addr, err := c.Route(partition)
if err != nil {
}
if err != nil {
return nil, err
}
}
// only normal partitions participate in scaling
return kind == enumspb.TASK_QUEUE_KIND_NORMAL
}