File: temporal.go

package info (click to toggle)
wait4x 3.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 744 kB
  • sloc: makefile: 248; sh: 13
file content (278 lines) | stat: -rw-r--r-- 7,628 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2019-2025 The Wait4X Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package temporal provides the Temporal checker for the Wait4X application.
package temporal

import (
	"context"
	"crypto/tls"
	"errors"
	"net"
	"os"
	"regexp"
	"time"

	"go.temporal.io/api/enums/v1"
	"go.temporal.io/api/taskqueue/v1"
	"go.temporal.io/api/workflowservice/v1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/health/grpc_health_v1"
	"wait4x.dev/v3/checker"
)

// Option configures a Temporal checker
type Option func(t *Temporal)

// CheckMode specifies the check mode
type CheckMode string

const (
	// DefaultConnectionTimeout is the default connection timeout duration
	DefaultConnectionTimeout = 3 * time.Second

	// DefaultInsecureTransport is the default insecure transport security
	DefaultInsecureTransport = false

	// DefaultInsecureSkipTLSVerify is the default insecure skip tls verify
	DefaultInsecureSkipTLSVerify = false

	// CheckModeServer is the "server" check mode
	CheckModeServer = "server"

	// CheckModeWorker is the "worker" check mode
	CheckModeWorker = "worker"
)

var (
	// ErrInvalidMode defines invalid mode error
	ErrInvalidMode = errors.New("invalid checkMode provided")
	// ErrNoNamespace defines no namespace error
	ErrNoNamespace = errors.New(`no namespace provided (use temporal.WithNamespace("__namespace__"))`)
	// ErrNoTaskQueue defines no task queue error
	ErrNoTaskQueue = errors.New(`no task queue provided (use temporal.WithTaskQueue("__task_queue__"))`)
)

// Temporal is a Temporal checker
type Temporal struct {
	checkMode                 CheckMode
	target                    string
	timeout                   time.Duration
	namespace                 string
	taskQueue                 string
	insecureTransport         bool
	insecureSkipTLSVerify     bool
	expectWorkerIdentityRegex string
}

// New creates a new Temporal checker
func New(checkMode CheckMode, target string, opts ...Option) checker.Checker {
	t := &Temporal{
		checkMode:             checkMode,
		target:                target,
		timeout:               DefaultConnectionTimeout,
		insecureTransport:     DefaultInsecureTransport,
		insecureSkipTLSVerify: DefaultInsecureSkipTLSVerify,
	}

	// apply the list of options to Temporal
	for _, opt := range opts {
		opt(t)
	}

	return t
}

// WithTimeout configures a timeout for maximum amount of time a dial will wait for a GRPC connection to complete
func WithTimeout(timeout time.Duration) Option {
	return func(t *Temporal) {
		t.timeout = timeout
	}
}

// WithNamespace configures the Temporal namespace that is mandatory for the CheckModeWorker
func WithNamespace(namespace string) Option {
	return func(t *Temporal) {
		t.namespace = namespace
	}
}

// WithTaskQueue configures the Temporal task queue that is mandatory for the CheckModeWorker
func WithTaskQueue(taskQueue string) Option {
	return func(t *Temporal) {
		t.taskQueue = taskQueue
	}
}

// WithInsecureTransport disables transport security
func WithInsecureTransport(insecureTransport bool) Option {
	return func(t *Temporal) {
		t.insecureTransport = insecureTransport
	}
}

// WithInsecureSkipTLSVerify configures insecure skip tls verify
func WithInsecureSkipTLSVerify(insecureSkipTLSVerify bool) Option {
	return func(t *Temporal) {
		t.insecureSkipTLSVerify = insecureSkipTLSVerify
	}
}

// WithExpectWorkerIdentityRegex configures worker (Poller) identity expectation that is mandatory for the CheckModeWorker
func WithExpectWorkerIdentityRegex(expectWorkerIdentityRegex string) Option {
	return func(t *Temporal) {
		t.expectWorkerIdentityRegex = expectWorkerIdentityRegex
	}
}

// Identity returns the identity of the Temporal checker
func (t *Temporal) Identity() (string, error) {
	return t.target, nil
}

// Check checks the Temporal connection
func (t *Temporal) Check(ctx context.Context) (err error) {
	conn, err := t.getGRPCConn()
	if err != nil {
		return err
	}
	defer func(conn *grpc.ClientConn) {
		if connErr := conn.Close(); connErr != nil {
			err = connErr
		}
	}(conn)
	switch t.checkMode {
	case CheckModeWorker:
		if t.namespace == "" {
			return ErrNoNamespace
		}

		if t.taskQueue == "" {
			return ErrNoTaskQueue
		}

		return t.checkWorker(ctx, conn)

	case CheckModeServer:
		return t.checkServer(ctx, conn)

	default:
		return ErrInvalidMode
	}
}

// getGRPCConn gets a GRPC connection
func (t *Temporal) getGRPCConn() (*grpc.ClientConn, error) {
	opts := []grpc.DialOption{
		grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
			d := net.Dialer{Timeout: t.timeout}
			return d.DialContext(ctx, "tcp", addr)
		}),
	}

	if t.insecureTransport {
		opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	} else {
		opts = append(
			opts,
			grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: t.insecureSkipTLSVerify})),
		)
	}

	conn, err := grpc.NewClient(t.target, opts...)
	if err != nil {
		if os.IsTimeout(err) {
			return nil, checker.NewExpectedError("timed out while making a grpc call", err)
		} else if checker.IsConnectionRefused(err) {
			return nil, checker.NewExpectedError("failed to establish a grpc connection", err)
		}

		return nil, err
	}

	return conn, nil
}

// checkServer checks the Temporal server
func (t *Temporal) checkServer(ctx context.Context, conn grpc.ClientConnInterface) error {
	healthClient := grpc_health_v1.NewHealthClient(conn)
	req := &grpc_health_v1.HealthCheckRequest{
		Service: "temporal.api.workflowservice.v1.WorkflowService",
	}

	resp, err := healthClient.Check(ctx, req)
	if err != nil {
		return checker.NewExpectedError("failed to health check", err)
	}

	if resp.GetStatus() != grpc_health_v1.HealthCheckResponse_SERVING {
		return checker.NewExpectedError(
			"health check returned unhealthy",
			nil,
			"status", resp.GetStatus(),
		)
	}

	return nil
}

// checkWorker checks the Temporal worker
func (t *Temporal) checkWorker(ctx context.Context, conn grpc.ClientConnInterface) error {
	client := workflowservice.NewWorkflowServiceClient(conn)
	req := &workflowservice.DescribeTaskQueueRequest{
		Namespace: t.namespace,
		TaskQueue: &taskqueue.TaskQueue{
			Name: t.taskQueue,
		},
		TaskQueueType: enums.TASK_QUEUE_TYPE_WORKFLOW,
	}

	resp, err := client.DescribeTaskQueue(ctx, req)
	if err != nil {
		return checker.NewExpectedError(
			"failed to describe the task queue",
			err,
		)
	}

	if len(resp.Pollers) == 0 {
		return checker.NewExpectedError("no worker (poller) registered", nil)
	}

	if t.expectWorkerIdentityRegex != "" {
		workerMatched := false
		for _, poller := range resp.Pollers {
			matched, err := regexp.MatchString(t.expectWorkerIdentityRegex, poller.Identity)
			if err != nil {
				return checker.NewExpectedError("failed to match string", err)
			}

			if matched {
				workerMatched = true
			}
		}

		if !workerMatched {
			return checker.NewExpectedError(
				"the worker (poller) hasn't registered yet",
				nil,
				"pattern", t.expectWorkerIdentityRegex,
			)
		}
	}

	return nil
}