88 lines
2.6 KiB
Go
88 lines
2.6 KiB
Go
// tasks 演示受理、重复提交、查询、分页与取消;此示例不启动业务 Worker。
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
orbit "git.yuntuo.hk/k2safe/orbit/sdk/go"
|
|
)
|
|
|
|
func main() {
|
|
if err := run(); err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
func run() error {
|
|
token, queue := os.Getenv("ORBIT_TOKEN"), os.Getenv("ORBIT_QUEUE_ID")
|
|
if path := os.Getenv("ORBIT_CREDENTIALS_FILE"); path != "" {
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return fmt.Errorf("read private credentials: %w", err)
|
|
}
|
|
var credentials struct {
|
|
Token string `json:"token"`
|
|
QueueID string `json:"queue_id"`
|
|
}
|
|
if err := json.Unmarshal(raw, &credentials); err != nil {
|
|
return fmt.Errorf("invalid credentials file")
|
|
}
|
|
if token == "" {
|
|
token = credentials.Token
|
|
}
|
|
if queue == "" {
|
|
queue = credentials.QueueID
|
|
}
|
|
}
|
|
client, err := orbit.NewClient(os.Getenv("ORBIT_URL"), orbit.Options{Token: token})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if queue == "" {
|
|
return fmt.Errorf("ORBIT_QUEUE_ID is required")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
var operation [16]byte
|
|
if _, err := rand.Read(operation[:]); err != nil {
|
|
return err
|
|
}
|
|
key := "example-" + hex.EncodeToString(operation[:])
|
|
// 生产接入应先在业务库保存稳定键;本示例的两次请求共用同一个键。
|
|
in := orbit.SubmitTaskRequest{QueueID: queue, Handler: "file.convert", HandlerVersion: "v1", PayloadVersion: "v1", Payload: json.RawMessage(`{"source_ref":"example/input.txt","format":"pdf","sequence":9007199254740993}`)}
|
|
first, err := client.SubmitTask(ctx, key, in)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
again, err := client.SubmitTask(ctx, key, in)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if first.Task.ID != again.Task.ID || !again.Deduplicated {
|
|
return fmt.Errorf("duplicate submission did not return the original task")
|
|
}
|
|
current, err := client.GetTask(ctx, first.Task.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
page, err := client.ListTasks(ctx, orbit.ListTasksRequest{QueueID: queue, Limit: 10})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cancelled, err := client.CancelTask(ctx, current.ID, key+"-cancel", orbit.CancelTaskRequest{Reason: "finish task acceptance example", ExpectedRevision: current.Revision})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("task=%s duplicate=%t listed=%d final_state=%s revision=%d\n", current.ID, again.Deduplicated, len(page.Items), cancelled.Task.State, cancelled.Task.Revision)
|
|
if cancelled.Task.State != orbit.TaskCancelled {
|
|
return fmt.Errorf("expected CANCELLED")
|
|
}
|
|
return nil
|
|
}
|