summaryrefslogtreecommitdiff
path: root/rhimport/session.go
blob: b00be1767685d880e73a70674c73130c866abb4c (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
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
//
//  rhimportd
//
//  The Radio Helsinki Rivendell Import Daemon
//
//
//  Copyright (C) 2015-2016 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of rhimportd.
//
//  rhimportd is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  rhimportd is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with rhimportd. If not, see <http://www.gnu.org/licenses/>.
//

package rhimport

import (
	"fmt"
	"net/http"
	"time"
)

const (
	SESSION_NEW = iota
	SESSION_RUNNING
	SESSION_CANCELED
	SESSION_DONE
	SESSION_TIMEOUT
)

type Session struct {
	ctx               Context
	state             int
	removeFunc        func()
	done              chan bool
	quit              chan bool
	timer             *time.Timer
	cancelIntChan     chan bool
	progressRateLimit time.Duration
	progressIntChan   chan ProgressData
	doneIntChan       chan Result
	runChan           chan time.Duration
	cancelChan        chan bool
	addProgressChan   chan sessionAddProgressHandlerRequest
	addDoneChan       chan sessionAddDoneHandlerRequest
	progressCBs       []*SessionProgressCB
	doneCBs           []*SessionDoneCB
}

type SessionProgressCB struct {
	cb       ProgressCB
	userdata interface{}
}

type SessionDoneCB struct {
	cb       DoneCB
	userdata interface{}
}

type ProgressData struct {
	Step     int
	StepName string
	Current  float64
	Total    float64
}

type sessionAddProgressHandlerResponse struct {
	err error
}

type sessionAddProgressHandlerRequest struct {
	userdata interface{}
	callback ProgressCB
	response chan<- sessionAddProgressHandlerResponse
}

type sessionAddDoneHandlerResponse struct {
	err error
}

type sessionAddDoneHandlerRequest struct {
	userdata interface{}
	callback DoneCB
	response chan<- sessionAddDoneHandlerResponse
}

func sessionProgressCallback(step int, stepName string, current, total float64, userdata interface{}) bool {
	out := userdata.(chan<- ProgressData)
	out <- ProgressData{step, stepName, current, total}
	return true
}

func sessionRun(ctx Context, done chan<- Result) {
	err := ctx.SanityCheck()
	if err != nil {
		done <- Result{ResponseCode: http.StatusBadRequest, ErrorString: err.Error()}
		return
	}

	var res *Result
	res, err = FetchFile(&ctx)
	if err != nil {
		done <- Result{ResponseCode: http.StatusInternalServerError, ErrorString: err.Error()}
		return
	}
	if res.ResponseCode != http.StatusOK {
		done <- *res
		return
	}

	res, err = ImportFile(&ctx)
	if err != nil {
		res.ResponseCode = http.StatusInternalServerError
		res.ErrorString = err.Error()
	}
	done <- *res
}

func (self *Session) run(timeout time.Duration) {
	self.ctx.ProgressCallBack = sessionProgressCallback
	self.ctx.ProgressCallBackData = (chan<- ProgressData)(self.progressIntChan)
	self.ctx.Cancel = self.cancelIntChan
	go sessionRun(self.ctx, self.doneIntChan)
	self.state = SESSION_RUNNING
	if timeout > 3*time.Hour {
		rhl.Printf("requested session timeout (%v) is to high - lowering to 3h", timeout)
		timeout = 3 * time.Hour
	}
	self.timer.Reset(timeout)
	return
}

func (self *Session) cancel() {
	rhdl.Println("Session: canceling running import")
	select {
	case self.cancelIntChan <- true:
	default: // session got canceled already??
	}
	self.state = SESSION_CANCELED
}

func (self *Session) addProgressHandler(userdata interface{}, cb ProgressCB) (resp sessionAddProgressHandlerResponse) {
	if self.state != SESSION_NEW && self.state != SESSION_RUNNING {
		resp.err = fmt.Errorf("session is already done/canceled")
	}
	self.progressCBs = append(self.progressCBs, &SessionProgressCB{cb, userdata})
	return
}

func (self *Session) addDoneHandler(userdata interface{}, cb DoneCB) (resp sessionAddDoneHandlerResponse) {
	if self.state != SESSION_NEW && self.state != SESSION_RUNNING {
		resp.err = fmt.Errorf("session is already done/canceled")
	}
	self.doneCBs = append(self.doneCBs, &SessionDoneCB{cb, userdata})
	return
}

func (self *Session) callProgressHandler(p *ProgressData) {
	for _, cb := range self.progressCBs {
		if cb.cb != nil {
			if keep := cb.cb(p.Step, p.StepName, p.Current, p.Total, cb.userdata); !keep {
				cb.cb = nil
			}
		}
	}
}

func (self *Session) callDoneHandler(r *Result) {
	for _, cb := range self.doneCBs {
		if cb.cb != nil {
			if keep := cb.cb(*r, cb.userdata); !keep {
				cb.cb = nil
			}
		}
	}
}

func (self *Session) dispatchRequests() {
	defer func() { self.done <- true }()

	var lastProgress *ProgressData
	progressPending := 0
	pt := time.NewTimer(self.progressRateLimit)
	pt.Stop()

	for {
		select {
		case <-self.quit:
			if self.state == SESSION_RUNNING {
				self.cancel()
			}
			return
		case <-self.timer.C:
			if self.state == SESSION_RUNNING {
				self.cancel()
			}
			self.state = SESSION_TIMEOUT
			r := &Result{ResponseCode: http.StatusInternalServerError, ErrorString: "session timed out"}
			self.callDoneHandler(r)
			if self.removeFunc != nil {
				self.removeFunc()
			}
		case t := <-self.runChan:
			if self.state == SESSION_NEW {
				self.run(t)
			}
		case <-self.cancelChan:
			if self.state == SESSION_RUNNING {
				self.cancel()
			}
		case req := <-self.addProgressChan:
			req.response <- self.addProgressHandler(req.userdata, req.callback)
		case req := <-self.addDoneChan:
			req.response <- self.addDoneHandler(req.userdata, req.callback)
		case <-pt.C:
			if progressPending > 1 && lastProgress != nil {
				self.callProgressHandler(lastProgress)
			}
			progressPending = 0
			lastProgress = nil
		case p := <-self.progressIntChan:
			if self.state == SESSION_RUNNING {
				if lastProgress == nil {
					self.callProgressHandler(&p)
					pt.Reset(self.progressRateLimit)
				}
				lastProgress = &p
				progressPending++
			}
		case r := <-self.doneIntChan:
			if self.state != SESSION_TIMEOUT {
				self.timer.Stop()
				self.state = SESSION_DONE
				self.callDoneHandler(&r)
				if self.removeFunc != nil {
					self.removeFunc()
				}
			}
		}
	}
}

// *********************************************************
// Public Interface

type SessionChan struct {
	runChan         chan<- time.Duration
	cancelChan      chan<- bool
	addProgressChan chan<- sessionAddProgressHandlerRequest
	addDoneChan     chan<- sessionAddDoneHandlerRequest
}

func (self *SessionChan) Run(timeout time.Duration) {
	select {
	case self.runChan <- timeout:
	default: // command is already pending or session is about to be closed/removed
	}
}

func (self *SessionChan) Cancel() {
	select {
	case self.cancelChan <- true:
	default: // cancel is already pending or session is about to be closed/removed
	}
}

func (self *SessionChan) AddProgressHandler(userdata interface{}, cb ProgressCB) error {
	resCh := make(chan sessionAddProgressHandlerResponse)
	req := sessionAddProgressHandlerRequest{}
	req.userdata = userdata
	req.callback = cb
	req.response = resCh
	select {
	case self.addProgressChan <- req:
	default:
		return fmt.Errorf("session is about to be closed/removed")
	}

	res := <-resCh
	return res.err
}

func (self *SessionChan) AddDoneHandler(userdata interface{}, cb DoneCB) error {
	resCh := make(chan sessionAddDoneHandlerResponse)
	req := sessionAddDoneHandlerRequest{}
	req.userdata = userdata
	req.callback = cb
	req.response = resCh
	select {
	case self.addDoneChan <- req:
	default:
		return fmt.Errorf("session is about to be closed/removed")
	}

	res := <-resCh
	return res.err
}

// *********************************************************
// Semi-Public Interface (only used by sessionStore)

func (self *Session) getInterface() *SessionChan {
	ch := &SessionChan{}
	ch.runChan = self.runChan
	ch.cancelChan = self.cancelChan
	ch.addProgressChan = self.addProgressChan
	ch.addDoneChan = self.addDoneChan
	return ch
}

func (self *Session) cleanup() {
	self.quit <- true
	rhdl.Printf("waiting for session to close")
	<-self.done
	close(self.quit)
	close(self.done)
	self.timer.Stop()
	//   don't close the channels we give out because this might lead to a panic if
	//   somebody wites to an already removed session
	// close(self.cancelIntChan)
	// close(self.progressIntChan)
	// close(self.doneIntChan)
	// close(self.runChan)
	// close(self.cancelChan)
	// close(self.addProgressChan)
	// close(self.addDoneChan)
	rhdl.Printf("session is now cleaned up")
}

func newSession(ctx *Context, removeFunc func()) (session *Session) {
	session = new(Session)
	session.state = SESSION_NEW
	session.removeFunc = removeFunc
	session.ctx = *ctx
	session.done = make(chan bool)
	session.timer = time.NewTimer(10 * time.Second)
	session.cancelIntChan = make(chan bool, 1)
	session.progressRateLimit = 100 * time.Millisecond // TODO: hardcoded value
	session.progressIntChan = make(chan ProgressData, 10)
	session.doneIntChan = make(chan Result, 1)
	session.runChan = make(chan time.Duration, 1)
	session.cancelChan = make(chan bool, 1)
	session.addProgressChan = make(chan sessionAddProgressHandlerRequest, 10)
	session.addDoneChan = make(chan sessionAddDoneHandlerRequest, 10)
	go session.dispatchRequests()
	return
}