-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexample_tmprl.pb.go
More file actions
2817 lines (2434 loc) · 107 KB
/
Copy pathexample_tmprl.pb.go
File metadata and controls
2817 lines (2434 loc) · 107 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Code generated by protoc-gen-go-tmprl. DO NOT EDIT.
//
// version:
// protoc-gen-go-tmprl version: master
// protoc-gen-go-tmprl commit: master
//
// source file: example/v1/example.proto
package examplev1
import (
context "context"
fmt "fmt"
uuid "github.com/google/uuid"
v1 "go.temporal.io/api/common/v1"
activity "go.temporal.io/sdk/activity"
client "go.temporal.io/sdk/client"
converter "go.temporal.io/sdk/converter"
temporal "go.temporal.io/sdk/temporal"
worker "go.temporal.io/sdk/worker"
workflow "go.temporal.io/sdk/workflow"
emptypb "google.golang.org/protobuf/types/known/emptypb"
time "time"
)
// Constants for Orders service
const (
// DefaultOrdersTaskQueueName Default task queue name for Orders
DefaultOrdersTaskQueueName = "orders"
// DefaultOrdersActivityScheduleToCloseTimeout Default activity schedule to close timeout
DefaultOrdersActivityScheduleToCloseTimeout = 86400
// WorkflowProcessOrderName is the registered name for workflow ProcessOrder.
WorkflowProcessOrderName = "example.v1.Orders.ProcessOrder"
// WorkflowShipOrderName is the registered name for workflow ShipOrder.
WorkflowShipOrderName = "example.v1.Orders.ShipOrder"
// WorkflowDailySalesReportName is the registered name for workflow DailySalesReport.
WorkflowDailySalesReportName = "example.v1.Orders.DailySalesReport"
// WorkflowTrackInventoryName is the registered name for workflow TrackInventory.
WorkflowTrackInventoryName = "example.v1.Orders.TrackInventory"
// ActivityChargePaymentName is the registered name for activity ChargePayment.
ActivityChargePaymentName = "example.v1.Orders.ChargePayment"
// ActivityPackItemsName is the registered name for activity PackItems.
ActivityPackItemsName = "example.v1.Orders.PackItems"
// ActivityDispatchCourierName is the registered name for activity DispatchCourier.
ActivityDispatchCourierName = "courier.Dispatch"
// SignalCancelOrderName is the registered name for signal CancelOrder.
SignalCancelOrderName = "example.v1.Orders.CancelOrder"
// SignalRestockName is the registered name for signal Restock.
SignalRestockName = "example.v1.Orders.Restock"
// QueryGetOrderStatusName is the registered name for query GetOrderStatus.
QueryGetOrderStatusName = "example.v1.Orders.GetOrderStatus"
// QueryGetStockName is the registered name for query GetStock.
QueryGetStockName = "example.v1.Orders.GetStock"
// UpdateChangeShippingAddressName is the registered name for update ChangeShippingAddress.
UpdateChangeShippingAddressName = "example.v1.Orders.ChangeShippingAddress"
// UpdateReserveName is the registered name for update Reserve.
UpdateReserveName = "example.v1.Orders.Reserve"
)
// OrdersService Interface that must be implemented to register workflows and activities
//
// Service Orders is a small e-commerce style fulfillment service used as a
// guided tour of everything this plugin generates:
//
// - workflows: ProcessOrder (long lived), ShipOrder (child), DailySalesReport (scheduled)
// - activities: ChargePayment (retries + non-retryable errors), PackItems (heartbeats), DispatchCourier (custom name)
// - signals: CancelOrder
// - queries: GetOrderStatus
// - updates: ChangeShippingAddress (validated, synchronous request/response)
//
// See `example/worker` for the implementation and `example/client` for a
// runnable walkthrough of all of the above.
type OrdersService interface {
// ProcessOrder ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
ProcessOrder(ctx workflow.Context, req *ProcessOrderRequest) (*ProcessOrderResponse, error)
// ShipOrder ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
ShipOrder(ctx workflow.Context, req *ShipOrderRequest) (*ShipOrderResponse, error)
// DailySalesReport DailySalesReport is a fast workflow meant to be driven by a Temporal
// schedule -- see the schedule part of the client walkthrough
DailySalesReport(ctx workflow.Context, req *emptypb.Empty) (*DailySalesReportResponse, error)
// TrackInventory TrackInventory is a long-lived "entity" workflow tracking the stock of
// one SKU. It rolls over with continue-as-new after a number of restocks,
// which makes it the demo for how BLOCKED updates interact with
// continue-as-new: the workflow drains its update handlers (see
// workflow.AllHandlersFinished) before rolling over, so a Reserve update
// parked on "not enough stock" is answered before the run ends
TrackInventory(ctx workflow.Context, req *TrackInventoryRequest) (*GetStockResponse, error)
// ChargePayment ChargePayment captures the money. The retry policy retries transient
// payment provider hiccups with exponential backoff, but gives up
// immediately when the card is declined: "CardDeclined" is listed in
// non_retryable_error_types and the worker returns application errors of
// that type when the card is bad
ChargePayment(ctx context.Context, req *ChargePaymentRequest) (*ChargePaymentResponse, error)
// PackItems PackItems packs the order, one parcel per item. It is slow, so it
// records a heartbeat after every parcel: if the worker dies mid-pack,
// Temporal notices within heartbeat_timeout and reschedules the activity
PackItems(ctx context.Context, req *PackItemsRequest) (*PackItemsResponse, error)
// DispatchCourier DispatchCourier books a courier and returns a tracking number. The
// `name` option overrides the registered activity name, which otherwise
// defaults to <package>.<service>.<method>
DispatchCourier(ctx context.Context, req *DispatchCourierRequest) (*DispatchCourierResponse, error)
}
// UnimplementedOrdersService Stub implementation that panics
type UnimplementedOrdersService struct{}
func (UnimplementedOrdersService) ProcessOrder(ctx workflow.Context, req *ProcessOrderRequest) (*ProcessOrderResponse, error) {
panic("ProcessOrder not implemented")
}
func (UnimplementedOrdersService) ShipOrder(ctx workflow.Context, req *ShipOrderRequest) (*ShipOrderResponse, error) {
panic("ShipOrder not implemented")
}
func (UnimplementedOrdersService) DailySalesReport(ctx workflow.Context, req *emptypb.Empty) (*DailySalesReportResponse, error) {
panic("DailySalesReport not implemented")
}
func (UnimplementedOrdersService) TrackInventory(ctx workflow.Context, req *TrackInventoryRequest) (*GetStockResponse, error) {
panic("TrackInventory not implemented")
}
func (UnimplementedOrdersService) ChargePayment(ctx context.Context, req *ChargePaymentRequest) (*ChargePaymentResponse, error) {
panic("ChargePayment not implemented")
}
func (UnimplementedOrdersService) PackItems(ctx context.Context, req *PackItemsRequest) (*PackItemsResponse, error) {
panic("PackItems not implemented")
}
func (UnimplementedOrdersService) DispatchCourier(ctx context.Context, req *DispatchCourierRequest) (*DispatchCourierResponse, error) {
panic("DispatchCourier not implemented")
}
// OrdersClient Client for the Orders service
type OrdersClient struct {
client client.Client
taskQueue string
}
// NewOrdersClient Returns a new instance of the client.
// If `taskQueue` stays empty the default one will be used
func NewOrdersClient(client client.Client, taskQueue ...string) (*OrdersClient, error) {
clientTaskQueue := DefaultOrdersTaskQueueName
if len(taskQueue) > 0 {
clientTaskQueue = taskQueue[0]
}
return &OrdersClient{
client: client,
taskQueue: clientTaskQueue,
}, nil
}
// ExecuteWorkflowProcessOrder executes the workflow and returns a future to it
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) ExecuteWorkflowProcessOrder(ctx context.Context, req *ProcessOrderRequest, options ...client.StartWorkflowOptions) (client.WorkflowRun, error) {
wOptions := client.StartWorkflowOptions{}
if len(options) > 0 {
wOptions = options[0]
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = c.taskQueue
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = DefaultOrdersTaskQueueName
}
if wOptions.ID == "" {
wOptions.ID = fmt.Sprintf("%s/%s", WorkflowProcessOrderName, uuid.NewString())
}
// Apply timeout options
if wOptions.WorkflowExecutionTimeout == 0 {
wOptions.WorkflowExecutionTimeout = time.Duration(3600) * time.Second
}
return c.client.ExecuteWorkflow(ctx, wOptions, WorkflowProcessOrderName, req)
}
// ExecuteWorkflowProcessOrderSync executes the workflow and returns the result when finished
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) ExecuteWorkflowProcessOrderSync(ctx context.Context, req *ProcessOrderRequest, options ...client.StartWorkflowOptions) (*ProcessOrderResponse, error) {
future, err := c.ExecuteWorkflowProcessOrder(ctx, req, options...)
if err != nil {
return nil, err
}
var resp *ProcessOrderResponse
err = future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// GetWorkflowProcessOrderResult gets the result of a given workflow
func (c *OrdersClient) GetWorkflowProcessOrderResult(ctx context.Context, workflowId string, runId string) (*ProcessOrderResponse, error) {
future := c.client.GetWorkflow(ctx, workflowId, runId)
var resp *ProcessOrderResponse
err := future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// ExecuteChildProcessOrder executes the workflow as a child workflow and returns a future to it
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) ExecuteChildProcessOrder(ctx workflow.Context, req *ProcessOrderRequest, options ...workflow.ChildWorkflowOptions) (workflow.ChildWorkflowFuture, error) {
wOptions := workflow.ChildWorkflowOptions{}
if len(options) > 0 {
wOptions = options[0]
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = c.taskQueue
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = DefaultOrdersTaskQueueName
}
if wOptions.WorkflowID == "" {
var id string
genId := workflow.SideEffect(ctx, func(ctx workflow.Context) interface{} {
return fmt.Sprintf("%s/%s", WorkflowProcessOrderName, uuid.NewString())
})
err := genId.Get(&id)
if err != nil {
return nil, err
}
wOptions.WorkflowID = id
}
// Apply timeout options
if wOptions.WorkflowExecutionTimeout == 0 {
wOptions.WorkflowExecutionTimeout = time.Duration(3600) * time.Second
}
return workflow.ExecuteChildWorkflow(workflow.WithChildOptions(ctx, wOptions), WorkflowProcessOrderName, req), nil
}
// ExecuteChildProcessOrderSync executes the workflow as a child workflow and returns the result when finished
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) ExecuteChildProcessOrderSync(ctx workflow.Context, req *ProcessOrderRequest, options ...workflow.ChildWorkflowOptions) (*ProcessOrderResponse, error) {
future, err := c.ExecuteChildProcessOrder(ctx, req, options...)
if err != nil {
return nil, err
}
var resp *ProcessOrderResponse
err = future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// CreateScheduleProcessOrder creates a schedule for ProcessOrder
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) CreateScheduleProcessOrder(ctx context.Context, scheduleID string, req *ProcessOrderRequest, options ...client.ScheduleOptions) (client.ScheduleHandle, error) {
scheduleOptions := client.ScheduleOptions{
ID: scheduleID,
Action: &client.ScheduleWorkflowAction{
ID: scheduleID,
Workflow: WorkflowProcessOrderName,
Args: []interface{}{req},
TaskQueue: c.taskQueue,
WorkflowExecutionTimeout: time.Duration(3600) * time.Second,
},
}
if len(options) > 0 {
mergeScheduleOptionsOrders(&scheduleOptions, options[0], true)
}
applyScheduleDefaultsOrders(&scheduleOptions, DefaultOrdersTaskQueueName)
return c.client.ScheduleClient().Create(ctx, scheduleOptions)
}
// GetScheduleProcessOrder gets a handle to an existing schedule for ProcessOrder
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) GetScheduleProcessOrder(ctx context.Context, scheduleID string) client.ScheduleHandle {
return c.client.ScheduleClient().GetHandle(ctx, scheduleID)
}
// DescribeScheduleProcessOrder reads a schedule for ProcessOrder and returns the
// DECODED workflow request alongside the full schedule description (spec, policy,
// action timeouts, paused state, ...).
//
// The Temporal SDK returns a schedule action's input arguments as raw, undecoded
// payloads, so this decodes the first argument back into the workflow's request
// type. Pass the same data converter the client was built with when the input is
// encrypted/custom-encoded (e.g. a codec/keyring converter); omit it to use the
// default converter. This is the typed read-back counterpart to
// UpsertScheduleProcessOrder — useful for exporting/backing up schedules.
func (c *OrdersClient) DescribeScheduleProcessOrder(ctx context.Context, scheduleID string, dataConverter ...converter.DataConverter) (*ProcessOrderRequest, *client.ScheduleDescription, error) {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
desc, err := handle.Describe(ctx)
if err != nil {
return nil, nil, err
}
action, ok := desc.Schedule.Action.(*client.ScheduleWorkflowAction)
if !ok {
return nil, desc, fmt.Errorf("schedule %q action is not a workflow action", scheduleID)
}
if len(action.Args) == 0 {
return nil, desc, fmt.Errorf("schedule %q has no input arguments", scheduleID)
}
payload, ok := action.Args[0].(*v1.Payload)
if !ok {
return nil, desc, fmt.Errorf("schedule %q input argument is not a raw payload (already decoded?)", scheduleID)
}
dc := converter.GetDefaultDataConverter()
if len(dataConverter) > 0 && dataConverter[0] != nil {
dc = dataConverter[0]
}
req := new(ProcessOrderRequest)
if err := dc.FromPayload(payload, req); err != nil {
return nil, desc, fmt.Errorf("decoding schedule %q input: %w", scheduleID, err)
}
return req, desc, nil
}
// DeleteScheduleProcessOrder deletes a schedule for ProcessOrder
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) DeleteScheduleProcessOrder(ctx context.Context, scheduleID string) error {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
return handle.Delete(ctx)
}
// PauseScheduleProcessOrder pauses a running schedule for ProcessOrder. The note is
// recorded by Temporal on the schedule's audit trail (visible via Describe). If
// the schedule is already paused this is a no-op: we Describe first and skip the
// Pause API call when .Schedule.State.Paused is already true, so it's safe to
// call on every reconcile/bootstrap path without spamming the server.
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) PauseScheduleProcessOrder(ctx context.Context, scheduleID string, note string) error {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
desc, err := handle.Describe(ctx)
if err != nil {
return err
}
if desc.Schedule.State != nil && desc.Schedule.State.Paused {
return nil
}
return handle.Pause(ctx, client.SchedulePauseOptions{Note: note})
}
// UnpauseScheduleProcessOrder resumes a paused schedule for ProcessOrder. Like
// PauseScheduleProcessOrder, this is a read-then-write: we Describe first and
// return nil if the schedule is already running, so idempotent bootstrap code
// doesn't pay an extra Unpause round-trip per reconcile tick.
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) UnpauseScheduleProcessOrder(ctx context.Context, scheduleID string, note string) error {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
desc, err := handle.Describe(ctx)
if err != nil {
return err
}
if desc.Schedule.State == nil || !desc.Schedule.State.Paused {
return nil
}
return handle.Unpause(ctx, client.ScheduleUnpauseOptions{Note: note})
}
// ListScheduleProcessOrder lists all schedules for ProcessOrder workflow
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) ListScheduleProcessOrder(ctx context.Context, pageSize int) ([]client.ScheduleListEntry, error) {
var schedules []client.ScheduleListEntry
iter, err := c.client.ScheduleClient().List(ctx, client.ScheduleListOptions{
PageSize: pageSize,
})
if err != nil {
return nil, err
}
for iter.HasNext() {
entry, err := iter.Next()
if err != nil {
return nil, err
}
// Filter by workflow type
if entry.WorkflowType.Name == WorkflowProcessOrderName {
schedules = append(schedules, *entry)
}
}
return schedules, nil
}
// UpsertScheduleProcessOrder creates or updates a schedule for ProcessOrder
//
// ProcessOrder drives an order from payment to shipping. While it runs it
// can be queried (GetOrderStatus), updated (ChangeShippingAddress) and
// cancelled (CancelOrder signal)
func (c *OrdersClient) UpsertScheduleProcessOrder(ctx context.Context, scheduleID string, req *ProcessOrderRequest, options ...client.ScheduleOptions) (client.ScheduleHandle, error) {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
// Try to describe the schedule to see if it exists
_, err := handle.Describe(ctx)
if err != nil {
// Schedule doesn't exist, create it
return c.CreateScheduleProcessOrder(ctx, scheduleID, req, options...)
}
// Schedule exists, update it
scheduleOptions := client.ScheduleOptions{
ID: scheduleID,
Action: &client.ScheduleWorkflowAction{
ID: scheduleID,
Workflow: WorkflowProcessOrderName,
Args: []interface{}{req},
TaskQueue: c.taskQueue,
WorkflowExecutionTimeout: time.Duration(3600) * time.Second,
},
}
if len(options) > 0 {
// Upsert never flips Paused on a running schedule; everything else merges
// identically to CreateSchedule.
mergeScheduleOptionsOrders(&scheduleOptions, options[0], false)
}
applyScheduleDefaultsOrders(&scheduleOptions, DefaultOrdersTaskQueueName)
// Update the schedule. The closure starts from the schedule as it exists on
// the server (input.Description.Schedule) and overlays ONLY what the caller
// supplied, so an upsert that just changes the request does not silently
// blank the spec, drop search attributes, or reset sibling policy fields.
err = handle.Update(ctx, client.ScheduleUpdateOptions{
DoUpdate: func(input client.ScheduleUpdateInput) (*client.ScheduleUpdate, error) {
schedule := input.Description.Schedule
// Rebind the action so the updated request/args take effect.
schedule.Action = scheduleOptions.Action
// Only replace the spec when the caller supplied scheduling info;
// otherwise keep the existing spec so the schedule keeps firing.
if !scheduleSpecIsZeroOrders(scheduleOptions.Spec) {
schedule.Spec = &scheduleOptions.Spec
}
// Merge policy fields onto the existing policy instead of replacing
// it, so changing one field does not reset the others.
if scheduleOptions.Overlap != 0 || scheduleOptions.CatchupWindow != 0 || scheduleOptions.PauseOnFailure {
if schedule.Policy == nil {
schedule.Policy = &client.SchedulePolicies{}
}
if scheduleOptions.Overlap != 0 {
schedule.Policy.Overlap = scheduleOptions.Overlap
}
if scheduleOptions.CatchupWindow != 0 {
schedule.Policy.CatchupWindow = scheduleOptions.CatchupWindow
}
if scheduleOptions.PauseOnFailure {
schedule.Policy.PauseOnFailure = scheduleOptions.PauseOnFailure
}
}
update := &client.ScheduleUpdate{Schedule: &schedule}
// A nil pointer leaves the schedule's search attributes intact; only
// send a non-empty set (an empty non-nil set removes all of them).
if scheduleOptions.TypedSearchAttributes.Size() > 0 {
update.TypedSearchAttributes = &scheduleOptions.TypedSearchAttributes
}
return update, nil
},
})
if err != nil {
return nil, err
}
return handle, nil
}
// ExecuteWorkflowShipOrder executes the workflow and returns a future to it
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) ExecuteWorkflowShipOrder(ctx context.Context, req *ShipOrderRequest, options ...client.StartWorkflowOptions) (client.WorkflowRun, error) {
wOptions := client.StartWorkflowOptions{}
if len(options) > 0 {
wOptions = options[0]
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = c.taskQueue
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = DefaultOrdersTaskQueueName
}
if wOptions.ID == "" {
wOptions.ID = fmt.Sprintf("%s/%s", WorkflowShipOrderName, uuid.NewString())
}
// Apply timeout options
if wOptions.WorkflowExecutionTimeout == 0 {
wOptions.WorkflowExecutionTimeout = time.Duration(3600) * time.Second
}
return c.client.ExecuteWorkflow(ctx, wOptions, WorkflowShipOrderName, req)
}
// ExecuteWorkflowShipOrderSync executes the workflow and returns the result when finished
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) ExecuteWorkflowShipOrderSync(ctx context.Context, req *ShipOrderRequest, options ...client.StartWorkflowOptions) (*ShipOrderResponse, error) {
future, err := c.ExecuteWorkflowShipOrder(ctx, req, options...)
if err != nil {
return nil, err
}
var resp *ShipOrderResponse
err = future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// GetWorkflowShipOrderResult gets the result of a given workflow
func (c *OrdersClient) GetWorkflowShipOrderResult(ctx context.Context, workflowId string, runId string) (*ShipOrderResponse, error) {
future := c.client.GetWorkflow(ctx, workflowId, runId)
var resp *ShipOrderResponse
err := future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// ExecuteChildShipOrder executes the workflow as a child workflow and returns a future to it
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) ExecuteChildShipOrder(ctx workflow.Context, req *ShipOrderRequest, options ...workflow.ChildWorkflowOptions) (workflow.ChildWorkflowFuture, error) {
wOptions := workflow.ChildWorkflowOptions{}
if len(options) > 0 {
wOptions = options[0]
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = c.taskQueue
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = DefaultOrdersTaskQueueName
}
if wOptions.WorkflowID == "" {
var id string
genId := workflow.SideEffect(ctx, func(ctx workflow.Context) interface{} {
return fmt.Sprintf("%s/%s", WorkflowShipOrderName, uuid.NewString())
})
err := genId.Get(&id)
if err != nil {
return nil, err
}
wOptions.WorkflowID = id
}
// Apply timeout options
if wOptions.WorkflowExecutionTimeout == 0 {
wOptions.WorkflowExecutionTimeout = time.Duration(3600) * time.Second
}
return workflow.ExecuteChildWorkflow(workflow.WithChildOptions(ctx, wOptions), WorkflowShipOrderName, req), nil
}
// ExecuteChildShipOrderSync executes the workflow as a child workflow and returns the result when finished
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) ExecuteChildShipOrderSync(ctx workflow.Context, req *ShipOrderRequest, options ...workflow.ChildWorkflowOptions) (*ShipOrderResponse, error) {
future, err := c.ExecuteChildShipOrder(ctx, req, options...)
if err != nil {
return nil, err
}
var resp *ShipOrderResponse
err = future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// CreateScheduleShipOrder creates a schedule for ShipOrder
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) CreateScheduleShipOrder(ctx context.Context, scheduleID string, req *ShipOrderRequest, options ...client.ScheduleOptions) (client.ScheduleHandle, error) {
scheduleOptions := client.ScheduleOptions{
ID: scheduleID,
Action: &client.ScheduleWorkflowAction{
ID: scheduleID,
Workflow: WorkflowShipOrderName,
Args: []interface{}{req},
TaskQueue: c.taskQueue,
WorkflowExecutionTimeout: time.Duration(3600) * time.Second,
},
}
if len(options) > 0 {
mergeScheduleOptionsOrders(&scheduleOptions, options[0], true)
}
applyScheduleDefaultsOrders(&scheduleOptions, DefaultOrdersTaskQueueName)
return c.client.ScheduleClient().Create(ctx, scheduleOptions)
}
// GetScheduleShipOrder gets a handle to an existing schedule for ShipOrder
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) GetScheduleShipOrder(ctx context.Context, scheduleID string) client.ScheduleHandle {
return c.client.ScheduleClient().GetHandle(ctx, scheduleID)
}
// DescribeScheduleShipOrder reads a schedule for ShipOrder and returns the
// DECODED workflow request alongside the full schedule description (spec, policy,
// action timeouts, paused state, ...).
//
// The Temporal SDK returns a schedule action's input arguments as raw, undecoded
// payloads, so this decodes the first argument back into the workflow's request
// type. Pass the same data converter the client was built with when the input is
// encrypted/custom-encoded (e.g. a codec/keyring converter); omit it to use the
// default converter. This is the typed read-back counterpart to
// UpsertScheduleShipOrder — useful for exporting/backing up schedules.
func (c *OrdersClient) DescribeScheduleShipOrder(ctx context.Context, scheduleID string, dataConverter ...converter.DataConverter) (*ShipOrderRequest, *client.ScheduleDescription, error) {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
desc, err := handle.Describe(ctx)
if err != nil {
return nil, nil, err
}
action, ok := desc.Schedule.Action.(*client.ScheduleWorkflowAction)
if !ok {
return nil, desc, fmt.Errorf("schedule %q action is not a workflow action", scheduleID)
}
if len(action.Args) == 0 {
return nil, desc, fmt.Errorf("schedule %q has no input arguments", scheduleID)
}
payload, ok := action.Args[0].(*v1.Payload)
if !ok {
return nil, desc, fmt.Errorf("schedule %q input argument is not a raw payload (already decoded?)", scheduleID)
}
dc := converter.GetDefaultDataConverter()
if len(dataConverter) > 0 && dataConverter[0] != nil {
dc = dataConverter[0]
}
req := new(ShipOrderRequest)
if err := dc.FromPayload(payload, req); err != nil {
return nil, desc, fmt.Errorf("decoding schedule %q input: %w", scheduleID, err)
}
return req, desc, nil
}
// DeleteScheduleShipOrder deletes a schedule for ShipOrder
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) DeleteScheduleShipOrder(ctx context.Context, scheduleID string) error {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
return handle.Delete(ctx)
}
// PauseScheduleShipOrder pauses a running schedule for ShipOrder. The note is
// recorded by Temporal on the schedule's audit trail (visible via Describe). If
// the schedule is already paused this is a no-op: we Describe first and skip the
// Pause API call when .Schedule.State.Paused is already true, so it's safe to
// call on every reconcile/bootstrap path without spamming the server.
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) PauseScheduleShipOrder(ctx context.Context, scheduleID string, note string) error {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
desc, err := handle.Describe(ctx)
if err != nil {
return err
}
if desc.Schedule.State != nil && desc.Schedule.State.Paused {
return nil
}
return handle.Pause(ctx, client.SchedulePauseOptions{Note: note})
}
// UnpauseScheduleShipOrder resumes a paused schedule for ShipOrder. Like
// PauseScheduleShipOrder, this is a read-then-write: we Describe first and
// return nil if the schedule is already running, so idempotent bootstrap code
// doesn't pay an extra Unpause round-trip per reconcile tick.
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) UnpauseScheduleShipOrder(ctx context.Context, scheduleID string, note string) error {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
desc, err := handle.Describe(ctx)
if err != nil {
return err
}
if desc.Schedule.State == nil || !desc.Schedule.State.Paused {
return nil
}
return handle.Unpause(ctx, client.ScheduleUnpauseOptions{Note: note})
}
// ListScheduleShipOrder lists all schedules for ShipOrder workflow
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) ListScheduleShipOrder(ctx context.Context, pageSize int) ([]client.ScheduleListEntry, error) {
var schedules []client.ScheduleListEntry
iter, err := c.client.ScheduleClient().List(ctx, client.ScheduleListOptions{
PageSize: pageSize,
})
if err != nil {
return nil, err
}
for iter.HasNext() {
entry, err := iter.Next()
if err != nil {
return nil, err
}
// Filter by workflow type
if entry.WorkflowType.Name == WorkflowShipOrderName {
schedules = append(schedules, *entry)
}
}
return schedules, nil
}
// UpsertScheduleShipOrder creates or updates a schedule for ShipOrder
//
// ShipOrder hands the package over to a courier. ProcessOrder runs it as a
// child workflow so shipping shows up as its own execution in the UI
func (c *OrdersClient) UpsertScheduleShipOrder(ctx context.Context, scheduleID string, req *ShipOrderRequest, options ...client.ScheduleOptions) (client.ScheduleHandle, error) {
handle := c.client.ScheduleClient().GetHandle(ctx, scheduleID)
// Try to describe the schedule to see if it exists
_, err := handle.Describe(ctx)
if err != nil {
// Schedule doesn't exist, create it
return c.CreateScheduleShipOrder(ctx, scheduleID, req, options...)
}
// Schedule exists, update it
scheduleOptions := client.ScheduleOptions{
ID: scheduleID,
Action: &client.ScheduleWorkflowAction{
ID: scheduleID,
Workflow: WorkflowShipOrderName,
Args: []interface{}{req},
TaskQueue: c.taskQueue,
WorkflowExecutionTimeout: time.Duration(3600) * time.Second,
},
}
if len(options) > 0 {
// Upsert never flips Paused on a running schedule; everything else merges
// identically to CreateSchedule.
mergeScheduleOptionsOrders(&scheduleOptions, options[0], false)
}
applyScheduleDefaultsOrders(&scheduleOptions, DefaultOrdersTaskQueueName)
// Update the schedule. The closure starts from the schedule as it exists on
// the server (input.Description.Schedule) and overlays ONLY what the caller
// supplied, so an upsert that just changes the request does not silently
// blank the spec, drop search attributes, or reset sibling policy fields.
err = handle.Update(ctx, client.ScheduleUpdateOptions{
DoUpdate: func(input client.ScheduleUpdateInput) (*client.ScheduleUpdate, error) {
schedule := input.Description.Schedule
// Rebind the action so the updated request/args take effect.
schedule.Action = scheduleOptions.Action
// Only replace the spec when the caller supplied scheduling info;
// otherwise keep the existing spec so the schedule keeps firing.
if !scheduleSpecIsZeroOrders(scheduleOptions.Spec) {
schedule.Spec = &scheduleOptions.Spec
}
// Merge policy fields onto the existing policy instead of replacing
// it, so changing one field does not reset the others.
if scheduleOptions.Overlap != 0 || scheduleOptions.CatchupWindow != 0 || scheduleOptions.PauseOnFailure {
if schedule.Policy == nil {
schedule.Policy = &client.SchedulePolicies{}
}
if scheduleOptions.Overlap != 0 {
schedule.Policy.Overlap = scheduleOptions.Overlap
}
if scheduleOptions.CatchupWindow != 0 {
schedule.Policy.CatchupWindow = scheduleOptions.CatchupWindow
}
if scheduleOptions.PauseOnFailure {
schedule.Policy.PauseOnFailure = scheduleOptions.PauseOnFailure
}
}
update := &client.ScheduleUpdate{Schedule: &schedule}
// A nil pointer leaves the schedule's search attributes intact; only
// send a non-empty set (an empty non-nil set removes all of them).
if scheduleOptions.TypedSearchAttributes.Size() > 0 {
update.TypedSearchAttributes = &scheduleOptions.TypedSearchAttributes
}
return update, nil
},
})
if err != nil {
return nil, err
}
return handle, nil
}
// ExecuteWorkflowDailySalesReport executes the workflow and returns a future to it
//
// DailySalesReport is a fast workflow meant to be driven by a Temporal
// schedule -- see the schedule part of the client walkthrough
func (c *OrdersClient) ExecuteWorkflowDailySalesReport(ctx context.Context, req *emptypb.Empty, options ...client.StartWorkflowOptions) (client.WorkflowRun, error) {
wOptions := client.StartWorkflowOptions{}
if len(options) > 0 {
wOptions = options[0]
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = c.taskQueue
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = DefaultOrdersTaskQueueName
}
if wOptions.ID == "" {
wOptions.ID = fmt.Sprintf("%s/%s", WorkflowDailySalesReportName, uuid.NewString())
}
// Apply timeout options
if wOptions.WorkflowExecutionTimeout == 0 {
wOptions.WorkflowExecutionTimeout = time.Duration(3600) * time.Second
}
return c.client.ExecuteWorkflow(ctx, wOptions, WorkflowDailySalesReportName, req)
}
// ExecuteWorkflowDailySalesReportSync executes the workflow and returns the result when finished
//
// DailySalesReport is a fast workflow meant to be driven by a Temporal
// schedule -- see the schedule part of the client walkthrough
func (c *OrdersClient) ExecuteWorkflowDailySalesReportSync(ctx context.Context, req *emptypb.Empty, options ...client.StartWorkflowOptions) (*DailySalesReportResponse, error) {
future, err := c.ExecuteWorkflowDailySalesReport(ctx, req, options...)
if err != nil {
return nil, err
}
var resp *DailySalesReportResponse
err = future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// GetWorkflowDailySalesReportResult gets the result of a given workflow
func (c *OrdersClient) GetWorkflowDailySalesReportResult(ctx context.Context, workflowId string, runId string) (*DailySalesReportResponse, error) {
future := c.client.GetWorkflow(ctx, workflowId, runId)
var resp *DailySalesReportResponse
err := future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// ExecuteChildDailySalesReport executes the workflow as a child workflow and returns a future to it
//
// DailySalesReport is a fast workflow meant to be driven by a Temporal
// schedule -- see the schedule part of the client walkthrough
func (c *OrdersClient) ExecuteChildDailySalesReport(ctx workflow.Context, req *emptypb.Empty, options ...workflow.ChildWorkflowOptions) (workflow.ChildWorkflowFuture, error) {
wOptions := workflow.ChildWorkflowOptions{}
if len(options) > 0 {
wOptions = options[0]
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = c.taskQueue
}
if wOptions.TaskQueue == "" {
wOptions.TaskQueue = DefaultOrdersTaskQueueName
}
if wOptions.WorkflowID == "" {
var id string
genId := workflow.SideEffect(ctx, func(ctx workflow.Context) interface{} {
return fmt.Sprintf("%s/%s", WorkflowDailySalesReportName, uuid.NewString())
})
err := genId.Get(&id)
if err != nil {
return nil, err
}
wOptions.WorkflowID = id
}
// Apply timeout options
if wOptions.WorkflowExecutionTimeout == 0 {
wOptions.WorkflowExecutionTimeout = time.Duration(3600) * time.Second
}
return workflow.ExecuteChildWorkflow(workflow.WithChildOptions(ctx, wOptions), WorkflowDailySalesReportName, req), nil
}
// ExecuteChildDailySalesReportSync executes the workflow as a child workflow and returns the result when finished
//
// DailySalesReport is a fast workflow meant to be driven by a Temporal
// schedule -- see the schedule part of the client walkthrough
func (c *OrdersClient) ExecuteChildDailySalesReportSync(ctx workflow.Context, req *emptypb.Empty, options ...workflow.ChildWorkflowOptions) (*DailySalesReportResponse, error) {
future, err := c.ExecuteChildDailySalesReport(ctx, req, options...)
if err != nil {
return nil, err
}
var resp *DailySalesReportResponse
err = future.Get(ctx, &resp)
if err != nil {
return nil, err
}
return resp, nil
}
// CreateScheduleDailySalesReport creates a schedule for DailySalesReport
//
// DailySalesReport is a fast workflow meant to be driven by a Temporal
// schedule -- see the schedule part of the client walkthrough
func (c *OrdersClient) CreateScheduleDailySalesReport(ctx context.Context, scheduleID string, req *emptypb.Empty, options ...client.ScheduleOptions) (client.ScheduleHandle, error) {
scheduleOptions := client.ScheduleOptions{
ID: scheduleID,