├── .gitignore ├── LICENSE ├── README.md ├── cache.go ├── cache_test.go ├── config.go ├── example ├── README.md └── main.go ├── go.mod ├── go.sum ├── peer.go ├── server.go ├── util.go └── vegam.go /.gitignore: -------------------------------------------------------------------------------- 1 | example/main -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2018] [vegamcache Authors] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vegamcache 2 | vegamcache is a distributed in-memory cache built using gossip protocol for golang. 3 | 4 | # what is the difference between other distributed cache service? 5 | In vegamcache, network calls are not used for retriving data for each Get. Instead data will be replicated across the node using gossip in backgroud. 6 | 7 | Expired keys are removed on gossip instead of having a seperate GC. 8 | # seri why ? 9 | Go is fun. I learned lot of thing regarding distributed system and also I'm jobless. Looking for internship. If anyone interested, do ping me at rbalajis25@gmail.com 10 | 11 | # Drawback 12 | - Can be used only in golang 13 | - Consumes lot of main memory.(If you worring about memory, folks at google did a good job on group cache) 14 | 15 | # Need to be done 16 | - sharding the cache instead of storing it in a single hashmap 17 | - benchmarking against other cache service 18 | 19 | # Example 20 | 21 | ## Clustered Cache 22 | 23 | ```go 24 | vg, err := vegamcache.NewVegam(&vegamcache.VegamConfig{Port: 8087, 25 | PeerName: "00:00:00:00:00:01", 26 | Peers: []string{"remoteip1:port","remoteip2:port"}, 27 | Logger: log.New(ioutil.Discard, "", 0)}) 28 | vg.Start() 29 | defer vg.Stop() 30 | if err != nil { 31 | panic(err) 32 | } 33 | vg.Put("foo", "bar", time.Second*200) 34 | val, exist := vg.Get("foo") 35 | if exist { 36 | fmt.Println(val) 37 | } 38 | ``` 39 | 40 | ## Single Node Cache 41 | 42 | ```go 43 | vg := vegamcache.NewCache() 44 | vg.Put("foo", "bar", time.Second*200) 45 | val, exist := vg.Get("foo") 46 | if exist { 47 | fmt.Println(val) 48 | } 49 | ``` 50 | 51 | # Contribution 52 | 53 | Feel free to send PR. :) -------------------------------------------------------------------------------- /cache.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "bytes" 18 | "encoding/gob" 19 | "sync" 20 | "time" 21 | 22 | "github.com/weaveworks/mesh" 23 | ) 24 | 25 | type Value struct { 26 | Data interface{} 27 | LastWrite int64 28 | Expiry int64 29 | } 30 | type cache struct { 31 | sync.Mutex 32 | set map[string]Value 33 | } 34 | 35 | var _ mesh.GossipData = &cache{} 36 | 37 | type externalCache struct { 38 | cache *cache 39 | } 40 | 41 | func NewCache() *externalCache { 42 | return &externalCache{&cache{ 43 | set: make(map[string]Value), 44 | }} 45 | } 46 | 47 | func (ec *externalCache) Get(key string) (interface{}, bool) { 48 | return ec.cache.get(key) 49 | } 50 | 51 | func (ec *externalCache) Put(key string, val interface{}, ttl time.Duration) { 52 | var expiryTime int64 53 | if ttl == 0 { 54 | expiryTime = 0 55 | } else { 56 | expiryTime = time.Now().Add(ttl).UnixNano() 57 | } 58 | ec.cache.put(key, Value{ 59 | Data: val, 60 | Expiry: expiryTime, 61 | }) 62 | } 63 | func (c *cache) Encode() [][]byte { 64 | c.Lock() 65 | defer c.Unlock() 66 | var buf bytes.Buffer 67 | if err := gob.NewEncoder(&buf).Encode(c.set); err != nil { 68 | panic(err) 69 | } 70 | return [][]byte{buf.Bytes()} 71 | } 72 | 73 | func (c *cache) Merge(other mesh.GossipData) mesh.GossipData { 74 | return c.mergeComplete(other.(*cache).copy().set) 75 | } 76 | 77 | func (c *cache) mergeComplete(other map[string]Value) mesh.GossipData { 78 | c.Lock() 79 | defer c.Unlock() 80 | for k, v := range other { 81 | val, ok := c.set[k] 82 | if !ok { 83 | if v.Expiry < time.Now().UnixNano() { 84 | continue 85 | } 86 | c.set[k] = v 87 | } 88 | // checking existing expiry 89 | if val.Expiry < time.Now().UnixNano() { 90 | delete(c.set, k) 91 | } 92 | if val.LastWrite < v.LastWrite { 93 | c.set[k] = v 94 | continue 95 | } 96 | } 97 | return c 98 | } 99 | 100 | func (c *cache) mergeDelta(set map[string]Value) (delta mesh.GossipData) { 101 | for k, v := range set { 102 | val, ok := c.set[k] 103 | if ok && val.LastWrite > v.LastWrite { 104 | delete(set, k) 105 | continue 106 | } 107 | // expired value is not added 108 | if val.Expiry != 0 && val.Expiry < time.Now().UnixNano() { 109 | delete(set, k) 110 | continue 111 | } 112 | c.set[k] = v 113 | } 114 | return &cache{set: set} 115 | } 116 | 117 | func (c *cache) mergeRecived(set map[string]Value) (recived mesh.GossipData) { 118 | for k, v := range set { 119 | val, ok := c.set[k] 120 | if ok && val.LastWrite > v.LastWrite { 121 | delete(set, k) 122 | continue 123 | } 124 | // expired value is not added 125 | if val.Expiry != 0 && val.Expiry < time.Now().UnixNano() { 126 | delete(set, k) 127 | continue 128 | } 129 | c.set[k] = v 130 | } 131 | if len(set) == 0 { 132 | return nil 133 | } 134 | return &cache{set: set} 135 | } 136 | 137 | func (c *cache) copy() *cache { 138 | return &cache{ 139 | set: c.set, 140 | } 141 | } 142 | 143 | func (c *cache) get(key string) (interface{}, bool) { 144 | c.Lock() 145 | defer c.Unlock() 146 | if val, ok := c.set[key]; ok { 147 | if val.Expiry == 0 || val.Expiry > time.Now().UnixNano() { 148 | return val.Data, true 149 | } 150 | delete(c.set, key) 151 | return nil, false 152 | } 153 | return nil, false 154 | } 155 | 156 | func (c *cache) put(key string, val Value) { 157 | c.Lock() 158 | defer c.Unlock() 159 | c.set[key] = val 160 | } 161 | -------------------------------------------------------------------------------- /cache_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "testing" 18 | "time" 19 | ) 20 | 21 | func TestCache(t *testing.T) { 22 | c := &cache{ 23 | set: make(map[string]Value), 24 | } 25 | c.put("foo", Value{ 26 | Data: "bar", 27 | Expiry: time.Now().Add(5 * time.Second).UnixNano(), 28 | LastWrite: time.Now().UnixNano(), 29 | }) 30 | val, _ := c.get("foo") 31 | if val.(string) != "bar" { 32 | t.Fatalf("expected bar got %s", val) 33 | } 34 | } 35 | 36 | func TestExpiry(t *testing.T) { 37 | c := &cache{ 38 | set: make(map[string]Value), 39 | } 40 | c.put("foo", Value{ 41 | Data: "bar", 42 | Expiry: time.Now().Add(5 * time.Second).UnixNano(), 43 | LastWrite: time.Now().UnixNano(), 44 | }) 45 | time.Sleep(5 * time.Second) 46 | _, exist := c.get("foo") 47 | if exist { 48 | t.Fatalf("value has to be exipred after 5 seconds") 49 | } 50 | } 51 | 52 | func TestMerges(t *testing.T) { 53 | c := &cache{ 54 | set: make(map[string]Value), 55 | } 56 | c.put("foo", Value{ 57 | Data: "bar", 58 | Expiry: time.Now().Add(5 * time.Second).UnixNano(), 59 | LastWrite: time.Now().UnixNano(), 60 | }) 61 | completedData := c.mergeComplete(map[string]Value{"bar": Value{Data: "foo"}}) 62 | if len(completedData.(*cache).set) != 2 { 63 | t.Fatalf("merge complete has to give the entire data") 64 | } 65 | for _, val := range []string{"foo", "bar"} { 66 | _, ok := completedData.(*cache).set[val] 67 | if !ok { 68 | t.Fatalf("%s not exist in set", val) 69 | } 70 | } 71 | recivedData := c.mergeRecived(map[string]Value{"bar": Value{Data: "foo"}}) 72 | if len(recivedData.(*cache).set) != 1 { 73 | t.Fatalf("merge recived has to reture only recived data") 74 | } 75 | _, ok := recivedData.(*cache).set["bar"] 76 | if !ok { 77 | t.Fatal("bar not exist in set") 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "log" 18 | "math/rand" 19 | "os" 20 | 21 | "github.com/weaveworks/mesh" 22 | ) 23 | 24 | type VegamConfig struct { 25 | Port int 26 | Channel string 27 | Password string 28 | NickName string 29 | Peers []string 30 | PeerName string 31 | Host string 32 | Logger *log.Logger 33 | } 34 | 35 | func initConfig(config *VegamConfig) { 36 | if config.Port == 0 { 37 | config.Port = mesh.Port 38 | } 39 | if config.NickName == "" { 40 | name, err := os.Hostname() 41 | if err != nil { 42 | panic(err) 43 | } 44 | config.NickName = name + string(rand.Int()) 45 | } 46 | if config.Channel == "" { 47 | config.Channel = "default" 48 | } 49 | if config.PeerName == "" { 50 | config.PeerName = mustHardwareAddr() 51 | } 52 | if config.Host == "" { 53 | config.Host = "0.0.0.0" 54 | } 55 | if config.Logger == nil { 56 | config.Logger = log.New(os.Stdout, "", 0) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Example 2 | 3 | Complile the code 4 | 5 | ``` 6 | go build main.go 7 | ``` 8 | 9 | Run the Get 10 | 11 | ``` 12 | ./main 13 | ``` 14 | 15 | Run the Put 16 | 17 | ``` 18 | ./main --action false 19 | ``` -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "bytes" 18 | "flag" 19 | "fmt" 20 | "io/ioutil" 21 | "log" 22 | "net/http" 23 | "time" 24 | 25 | "github.com/balajijinnah/vegamcache" 26 | ) 27 | 28 | func main() { 29 | var get = flag.String("action", "true", "get or put") 30 | flag.Parse() 31 | if *get == "true" { 32 | fmt.Print("GET IS RUNNING") 33 | vg, _ := vegamcache.NewVegam(&vegamcache.VegamConfig{Port: 8087, 34 | PeerName: "00:00:00:00:00:01", 35 | Logger: log.New(ioutil.Discard, "", 0)}) 36 | vg.Start() 37 | ticker := time.NewTicker(500 * time.Millisecond) 38 | go func() { 39 | for _ = range ticker.C { 40 | val, exist := vg.Get("foo") 41 | if exist && val.(string) == "bar" { 42 | fmt.Println(val) 43 | fmt.Println("value got from another node") 44 | ticker.Stop() 45 | } else { 46 | fmt.Println(val) 47 | } 48 | } 49 | }() 50 | stop := make(chan int) 51 | <-stop 52 | } else { 53 | fmt.Print("PUT IS RUNNING") 54 | vg, _ := vegamcache.NewVegam(&vegamcache.VegamConfig{Port: 8082, 55 | PeerName: "00:00:00:00:00:02"}) 56 | vg.Start() 57 | vg.Put("foo", "bar", time.Second*200) 58 | fmt.Print(vg.Get("foo")) 59 | go vegamcache.ListenServer(vg, ":8000") 60 | req, _ := http.NewRequest("PATCH", "http://localhost:8000/update", bytes.NewBuffer( 61 | []byte(`{ 62 | "peers":[ 63 | "localhost:8087" 64 | ] 65 | }`), 66 | )) 67 | req.Header.Set("Content-Type", "application/json") 68 | client := &http.Client{} 69 | resp, err := client.Do(req) 70 | if err != nil { 71 | panic(err) 72 | } 73 | defer resp.Body.Close() 74 | 75 | fmt.Println("response Status:", resp.Status) 76 | fmt.Println("response Headers:", resp.Header) 77 | body, _ := ioutil.ReadAll(resp.Body) 78 | fmt.Println("response Body:", string(body)) 79 | stop := make(chan int) 80 | <-stop 81 | } 82 | // vg := vegamcache.NewCache() 83 | // vg.Put("foo", "bar", 5*time.Second) 84 | // val, _ := vg.Get("foo") 85 | // fmt.Print(val) 86 | } 87 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/balajijinnah/vegamcache 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/sch00lb0y/vegamcache v0.0.0-20190426101553-4a9a08cc9add // indirect 7 | github.com/weaveworks/mesh v0.0.0-20190731104741-b7aea39ecc40 8 | golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 // indirect 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/sch00lb0y/vegamcache v0.0.0-20190426101553-4a9a08cc9add h1:WM7cjvgYsc9BmOyAvLCCMMBse7GnTXL0YnE69FaPOyQ= 2 | github.com/sch00lb0y/vegamcache v0.0.0-20190426101553-4a9a08cc9add/go.mod h1:sx3Rpfh6zobCJtABSIeis9pebfklcTLXmMQAaLoCEK8= 3 | github.com/weaveworks/mesh v0.0.0-20190731104741-b7aea39ecc40 h1:X5iIHn9gFl99AU3CCn511jrFftQJm8M1jngS3YOVr3o= 4 | github.com/weaveworks/mesh v0.0.0-20190731104741-b7aea39ecc40/go.mod h1:mcON9Ws1aW0crSErpXWp7U1ErCDEKliDX2OhVlbWRKk= 5 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 6 | golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc= 7 | golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 8 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 9 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 10 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 11 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 12 | -------------------------------------------------------------------------------- /peer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "github.com/weaveworks/mesh" 18 | ) 19 | 20 | type peer struct { 21 | cache *cache 22 | } 23 | 24 | var _ mesh.Gossiper = &peer{} 25 | 26 | func (p *peer) Gossip() (complete mesh.GossipData) { 27 | return p.cache.copy() 28 | } 29 | 30 | func (p *peer) OnGossip(buf []byte) (delta mesh.GossipData, err error) { 31 | set, err := decodeSet(buf) 32 | if err != nil { 33 | return nil, err 34 | } 35 | return p.cache.mergeDelta(set), nil 36 | } 37 | 38 | func (p *peer) OnGossipBroadcast(src mesh.PeerName, buf []byte) (recived mesh.GossipData, err error) { 39 | set, err := decodeSet(buf) 40 | if err != nil { 41 | return nil, err 42 | } 43 | return p.cache.mergeRecived(set), nil 44 | } 45 | 46 | func (p *peer) OnGossipUnicast(src mesh.PeerName, buf []byte) error { 47 | set, err := decodeSet(buf) 48 | if err != nil { 49 | return err 50 | } 51 | p.cache.mergeComplete(set) 52 | return nil 53 | } 54 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "encoding/json" 18 | "net/http" 19 | ) 20 | 21 | type UpdateRequest struct { 22 | Peers []string `json:"peers"` 23 | } 24 | 25 | type UpdateResponse struct { 26 | Updated bool `json:"updated"` 27 | ErrorDescription string `json:"error_description"` 28 | } 29 | 30 | func marshal(data interface{}) []byte { 31 | marshaledData, err := json.Marshal(data) 32 | if err != nil { 33 | panic(err) 34 | } 35 | return marshaledData 36 | } 37 | func updateHandler(v *Vegam) func(w http.ResponseWriter, r *http.Request) { 38 | return func(w http.ResponseWriter, r *http.Request) { 39 | var peers UpdateRequest 40 | defer r.Body.Close() 41 | if r.Method != "PATCH" { 42 | w.WriteHeader(http.StatusBadRequest) 43 | w.Write(marshal(UpdateResponse{ 44 | Updated: false, 45 | ErrorDescription: "http method not allowed", 46 | })) 47 | return 48 | } 49 | decoder := json.NewDecoder(r.Body) 50 | err := decoder.Decode(&peers) 51 | if err != nil { 52 | w.WriteHeader(http.StatusInternalServerError) 53 | w.Write(marshal(UpdateResponse{ 54 | Updated: false, 55 | ErrorDescription: err.Error(), 56 | })) 57 | return 58 | } 59 | v.router.ConnectionMaker.InitiateConnections(peers.Peers, true) 60 | w.Write(marshal(UpdateResponse{ 61 | Updated: true, 62 | })) 63 | } 64 | 65 | } 66 | func ListenServer(v *Vegam, port string) error { 67 | http.HandleFunc("/update", updateHandler(v)) 68 | return http.ListenAndServe(port, nil) 69 | } 70 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "bytes" 18 | "encoding/gob" 19 | "net" 20 | ) 21 | 22 | func mustHardwareAddr() string { 23 | ifaces, err := net.Interfaces() 24 | if err != nil { 25 | panic(err) 26 | } 27 | for _, iface := range ifaces { 28 | if s := iface.HardwareAddr.String(); s != "" { 29 | return s 30 | } 31 | } 32 | panic("no valid network interfaces") 33 | } 34 | 35 | func decodeSet(buf []byte) (map[string]Value, error) { 36 | var set map[string]Value 37 | if err := gob.NewDecoder(bytes.NewReader(buf)).Decode(&set); err != nil { 38 | return nil, err 39 | } 40 | return set, nil 41 | } 42 | -------------------------------------------------------------------------------- /vegam.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2018 The vegamcache Authors. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package vegamcache 15 | 16 | import ( 17 | "net" 18 | "time" 19 | 20 | "github.com/weaveworks/mesh" 21 | ) 22 | 23 | type Vegam struct { 24 | gossip mesh.Gossip 25 | peer *peer 26 | router *mesh.Router 27 | actions chan<- func() 28 | peers []string 29 | stop chan int 30 | } 31 | 32 | func NewVegam(vc *VegamConfig) (*Vegam, error) { 33 | initConfig(vc) 34 | peername, err := mesh.PeerNameFromString(vc.PeerName) 35 | if err != nil { 36 | return nil, err 37 | } 38 | router, err := mesh.NewRouter( 39 | mesh.Config{ 40 | Port: vc.Port, 41 | ProtocolMinVersion: mesh.ProtocolMinVersion, 42 | Password: []byte(vc.Password), 43 | Host: vc.Host, 44 | PeerDiscovery: true, 45 | TrustedSubnets: []*net.IPNet{}, 46 | }, 47 | peername, 48 | vc.NickName, 49 | mesh.NullOverlay{}, 50 | vc.Logger, 51 | ) 52 | if err != nil { 53 | return nil, err 54 | } 55 | peer := &peer{ 56 | cache: &cache{ 57 | set: make(map[string]Value), 58 | }, 59 | } 60 | gossip, err := router.NewGossip(vc.Channel, peer) 61 | if err != nil { 62 | return nil, err 63 | } 64 | return &Vegam{ 65 | gossip: gossip, 66 | peer: peer, 67 | router: router, 68 | peers: vc.Peers, 69 | stop: make(chan int), 70 | }, nil 71 | } 72 | 73 | func (v *Vegam) Start() { 74 | actions := make(chan func()) 75 | v.actions = actions 76 | v.router.Start() 77 | v.router.ConnectionMaker.InitiateConnections(v.peers, true) 78 | go v.loop(actions) 79 | } 80 | 81 | func (v *Vegam) loop(actions <-chan func()) { 82 | for { 83 | select { 84 | case f := <-actions: 85 | f() 86 | case <-v.stop: 87 | return 88 | } 89 | } 90 | } 91 | 92 | func (v *Vegam) Stop() { 93 | v.stop <- 1 94 | v.router.Stop() 95 | } 96 | 97 | func (v *Vegam) Get(key string) (val interface{}, exist bool) { 98 | val, exist = v.peer.cache.get(key) 99 | return 100 | } 101 | 102 | func (v *Vegam) Put(key string, val interface{}, expiry time.Duration) { 103 | var expiryTime int64 104 | if expiry == 0 { 105 | expiryTime = 0 106 | } else { 107 | expiryTime = time.Now().Add(expiry).UnixNano() 108 | } 109 | tempVal := Value{ 110 | Data: val, 111 | LastWrite: time.Now().UnixNano(), 112 | Expiry: expiryTime, 113 | } 114 | v.peer.cache.put(key, tempVal) 115 | tempCache := &cache{ 116 | set: make(map[string]Value), 117 | } 118 | tempCache.set[key] = tempVal 119 | v.actions <- func() { 120 | v.gossip.GossipBroadcast(tempCache) 121 | } 122 | } 123 | --------------------------------------------------------------------------------