summaryrefslogtreecommitdiff
path: root/node.go
blob: 15a60f5edc05fffe71fad487669f975bb1b0d0b6 (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
package tanja

import (
	. "sync"
)

type Node struct {
	lock   Mutex
	lastId int32
	regs   map[int32]*Registration
	links  map[*Link]bool
}

func NewNode() *Node {
	return &Node{regs: make(map[int32]*Registration), links: make(map[*Link]bool), lastId: 1}
}

func (n *Node) unregOne(r *Registration) {
	for l := range n.links {
		l.nodeUnreg(r.id)
	}

	r.active = false
	r.unreg()
	delete(n.regs, r.id)
}

func (n *Node) unregMatch(f func(r *Registration) bool) {
	for _, r := range n.regs {
		if f(r) {
			n.unregOne(r)
		}
	}
}

func (n *Node) reg(r *Registration) {
	old := n.lastId
	for old == n.lastId || n.regs[n.lastId] != nil {
		n.lastId++
		if n.lastId < 0 {
			n.lastId = 1
		}
	}
	r.id = n.lastId
	n.regs[n.lastId] = r
	r.active = true

	for l := range n.links {
		l.nodeReg(r)
	}
}

func (n *Node) send(t Tuple, path *ReturnPath, ign interface{}) {
	// TODO: Some way of preventing that a message is routed back to the link
	// it came from.
	for _, r := range n.regs {
		if ign != r.recv && t.Match(r.pat) {
			var p *ReturnPath
			if r.willReply {
				p = path
				p.ref()
			}
			// Pass a reference to the Tuple to allow duplicate detection.
			r.send(&t, p)
		}
	}

	// Make sure to send path closed notification if there's nobody to reply.
	path.ref()
	path.unref()
}