summaryrefslogtreecommitdiff
path: root/src/globster/hub/hub.go
blob: 5bf7f793fa76917fd84888f503c68c68c495b500 (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
package hub

import (
	"globster/adc"
	"go.blicky.net/tanja"
	"net"
	"time"
)

// TODO: Do the connect() and write()s in a separate goroutine.

type hub struct {
	name string
	ses  *tanja.Session
	conn net.Conn
}

func newHub(node *tanja.Node, name string) *hub {
	s := &hub{name: name, ses: node.Session()}

	s.ses.RegRPC(s, func(s string) tanja.Tuple {
		if s[0] != 'T' {
			return nil
		}
		return tanja.Tup("hub", name, s[1:])
	})

	s.ses.Send(false, "hub", name, "Created")
	go s.ses.Run()
	return s
}

func (s *hub) Texists(m *tanja.Message) {
	m.Reply(s.name)
	m.Close()
}

func (s *hub) Tconnect(addr string) {
	if s.conn != nil {
		return
	}
	var e error
	s.conn, e = net.DialTimeout("tcp", addr, 30*time.Second)
	if e != nil {
		s.ses.Send(false, "hub", s.name, "Disconnected", e.Error())
	} else {
		s.ses.Send(false, "hub", s.name, "Connected", s.conn.RemoteAddr().String())
		adc.NewWriter(s.conn).Write(&adc.Message{Header: adc.SUP.SetType('I')})
	}
}

func (s *hub) Tdisconnect(m *tanja.Message, r ...tanja.Element) {
	if s.conn != nil {
		s.conn.Close()
		s.conn = nil
		s.ses.Sendt(false, append(tanja.Tup("hub", s.name, "Disconnected"), r...))
	}
	// Only close the return-path after disconnect, to allow users to wait for
	// successful disconnect.
	m.Close()
}

func (s *hub) close() {
	r := s.ses.Send(true, "hub", s.name, "disconnect")
	<-r.Chan()
	r.Close()

	s.ses.Close()
	s.ses.Send(false, "hub", s.name, "Closed")
}