github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+incompatible/private/constellation/constellation.go (about) 1 package constellation 2 3 import ( 4 "fmt" 5 "github.com/patrickmn/go-cache" 6 "os" 7 "path/filepath" 8 "time" 9 ) 10 11 type Constellation struct { 12 node *Client 13 c *cache.Cache 14 } 15 16 func (g *Constellation) Send(data []byte, from string, to []string) (out []byte, err error) { 17 out, err = g.node.SendPayload(data, from, to) 18 if err != nil { 19 return nil, err 20 } 21 g.c.Set(string(out), data, cache.DefaultExpiration) 22 return out, nil 23 } 24 25 func (g *Constellation) Receive(data []byte) ([]byte, error) { 26 if len(data) == 0 { 27 return data, nil 28 } 29 // Ignore this error since not being a recipient of 30 // a payload isn't an error. 31 // TODO: Return an error if it's anything OTHER than 32 // 'you are not a recipient.' 33 dataStr := string(data) 34 x, found := g.c.Get(dataStr) 35 if found { 36 return x.([]byte), nil 37 } 38 pl, _ := g.node.ReceivePayload(data) 39 g.c.Set(dataStr, pl, cache.DefaultExpiration) 40 return pl, nil 41 } 42 43 func New(path string) (*Constellation, error) { 44 info, err := os.Lstat(path) 45 if err != nil { 46 return nil, err 47 } 48 // We accept either the socket or a configuration file that points to 49 // a socket. 50 isSocket := info.Mode() & os.ModeSocket != 0 51 if !isSocket { 52 cfg, err := LoadConfig(path) 53 if err != nil { 54 return nil, err 55 } 56 path = filepath.Join(cfg.WorkDir, cfg.Socket) 57 } 58 err = RunNode(path) 59 if err != nil { 60 return nil, err 61 } 62 n, err := NewClient(path) 63 if err != nil { 64 return nil, err 65 } 66 return &Constellation{ 67 node: n, 68 c: cache.New(5*time.Minute, 5*time.Minute), 69 }, nil 70 } 71 72 func MustNew(path string) *Constellation { 73 g, err := New(path) 74 if err != nil { 75 panic(fmt.Sprintf("MustNew: Failed to connect to Constellation (%s): %v", path, err)) 76 } 77 return g 78 } 79 80 func MaybeNew(path string) *Constellation { 81 if path == "" { 82 return nil 83 } 84 return MustNew(path) 85 }