forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemulator_push_queue.go
More file actions
83 lines (67 loc) · 1.94 KB
/
emulator_push_queue.go
File metadata and controls
83 lines (67 loc) · 1.94 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
package services
import (
"context"
"fmt"
"net/http"
"time"
"github.com/carlmjohnson/requests"
"github.com/palantir/stacktrace"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/google/uuid"
)
type emulatorPushQueue struct {
config PushQueueConfig
client *http.Client
logger telemetry.Logger
tracer telemetry.Tracer
}
// EmulatorPushQueue creates a new googlePushQueue
func EmulatorPushQueue(
logger telemetry.Logger,
tracer telemetry.Tracer,
client *http.Client,
config PushQueueConfig,
) PushQueue {
return &emulatorPushQueue{
tracer: tracer,
logger: logger.WithService(fmt.Sprintf("%T", emulatorPushQueue{})),
client: client,
config: config,
}
}
// Enqueue a task to the queue
func (queue *emulatorPushQueue) Enqueue(ctx context.Context, task *PushQueueTask, timeout time.Duration) (queueID string, err error) {
ctx, span, ctxLogger := queue.tracer.StartWithLogger(ctx, queue.logger)
defer span.End()
queueID = uuid.New().String()
time.AfterFunc(timeout, queue.push(*task, queueID))
ctxLogger.Info(fmt.Sprintf(
"task added to [%s] queue with ID [%s] and scheduled at [%s]",
queue.config.Name,
queueID,
time.Now().UTC().Add(timeout),
))
return queueID, nil
}
func (queue *emulatorPushQueue) push(task PushQueueTask, queueID string) func() {
return func() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
request := requests.
URL(task.URL).
Client(queue.client).
Method(task.Method).
BodyBytes(task.Body)
// add headers
for key, value := range task.Headers {
request.Header(key, value)
}
// add content type
request.Header("Content-Type", "application/json")
if err := request.Fetch(ctx); err != nil {
queue.logger.Error(stacktrace.Propagate(err, fmt.Sprintf("cannot send http request to [%s] for queue task [%s]", task.URL, queueID)))
return
}
queue.logger.Info(fmt.Sprintf("queue task [%s] sent to URL [%s]", queueID, task.URL))
}
}