summaryrefslogtreecommitdiffstats
path: root/modules/queue/queue_wrapped.go
blob: c52e6e467360e041c414fad41de47077392ab071 (plain)
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
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package queue

import (
	"context"
	"fmt"
	"reflect"
	"sync"
	"time"

	"code.gitea.io/gitea/modules/log"
)

// WrappedQueueType is the type for a wrapped delayed starting queue
const WrappedQueueType Type = "wrapped"

// WrappedQueueConfiguration is the configuration for a WrappedQueue
type WrappedQueueConfiguration struct {
	Underlying  Type
	Timeout     time.Duration
	MaxAttempts int
	Config      interface{}
	QueueLength int
	Name        string
}

type delayedStarter struct {
	internal    Queue
	underlying  Type
	cfg         interface{}
	timeout     time.Duration
	maxAttempts int
	name        string
}

// setInternal must be called with the lock locked.
func (q *delayedStarter) setInternal(atShutdown func(context.Context, func()), handle HandlerFunc, exemplar interface{}) error {
	var ctx context.Context
	var cancel context.CancelFunc
	if q.timeout > 0 {
		ctx, cancel = context.WithTimeout(context.Background(), q.timeout)
	} else {
		ctx, cancel = context.WithCancel(context.Background())
	}

	defer cancel()
	// Ensure we also stop at shutdown
	atShutdown(ctx, func() {
		cancel()
	})

	i := 1
	for q.internal == nil {
		select {
		case <-ctx.Done():
			return fmt.Errorf("Timedout creating queue %v with cfg %v in %s", q.underlying, q.cfg, q.name)
		default:
			queue, err := NewQueue(q.underlying, handle, q.cfg, exemplar)
			if err == nil {
				q.internal = queue
				break
			}
			if err.Error() != "resource temporarily unavailable" {
				log.Warn("[Attempt: %d] Failed to create queue: %v for %s cfg: %v error: %v", i, q.underlying, q.name, q.cfg, err)
			}
			i++
			if q.maxAttempts > 0 && i > q.maxAttempts {
				return fmt.Errorf("Unable to create queue %v for %s with cfg %v by max attempts: error: %v", q.underlying, q.name, q.cfg, err)
			}
			sleepTime := 100 * time.Millisecond
			if q.timeout > 0 && q.maxAttempts > 0 {
				sleepTime = (q.timeout - 200*time.Millisecond) / time.Duration(q.maxAttempts)
			}
			t := time.NewTimer(sleepTime)
			select {
			case <-ctx.Done():
				t.Stop()
			case <-t.C:
			}
		}
	}
	return nil
}

// WrappedQueue wraps a delayed starting queue
type WrappedQueue struct {
	delayedStarter
	lock     sync.Mutex
	handle   HandlerFunc
	exemplar interface{}
	channel  chan Data
}

// NewWrappedQueue will attempt to create a queue of the provided type,
// but if there is a problem creating this queue it will instead create
// a WrappedQueue with delayed startup of the queue instead and a
// channel which will be redirected to the queue
func NewWrappedQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
	configInterface, err := toConfig(WrappedQueueConfiguration{}, cfg)
	if err != nil {
		return nil, err
	}
	config := configInterface.(WrappedQueueConfiguration)

	queue, err := NewQueue(config.Underlying, handle, config.Config, exemplar)
	if err == nil {
		// Just return the queue there is no need to wrap
		return queue, nil
	}
	if IsErrInvalidConfiguration(err) {
		// Retrying ain't gonna make this any better...
		return nil, ErrInvalidConfiguration{cfg: cfg}
	}

	queue = &WrappedQueue{
		handle:   handle,
		channel:  make(chan Data, config.QueueLength),
		exemplar: exemplar,
		delayedStarter: delayedStarter{
			cfg:         config.Config,
			underlying:  config.Underlying,
			timeout:     config.Timeout,
			maxAttempts: config.MaxAttempts,
			name:        config.Name,
		},
	}
	_ = GetManager().Add(queue, WrappedQueueType, config, exemplar, nil)
	return queue, nil
}

// Name returns the name of the queue
func (q *WrappedQueue) Name() string {
	return q.name + "-wrapper"
}

// Push will push the data to the internal channel checking it against the exemplar
func (q *WrappedQueue) Push(data Data) error {
	if q.exemplar != nil {
		// Assert data is of same type as r.exemplar
		value := reflect.ValueOf(data)
		t := value.Type()
		exemplarType := reflect.ValueOf(q.exemplar).Type()
		if !t.AssignableTo(exemplarType) || data == nil {
			return fmt.Errorf("Unable to assign data: %v to same type as exemplar: %v in %s", data, q.exemplar, q.name)
		}
	}
	q.channel <- data
	return nil
}

// Run starts to run the queue and attempts to create the internal queue
func (q *WrappedQueue) Run(atShutdown, atTerminate func(context.Context, func())) {
	q.lock.Lock()
	if q.internal == nil {
		err := q.setInternal(atShutdown, q.handle, q.exemplar)
		q.lock.Unlock()
		if err != nil {
			log.Fatal("Unable to set the internal queue for %s Error: %v", q.Name(), err)
			return
		}
		go func() {
			for data := range q.channel {
				_ = q.internal.Push(data)
			}
		}()
	} else {
		q.lock.Unlock()
	}

	q.internal.Run(atShutdown, atTerminate)
	log.Trace("WrappedQueue: %s Done", q.name)
}

// Shutdown this queue and stop processing
func (q *WrappedQueue) Shutdown() {
	log.Trace("WrappedQueue: %s Shutdown", q.name)
	q.lock.Lock()
	defer q.lock.Unlock()
	if q.internal == nil {
		return
	}
	if shutdownable, ok := q.internal.(Shutdownable); ok {
		shutdownable.Shutdown()
	}
}

// Terminate this queue and close the queue
func (q *WrappedQueue) Terminate() {
	log.Trace("WrappedQueue: %s Terminating", q.name)
	q.lock.Lock()
	defer q.lock.Unlock()
	if q.internal == nil {
		return
	}
	if shutdownable, ok := q.internal.(Shutdownable); ok {
		shutdownable.Terminate()
	}
}

func init() {
	queuesMap[WrappedQueueType] = NewWrappedQueue
}