forked from yutopp/go-rtmp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transactions.go
85 lines (67 loc) · 1.81 KB
/
transactions.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
//
// Copyright (c) 2018- yutopp (yutopp@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//
package rtmp
import (
"bytes"
"io"
"sync"
"github.com/pkg/errors"
"github.com/yutopp/go-rtmp/message"
)
type transaction struct {
commandName string
encoding message.EncodingType
body *bytes.Buffer
lastErr error
doneCh chan struct{}
}
func (t *transaction) Reply(commandName string, encoding message.EncodingType, body io.Reader) {
t.commandName = commandName
t.encoding = encoding
t.body = new(bytes.Buffer)
_, err := io.Copy(t.body, body)
t.lastErr = err
close(t.doneCh)
}
type transactions struct {
transactions map[int64]*transaction
m sync.RWMutex
}
func newTransactions() *transactions {
return &transactions{
transactions: make(map[int64]*transaction),
}
}
func (ts *transactions) Create(transactionID int64) (*transaction, error) {
ts.m.Lock()
defer ts.m.Unlock()
_, ok := ts.transactions[transactionID]
if ok {
return nil, errors.Errorf("Transaction already exists: TransactionID = %d", transactionID)
}
ts.transactions[transactionID] = &transaction{
doneCh: make(chan struct{}),
}
return ts.transactions[transactionID], nil
}
func (ts *transactions) Delete(transactionID int64) error {
ts.m.Lock()
defer ts.m.Unlock()
_, ok := ts.transactions[transactionID]
if !ok {
return errors.Errorf("Transaction not exists: TransactionID = %d", transactionID)
}
delete(ts.transactions, transactionID)
return nil
}
func (ts *transactions) At(transactionID int64) (*transaction, error) {
t, ok := ts.transactions[transactionID]
if !ok {
return nil, errors.Errorf("Transaction is not found: TransactionID = %d", transactionID)
}
return t, nil
}