|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "time" |
| 8 | + |
| 9 | + pb "github.com/mateusmlo/taskqueue/proto" |
| 10 | + "google.golang.org/grpc" |
| 11 | + "google.golang.org/grpc/credentials" |
| 12 | +) |
| 13 | + |
| 14 | +func main() { |
| 15 | + ctx := context.Background() |
| 16 | + tc, err := credentials.NewClientTLSFromFile("cert/server.crt", "localhost") |
| 17 | + if err != nil { |
| 18 | + fmt.Printf("Failed to load TLS credentials: %s\n", err.Error()) |
| 19 | + panic(err) |
| 20 | + } |
| 21 | + |
| 22 | + clientConn, err := grpc.NewClient("localhost:50051", grpc.WithTransportCredentials(tc)) |
| 23 | + if err != nil { |
| 24 | + fmt.Printf("Failed to connect to server: %s\n", err.Error()) |
| 25 | + panic(err) |
| 26 | + } |
| 27 | + defer clientConn.Close() |
| 28 | + |
| 29 | + taskClient := pb.NewTaskQueueClient(clientConn) |
| 30 | + |
| 31 | + res, err := taskClient.SubmitTask(ctx, &pb.SubmitTaskRequest{ |
| 32 | + Type: "reverseStr", |
| 33 | + Payload: []byte("hello world"), |
| 34 | + Priority: int32(pb.Priority_HIGH), |
| 35 | + MaxRetries: 3, |
| 36 | + }) |
| 37 | + |
| 38 | + if err != nil { |
| 39 | + log.Fatalf("Task failed to submit: %s\n", err.Error()) |
| 40 | + } |
| 41 | + |
| 42 | + taskID := res.TaskId |
| 43 | + |
| 44 | + ctxDeadline, cancelFunc := context.WithTimeout(ctx, 10*time.Second) |
| 45 | + |
| 46 | + for { |
| 47 | + fmt.Print("Polling task status...\n") |
| 48 | + |
| 49 | + taskStatusRes, err := taskClient.GetTaskStatus(ctxDeadline, &pb.GetTaskStatusRequest{ |
| 50 | + TaskId: taskID, |
| 51 | + }) |
| 52 | + |
| 53 | + if err != nil { |
| 54 | + log.Fatalf("Failed to get task status: %s\n", err.Error()) |
| 55 | + } |
| 56 | + |
| 57 | + if taskStatusRes.Status == pb.TaskStatus_COMPLETED { |
| 58 | + log.Print("Task completed, fetching result...\n") |
| 59 | + cancelFunc() |
| 60 | + break |
| 61 | + } |
| 62 | + |
| 63 | + time.Sleep(1 * time.Second) |
| 64 | + } |
| 65 | + |
| 66 | + taskRes, err := taskClient.GetTaskResult(ctx, &pb.GetTaskResultRequest{TaskId: taskID}) |
| 67 | + if err != nil { |
| 68 | + log.Fatalf("Failed to get task result: %s\n", err.Error()) |
| 69 | + panic(err) |
| 70 | + } |
| 71 | + |
| 72 | + fmt.Printf("Task result: %s\n", taskRes.GetResult()) |
| 73 | +} |
0 commit comments