util.go 1.8 KB
Newer Older
1
2
3
4
5
package main

import (
	"log"
	"time"
6
7

	"github.com/keroserene/go-webrtc"
8
9
)

Serene Han's avatar
Serene Han committed
10
11
12
13
const (
	LogTimeInterval = 5
)

14
type IceServerList []webrtc.ConfigurationOption
15
16
17
18
19

func (i *IceServerList) String() string {
	return fmt.Sprint(*i)
}

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
type BytesLogger interface {
	Log()
	AddOutbound(int)
	AddInbound(int)
}

// Default BytesLogger does nothing.
type BytesNullLogger struct{}

func (b BytesNullLogger) Log()                   {}
func (b BytesNullLogger) AddOutbound(amount int) {}
func (b BytesNullLogger) AddInbound(amount int)  {}

// BytesSyncLogger uses channels to safely log from multiple sources with output
// occuring at reasonable intervals.
type BytesSyncLogger struct {
36
37
38
39
40
41
42
43
44
	outboundChan chan int
	inboundChan  chan int
	outbound     int
	inbound      int
	outEvents    int
	inEvents     int
	isLogging    bool
}

45
func (b *BytesSyncLogger) Log() {
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
	b.isLogging = true
	var amount int
	output := func() {
		log.Printf("Traffic Bytes (in|out): %d | %d -- (%d OnMessages, %d Sends)",
			b.inbound, b.outbound, b.inEvents, b.outEvents)
		b.outbound = 0
		b.outEvents = 0
		b.inbound = 0
		b.inEvents = 0
	}
	last := time.Now()
	for {
		select {
		case amount = <-b.outboundChan:
			b.outbound += amount
			b.outEvents++
			last := time.Now()
Serene Han's avatar
Serene Han committed
63
			if time.Since(last) > time.Second*LogTimeInterval {
64
65
66
67
68
69
				last = time.Now()
				output()
			}
		case amount = <-b.inboundChan:
			b.inbound += amount
			b.inEvents++
Serene Han's avatar
Serene Han committed
70
			if time.Since(last) > time.Second*LogTimeInterval {
71
72
73
				last = time.Now()
				output()
			}
Serene Han's avatar
Serene Han committed
74
		case <-time.After(time.Second * LogTimeInterval):
75
76
77
78
79
80
81
			if b.inEvents > 0 || b.outEvents > 0 {
				output()
			}
		}
	}
}

82
func (b *BytesSyncLogger) AddOutbound(amount int) {
83
84
85
86
87
88
	if !b.isLogging {
		return
	}
	b.outboundChan <- amount
}

89
func (b *BytesSyncLogger) AddInbound(amount int) {
90
91
92
93
94
	if !b.isLogging {
		return
	}
	b.inboundChan <- amount
}