-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
637 lines (601 loc) · 22.2 KB
/
service.go
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
package worker
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"path/filepath"
"time"
amessages "github.com/airenas/async-api/pkg/messages"
"github.com/airenas/go-app/pkg/goapp"
"github.com/airenas/roxy/internal/pkg/api"
"github.com/airenas/roxy/internal/pkg/messages"
"github.com/airenas/roxy/internal/pkg/persistence"
"github.com/airenas/roxy/internal/pkg/status"
tapi "github.com/airenas/roxy/internal/pkg/transcriber/api"
"github.com/airenas/roxy/internal/pkg/utils"
"github.com/airenas/roxy/internal/pkg/utils/handler"
"github.com/vgarvardt/gue/v5"
)
// MsgSender provides send msg functionality
type MsgSender interface {
SendMessage(context.Context, amessages.Message, *messages.Options) error
}
// DB provides persistnce functionality
type DB interface {
LoadRequest(ctx context.Context, id string) (*persistence.ReqData, error)
LoadStatus(ctx context.Context, id string) (*persistence.Status, error)
LoadWorkData(ctx context.Context, id string) (*persistence.WorkData, error)
InsertWorkData(context.Context, *persistence.WorkData) error
UpdateStatus(context.Context, *persistence.Status) error
UpdateWorkData(context.Context, *persistence.WorkData) error
}
// Filer retrieves files
type Filer interface {
LoadFile(ctx context.Context, fileName string) (io.ReadSeekCloser, error)
SaveFile(ctx context.Context, name string, r io.Reader, fileSize int64) error
}
type UsageRestorer interface {
Do(ctx context.Context, msgID, reqID, errStr string) error
}
// TranscriberProvider provides transcriber
type TranscriberProvider interface {
Get(key string, allowOther bool) (tapi.Transcriber, string, error)
}
// ServiceData keeps data required for service work
type ServiceData struct {
GueClient *gue.Client
WorkerCount int // ASR worker
WorkerOtherCount int // for handling statuses, etc
MsgSender MsgSender
DB DB
Filer Filer
TranscriberPr TranscriberProvider
UsageRestorer UsageRestorer
Testing bool
RetryDelay time.Duration
}
const (
wrkOtherQueuePrefix = "ROXY/Work1"
wrkStatusQueue = "wrk-status"
wrkStatusClean = "wrk-clean"
wrkStatusFail = "wrk-fail"
wrkUpload = "wrk-upload"
wrkRestoreUsage = "wrk-restore-usage"
wrkFail = "wrk-fail"
)
// StartWorkerService starts the event queue listener service to listen for events
// returns channel for tracking if all jobs are finished
func StartWorkerService(ctx context.Context, data *ServiceData) (chan struct{}, error) {
if err := validate(data); err != nil {
return nil, err
}
goapp.Log.Info().Int("workers", data.WorkerCount).Int("workersOther", data.WorkerOtherCount).Msg("Starting listen for messages")
if data.Testing {
goapp.Log.Warn().Msg("SERVICE IN TEST MODE")
}
goapp.Log.Info().Dur("delay", data.RetryDelay).Msg("cfg: retry on no transcriber after")
wm := gue.WorkMap{
wrkUpload: handler.Create(data, handleASR, handler.DefaultOpts[messages.ASRMessage]().WithFailure(asrFailureHandler(data)).
WithTimeout(time.Minute*120).WithBackoff(handler.DefaultBackoffOrTest(data.Testing))),
}
ctxInt, cf := context.WithCancel(ctx)
defer func() { cf() }()
ecASR, err := startPool(ctxInt, data, data.WorkerCount, wm, messages.Work, "asr-worker")
if err != nil {
return nil, fmt.Errorf("could not start pool: %w", err)
}
wmOther := gue.WorkMap{
wrkStatusQueue: handler.Create(data, handleStatus, handler.DefaultOpts[messages.StatusMessage]().WithFailure(statusFailureHandler(data)).
WithBackoff(handler.DefaultBackoffOrTest(data.Testing))),
wrkStatusClean: handler.Create(data, handleClean, handler.DefaultOpts[messages.CleanMessage]().WithBackoff(handler.DefaultBackoffOrTest(data.Testing))),
wrkStatusFail: handler.Create(data, handleFailure, handler.DefaultOpts[messages.ASRMessage]().WithBackoff(handler.DefaultBackoffOrTest(data.Testing))),
wrkRestoreUsage: handler.Create(data, handleRestoreUsage, handler.DefaultOpts[messages.ASRMessage]().WithBackoff(handler.DefaultBackoffOrTest(data.Testing))),
}
ecOther, err := startPool(ctxInt, data, data.WorkerOtherCount, wmOther, wrkOtherQueuePrefix, "asr-worker-other")
if err != nil {
return nil, fmt.Errorf("could not start pool: %w", err)
}
res := make(chan struct{}, 1)
cfInt := cf
cf = func() {}
go func() {
// wait for any pool to finish
select {
case <-ecASR:
case <-ecOther:
}
// drop context
cfInt()
// wait for both pool to finish
<-ecASR
<-ecOther
goapp.Log.Info().Msg("pool workers finished")
close(res)
}()
return res, nil
}
func startPool(ctx context.Context, data *ServiceData, count int, wm gue.WorkMap, queue, name string) (<-chan struct{}, error) {
pool, err := gue.NewWorkerPool(
data.GueClient, wm, count,
gue.WithPoolQueue(queue),
gue.WithPoolLogger(utils.NewGueLoggerAdapter()),
gue.WithPoolPollInterval(500*time.Millisecond),
gue.WithPoolPollStrategy(gue.RunAtPollStrategy),
gue.WithPoolID(name),
)
if err != nil {
return nil, fmt.Errorf("could not build gue workers pool: %w", err)
}
res := make(chan struct{}, 1)
go func() {
goapp.Log.Info().Int("workers", count).Str("name", name).Str("queue", queue).Msg("starting pool")
if err := pool.Run(ctx); err != nil {
goapp.Log.Error().Err(err).Msg("pool error")
}
goapp.Log.Info().Str("name", name).Msg("exit workers")
close(res)
}()
return res, nil
}
func handleASR(ctx context.Context, m *messages.ASRMessage, data *ServiceData) error {
goapp.Log.Info().Str("ID", m.ID).Msg("handling asr")
err := data.MsgSender.SendMessage(ctx, &amessages.InformMessage{
QueueMessage: *amessages.NewQueueMessageFromM(&m.QueueMessage),
Type: amessages.InformTypeStarted, At: time.Now()}, messages.DefaultOpts(messages.Inform))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("load request")
req, err := data.DB.LoadRequest(ctx, m.ID)
if err != nil {
return fmt.Errorf("can't load request: %w", err)
}
goapp.Log.Debug().Str("ID", m.ID).Msgf("loaded %v", req)
goapp.Log.Info().Str("ID", m.ID).Msg("load work data")
wd, err := data.DB.LoadWorkData(ctx, m.ID)
if err != nil {
return fmt.Errorf("can't load work data: %w", err)
}
goapp.Log.Debug().Str("ID", m.ID).Msgf("loaded %v", wd)
oldSrv := ""
if wd != nil {
oldSrv = utils.FromSQLStr(wd.Transcriber)
}
transcriber, trSrv, err := data.TranscriberPr.Get(oldSrv, true)
if err != nil {
return fmt.Errorf("can't get transcriber: %w", err)
}
if transcriber == nil {
goapp.Log.Info().Str("ID", m.ID).Msg("no available transcribers")
maxWaitTime := time.Hour * 12
if req.Created.Add(maxWaitTime).Before(time.Now()) {
goapp.Log.Info().Str("ID", m.ID).Msg("already to late")
return fmt.Errorf("no available transcriber in %s, added %s", maxWaitTime.String(), req.Created.Format(time.RFC3339))
}
// sleep for data.RetryDelay
err := data.MsgSender.SendMessage(ctx, m, messages.DefaultOpts(messages.Upload).Delay(data.RetryDelay))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
return nil
}
if wd == nil {
extID, err := upload(ctx, req, transcriber, data)
if err != nil {
return fmt.Errorf("can't upload: %w", err)
}
wd = &persistence.WorkData{ID: req.ID, ExternalID: extID, Created: time.Now(),
Transcriber: utils.ToSQLStr(trSrv), TryCount: 1}
err = data.DB.InsertWorkData(ctx, wd)
if err != nil {
return fmt.Errorf("can't save work data: %w", err)
}
} else if oldSrv != trSrv {
if wd.TryCount > 3 {
goapp.Log.Info().Str("ID", m.ID).Msg("too many retries")
return fmt.Errorf("too many retries: %d", wd.TryCount)
}
goapp.Log.Info().Str("ID", m.ID).Str("old", oldSrv).Str("new", trSrv).Msgf("try new srv")
extID, err := upload(ctx, req, transcriber, data)
if err != nil {
return fmt.Errorf("can't upload: %w", err)
}
wd.ExternalID = extID
wd.Transcriber = utils.ToSQLStr(trSrv)
wd.TryCount += 1
err = data.DB.UpdateWorkData(ctx, wd)
if err != nil {
return fmt.Errorf("can't update work data: %w", err)
}
} else {
if wd.TryCount > 5 {
goapp.Log.Info().Str("ID", m.ID).Msg("too many retries for same transcriber")
return fmt.Errorf("too many retries: %d", wd.TryCount)
}
wd.TryCount += 1
err = data.DB.UpdateWorkData(ctx, wd)
if err != nil {
return fmt.Errorf("can't update work data: %w", err)
}
}
// wait for finish
err = waitStatus(ctx, wd, data)
if err != nil {
return fmt.Errorf("can't wait for finish: %w", err)
}
goapp.Log.Info().Str("ID", wd.ID).Msg("Transcription completed")
return nil
}
func asrFailureHandler(data *ServiceData) func(context.Context, *messages.ASRMessage, error, *gue.Job) (bool, time.Duration, error) {
return func(ctx context.Context, m *messages.ASRMessage, err error, j *gue.Job) (bool, time.Duration, error) {
delay := time.Duration(0)
tErr := &errTranscriber{}
if errors.As(err, &tErr) {
goapp.Log.Info().Str("ID", m.ID).Msg("got transcriber error")
delay = data.RetryDelay
}
if j.ErrorCount < 5 {
return true, delay, nil
}
if _err := sendStatusChangeFailure(ctx, data.MsgSender, m.ID, err.Error()); _err != nil {
goapp.Log.Error().Err(_err).Str("ID", m.ID).Msg("fail send status failure msg")
}
if _err := sendFailure(ctx, data.MsgSender, m.ID); _err != nil {
goapp.Log.Error().Err(_err).Str("ID", m.ID).Msg("fail send failure msg")
}
return false, 0, nil
}
}
type errTranscriber struct {
err error
}
func (e *errTranscriber) Error() string {
return fmt.Sprintf("transcriber error: %v", e.err)
}
func (e *errTranscriber) Unwrap() error {
return e.err
}
func statusFailureHandler(data *ServiceData) func(context.Context, *messages.StatusMessage, error, *gue.Job) (bool, time.Duration, error) {
return func(ctx context.Context, m *messages.StatusMessage, err error, j *gue.Job) (bool, time.Duration, error) {
delay := time.Duration(0)
tErr := &errTranscriber{}
if errors.As(err, &tErr) {
goapp.Log.Info().Str("ID", m.ID).Msg("got transcriber error")
delay = data.RetryDelay
}
if j.ErrorCount < 3 {
return true, delay, nil
}
if errors.As(err, &tErr) {
goapp.Log.Info().Str("ID", m.ID).Msg("retry transcription - transcriber result retrieve error")
err := data.MsgSender.SendMessage(ctx, &messages.ASRMessage{
QueueMessage: amessages.QueueMessage{ID: m.ID}}, messages.DefaultOpts(messages.Upload).Delay(data.RetryDelay))
if err != nil {
return true, data.RetryDelay, fmt.Errorf("can't send msg: %w", err)
}
} else {
if _err := sendStatusChangeFailure(ctx, data.MsgSender, m.ID, err.Error()); _err != nil {
goapp.Log.Error().Err(_err).Str("ID", m.ID).Msg("fail send status failure msg")
}
if _err := sendFailure(ctx, data.MsgSender, m.ID); _err != nil {
goapp.Log.Error().Err(_err).Str("ID", m.ID).Msg("fail send failure msg")
}
}
return false, 0, nil
}
}
func sendFailure(ctx context.Context, sender MsgSender, ID string) error {
goapp.Log.Info().Str("ID", ID).Msg("sending failure msg")
return sender.SendMessage(ctx, &amessages.InformMessage{
QueueMessage: amessages.QueueMessage{ID: ID},
Type: amessages.InformTypeFailed, At: time.Now()}, messages.DefaultOpts(messages.Inform))
}
func sendStatusChangeFailure(ctx context.Context, sender MsgSender, ID string, errStr string) error {
goapp.Log.Info().Str("ID", ID).Msg("sending failure status change msg")
return sender.SendMessage(ctx, &messages.ASRMessage{
QueueMessage: amessages.QueueMessage{ID: ID, Error: errStr}}, messages.DefaultOpts(wrkOtherQueuePrefix+":"+wrkFail))
}
func handleStatus(ctx context.Context, m *messages.StatusMessage, data *ServiceData) error {
goapp.Log.Info().Str("ID", m.ID).Str("extID", m.ExternalID).Str("status", m.Status).Msg("handling")
transcriber, _, err := data.TranscriberPr.Get(m.Transcriber, false)
if err != nil {
return fmt.Errorf("can't get active transcriber by `%s`: %w", m.Transcriber, err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("load status")
status, err := data.DB.LoadStatus(ctx, m.ID)
if err != nil {
return fmt.Errorf("can't load status: %w", err)
}
// do not update if status is older
// but make exception if status update was long time ago - maybe retry
if int32(m.Progress) < utils.FromSQLInt32OrZero(status.Progress) && status.Updated.After(time.Now().Add(-30*time.Minute)) {
goapp.Log.Warn().Str("ID", m.ID).Str("status", m.Status).Int32("oldProgress", utils.FromSQLInt32OrZero(status.Progress)).Int("progress", m.Progress).Msg("obsolete")
return nil
}
goapp.Log.Debug().Str("ID", m.ID).Msgf("loaded %v", status)
if m.AudioReady && !status.AudioReady {
goapp.Log.Info().Str("ID", m.ExternalID).Msg("get audio")
f, err := transcriber.GetAudio(ctx, m.ExternalID)
if err != nil {
return &errTranscriber{err: fmt.Errorf("can't get audio: %w", err)}
}
name := filepath.Join(m.ID, m.ID+".mp3") // only such case now supported
err = data.Filer.SaveFile(ctx, name, bytes.NewReader(f.Content), int64(len(f.Content)))
if err != nil {
return fmt.Errorf("can't save file: %w", err)
}
status.AudioReady = true
}
if len(m.AvailableResults) != len(status.AvailableResults) {
for _, fn := range m.AvailableResults {
goapp.Log.Info().Str("ID", m.ID).Str("file", fn).Msg("get data")
f, err := transcriber.GetResult(ctx, m.ExternalID, fn)
if err != nil {
return &errTranscriber{err: fmt.Errorf("can't get data: %w", err)}
}
err = data.Filer.SaveFile(ctx, fmt.Sprintf("%s/%s", m.ID, f.Name), bytes.NewReader(f.Content), int64(len(f.Content)))
if err != nil {
return fmt.Errorf("can't save file: %w", err)
}
}
status.AvailableResults = m.AvailableResults
}
status.Error = utils.ToSQLStr(m.Error)
status.ErrorCode = utils.ToSQLStr(m.ErrorCode)
status.Progress = utils.ToSQLInt32(int32(m.Progress))
status.Status = m.Status
status.RecognizedText = utils.ToSQLStr(limit(m.RecognizedText, 200))
if err := data.DB.UpdateStatus(ctx, status); err != nil {
return fmt.Errorf("can't save status: %w", err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("Status update completed")
err = data.MsgSender.SendMessage(ctx, &messages.ASRMessage{
QueueMessage: amessages.QueueMessage{ID: m.ID}}, messages.DefaultOpts(messages.StatusChange))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
if isCompleted(m.Status, m.Error) {
err = data.MsgSender.SendMessage(ctx, &messages.CleanMessage{
QueueMessage: amessages.QueueMessage{ID: m.ID},
ExternalID: m.ExternalID, Transcriber: m.Transcriber},
messages.DefaultOpts(wrkOtherQueuePrefix+":"+wrkStatusClean))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
err := data.MsgSender.SendMessage(ctx, &amessages.InformMessage{
QueueMessage: *amessages.NewQueueMessageFromM(&m.QueueMessage),
Type: getInformFinishType(m.Error), At: time.Now()}, messages.DefaultOpts(messages.Inform))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
if m.Error != "" {
err = data.MsgSender.SendMessage(ctx, &messages.ASRMessage{
QueueMessage: *amessages.NewQueueMessageFromM(&m.QueueMessage)}, messages.DefaultOpts(wrkOtherQueuePrefix+":"+wrkRestoreUsage))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
}
}
return nil
}
func limit(s string, l int) string {
if len(s) > l {
r := []rune(s) // make sure we don't break utf-8
if len(r) > l {
return string(r[:l-3]) + "..."
}
}
return s
}
func getInformFinishType(errStr string) string {
if errStr == "" {
return amessages.InformTypeFinished
}
return amessages.InformTypeFailed
}
func handleFailure(ctx context.Context, m *messages.ASRMessage, data *ServiceData) error {
goapp.Log.Info().Str("ID", m.ID).Msg("handling failure")
goapp.Log.Info().Str("ID", m.ID).Msg("load status")
statusRec, err := data.DB.LoadStatus(ctx, m.ID)
if err != nil {
return fmt.Errorf("can't load status: %w", err)
}
if statusRec == nil {
return fmt.Errorf("no status record")
}
goapp.Log.Debug().Str("ID", m.ID).Msgf("loaded %v", statusRec)
if statusRec.Error.String != "" {
goapp.Log.Info().Str("ID", m.ID).Msg("error set - ignore")
}
statusRec.Error = utils.ToSQLStr(m.Error)
statusRec.ErrorCode = utils.ToSQLStr(status.ServiceError.String())
if err := data.DB.UpdateStatus(ctx, statusRec); err != nil {
return fmt.Errorf("can't save status: %w", err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("Status update completed")
goapp.Log.Info().Str("ID", m.ID).Msg("send status change")
err = data.MsgSender.SendMessage(ctx, &messages.ASRMessage{
QueueMessage: amessages.QueueMessage{ID: m.ID}}, messages.DefaultOpts(messages.StatusChange))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
err = data.MsgSender.SendMessage(ctx, &messages.ASRMessage{
QueueMessage: amessages.QueueMessage{ID: m.ID}}, messages.DefaultOpts(wrkOtherQueuePrefix+":"+wrkRestoreUsage))
if err != nil {
return fmt.Errorf("can't send msg: %w", err)
}
return nil
}
func handleRestoreUsage(ctx context.Context, m *messages.ASRMessage, data *ServiceData) error {
goapp.Log.Info().Str("ID", m.ID).Msg("handling restore")
req, err := data.DB.LoadRequest(ctx, m.ID)
if err != nil {
return fmt.Errorf("can't load request: %w", err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("loaded request")
st, err := data.DB.LoadStatus(ctx, m.ID)
if err != nil {
return fmt.Errorf("can't load status: %w", err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("loaded status")
if status.ECServiceError.String() == utils.FromSQLStr(st.ErrorCode) {
if err := data.UsageRestorer.Do(ctx, req.ID, req.RequestID, utils.FromSQLStr(st.Error)); err != nil {
return fmt.Errorf("can't restore: %w", err)
}
goapp.Log.Info().Str("ID", m.ID).Msg("restore done")
} else {
goapp.Log.Warn().Str("ID", m.ID).Str("errCode", utils.FromSQLStr(st.ErrorCode)).Msg("restore skip")
}
return nil
}
func handleClean(ctx context.Context, m *messages.CleanMessage, data *ServiceData) error {
goapp.Log.Info().Str("ID", m.ID).Str("extID", m.ExternalID).Msg("handling clean")
transcriber, _, err := data.TranscriberPr.Get(m.Transcriber, false)
if err != nil {
return fmt.Errorf("can't get active transcriber by `%s`: %w", m.Transcriber, err)
}
if err := transcriber.Clean(ctx, m.ExternalID); err != nil {
return fmt.Errorf("can't clean external data: %w", err)
}
return nil
}
func isCompleted(st, errStr string) bool {
return status.From(st) == status.Completed || errStr != ""
}
func waitStatus(ctx context.Context, wd *persistence.WorkData, data *ServiceData) error {
transcriber, _, err := data.TranscriberPr.Get(utils.FromSQLStr(wd.Transcriber), false)
if err != nil {
return fmt.Errorf("can't get transcriber %s: %w", utils.FromSQLStr(wd.Transcriber), err)
}
manualCheck := time.Second * 20
stCh, cf, err := transcriber.HookToStatus(ctx, wd.ExternalID)
if err != nil {
return &errTranscriber{err: fmt.Errorf("can't hook to status: %w", err)}
}
defer cf()
for {
select {
case <-ctx.Done():
goapp.Log.Info().Msg("exit status channel loop")
return nil
case d, ok := <-stCh:
{
if !ok {
goapp.Log.Info().Msg("closed status channel")
return fmt.Errorf("close channel without finish")
}
finish, err := processStatus(ctx, &d, wd, data)
if err != nil {
return fmt.Errorf("can't process status: %w", err)
}
if finish {
return nil
}
}
case <-time.After(manualCheck):
{
goapp.Log.Info().Msg("manual status check")
d, err := transcriber.GetStatus(ctx, wd.ExternalID)
if err != nil {
return fmt.Errorf("can't get status: %w", err)
}
if isCompleted(d.Status, d.Error) { // send msg only if completed
finish, err := processStatus(ctx, d, wd, data)
if err != nil {
return fmt.Errorf("can't process status: %w", err)
}
if finish {
return nil
}
}
}
}
}
}
func processStatus(ctx context.Context, statusData *tapi.StatusData, wd *persistence.WorkData, data *ServiceData) (bool, error) {
goapp.Log.Info().Str("status", statusData.Status).Str("ID", wd.ID).Msg("status")
err := data.MsgSender.SendMessage(ctx, &messages.StatusMessage{
QueueMessage: amessages.QueueMessage{ID: wd.ID},
Status: statusData.Status,
Error: statusData.Error,
Progress: statusData.Progress,
ErrorCode: statusData.ErrorCode,
AudioReady: statusData.AudioReady,
AvailableResults: statusData.AvResults,
RecognizedText: statusData.RecognizedText,
ExternalID: wd.ExternalID,
Transcriber: utils.FromSQLStr(wd.Transcriber),
}, messages.DefaultOpts(wrkOtherQueuePrefix+":"+wrkStatusQueue))
if err != nil {
return false, fmt.Errorf("can't send msg: %w", err)
}
return isCompleted(statusData.Status, statusData.Error), nil
}
func upload(ctx context.Context, req *persistence.ReqData, transcriber tapi.Transcriber, data *ServiceData) (string, error) {
fileLoadFunc := func(ctxInt context.Context) (*tapi.UploadData, func(), error) {
goapp.Log.Info().Str("ID", req.ID).Msg("get files")
filesMap := map[string]io.Reader{}
files := []io.ReadCloser{}
closeFunc := func() {
for _, r := range files {
_ = r.Close()
}
}
for _, f := range req.FileNames {
file, err := data.Filer.LoadFile(ctxInt, utils.MakeFileName(req.ID, f))
if err != nil {
closeFunc()
return nil, nil, fmt.Errorf("can't load file: %w", err)
}
files = append(files, file)
filesMap[f] = file
goapp.Log.Info().Str("ID", req.ID).Msg("loaded")
}
return &tapi.UploadData{Params: prepareParams(req.Params), Files: filesMap}, closeFunc, nil
}
goapp.Log.Info().Str("ID", req.ID).Msg("uploading")
extID, err := transcriber.Upload(ctx, fileLoadFunc)
if err != nil {
return "", &errTranscriber{err: fmt.Errorf("can't upload: %w", err)}
}
return extID, nil
}
// prepareParams drops email
func prepareParams(in map[string]string) map[string]string {
res := map[string]string{}
for k, v := range in {
if k != api.PrmEmail {
res[k] = v
}
}
return res
}
func validate(data *ServiceData) error {
if data.GueClient == nil {
return fmt.Errorf("no gue client")
}
if data.WorkerCount < 1 {
return fmt.Errorf("no worker count provided")
}
if data.WorkerOtherCount < 1 {
return fmt.Errorf("no worker other count provided")
}
if data.MsgSender == nil {
return fmt.Errorf("no msg sender")
}
if data.Filer == nil {
return fmt.Errorf("no Filer")
}
if data.DB == nil {
return fmt.Errorf("no DB")
}
if data.TranscriberPr == nil {
return fmt.Errorf("no TranscriberProvider")
}
if data.UsageRestorer == nil {
return fmt.Errorf("no UsageRestorer")
}
return nil
}