summaryrefslogtreecommitdiff
path: root/rhimport/session.go
blob: 5bec54dd1181a68781f0f8730d683e5ed664fce3 (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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//
//  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"
	"path"
	"strings"
	"time"
)

const (
	_SESSION_NEW = iota
	_SESSION_RUNNING
	_SESSION_CANCELED
	_SESSION_DONE
	_SESSION_TIMEOUT
)

type sessionProgressCB struct {
	cb       ProgressCB
	userdata interface{}
}

type sessionDoneCB struct {
	cb       DoneCB
	userdata interface{}
}

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
}

type attachUploaderResponse struct {
	cancel     <-chan bool
	attachment chan<- AttachmentChunk
}

type attachUploaderRequest struct {
	response chan<- attachUploaderResponse
}

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
	attachUploaderChan chan attachUploaderRequest
	progressCBs        []*sessionProgressCB
	doneCBs            []*sessionDoneCB
	cancelUploader     chan bool
	removeWorkDir      bool
}

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

func (s *session) runner() {
	err := s.ctx.SanityCheck()
	if err != nil {
		s.doneIntChan <- Result{ResponseCode: http.StatusBadRequest, ErrorString: err.Error()}
		return
	}

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

	if res, err = NormalizeFile(&s.ctx); err != nil {
		s.doneIntChan <- Result{ResponseCode: http.StatusInternalServerError, ErrorString: err.Error()}
		return
	}
	if res.ResponseCode != http.StatusOK {
		s.doneIntChan <- *res
		return
	}

	if s.ctx.SourceFilePolicy == Keep {
		s.removeWorkDir = false
	}
	if res, err = ImportFile(&s.ctx); err != nil {
		res.ResponseCode = http.StatusInternalServerError
		res.ErrorString = err.Error()
	}
	if s.ctx.SourceFilePolicy == Keep {
		res.SourceFile = "tmp://" + path.Clean("/"+strings.TrimPrefix(s.ctx.SourceFile, s.ctx.conf.TempDir))
	}
	s.doneIntChan <- *res
}

func (s *session) run(timeout time.Duration) {
	s.ctx.ProgressCallBack = sessionProgressCallback
	s.ctx.ProgressCallBackData = (chan<- ProgressData)(s.progressIntChan)
	s.ctx.Cancel = s.cancelIntChan
	go s.runner()
	s.state = _SESSION_RUNNING
	if timeout <= 0 || timeout > 3*time.Hour {
		s.ctx.stdlog.Printf("requested session timeout (%v) is invalid or too high - setting it to 3h", timeout)
		timeout = 3 * time.Hour
	}
	s.timer.Reset(timeout)
	return
}

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

func (s *session) addProgressHandler(userdata interface{}, cb ProgressCB) (resp sessionAddProgressHandlerResponse) {
	if s.state != _SESSION_NEW && s.state != _SESSION_RUNNING {
		resp.err = fmt.Errorf("session is already done/canceled")
	}
	s.progressCBs = append(s.progressCBs, &sessionProgressCB{cb, userdata})
	return
}

func (s *session) addDoneHandler(userdata interface{}, cb DoneCB) (resp sessionAddDoneHandlerResponse) {
	if s.state != _SESSION_NEW && s.state != _SESSION_RUNNING {
		resp.err = fmt.Errorf("session is already done/canceled")
	}
	s.doneCBs = append(s.doneCBs, &sessionDoneCB{cb, userdata})
	return
}

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

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

func (s *session) attachUploader() (resp attachUploaderResponse) {
	if s.cancelUploader != nil {
		return
	}
	s.cancelUploader = make(chan bool, 1)
	resp.cancel = s.cancelUploader
	resp.attachment = s.ctx.AttachmentChan
	return
}

func (s *session) dispatchRequests() {
	defer func() {
		if s.cancelUploader != nil {
			close(s.cancelUploader)
		}
		s.done <- true
	}()

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

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

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

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

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

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

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

	res := <-resCh
	return res.err
}

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

	res := <-resCh
	return res.err
}

func (s *Session) AttachUploader() (<-chan bool, chan<- AttachmentChunk) {
	resCh := make(chan attachUploaderResponse)
	req := attachUploaderRequest{}
	req.response = resCh
	select {
	case s.attachUploaderChan <- req:
	default:
		// session is about to be closed/removed
		return nil, nil
	}

	res := <-resCh
	return res.cancel, res.attachment
}

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

func (s *session) getInterface() *Session {
	ch := &Session{}
	ch.runChan = s.runChan
	ch.cancelChan = s.cancelChan
	ch.addProgressChan = s.addProgressChan
	ch.addDoneChan = s.addDoneChan
	ch.attachUploaderChan = s.attachUploaderChan
	return ch
}

func (s *session) cleanup() {
	s.quit <- true
	s.ctx.dbglog.Printf("Session: waiting for session to close")
	<-s.done
	close(s.quit)
	close(s.done)
	s.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(s.cancelIntChan)
	// close(s.progressIntChan)
	// close(s.doneIntChan)
	// close(s.runChan)
	// close(s.cancelChan)
	// close(s.addProgressChan)
	// close(s.addDoneChan)
	// close(s.attachUploader)
	if s.removeWorkDir {
		s.ctx.RemoveTempWorkDir()
	}
	s.ctx.dbglog.Printf("Session: cleanup is now done")
}

func newSession(ctx *Context, removeFunc func()) (s *session, err error) {
	s = &session{}
	s.state = _SESSION_NEW
	s.removeFunc = removeFunc
	s.ctx = *ctx
	if err = s.ctx.CreateTempWorkDir(); err != nil {
		return
	}
	s.removeWorkDir = true
	s.quit = make(chan bool, 1)
	s.done = make(chan bool)
	s.timer = time.NewTimer(10 * time.Second)
	s.cancelIntChan = make(chan bool, 1)
	s.progressRateLimit = 100 * time.Millisecond // TODO: hardcoded value
	s.progressIntChan = make(chan ProgressData, 10)
	s.doneIntChan = make(chan Result, 1)
	s.runChan = make(chan time.Duration, 1)
	s.cancelChan = make(chan bool, 1)
	s.addProgressChan = make(chan sessionAddProgressHandlerRequest, 10)
	s.addDoneChan = make(chan sessionAddDoneHandlerRequest, 10)
	s.attachUploaderChan = make(chan attachUploaderRequest, 1)
	go s.dispatchRequests()
	return
}