-
Notifications
You must be signed in to change notification settings - Fork 6
/
test_joblib_test.go
328 lines (276 loc) · 11.1 KB
/
test_joblib_test.go
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package asyncjob_test
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/Azure/go-asyncjob"
"github.com/Azure/go-asynctask"
)
type testingLoggerKey string
const testLoggingContextKey testingLoggerKey = "test-logging"
// SqlSummaryAsyncJobDefinition is the job definition for the SqlSummaryJobLib
//
// JobDefinition fit perfectly in init() function
var SqlSummaryAsyncJobDefinition *asyncjob.JobDefinitionWithResult[*SqlSummaryJobLib, *SummarizedResult]
func init() {
var err error
SqlSummaryAsyncJobDefinition, err = BuildJobWithResult(map[string]asyncjob.RetryPolicy{})
if err != nil {
panic(err)
}
SqlSummaryAsyncJobDefinition.Seal()
}
type SqlSummaryJobLib struct {
Params *SqlSummaryJobParameters
// assume you have some state that you want to share between steps
// you can use a mutex to protect the data writen between different steps
// this kind of error is not fault of this library.
data map[string]interface{}
mutex sync.Mutex
}
func NewSqlJobLib(params *SqlSummaryJobParameters) *SqlSummaryJobLib {
return &SqlSummaryJobLib{
Params: params,
data: make(map[string]interface{}),
mutex: sync.Mutex{},
}
}
func connectionStepFunc(sql *SqlSummaryJobLib) asynctask.AsyncFunc[*SqlConnection] {
return func(ctx context.Context) (*SqlConnection, error) {
return sql.GetConnection(ctx, &sql.Params.ServerName)
}
}
func checkAuthStepFunc(sql *SqlSummaryJobLib) asynctask.AsyncFunc[interface{}] {
return asynctask.ActionToFunc(func(ctx context.Context) error {
return sql.CheckAuth(ctx)
})
}
func tableClient1StepFunc(sql *SqlSummaryJobLib) asynctask.ContinueFunc[*SqlConnection, *SqlTableClient] {
return func(ctx context.Context, conn *SqlConnection) (*SqlTableClient, error) {
return sql.GetTableClient(ctx, conn, &sql.Params.Table1)
}
}
func tableClient2StepFunc(sql *SqlSummaryJobLib) asynctask.ContinueFunc[*SqlConnection, *SqlTableClient] {
return func(ctx context.Context, conn *SqlConnection) (*SqlTableClient, error) {
return sql.GetTableClient(ctx, conn, &sql.Params.Table2)
}
}
func queryTable1StepFunc(sql *SqlSummaryJobLib) asynctask.ContinueFunc[*SqlTableClient, *SqlQueryResult] {
return func(ctx context.Context, tableClient *SqlTableClient) (*SqlQueryResult, error) {
return sql.ExecuteQuery(ctx, tableClient, &sql.Params.Query1)
}
}
func queryTable2StepFunc(sql *SqlSummaryJobLib) asynctask.ContinueFunc[*SqlTableClient, *SqlQueryResult] {
return func(ctx context.Context, tableClient *SqlTableClient) (*SqlQueryResult, error) {
return sql.ExecuteQuery(ctx, tableClient, &sql.Params.Query2)
}
}
func summarizeQueryResultStepFunc(sql *SqlSummaryJobLib) asynctask.AfterBothFunc[*SqlQueryResult, *SqlQueryResult, *SummarizedResult] {
return func(ctx context.Context, query1Result *SqlQueryResult, query2Result *SqlQueryResult) (*SummarizedResult, error) {
return sql.SummarizeQueryResult(ctx, query1Result, query2Result)
}
}
func emailNotificationStepFunc(sql *SqlSummaryJobLib) asynctask.AsyncFunc[interface{}] {
return asynctask.ActionToFunc(func(ctx context.Context) error {
return sql.EmailNotification(ctx)
})
}
func BuildJob(retryPolicies map[string]asyncjob.RetryPolicy) (*asyncjob.JobDefinition[*SqlSummaryJobLib], error) {
job := asyncjob.NewJobDefinition[*SqlSummaryJobLib]("sqlSummaryJob")
connTsk, err := asyncjob.AddStep(job, "GetConnection", connectionStepFunc, asyncjob.WithRetry(retryPolicies["GetConnection"]), asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step GetConnection: %w", err)
}
checkAuthTask, err := asyncjob.AddStep(job, "CheckAuth", checkAuthStepFunc, asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step CheckAuth: %w", err)
}
table1ClientTsk, err := asyncjob.StepAfter(job, "GetTableClient1", connTsk, tableClient1StepFunc, asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step GetTableClient1: %w", err)
}
qery1ResultTsk, err := asyncjob.StepAfter(job, "QueryTable1", table1ClientTsk, queryTable1StepFunc, asyncjob.WithRetry(retryPolicies["QueryTable1"]), asyncjob.ExecuteAfter(checkAuthTask), asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step QueryTable1: %w", err)
}
table2ClientTsk, err := asyncjob.StepAfter(job, "GetTableClient2", connTsk, tableClient2StepFunc, asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step GetTableClient2: %w", err)
}
qery2ResultTsk, err := asyncjob.StepAfter(job, "QueryTable2", table2ClientTsk, queryTable2StepFunc, asyncjob.WithRetry(retryPolicies["QueryTable2"]), asyncjob.ExecuteAfter(checkAuthTask), asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step QueryTable2: %w", err)
}
summaryTsk, err := asyncjob.StepAfterBoth(job, "Summarize", qery1ResultTsk, qery2ResultTsk, summarizeQueryResultStepFunc, asyncjob.WithRetry(retryPolicies["Summarize"]), asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step Summarize: %w", err)
}
_, err = asyncjob.AddStep(job, "EmailNotification", emailNotificationStepFunc, asyncjob.ExecuteAfter(summaryTsk), asyncjob.WithContextEnrichment(EnrichContext))
if err != nil {
return nil, fmt.Errorf("error adding step EmailNotification: %w", err)
}
return job, nil
}
func BuildJobWithResult(retryPolicies map[string]asyncjob.RetryPolicy) (*asyncjob.JobDefinitionWithResult[*SqlSummaryJobLib, *SummarizedResult], error) {
job, err := BuildJob(retryPolicies)
if err != nil {
return nil, err
}
summaryStepMeta, ok := job.GetStep("Summarize")
if !ok {
return nil, fmt.Errorf("step Summarize not found")
}
summaryStep, ok := summaryStepMeta.(*asyncjob.StepDefinition[*SummarizedResult])
if !ok {
return nil, fmt.Errorf("step Summarize have different generic type parameter: %T", summaryStepMeta)
}
return asyncjob.JobWithResult(job, summaryStep)
}
type SqlSummaryJobParameters struct {
ServerName string
Table1 string
Query1 string
Table2 string
Query2 string
ErrorInjection map[string]func() error
PanicInjection map[string]bool
}
type SqlConnection struct {
ServerName string
}
type SqlTableClient struct {
ServerName string
TableName string
}
type SqlQueryResult struct {
Data map[string]interface{}
}
type SummarizedResult struct {
QueryResult1 map[string]interface{}
QueryResult2 map[string]interface{}
}
func (sql *SqlSummaryJobLib) GetConnection(ctx context.Context, serverName *string) (*SqlConnection, error) {
sql.Logging(ctx, "GetConnection")
if sql.Params.ErrorInjection != nil {
if errFunc, ok := sql.Params.ErrorInjection["GetConnection"]; ok {
if err := errFunc(); err != nil {
return nil, err
}
}
}
return &SqlConnection{ServerName: *serverName}, nil
}
func (sql *SqlSummaryJobLib) GetTableClient(ctx context.Context, conn *SqlConnection, tableName *string) (*SqlTableClient, error) {
sql.Logging(ctx, fmt.Sprintf("GetTableClient with tableName: %s", *tableName))
injectionKey := fmt.Sprintf("GetTableClient.%s.%s", conn.ServerName, *tableName)
if sql.Params.PanicInjection != nil {
if shouldPanic, ok := sql.Params.PanicInjection[injectionKey]; ok && shouldPanic {
panic("as you wish")
}
}
if sql.Params.ErrorInjection != nil {
if errFunc, ok := sql.Params.ErrorInjection[injectionKey]; ok {
if err := errFunc(); err != nil {
return nil, err
}
}
}
return &SqlTableClient{ServerName: conn.ServerName, TableName: *tableName}, nil
}
func (sql *SqlSummaryJobLib) CheckAuth(ctx context.Context) error {
sql.Logging(ctx, "CheckAuth")
injectionKey := "CheckAuth"
if sql.Params.PanicInjection != nil {
if shouldPanic, ok := sql.Params.PanicInjection[injectionKey]; ok && shouldPanic {
panic("as you wish")
}
}
if sql.Params.ErrorInjection != nil {
if errFunc, ok := sql.Params.ErrorInjection[injectionKey]; ok {
if err := errFunc(); err != nil {
return err
}
}
}
return nil
}
func (sql *SqlSummaryJobLib) ExecuteQuery(ctx context.Context, tableClient *SqlTableClient, queryString *string) (*SqlQueryResult, error) {
sql.Logging(ctx, fmt.Sprintf("ExecuteQuery: %s", *queryString))
injectionKey := fmt.Sprintf("ExecuteQuery.%s.%s.%s", tableClient.ServerName, tableClient.TableName, *queryString)
if sql.Params.PanicInjection != nil {
if shouldPanic, ok := sql.Params.PanicInjection[injectionKey]; ok && shouldPanic {
panic("as you wish")
}
}
if sql.Params.ErrorInjection != nil {
if errFunc, ok := sql.Params.ErrorInjection[injectionKey]; ok {
if err := errFunc(); err != nil {
return nil, err
}
}
}
// assume you have some state that you want to share between steps
// you can use a mutex to protect the data writen between different steps
// uncomment the mutex code, and run test with --race
sql.mutex.Lock()
defer sql.mutex.Unlock()
sql.data["serverName"] = tableClient.ServerName
sql.data[tableClient.TableName] = *queryString
return &SqlQueryResult{Data: map[string]interface{}{"serverName": tableClient.ServerName, "tableName": tableClient.TableName, "queryName": *queryString}}, nil
}
func (sql *SqlSummaryJobLib) SummarizeQueryResult(ctx context.Context, result1 *SqlQueryResult, result2 *SqlQueryResult) (*SummarizedResult, error) {
sql.Logging(ctx, "SummarizeQueryResult")
injectionKey := "SummarizeQueryResult"
if sql.Params.PanicInjection != nil {
if shouldPanic, ok := sql.Params.PanicInjection[injectionKey]; ok && shouldPanic {
panic("as you wish")
}
}
if sql.Params.ErrorInjection != nil {
if errFunc, ok := sql.Params.ErrorInjection[injectionKey]; ok {
if err := errFunc(); err != nil {
return nil, err
}
}
}
return &SummarizedResult{QueryResult1: result1.Data, QueryResult2: result2.Data}, nil
}
func (sql *SqlSummaryJobLib) EmailNotification(ctx context.Context) error {
sql.Logging(ctx, "EmailNotification")
return nil
}
func (sql *SqlSummaryJobLib) Logging(ctx context.Context, msg string) {
if tI := ctx.Value(testLoggingContextKey); tI != nil {
t := tI.(*testing.T)
jobName := ctx.Value("asyncjob.jobName")
jobId := ctx.Value("asyncjob.jobId")
stepName := ctx.Value("asyncjob.stepName")
t.Logf("[Job: %s-%s, Step: %s] %s", jobName, jobId, stepName, msg)
} else {
fmt.Println(msg)
}
}
func EnrichContext(ctx context.Context, instanceMeta asyncjob.StepInstanceMeta) context.Context {
ctx = context.WithValue(ctx, "asyncjob.jobName", instanceMeta.GetJobInstance().GetJobDefinition().GetName())
ctx = context.WithValue(ctx, "asyncjob.jobId", instanceMeta.GetJobInstance().GetJobInstanceId())
ctx = context.WithValue(ctx, "asyncjob.stepName", instanceMeta.GetStepDefinition().GetName())
return ctx
}
type linearRetryPolicy struct {
sleepInterval time.Duration
maxRetryCount uint
}
func newLinearRetryPolicy(sleepInterval time.Duration, maxRetryCount uint) asyncjob.RetryPolicy {
return &linearRetryPolicy{
sleepInterval: sleepInterval,
maxRetryCount: maxRetryCount,
}
}
func (lrp *linearRetryPolicy) ShouldRetry(_ error, tried uint) (bool, time.Duration) {
if tried < lrp.maxRetryCount {
return true, lrp.sleepInterval
}
return false, time.Duration(0)
}