├── .gitignore ├── test ├── go.mod ├── stressTest.go └── rpc_client.go ├── go.work ├── original.png ├── cluster ├── nodes.json ├── manager │ ├── node_service.go │ └── manager.go └── main.go ├── data └── README.md ├── logs └── README.md ├── go.mod ├── cli ├── go.mod ├── go.sum └── main.go ├── config ├── config.json └── conf.go ├── server ├── db │ ├── heap.go │ ├── benchmark_test.go │ └── store.go ├── rpc │ └── rpc.go └── http │ └── handler.go ├── go.sum ├── utils └── logger │ └── logger.go ├── docs ├── swagger.yaml └── index.html ├── main.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | data/* 2 | 3 | logs/* -------------------------------------------------------------------------------- /test/go.mod: -------------------------------------------------------------------------------- 1 | module test 2 | 3 | go 1.23 4 | -------------------------------------------------------------------------------- /go.work: -------------------------------------------------------------------------------- 1 | go 1.23 2 | 3 | use ( 4 | . 5 | ./cli 6 | ) 7 | -------------------------------------------------------------------------------- /original.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shafigh75/Memorandum/HEAD/original.png -------------------------------------------------------------------------------- /cluster/nodes.json: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": [ 3 | "127.0.0.1:1234", 4 | "1.1.1.1:1234", 5 | "2.2.2.2:1234" 6 | ] 7 | } -------------------------------------------------------------------------------- /data/README.md: -------------------------------------------------------------------------------- 1 | ### data 2 | this directory is meant to store the WAL logs. if you don't want to use it you can change the WAL_path variable in config file. 3 | -------------------------------------------------------------------------------- /logs/README.md: -------------------------------------------------------------------------------- 1 | ### LOGS 2 | there are two types of app-level logs that are generated here: 3 | 1. http.log: HTTP server logs which are generated from user requests on HTTP port 4 | 2. rpc.log: RPC logs which are generated from CLI 5 | 6 | **NOTE**: you can change the files path from config file using http_log_path and rpc_log_path variables. 7 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/shafigh75/Memorandum 2 | 3 | go 1.23 4 | 5 | require ( 6 | github.com/chzyer/readline v1.5.1 7 | github.com/spf13/cobra v1.8.1 8 | ) 9 | 10 | require ( 11 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 12 | github.com/spf13/pflag v1.0.5 // indirect 13 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect 14 | ) 15 | -------------------------------------------------------------------------------- /cli/go.mod: -------------------------------------------------------------------------------- 1 | module cli 2 | 3 | go 1.23 4 | 5 | require ( 6 | github.com/chzyer/readline v1.5.1 7 | github.com/shafigh75/Memorandum v0.0.0-20241230052948-4fff8fba6d64 8 | github.com/spf13/cobra v1.8.1 9 | ) 10 | 11 | require ( 12 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 13 | github.com/spf13/pflag v1.0.5 // indirect 14 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /config/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "http_port": ":6060", 3 | "rpc_port": ":1234", 4 | "cluster_port": ":5036", 5 | "WAL_path": "/home/test/Memorandum/data/wal.bin", 6 | "http_log_path": "/home/test/Memorandum/logs/http.log", 7 | "rpc_log_path": "/home/test/Memorandum/logs/rpc.log", 8 | "WAL_bufferSize": 4096, 9 | "WAL_flushInterval": 30, 10 | "cleanup_interval": 10, 11 | "heartbeat_interval": 10, 12 | "configCheck_interval": 10, 13 | "auth_enabled": true, 14 | "wal_enabled": true, 15 | "cluster_enabled": true, 16 | "shard_count": 32, 17 | "replica_count": 0, 18 | "auth_token": "f5e0c51b7f3c6e6b57deb13b3017c32e" 19 | } -------------------------------------------------------------------------------- /server/db/heap.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import "container/heap" 4 | 5 | // A MinHeap is a min-heap of ValueWithTTL items. 6 | type MinHeap []heapEntry 7 | 8 | type heapEntry struct { 9 | key string 10 | valueWithTTL ValueWithTTL 11 | index int // Index of the item in the heap. 12 | } 13 | 14 | func (h MinHeap) Len() int { return len(h) } 15 | func (h MinHeap) Less(i, j int) bool { 16 | return h[i].valueWithTTL.Expiration < h[j].valueWithTTL.Expiration 17 | } 18 | func (h MinHeap) Swap(i, j int) { 19 | h[i], h[j] = h[j], h[i] 20 | h[i].index = i 21 | h[j].index = j 22 | } 23 | 24 | func (h *MinHeap) Push(x interface{}) { 25 | n := len(*h) 26 | item := x.(heapEntry) 27 | item.index = n 28 | *h = append(*h, item) 29 | } 30 | 31 | func (h *MinHeap) Pop() interface{} { 32 | old := *h 33 | n := len(old) 34 | item := old[n-1] 35 | old[n-1] = heapEntry{} // Avoid memory leak 36 | item.index = -1 // For safety 37 | *h = old[0 : n-1] 38 | return item 39 | } 40 | 41 | func (h *MinHeap) RemoveByKey(key string) { 42 | for i, entry := range *h { 43 | if entry.key == key { 44 | // Remove the entry from the heap 45 | heap.Remove(h, i) 46 | break 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /server/db/benchmark_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func setupBenchmarkStore() *ShardedInMemoryStore { 9 | store, err := LoadConfigAndCreateStore("../../config/config.json") 10 | if err != nil { 11 | panic("ERROR starting the benchmark" + err.Error()) 12 | } 13 | return store 14 | } 15 | 16 | func BenchmarkSet(b *testing.B) { 17 | store := setupBenchmarkStore() 18 | defer store.Close() 19 | 20 | b.ResetTimer() 21 | for i := 0; i < b.N; i++ { 22 | key := fmt.Sprintf("key%d", i) 23 | value := fmt.Sprintf("value%d", i) 24 | store.Set(key, value, 30) 25 | } 26 | } 27 | 28 | func BenchmarkGet(b *testing.B) { 29 | store := setupBenchmarkStore() 30 | defer store.Close() 31 | 32 | // Prepopulate store with data 33 | for i := 0; i < 10000; i++ { 34 | key := fmt.Sprintf("key%d", i) 35 | value := fmt.Sprintf("value%d", i) 36 | store.Set(key, value, 30) 37 | } 38 | 39 | b.ResetTimer() 40 | for i := 0; i < b.N; i++ { 41 | key := fmt.Sprintf("key%d", i%10000) 42 | store.Get(key) 43 | } 44 | } 45 | 46 | func BenchmarkDelete(b *testing.B) { 47 | store := setupBenchmarkStore() 48 | defer store.Close() 49 | 50 | // Prepopulate store with data 51 | for i := 0; i < 10000; i++ { 52 | key := fmt.Sprintf("key%d", i) 53 | value := fmt.Sprintf("value%d", i) 54 | store.Set(key, value, 30) 55 | } 56 | 57 | b.ResetTimer() 58 | for i := 0; i < b.N; i++ { 59 | key := fmt.Sprintf("key%d", i%10000) 60 | store.Delete(key) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= 2 | github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= 3 | github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= 4 | github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= 5 | github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= 6 | github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= 7 | github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 8 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 9 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 10 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 11 | github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= 12 | github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= 13 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 14 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 15 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 h1:y/woIyUBFbpQGKS0u1aHF/40WUDnek3fPOyD08H5Vng= 16 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 17 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 18 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 19 | -------------------------------------------------------------------------------- /utils/logger/logger.go: -------------------------------------------------------------------------------- 1 | package logger 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | "time" 8 | ) 9 | 10 | // LogEntry represents a single log entry. 11 | type LogEntry struct { 12 | Timestamp string `json:"timestamp"` 13 | Message string `json:"message"` 14 | } 15 | 16 | // Logger is a custom logger that writes logs to both the terminal and a JSON file. 17 | type Logger struct { 18 | filePath string 19 | file *os.File 20 | } 21 | 22 | // NewLogger creates a new Logger instance. 23 | func NewLogger(filePath string) (*Logger, error) { 24 | file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 25 | if err != nil { 26 | return nil, err 27 | } 28 | 29 | return &Logger{ 30 | filePath: filePath, 31 | file: file, 32 | }, nil 33 | } 34 | 35 | // Log logs a message or error to the terminal and the JSON file. 36 | func (l *Logger) Log(message interface{}) { 37 | // Create a log entry 38 | entry := LogEntry{ 39 | Timestamp: time.Now().Format(time.RFC3339), 40 | Message: fmt.Sprintf("%v", message), 41 | } 42 | 43 | // Print to terminal 44 | fmt.Printf("[%s] : %s\n", entry.Timestamp, entry.Message) 45 | 46 | // Write to JSON file 47 | if err := l.writeJSONLog(entry); err != nil { 48 | fmt.Printf("Error writing to log file: %v\n", err) 49 | } 50 | } 51 | 52 | // writeJSONLog writes a log entry to the JSON file. 53 | func (l *Logger) writeJSONLog(entry LogEntry) error { 54 | encoder := json.NewEncoder(l.file) 55 | encoder.SetIndent("", " ") // Pretty print 56 | if err := encoder.Encode(entry); err != nil { 57 | return err 58 | } 59 | return nil 60 | } 61 | 62 | // Close closes the log file. 63 | func (l *Logger) Close() { 64 | if l.file != nil { 65 | l.file.Close() 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /cli/go.sum: -------------------------------------------------------------------------------- 1 | github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= 2 | github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= 3 | github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= 4 | github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= 5 | github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= 6 | github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= 7 | github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 8 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 9 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 10 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 11 | github.com/shafigh75/Memorandum v0.0.0-20241230052948-4fff8fba6d64 h1:iyZbgnLJSqzjnzgxRtcIyA8jEMwF9jb11OWP+Ai3O60= 12 | github.com/shafigh75/Memorandum v0.0.0-20241230052948-4fff8fba6d64/go.mod h1:m17TFgZPptu0coGhY5lGpuWju2LZ3nGyW8OH3QrET+8= 13 | github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= 14 | github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= 15 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 16 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 17 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5 h1:y/woIyUBFbpQGKS0u1aHF/40WUDnek3fPOyD08H5Vng= 18 | golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 19 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 20 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 21 | -------------------------------------------------------------------------------- /config/conf.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os" 7 | ) 8 | 9 | // Config holds the configuration settings. 10 | type Config struct { 11 | HTTPPort string `json:"http_port"` // port for http 12 | RPCPort string `json:"rpc_port"` // port for rpc 13 | ClusterPort string `json:"cluster_port"` // port for clustreing 14 | CleanupInterval int64 `json:"cleanup_interval"` // memory cleanup interval in seconds 15 | HeartbeatInterval int64 `json:"heartbeat_interval"` // check nodes health interval in seconds 16 | ConfigCheckInterval int64 `json:"configCheck_interval"` // interval to re-add nodes in seconds 17 | AuthEnabled bool `json:"auth_enabled"` // set to true to enable auth 18 | AuthToken string `json:"auth_token"` // Token for authentication 19 | WalPath string `json:"WAL_path"` // path for wal.bin file 20 | HttpLogPath string `json:"http_log_path"` // http log file path 21 | RPCLogPath string `json:"rpc_log_path"` // rpc log file path 22 | WalBufferSize int `json:"WAL_bufferSize"` // buffer size for each wal flush 23 | WalEnabled bool `json:"wal_enabled"` // turn wal logging on or off 24 | ClusterEnabled bool `json:"cluster_enabled"` // turn wal logging on or off 25 | WalFlushInterval int `json:"WAL_flushInterval"` // wal flush interval in seconds 26 | NumShards int `json:"shard_count"` // number of node shards 27 | ReplicaCount int `json:"replica_count"` // number of nodes to replicate our data 28 | } 29 | 30 | // LoadConfig reads the configuration from a JSON file. 31 | func LoadConfig(filePath string) (*Config, error) { 32 | file, err := os.Open(filePath) 33 | if err != nil { 34 | return nil, err 35 | } 36 | defer file.Close() 37 | 38 | byteValue, _ := ioutil.ReadAll(file) 39 | var config Config 40 | if err := json.Unmarshal(byteValue, &config); err != nil { 41 | return nil, err 42 | } 43 | return &config, nil 44 | } 45 | -------------------------------------------------------------------------------- /test/stressTest.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "net/http" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | const ( 13 | baseURL = "http://localhost:6060" 14 | numKeys = 50000 // Number of keys to set 15 | numGoroutines = 100 // Number of concurrent goroutines 16 | ) 17 | 18 | func setKey(key int, wg *sync.WaitGroup) { 19 | defer wg.Done() 20 | value := fmt.Sprintf("value-%d", key) 21 | ttl := 10 // TTL in seconds 22 | 23 | reqBody, _ := json.Marshal(map[string]interface{}{ 24 | "key": fmt.Sprintf("key-%d", key), 25 | "value": value, 26 | "ttl": ttl, 27 | }) 28 | 29 | _, err := http.Post(baseURL+"/set", "application/json", bytes.NewBuffer(reqBody)) 30 | if err != nil { 31 | fmt.Printf("Error setting key: %v\n", err) 32 | } 33 | } 34 | 35 | func getKey(key int, wg *sync.WaitGroup) { 36 | defer wg.Done() 37 | resp, err := http.Get(fmt.Sprintf("%s/get?key=key-%d", baseURL, key)) 38 | if err != nil { 39 | fmt.Printf("Error getting key: %v\n", err) 40 | return 41 | } 42 | defer resp.Body.Close() 43 | } 44 | 45 | func deleteKey(key int, wg *sync.WaitGroup) { 46 | defer wg.Done() 47 | req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/delete?key=key-%d", baseURL, key), nil) 48 | if err != nil { 49 | fmt.Printf("Error creating delete request: %v\n", err) 50 | return 51 | } 52 | _, err = http.DefaultClient.Do(req) 53 | if err != nil { 54 | fmt.Printf("Error deleting key: %v\n", err) 55 | } 56 | } 57 | 58 | func main() { 59 | var wg sync.WaitGroup 60 | 61 | // Set keys 62 | start := time.Now() 63 | for i := 0; i < numKeys; i++ { 64 | wg.Add(1) 65 | go setKey(i, &wg) 66 | } 67 | wg.Wait() 68 | fmt.Printf("Set %d keys in %v\n", numKeys, time.Since(start)) 69 | 70 | // Get keys 71 | start = time.Now() 72 | for i := 0; i < numKeys; i++ { 73 | wg.Add(1) 74 | go getKey(i, &wg) 75 | } 76 | wg.Wait() 77 | fmt.Printf("Got %d keys in %v\n", numKeys, time.Since(start)) 78 | 79 | // Delete keys 80 | start = time.Now() 81 | for i := 0; i < numKeys; i++ { 82 | wg.Add(1) 83 | go deleteKey(i, &wg) 84 | } 85 | wg.Wait() 86 | fmt.Printf("Deleted %d keys in %v\n", numKeys, time.Since(start)) 87 | } 88 | -------------------------------------------------------------------------------- /test/rpc_client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/rpc" 6 | ) 7 | 8 | // RPCRequest and RPCResponse structures 9 | type RPCRequest struct { 10 | Key string `json:"key"` 11 | Value string `json:"value,omitempty"` 12 | TTL int64 `json:"ttl"` // TTL in seconds 13 | } 14 | 15 | type RPCResponse struct { 16 | Success bool `json:"success"` 17 | Data string `json:"data,omitempty"` 18 | Error string `json:"error,omitempty"` 19 | } 20 | 21 | func main() { 22 | // Connect to the RPC server 23 | client, err := rpc.Dial("tcp", "localhost:1234") 24 | if err != nil { 25 | fmt.Println("Error connecting to RPC server:", err) 26 | return 27 | } 28 | defer client.Close() 29 | 30 | // Example: Set a key 31 | setReq := RPCRequest{Key: "exampleKey", Value: "exampleValue", TTL: 60} 32 | var setResp RPCResponse 33 | err = client.Call("RPCService.RPCSet", &setReq, &setResp) 34 | if err != nil { 35 | fmt.Println("Error calling RPCSet:", err) 36 | return 37 | } 38 | fmt.Println("Set Response:", setResp) 39 | 40 | // Example: Get the key 41 | getReq := RPCRequest{Key: "exampleKey"} 42 | var getResp RPCResponse 43 | err = client.Call("RPCService.RPCGet", &getReq, &getResp) 44 | if err != nil { 45 | fmt.Println("Error calling RPCGet:", err) 46 | return 47 | } 48 | fmt.Println("Get Response:", getResp) 49 | 50 | // Example: Delete the key 51 | deleteReq := RPCRequest{Key: "exampleKey"} 52 | var deleteResp RPCResponse 53 | err = client.Call("RPCService.RPCDelete", &deleteReq, &deleteResp) 54 | if err != nil { 55 | fmt.Println("Error calling RPCDelete:", err) 56 | return 57 | } 58 | fmt.Println("Delete Response:", deleteResp) 59 | 60 | // Attempt to get the key again after deletion 61 | err = client.Call("RPCService.RPCGet", &getReq, &getResp) 62 | if err != nil { 63 | fmt.Println("Error calling RPCGet after deletion:", err) 64 | return 65 | } 66 | fmt.Println("Get Response after deletion:", getResp) 67 | } 68 | -------------------------------------------------------------------------------- /docs/swagger.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | title: Memorandum API 4 | description: API documentation for the Memorandum key-value store. 5 | version: 1.0.0 6 | servers: 7 | - url: http://localhost:6060 8 | description: Local server for testing 9 | 10 | paths: 11 | /set: 12 | post: 13 | summary: Set a key-value pair in the store 14 | operationId: setKeyValue 15 | requestBody: 16 | description: Key-value pair and TTL 17 | required: true 18 | content: 19 | application/json: 20 | schema: 21 | type: object 22 | properties: 23 | key: 24 | type: string 25 | description: The key to store. 26 | example: myKey 27 | value: 28 | type: string 29 | description: The value to store. 30 | example: myValue 31 | ttl: 32 | type: integer 33 | description: Time-to-live in seconds. 34 | example: 60 35 | responses: 36 | '200': 37 | description: Successful operation 38 | content: 39 | application/json: 40 | schema: 41 | $ref: '#/components/schemas/APIResponse' 42 | 43 | 44 | /get: 45 | get: 46 | summary: Get the value for a given key 47 | operationId: getKeyValue 48 | parameters: 49 | - name: key 50 | in: query 51 | required: true 52 | schema: 53 | type: string 54 | description: The key to retrieve. 55 | example: myKey 56 | responses: 57 | '200': 58 | description: Successful operation 59 | content: 60 | application/json: 61 | schema: 62 | $ref: '#/components/schemas/APIResponse' 63 | 64 | 65 | /delete: 66 | delete: 67 | summary: Delete a key from the store 68 | operationId: deleteKeyValue 69 | parameters: 70 | - name: key 71 | in: query 72 | required: true 73 | schema: 74 | type: string 75 | description: The key to delete. 76 | example: myKey 77 | responses: 78 | '200': 79 | description: Successful operation 80 | content: 81 | application/json: 82 | schema: 83 | $ref: '#/components/schemas/APIResponse' 84 | 85 | 86 | components: 87 | schemas: 88 | APIResponse: 89 | type: object 90 | properties: 91 | success: 92 | type: boolean 93 | description: Indicates if the operation was successful. 94 | example: true 95 | data: 96 | type: object 97 | description: The data returned by the operation (if any). 98 | nullable: true 99 | example: myValue 100 | error: 101 | type: string 102 | description: The error message (if any). 103 | nullable: true 104 | example: Key not found or expired 105 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "net/http" 7 | "os" 8 | "os/signal" 9 | "strings" 10 | "syscall" 11 | "time" 12 | 13 | "github.com/shafigh75/Memorandum/cluster" 14 | 15 | "github.com/shafigh75/Memorandum/config" 16 | "github.com/shafigh75/Memorandum/server/db" 17 | httpHandler "github.com/shafigh75/Memorandum/server/http" 18 | rpcHandler "github.com/shafigh75/Memorandum/server/rpc" 19 | Logger "github.com/shafigh75/Memorandum/utils/logger" 20 | ) 21 | 22 | const ( 23 | Red = "\033[31m" 24 | Green = "\033[32m" 25 | Yellow = "\033[33m" 26 | Blue = "\033[34m" 27 | Reset = "\033[0m" 28 | ) 29 | 30 | func printBanner(name string) { 31 | // Define the banner style 32 | border := strings.Repeat("=", len(name)+4) 33 | starBorder := strings.Repeat("*", len(name)+4) 34 | 35 | // Print the banner 36 | fmt.Println(Green + starBorder) 37 | fmt.Printf("* %s *\n", name) 38 | fmt.Println(border) 39 | fmt.Println("In-memory database for efficient data management.") 40 | fmt.Println(starBorder + Reset) 41 | } 42 | 43 | func main() { 44 | printBanner("Memorandum") 45 | // Load configuration 46 | confPath := "config/config.json" 47 | config, err := config.LoadConfig(confPath) 48 | if err != nil { 49 | fmt.Println(Red+"Error loading config:"+Reset, err) 50 | return 51 | } 52 | 53 | store, err := db.LoadConfigAndCreateStore(confPath) 54 | if err != nil { 55 | fmt.Println(Red+"Error creating Store:"+Reset, err) 56 | return 57 | } 58 | 59 | httpLogPath := config.HttpLogPath 60 | httpLogger, err := Logger.NewLogger(httpLogPath) 61 | if err != nil { 62 | fmt.Println(Red+"Error creating Logger:"+Reset, err) 63 | return 64 | } 65 | 66 | // Start the cleanup routine based on the config 67 | store.StartCleanupRoutine(time.Duration(config.CleanupInterval) * time.Second) 68 | 69 | // Create a new HTTP server 70 | httpServer := &http.Server{ 71 | Addr: config.HTTPPort, 72 | Handler: httpHandler.NewHandler(store, httpLogger), // Use the handler created from the store 73 | } 74 | 75 | // Start the HTTP server in a goroutine 76 | go func() { 77 | fmt.Println("Starting HTTP server on", config.HTTPPort) 78 | if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { 79 | fmt.Println(Red+"Error starting HTTP server:"+Reset, err) 80 | } 81 | }() 82 | 83 | // Start the RPC server in a goroutine 84 | rpcLogPath := config.RPCLogPath 85 | rpcLogger, err := Logger.NewLogger(rpcLogPath) 86 | if err != nil { 87 | fmt.Println(Yellow + "logger is disabled ..." + Reset) 88 | } 89 | go rpcHandler.StartRPCServer(store, config.RPCPort, rpcLogger) 90 | 91 | isClustered := config.ClusterEnabled 92 | if isClustered { 93 | fmt.Println(Red + "Running in cluster Mode, starting server ..." + Reset) 94 | go cluster.StartHTTPServer(config.ClusterPort) 95 | } else { 96 | fmt.Println(Red + "Running as standalone server ... " + Reset) 97 | } 98 | 99 | // Channel to listen for shutdown signals 100 | signalChan := make(chan os.Signal, 1) 101 | signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM) 102 | 103 | // Wait for a shutdown signal 104 | <-signalChan 105 | fmt.Println(Blue + "Shutdown signal received. Initiating graceful shutdown..." + Reset) 106 | 107 | // Create a context with a timeout for the shutdown process 108 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 109 | defer cancel() 110 | 111 | // Shutdown the HTTP server gracefully 112 | if err := httpServer.Shutdown(ctx); err != nil { 113 | fmt.Println(Red+"Error shutting down HTTP server:"+Reset, err) 114 | } 115 | 116 | // close the store gracefully 117 | store.Close() 118 | fmt.Println(Green + "Shutdown complete." + Reset) 119 | } 120 | -------------------------------------------------------------------------------- /cluster/manager/node_service.go: -------------------------------------------------------------------------------- 1 | package manager 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/rpc" 7 | 8 | "github.com/shafigh75/Memorandum/config" 9 | ) 10 | 11 | type NodeService struct { 12 | ClusterManager *ClusterManager 13 | } 14 | 15 | func NewNodeService(cm *ClusterManager) *NodeService { 16 | return &NodeService{ClusterManager: cm} 17 | } 18 | 19 | type RPCRequest struct { 20 | Key string 21 | Value string 22 | TTL int64 23 | } 24 | 25 | type RPCResponse struct { 26 | Success bool 27 | Data string 28 | Error string 29 | } 30 | 31 | func (ns *NodeService) GetConfig() *config.Config { 32 | cfg, err := config.LoadConfig("config/config.json") 33 | if err != nil { 34 | log.Fatalf("Error loading config: %v", err) 35 | } 36 | return cfg 37 | } 38 | 39 | func (ns *NodeService) SetData(data map[string]string, ttl int64, reply *bool) error { 40 | cfg := ns.GetConfig() 41 | replica := cfg.ReplicaCount 42 | for key, value := range data { 43 | nodes := ns.ClusterManager.GetNodes(key, replica) // 1 replica 44 | if len(nodes) == 0 { 45 | return fmt.Errorf("no active nodes available") 46 | } 47 | 48 | for _, node := range nodes { 49 | if !node.Active { 50 | continue 51 | } 52 | 53 | client, err := rpc.Dial("tcp", node.Address) 54 | if err != nil { 55 | log.Printf("RPC connection failed: %s - %v", node.Address, err) 56 | continue 57 | } 58 | 59 | req := RPCRequest{Key: key, Value: value, TTL: ttl} 60 | var resp RPCResponse 61 | if err := client.Call("RPCService.RPCSet", &req, &resp); err != nil { 62 | log.Printf("RPCSet failed: %s - %v", node.Address, err) 63 | client.Close() 64 | continue 65 | } 66 | 67 | client.Close() 68 | if !resp.Success { 69 | return fmt.Errorf("node %s failed to set key", node.Address) 70 | } 71 | } 72 | } 73 | 74 | *reply = true 75 | return nil 76 | } 77 | 78 | func (ns *NodeService) GetData(key string, reply *RPCResponse) error { 79 | cfg := ns.GetConfig() 80 | replica := cfg.ReplicaCount 81 | nodes := ns.ClusterManager.GetNodes(key, replica) 82 | if len(nodes) == 0 { 83 | return fmt.Errorf("no active nodes available") 84 | } 85 | 86 | for _, node := range nodes { 87 | if !node.Active { 88 | continue 89 | } 90 | 91 | client, err := rpc.Dial("tcp", node.Address) 92 | if err != nil { 93 | log.Printf("RPC connection failed: %s - %v", node.Address, err) 94 | continue 95 | } 96 | 97 | req := RPCRequest{Key: key} 98 | var resp RPCResponse 99 | if err := client.Call("RPCService.RPCGet", &req, &resp); err != nil { 100 | log.Printf("RPCGet failed: %s - %v", node.Address, err) 101 | client.Close() 102 | continue 103 | } 104 | 105 | client.Close() 106 | if resp.Success { 107 | *reply = resp 108 | return nil 109 | } 110 | } 111 | 112 | return fmt.Errorf("no key was found") 113 | } 114 | 115 | func (ns *NodeService) DeleteData(key string, reply *bool) error { 116 | cfg := ns.GetConfig() 117 | replica := cfg.ReplicaCount 118 | nodes := ns.ClusterManager.GetNodes(key, replica) 119 | if len(nodes) == 0 { 120 | return fmt.Errorf("no active nodes available") 121 | } 122 | 123 | for _, node := range nodes { 124 | if !node.Active { 125 | continue 126 | } 127 | 128 | client, err := rpc.Dial("tcp", node.Address) 129 | if err != nil { 130 | log.Printf("RPC connection failed: %s - %v", node.Address, err) 131 | continue 132 | } 133 | 134 | req := RPCRequest{Key: key} 135 | var resp RPCResponse 136 | if err := client.Call("RPCService.RPCDelete", &req, &resp); err != nil { 137 | log.Printf("RPCDelete failed: %s - %v", node.Address, err) 138 | client.Close() 139 | continue 140 | } 141 | 142 | client.Close() 143 | if resp.Success { 144 | *reply = true 145 | return nil 146 | } 147 | } 148 | 149 | return fmt.Errorf("all nodes failed to delete key") 150 | } 151 | -------------------------------------------------------------------------------- /server/rpc/rpc.go: -------------------------------------------------------------------------------- 1 | package rpc 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net" 7 | "net/rpc" 8 | "time" 9 | 10 | "github.com/shafigh75/Memorandum/server/db" 11 | "github.com/shafigh75/Memorandum/utils/logger" 12 | ) 13 | 14 | // RPCRequest represents the structure of an RPC request. 15 | type RPCRequest struct { 16 | Key string `json:"key"` 17 | Value string `json:"value,omitempty"` 18 | TTL int64 `json:"ttl"` // TTL in seconds 19 | } 20 | 21 | // RPCResponse represents the structure of an RPC response. 22 | type RPCResponse struct { 23 | Success bool `json:"success"` 24 | Data string `json:"data,omitempty"` 25 | Error string `json:"error,omitempty"` 26 | } 27 | 28 | // RPCService provides the RPC methods for the InMemoryStore. 29 | type RPCService struct { 30 | Store *db.ShardedInMemoryStore 31 | Logger *logger.Logger 32 | } 33 | 34 | // RPCSet sets a key-value pair in the store. 35 | func (s *RPCService) RPCSet(req *RPCRequest, resp *RPCResponse) error { 36 | s.Store.Set(req.Key, req.Value, req.TTL) 37 | resp.Success = true 38 | // Create a structured log message 39 | logMessage := map[string]interface{}{ 40 | "timestamp": time.Now().Format(time.RFC3339), 41 | "method": "rpc-set", 42 | "request": req, 43 | } 44 | 45 | // Convert the log message to JSON 46 | logJSON, err := json.Marshal(logMessage) 47 | if err != nil { 48 | // Handle JSON marshaling error (optional) 49 | s.Logger.Log("Error marshaling log message to JSON") 50 | return err 51 | } 52 | 53 | // Log the structured message as a JSON string 54 | s.Logger.Log(string(logJSON)) 55 | return nil 56 | } 57 | 58 | // RPCGet retrieves a value by key from the store. 59 | func (s *RPCService) RPCGet(req *RPCRequest, resp *RPCResponse) error { 60 | if value, exists := s.Store.Get(req.Key); exists { 61 | resp.Success = true 62 | resp.Data = value 63 | } else { 64 | resp.Success = false 65 | resp.Error = "Key not found or expired" 66 | } 67 | // Create a structured log message 68 | logMessage := map[string]interface{}{ 69 | "timestamp": time.Now().Format(time.RFC3339), 70 | "method": "rpc-get", 71 | "request": req, 72 | } 73 | 74 | // Convert the log message to JSON 75 | logJSON, err := json.Marshal(logMessage) 76 | if err != nil { 77 | // Handle JSON marshaling error (optional) 78 | s.Logger.Log("Error marshaling log message to JSON") 79 | return err 80 | } 81 | 82 | // Log the structured message as a JSON string 83 | s.Logger.Log(string(logJSON)) 84 | return nil 85 | } 86 | 87 | // RPCDelete removes a key-value pair from the store. 88 | func (s *RPCService) RPCDelete(req *RPCRequest, resp *RPCResponse) error { 89 | s.Store.Delete(req.Key) 90 | resp.Success = true 91 | // Create a structured log message 92 | logMessage := map[string]interface{}{ 93 | "timestamp": time.Now().Format(time.RFC3339), 94 | "method": "rpc-delete", 95 | "request": req, 96 | } 97 | 98 | // Convert the log message to JSON 99 | logJSON, err := json.Marshal(logMessage) 100 | if err != nil { 101 | // Handle JSON marshaling error (optional) 102 | s.Logger.Log("Error marshaling log message to JSON") 103 | return err 104 | } 105 | 106 | // Log the structured message as a JSON string 107 | s.Logger.Log(string(logJSON)) 108 | return nil 109 | } 110 | 111 | func (s *RPCService) Ping(args struct{}, reply *bool) error { 112 | *reply = true 113 | return nil 114 | } 115 | 116 | // StartRPCServer starts the RPC server. 117 | func StartRPCServer(store *db.ShardedInMemoryStore, port string, logger *logger.Logger) { 118 | rpcService := &RPCService{Store: store, Logger: logger} 119 | rpc.Register(rpcService) 120 | 121 | listener, err := net.Listen("tcp", port) 122 | if err != nil { 123 | panic("Error starting RPC server: " + err.Error()) 124 | } 125 | defer listener.Close() 126 | 127 | fmt.Println("Starting RPC server on", port) 128 | for { 129 | conn, err := listener.Accept() 130 | if err != nil { 131 | continue 132 | } 133 | go rpc.ServeConn(conn) // Handle each RPC connection in a new goroutine 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /server/http/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "net/http" 7 | "time" 8 | 9 | "github.com/shafigh75/Memorandum/config" 10 | "github.com/shafigh75/Memorandum/server/db" 11 | "github.com/shafigh75/Memorandum/utils/logger" 12 | ) 13 | 14 | // APIResponse represents a standard API response. 15 | type APIResponse struct { 16 | Success bool `json:"success"` 17 | Data interface{} `json:"data,omitempty"` 18 | Error string `json:"error,omitempty"` 19 | } 20 | 21 | // Handler struct to hold the store 22 | type Handler struct { 23 | Store *db.ShardedInMemoryStore 24 | Logger *logger.Logger 25 | } 26 | 27 | // NewHandler creates a new HTTP handler. 28 | func NewHandler(store *db.ShardedInMemoryStore, logger *logger.Logger) *Handler { 29 | return &Handler{Store: store, Logger: logger} 30 | } 31 | 32 | // ServeHTTP implements the http.Handler interface. 33 | func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 34 | configFilePath := "config/config.json" 35 | cfg, err := config.LoadConfig(configFilePath) 36 | if err != nil { 37 | fmt.Println("Error loading config:", err) 38 | return 39 | } 40 | if cfg.AuthEnabled { 41 | // Check for authentication if enabled 42 | authHeader := r.Header.Get("Authorization") 43 | if authHeader != "Bearer "+cfg.AuthToken { 44 | // Create a structured log message 45 | logMessage := map[string]interface{}{ 46 | "timestamp": time.Now().Format(time.RFC3339), 47 | "method": r.Method + ": UNAUTHORIZED", 48 | "url": r.URL.String(), 49 | "ip": r.RemoteAddr, 50 | } 51 | 52 | // Convert the log message to JSON 53 | logJSON, err := json.Marshal(logMessage) 54 | if err != nil { 55 | // Handle JSON marshaling error (optional) 56 | h.Logger.Log("Error marshaling log message to JSON") 57 | return 58 | } 59 | 60 | // Log the structured message as a JSON string 61 | h.Logger.Log(string(logJSON)) 62 | http.Error(w, "Unauthorized", http.StatusUnauthorized) 63 | return 64 | } 65 | } 66 | 67 | // Create a structured log message 68 | logMessage := map[string]interface{}{ 69 | "timestamp": time.Now().Format(time.RFC3339), 70 | "method": r.Method, 71 | "url": r.URL.String(), 72 | "ip": r.RemoteAddr, 73 | } 74 | 75 | // Convert the log message to JSON 76 | logJSON, err := json.Marshal(logMessage) 77 | if err != nil { 78 | // Handle JSON marshaling error (optional) 79 | h.Logger.Log("Error marshaling log message to JSON") 80 | return 81 | } 82 | 83 | // Log the structured message as a JSON string 84 | h.Logger.Log(string(logJSON)) 85 | switch r.Method { 86 | case http.MethodPost: 87 | h.SetHandler(w, r) 88 | case http.MethodGet: 89 | h.GetHandler(w, r) 90 | case http.MethodDelete: 91 | h.DeleteHandler(w, r) 92 | default: 93 | http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) 94 | } 95 | } 96 | 97 | // SetHandler handles the set request. 98 | func (h *Handler) SetHandler(w http.ResponseWriter, r *http.Request) { 99 | var req struct { 100 | Key string `json:"key"` 101 | Value string `json:"value"` 102 | TTL int64 `json:"ttl"` // TTL in seconds 103 | } 104 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 105 | http.Error(w, "Invalid request", http.StatusBadRequest) 106 | return 107 | } 108 | h.Store.Set(req.Key, req.Value, req.TTL) 109 | json.NewEncoder(w).Encode(APIResponse{Success: true}) 110 | } 111 | 112 | // GetHandler handles the get request. 113 | func (h *Handler) GetHandler(w http.ResponseWriter, r *http.Request) { 114 | key := r.URL.Query().Get("key") 115 | if value, exists := h.Store.Get(key); exists { 116 | json.NewEncoder(w).Encode(APIResponse{Success: true, Data: value}) 117 | } else { 118 | json.NewEncoder(w).Encode(APIResponse{Success: false, Error: "Key not found or expired"}) 119 | } 120 | } 121 | 122 | // DeleteHandler handles the delete request. 123 | func (h *Handler) DeleteHandler(w http.ResponseWriter, r *http.Request) { 124 | key := r.URL.Query().Get("key") 125 | h.Store.Delete(key) 126 | json.NewEncoder(w).Encode(APIResponse{Success: true}) 127 | } 128 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Memorandum Documentation 7 | 8 | 147 | 148 | 149 |
150 |

Welcome to Memorandum

151 |

Your go-to solution for managing key-value pairs.

152 |
153 |

Developed by: Mohammad Shafighi

154 |
155 |
156 |

About the Project

157 |

The Memorandum provides a simple and efficient way to store and retrieve key-value pairs. It is designed for developers who need a lightweight solution for data storage with optional authentication. It is written in Go and provides multiple interfaces to work with, including HTTP, RPC, CLI, and Go module.

158 | 159 |

Features

160 | 168 | 169 |

Getting Started

170 |

To get started with the Memorandum API, check out the documentation and examples below:

171 | View Documentation 172 | Report an Issue 173 |
174 | 175 | 183 | 184 | 185 | -------------------------------------------------------------------------------- /cluster/manager/manager.go: -------------------------------------------------------------------------------- 1 | package manager 2 | 3 | import ( 4 | "encoding/json" 5 | "hash/crc32" 6 | "io/ioutil" 7 | "log" 8 | "net/rpc" 9 | "os" 10 | "sync" 11 | "time" 12 | 13 | "github.com/shafigh75/Memorandum/config" 14 | ) 15 | 16 | type Node struct { 17 | Address string 18 | Active bool 19 | Index int 20 | } 21 | 22 | type ClusterManager struct { 23 | Nodes []*Node 24 | Mutex sync.Mutex 25 | HeartbeatInterval time.Duration 26 | configFile string 27 | LastModTime time.Time 28 | configCheckInterval time.Duration 29 | } 30 | 31 | func NewClusterManager(configFile string) *ClusterManager { 32 | cfg, err := config.LoadConfig("config/config.json") 33 | if err != nil { 34 | log.Fatalf("Error loading config: %v", err) 35 | } 36 | 37 | return &ClusterManager{ 38 | Nodes: make([]*Node, 0), 39 | HeartbeatInterval: time.Duration(cfg.HeartbeatInterval) * time.Second, 40 | configFile: configFile, 41 | configCheckInterval: time.Duration(cfg.ConfigCheckInterval) * time.Second, 42 | } 43 | } 44 | 45 | func (cm *ClusterManager) AddNode(address string) { 46 | cm.Mutex.Lock() 47 | defer cm.Mutex.Unlock() 48 | 49 | for _, node := range cm.Nodes { 50 | if node.Address == address { 51 | log.Printf("Node updated: %s", address) 52 | cm.Nodes[node.Index] = &Node{ 53 | Address: address, 54 | Active: true, 55 | Index: node.Index, 56 | } 57 | return 58 | } 59 | } 60 | 61 | newNode := &Node{ 62 | Address: address, 63 | Active: true, 64 | Index: len(cm.Nodes), 65 | } 66 | cm.Nodes = append(cm.Nodes, newNode) 67 | log.Printf("Node added: %s", address) 68 | } 69 | 70 | func (cm *ClusterManager) RemoveNode(address string) { 71 | cm.Mutex.Lock() 72 | defer cm.Mutex.Unlock() 73 | 74 | for i, node := range cm.Nodes { 75 | if node.Address == address { 76 | cm.Nodes = append(cm.Nodes[:i], cm.Nodes[i+1:]...) 77 | // Re-index remaining nodes 78 | for j := i; j < len(cm.Nodes); j++ { 79 | cm.Nodes[j].Index = j 80 | } 81 | log.Printf("Node removed: %s", address) 82 | return 83 | } 84 | } 85 | } 86 | 87 | func (cm *ClusterManager) StartHealthCheck() { 88 | ticker := time.NewTicker(cm.HeartbeatInterval) 89 | defer ticker.Stop() 90 | 91 | for range ticker.C { 92 | for _, node := range cm.Nodes { 93 | if !cm.PingNode(node.Address) { 94 | cm.Mutex.Lock() 95 | node.Active = false 96 | log.Printf("Node inactive: %s", node.Address) 97 | cm.Mutex.Unlock() 98 | } 99 | } 100 | } 101 | } 102 | 103 | func (cm *ClusterManager) PingNode(address string) bool { 104 | client, err := rpc.Dial("tcp", address) 105 | if err != nil { 106 | return false 107 | } 108 | defer client.Close() 109 | 110 | var reply bool 111 | err = client.Call("RPCService.Ping", struct{}{}, &reply) 112 | return err == nil && reply 113 | } 114 | 115 | func (cm *ClusterManager) GetActiveNodes() []string { 116 | cm.Mutex.Lock() 117 | defer cm.Mutex.Unlock() 118 | 119 | active := make([]string, 0) 120 | for _, node := range cm.Nodes { 121 | if node.Active { 122 | active = append(active, node.Address) 123 | } 124 | } 125 | return active 126 | } 127 | 128 | func (cm *ClusterManager) GetNodes(key string, replicas int) []*Node { 129 | cm.Mutex.Lock() 130 | defer cm.Mutex.Unlock() 131 | 132 | if len(cm.Nodes) == 0 { 133 | return nil 134 | } 135 | 136 | hash := crc32.ChecksumIEEE([]byte(key)) 137 | primaryIdx := int(hash) % len(cm.Nodes) 138 | nodes := make([]*Node, 0) 139 | 140 | active := make([]*Node, 0) 141 | for _, node := range cm.Nodes { 142 | if node.Active { 143 | active = append(active, node) 144 | } 145 | } 146 | for i := 0; i <= replicas; i++ { 147 | if len(active) == 0 { 148 | log.Println("Error: There is no active nodes") 149 | return nil 150 | } 151 | idx := (primaryIdx + i) % len(active) 152 | if idx < len(active) { 153 | nodes = append(nodes, active[idx]) 154 | } 155 | } 156 | return nodes 157 | } 158 | 159 | func (cm *ClusterManager) StartConfigMonitor() { 160 | ticker := time.NewTicker(cm.configCheckInterval) 161 | defer ticker.Stop() 162 | 163 | for range ticker.C { 164 | cm.syncWithConfig() 165 | } 166 | } 167 | 168 | func (cm *ClusterManager) syncWithConfig() { 169 | cm.Mutex.Lock() 170 | 171 | log.Println("syncing cluster ...") 172 | // 1. Check file modification time 173 | fi, err := os.Stat(cm.configFile) 174 | if err != nil || fi.ModTime().Before(cm.LastModTime) { 175 | cm.Mutex.Unlock() 176 | return 177 | } 178 | cm.LastModTime = fi.ModTime() 179 | 180 | // 2. Read config file 181 | file, err := os.Open(cm.configFile) 182 | if err != nil { 183 | cm.Mutex.Unlock() 184 | log.Printf("Error opening config: %v", err) 185 | return 186 | } 187 | bytes, err := ioutil.ReadAll(file) 188 | file.Close() 189 | if err != nil { 190 | cm.Mutex.Unlock() 191 | log.Printf("Error reading config: %v", err) 192 | return 193 | } 194 | 195 | var nodeConfig struct{ Nodes []string } 196 | if err := json.Unmarshal(bytes, &nodeConfig); err != nil { 197 | cm.Mutex.Unlock() 198 | log.Printf("Error parsing config: %v", err) 199 | return 200 | } 201 | 202 | // 3. Identify changes while locked 203 | var toAdd []string 204 | var toRemove []string 205 | 206 | // Find new nodes to add 207 | for _, addr := range nodeConfig.Nodes { 208 | exists := false 209 | for _, node := range cm.Nodes { 210 | if node.Address == addr && node.Active { 211 | exists = true 212 | break 213 | } 214 | } 215 | if !exists { 216 | toAdd = append(toAdd, addr) 217 | } 218 | } 219 | 220 | // Find stale nodes to remove 221 | for _, node := range cm.Nodes { 222 | found := false 223 | for _, configAddr := range nodeConfig.Nodes { 224 | if node.Address == configAddr { 225 | found = true 226 | break 227 | } 228 | } 229 | if !found { 230 | toRemove = append(toRemove, node.Address) 231 | } 232 | } 233 | 234 | cm.Mutex.Unlock() // Release lock before making changes 235 | 236 | // 4. Apply changes without holding the lock 237 | for _, addr := range toAdd { 238 | if cm.PingNode(addr) { 239 | cm.AddNode(addr) // Safe: AddNode handles its own locking 240 | } 241 | } 242 | 243 | for _, addr := range toRemove { 244 | cm.RemoveNode(addr) // Safe: RemoveNode handles its own locking 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /cli/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | "net/rpc" 9 | "strings" 10 | 11 | "github.com/shafigh75/Memorandum/config" 12 | 13 | "github.com/chzyer/readline" 14 | "github.com/spf13/cobra" 15 | ) 16 | 17 | // RPCRequest and RPCResponse structures 18 | type RPCRequest struct { 19 | Key string `json:"key"` 20 | Value string `json:"value,omitempty"` 21 | TTL int64 `json:"ttl"` // TTL in seconds 22 | } 23 | 24 | type RPCResponse struct { 25 | Success bool `json:"success"` 26 | Data string `json:"data,omitempty"` 27 | Error string `json:"error,omitempty"` 28 | } 29 | 30 | var ( 31 | client *rpc.Client 32 | authToken string 33 | isAuthenticated bool 34 | ) 35 | 36 | var rootCmd = &cobra.Command{ 37 | Use: "Memorandom-cli", 38 | Short: "Memorandum command line interface", 39 | Long: `This is a CLI application for Memorandum project. developed by: Mohammad Shafighi`, 40 | Run: func(cmd *cobra.Command, args []string) { 41 | fmt.Println("Welcome to Memorandum CLI! Type 'help' for available commands.") 42 | startREPL() 43 | }, 44 | } 45 | 46 | func startREPL() { 47 | // check if auth is enabled 48 | configFilePath := "config/config.json" 49 | cfg, err := config.LoadConfig(configFilePath) 50 | if err != nil { 51 | fmt.Println("Error loading config:", err) 52 | return 53 | } 54 | if !cfg.AuthEnabled { 55 | isAuthenticated = true 56 | } 57 | // Define completer 58 | completer := readline.NewPrefixCompleter( 59 | readline.PcItem("help"), 60 | readline.PcItem("exit"), 61 | readline.PcItem("auth"), 62 | readline.PcItem("passwd"), 63 | readline.PcItem("set", readline.PcItem("key"), readline.PcItem("value"), readline.PcItem("ttl")), 64 | readline.PcItem("get", readline.PcItem("key")), 65 | readline.PcItem("delete", readline.PcItem("key")), 66 | ) 67 | 68 | // Create readline instance 69 | rl, err := readline.NewEx(&readline.Config{ 70 | Prompt: "> ", 71 | HistoryFile: "/tmp/readline.tmp", 72 | AutoComplete: completer, 73 | InterruptPrompt: "^C", 74 | EOFPrompt: "exit", 75 | }) 76 | if err != nil { 77 | fmt.Println("Error creating readline:", err) 78 | return 79 | } 80 | defer rl.Close() 81 | 82 | for { 83 | line, err := rl.Readline() 84 | if err != nil { 85 | break 86 | } 87 | line = strings.TrimSpace(line) 88 | 89 | if line == "exit" { 90 | fmt.Println("Exiting REPL.") 91 | break 92 | } 93 | 94 | handleCommand(line) 95 | } 96 | } 97 | 98 | func handleCommand(input string) { 99 | args := strings.Fields(input) 100 | if len(args) == 0 { 101 | return 102 | } 103 | 104 | if !isAuthenticated && args[0] != "auth" { 105 | fmt.Println("Authentication required. Please use 'auth ' to authenticate.") 106 | return 107 | } 108 | 109 | switch args[0] { 110 | case "help": 111 | fmt.Println("Available commands: help, exit, auth [token], passwd, set [key] [value] [ttl], get [key], delete [key]") 112 | case "auth": 113 | if len(args) != 2 { 114 | fmt.Println("Usage: auth [token]") 115 | return 116 | } 117 | authenticate(args[1]) 118 | case "passwd": 119 | generatePassword() 120 | case "set": 121 | if len(args) < 3 { 122 | fmt.Println("Usage: set [key] [value] [ttl-optional]") 123 | return 124 | } 125 | key := args[1] 126 | ttl := int64(0) 127 | if _, err := fmt.Sscanf(args[len(args)-1], "%d", &ttl); err != nil { 128 | ttl = int64(0) 129 | args = append(args," ") 130 | } else if len(args) == 3 { 131 | ttl = int64(0) 132 | value := args[2] 133 | setKey(key, value, ttl) 134 | return 135 | } 136 | value := strings.Join(args[2:len(args)-1], " ") 137 | setKey(key, value, ttl) 138 | case "get": 139 | if len(args) != 2 { 140 | fmt.Println("Usage: get [key]") 141 | return 142 | } 143 | getKey(args[1]) 144 | case "delete": 145 | if len(args) != 2 { 146 | fmt.Println("Usage: delete [key]") 147 | return 148 | } 149 | deleteKey(args[1]) 150 | default: 151 | fmt.Printf("Unknown command: %s\n", input) 152 | } 153 | } 154 | 155 | func authenticate(token string) { 156 | if token == authToken { 157 | isAuthenticated = true 158 | fmt.Println("Authentication successful.") 159 | } else { 160 | fmt.Println("Authentication failed. Please check your token.") 161 | } 162 | } 163 | 164 | func generatePassword() { 165 | password := make([]byte, 16) // 16 bytes = 128 bits 166 | if _, err := rand.Read(password); err != nil { 167 | fmt.Println("Error generating password:", err) 168 | return 169 | } 170 | newToken := fmt.Sprintf("%x", password) 171 | 172 | // Update the config file with the new token 173 | configFilePath := "config/config.json" 174 | cfg, err := config.LoadConfig(configFilePath) 175 | if err != nil { 176 | fmt.Println("Error loading config:", err) 177 | return 178 | } 179 | 180 | cfg.AuthToken = newToken 181 | configData, err := json.MarshalIndent(cfg, "", " ") 182 | if err != nil { 183 | fmt.Println("Error marshalling config:", err) 184 | return 185 | } 186 | 187 | if err := ioutil.WriteFile(configFilePath, configData, 0644); err != nil { 188 | fmt.Println("Error writing config file:", err) 189 | return 190 | } 191 | 192 | fmt.Println("New password generated and saved to config:", newToken) 193 | } 194 | 195 | func setKey(key, value string, ttl int64) { 196 | req := RPCRequest{Key: key, Value: value, TTL: ttl} 197 | var resp RPCResponse 198 | err := client.Call("RPCService.RPCSet", &req, &resp) 199 | if err != nil { 200 | fmt.Println("Error calling RPCSet:", err) 201 | return 202 | } 203 | if resp.Success { 204 | fmt.Println("Key set successfully.") 205 | } else { 206 | fmt.Println("Error:", resp.Error) 207 | } 208 | } 209 | 210 | func getKey(key string) { 211 | req := RPCRequest{Key: key} 212 | var resp RPCResponse 213 | err := client.Call("RPCService.RPCGet", &req, &resp) 214 | if err != nil { 215 | fmt.Println("Error calling RPCGet:", err) 216 | return 217 | } 218 | if resp.Success { 219 | fmt.Printf("Value: %s\n", resp.Data) 220 | } else { 221 | fmt.Println("Error:", resp.Error) 222 | } 223 | } 224 | 225 | func deleteKey(key string) { 226 | req := RPCRequest{Key: key} 227 | var resp RPCResponse 228 | err := client.Call("RPCService.RPCDelete", &req, &resp) 229 | if err != nil { 230 | fmt.Println("Error calling RPCDelete:", err) 231 | return 232 | } 233 | if resp.Success { 234 | fmt.Println("Key deleted successfully.") 235 | } else { 236 | fmt.Println("Error:", resp.Error) 237 | } 238 | } 239 | 240 | func main() { 241 | // Load configuration 242 | cfg, err := config.LoadConfig("config/config.json") 243 | if err != nil { 244 | fmt.Println("Error loading config:", err) 245 | return 246 | } 247 | 248 | // Connect to the RPC server 249 | client, err = rpc.Dial("tcp", cfg.RPCPort) 250 | if err != nil { 251 | fmt.Println("Error connecting to RPC server:", err) 252 | return 253 | } 254 | defer client.Close() 255 | 256 | // Load the configuration to get the auth token 257 | authToken = cfg.AuthToken 258 | 259 | // Execute the root command 260 | if err := rootCmd.Execute(); err != nil { 261 | fmt.Println(err) 262 | return 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /cluster/main.go: -------------------------------------------------------------------------------- 1 | package cluster 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "log" 7 | "net/http" 8 | "os" 9 | "sync" 10 | 11 | "github.com/shafigh75/Memorandum/cluster/manager" 12 | "github.com/shafigh75/Memorandum/config" 13 | ) 14 | 15 | type NodeConfig struct { 16 | Nodes []string `json:"nodes"` 17 | } 18 | 19 | type HTTPResponse struct { 20 | Success bool `json:"success"` 21 | Data interface{} `json:"data,omitempty"` 22 | Error string `json:"error,omitempty"` 23 | } 24 | 25 | var nodesFileMutex sync.Mutex 26 | 27 | func authMiddleware(cfg *config.Config, next http.HandlerFunc) http.HandlerFunc { 28 | return func(w http.ResponseWriter, r *http.Request) { 29 | if cfg.AuthEnabled { 30 | authHeader := r.Header.Get("Authorization") 31 | if authHeader != "Bearer "+cfg.AuthToken { 32 | sendError(w, "Unauthorized", http.StatusUnauthorized) 33 | return 34 | } 35 | } 36 | next(w, r) 37 | } 38 | } 39 | 40 | func StartHTTPServer(port string) { 41 | cfg, err := config.LoadConfig("config/config.json") 42 | if err != nil { 43 | log.Fatalf("Error loading config: %v", err) 44 | } 45 | 46 | nodeService := initializeCluster() 47 | 48 | http.HandleFunc("/set", authMiddleware(cfg, handleSet(nodeService))) 49 | http.HandleFunc("/get/", authMiddleware(cfg, handleGet(nodeService))) 50 | http.HandleFunc("/delete/", authMiddleware(cfg, handleDelete(nodeService))) 51 | http.HandleFunc("/nodes", authMiddleware(cfg, handleNodes(nodeService))) 52 | http.HandleFunc("/nodes/add", authMiddleware(cfg, handleAddNode(nodeService))) 53 | 54 | log.Printf("memo-cluster running on port %s\n", port) 55 | log.Fatal(http.ListenAndServe(port, nil)) 56 | } 57 | 58 | func initializeCluster() *manager.NodeService { 59 | var nodeConfig NodeConfig 60 | configFile := "cluster/nodes.json" 61 | 62 | file, err := os.Open(configFile) 63 | if err != nil { 64 | log.Fatalf("Failed to open nodes.json: %v", err) 65 | } 66 | defer file.Close() 67 | 68 | bytes, err := ioutil.ReadAll(file) 69 | if err != nil { 70 | log.Fatalf("Failed to read nodes.json: %v", err) 71 | } 72 | 73 | if err := json.Unmarshal(bytes, &nodeConfig); err != nil { 74 | log.Fatalf("Failed to parse node config: %v", err) 75 | } 76 | 77 | clusterManager := manager.NewClusterManager(configFile) 78 | nodeService := manager.NewNodeService(clusterManager) 79 | 80 | for _, addr := range nodeConfig.Nodes { 81 | if clusterManager.PingNode(addr) { 82 | clusterManager.AddNode(addr) 83 | } 84 | } 85 | 86 | go clusterManager.StartHealthCheck() 87 | go clusterManager.StartConfigMonitor() 88 | 89 | return nodeService 90 | } 91 | 92 | type SetRequest struct { 93 | Key string `json:"key"` 94 | Value string `json:"value"` 95 | TTL int64 `json:"ttl"` 96 | } 97 | 98 | func handleSet(svc *manager.NodeService) http.HandlerFunc { 99 | return func(w http.ResponseWriter, r *http.Request) { 100 | if r.Method != http.MethodPost { 101 | sendError(w, "Method not allowed", http.StatusMethodNotAllowed) 102 | return 103 | } 104 | 105 | var requests []SetRequest 106 | if err := json.NewDecoder(r.Body).Decode(&requests); err != nil { 107 | sendError(w, "Invalid request body", http.StatusBadRequest) 108 | return 109 | } 110 | 111 | data := make(map[string]string) 112 | var ttl int64 113 | for _, req := range requests { 114 | data[req.Key] = req.Value 115 | ttl = req.TTL 116 | } 117 | 118 | var resp bool 119 | if err := svc.SetData(data, ttl, &resp); err != nil { 120 | log.Printf("Set error: %v", err) 121 | sendError(w, "Internal server error", http.StatusInternalServerError) 122 | return 123 | } 124 | 125 | sendResponse(w, HTTPResponse{ 126 | Success: true, 127 | Data: data, 128 | }, http.StatusOK) 129 | } 130 | } 131 | 132 | func handleGet(svc *manager.NodeService) http.HandlerFunc { 133 | return func(w http.ResponseWriter, r *http.Request) { 134 | if r.Method != http.MethodGet { 135 | sendError(w, "Method not allowed", http.StatusMethodNotAllowed) 136 | return 137 | } 138 | 139 | key := r.URL.Path[len("/get/"):] 140 | if key == "" { 141 | sendError(w, "Key required", http.StatusBadRequest) 142 | return 143 | } 144 | 145 | var resp manager.RPCResponse 146 | if err := svc.GetData(key, &resp); err != nil { 147 | log.Printf("Get error: %v", err) 148 | sendError(w, err.Error(), http.StatusOK) 149 | return 150 | } 151 | 152 | sendResponse(w, HTTPResponse{ 153 | Success: true, 154 | Data: resp.Data, 155 | }, http.StatusOK) 156 | } 157 | } 158 | 159 | func handleDelete(svc *manager.NodeService) http.HandlerFunc { 160 | return func(w http.ResponseWriter, r *http.Request) { 161 | if r.Method != http.MethodDelete { 162 | sendError(w, "Method not allowed", http.StatusMethodNotAllowed) 163 | return 164 | } 165 | 166 | key := r.URL.Path[len("/delete/"):] 167 | if key == "" { 168 | sendError(w, "Key required", http.StatusBadRequest) 169 | return 170 | } 171 | 172 | var resp bool 173 | if err := svc.DeleteData(key, &resp); err != nil { 174 | log.Printf("Delete error: %v", err) 175 | sendError(w, "Internal server error", http.StatusInternalServerError) 176 | return 177 | } 178 | 179 | sendResponse(w, HTTPResponse{ 180 | Success: resp, 181 | }, http.StatusOK) 182 | } 183 | } 184 | 185 | func handleNodes(svc *manager.NodeService) http.HandlerFunc { 186 | return func(w http.ResponseWriter, r *http.Request) { 187 | activeNodes := svc.ClusterManager.GetActiveNodes() 188 | sendResponse(w, HTTPResponse{ 189 | Success: true, 190 | Data: activeNodes, 191 | }, http.StatusOK) 192 | } 193 | } 194 | 195 | func handleAddNode(svc *manager.NodeService) http.HandlerFunc { 196 | return func(w http.ResponseWriter, r *http.Request) { 197 | if r.Method != http.MethodPost { 198 | sendError(w, "Method not allowed", http.StatusMethodNotAllowed) 199 | return 200 | } 201 | 202 | var request struct{ Address string } 203 | if err := json.NewDecoder(r.Body).Decode(&request); err != nil { 204 | sendError(w, "Invalid request body", http.StatusBadRequest) 205 | return 206 | } 207 | 208 | if err := updateNodesJSON(request.Address); err != nil { 209 | log.Printf("Add node error: %v", err) 210 | sendError(w, "Failed to update cluster", http.StatusInternalServerError) 211 | return 212 | } 213 | 214 | svc.ClusterManager.AddNode(request.Address) 215 | sendResponse(w, HTTPResponse{ 216 | Success: true, 217 | Data: request.Address, 218 | }, http.StatusCreated) 219 | } 220 | } 221 | 222 | func updateNodesJSON(newNode string) error { 223 | nodesFileMutex.Lock() 224 | defer nodesFileMutex.Unlock() 225 | 226 | var nodeConfig NodeConfig 227 | file, err := os.Open("cluster/nodes.json") 228 | if err != nil { 229 | return err 230 | } 231 | defer file.Close() 232 | 233 | bytes, err := ioutil.ReadAll(file) 234 | if err != nil { 235 | return err 236 | } 237 | 238 | if err := json.Unmarshal(bytes, &nodeConfig); err != nil { 239 | return err 240 | } 241 | 242 | for _, addr := range nodeConfig.Nodes { 243 | if addr == newNode { 244 | return nil 245 | } 246 | } 247 | 248 | nodeConfig.Nodes = append(nodeConfig.Nodes, newNode) 249 | newData, err := json.MarshalIndent(nodeConfig, "", " ") 250 | if err != nil { 251 | return err 252 | } 253 | 254 | return ioutil.WriteFile("cluster/nodes.json", newData, 0644) 255 | } 256 | 257 | func sendResponse(w http.ResponseWriter, resp HTTPResponse, status int) { 258 | w.Header().Set("Content-Type", "application/json") 259 | w.WriteHeader(status) 260 | json.NewEncoder(w).Encode(resp) 261 | } 262 | 263 | func sendError(w http.ResponseWriter, msg string, status int) { 264 | sendResponse(w, HTTPResponse{ 265 | Success: false, 266 | Error: msg, 267 | }, status) 268 | } 269 | -------------------------------------------------------------------------------- /server/db/store.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "bytes" 5 | "container/heap" 6 | "encoding/binary" 7 | "fmt" 8 | "hash/crc32" 9 | "io" 10 | "os" 11 | "sync" 12 | "time" 13 | 14 | "github.com/shafigh75/Memorandum/config" // Adjust the import path as necessary 15 | ) 16 | 17 | // ValueWithTTL represents a value with its expiration time. 18 | type ValueWithTTL struct { 19 | Value string 20 | Expiration int64 // Unix timestamp in seconds 21 | } 22 | 23 | // WriteAheadLogEntry represents a binary log entry for WAL. 24 | type WriteAheadLogEntry struct { 25 | Action string 26 | Key string 27 | Value string 28 | TTL int64 29 | Timestamp int64 30 | Checksum uint32 // Integrity check using CRC32 31 | } 32 | 33 | // WAL represents the Write-Ahead Log. 34 | type WAL struct { 35 | file *os.File 36 | mu sync.Mutex 37 | buffer []WriteAheadLogEntry 38 | bufferSize int 39 | flushTicker *time.Ticker 40 | flushDone chan struct{} 41 | queue chan WriteAheadLogEntry 42 | queueWG sync.WaitGroup 43 | } 44 | 45 | // NewWAL creates a new WAL instance. 46 | func NewWAL(filename string, bufferSize int, flushInterval time.Duration) (*WAL, error) { 47 | file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | wal := &WAL{ 53 | file: file, 54 | buffer: make([]WriteAheadLogEntry, 0, bufferSize), 55 | bufferSize: bufferSize, 56 | flushTicker: time.NewTicker(flushInterval), 57 | flushDone: make(chan struct{}), 58 | queue: make(chan WriteAheadLogEntry, bufferSize), 59 | } 60 | 61 | wal.queueWG.Add(1) 62 | go wal.startFlushRoutine() 63 | go wal.startQueueProcessor() 64 | return wal, nil 65 | } 66 | 67 | // DummyWAL is a no-op WAL implementation. 68 | type DummyWAL struct{} 69 | 70 | func (d *DummyWAL) Log(entry WriteAheadLogEntry) error { return nil } 71 | func (d *DummyWAL) Close() error { return nil } 72 | 73 | var isWalRecovery bool 74 | 75 | // Log writes a log entry to the WAL. 76 | func (wal *WAL) Log(entry WriteAheadLogEntry) error { 77 | wal.queue <- entry 78 | return nil 79 | } 80 | 81 | // flush writes the buffered log entries to the WAL file in binary format. 82 | func (wal *WAL) flush() error { 83 | if len(wal.buffer) == 0 { 84 | return nil 85 | } 86 | 87 | var buf bytes.Buffer 88 | for _, entry := range wal.buffer { 89 | if err := encodeEntry(&buf, entry); err != nil { 90 | return err 91 | } 92 | } 93 | 94 | // Write binary data to the WAL file 95 | if _, err := wal.file.Write(buf.Bytes()); err != nil { 96 | return err 97 | } 98 | 99 | wal.buffer = wal.buffer[:0] // Clear the buffer 100 | return nil 101 | } 102 | 103 | // startFlushRoutine periodically flushes the log entries. 104 | func (wal *WAL) startFlushRoutine() { 105 | defer close(wal.flushDone) 106 | for { 107 | select { 108 | case <-wal.flushTicker.C: 109 | wal.mu.Lock() 110 | if err := wal.flush(); err != nil { 111 | fmt.Println("Error flushing WAL: ", err.Error()) 112 | } 113 | wal.mu.Unlock() 114 | } 115 | } 116 | } 117 | 118 | // startQueueProcessor processes the queue and adds entries to the buffer. 119 | func (wal *WAL) startQueueProcessor() { 120 | defer wal.queueWG.Done() 121 | for entry := range wal.queue { 122 | wal.mu.Lock() 123 | entry.Checksum = crc32.ChecksumIEEE([]byte(entry.Key + entry.Value)) 124 | wal.buffer = append(wal.buffer, entry) 125 | if len(wal.buffer) >= wal.bufferSize { 126 | if err := wal.flush(); err != nil { 127 | fmt.Println("Error flushing WAL: ", err.Error()) 128 | } 129 | } 130 | wal.mu.Unlock() 131 | } 132 | } 133 | 134 | // Close closes the WAL file and flushes any remaining entries. 135 | func (wal *WAL) Close() error { 136 | wal.flushTicker.Stop() 137 | close(wal.queue) 138 | wal.queueWG.Wait() 139 | wal.mu.Lock() 140 | defer wal.mu.Unlock() 141 | if err := wal.flush(); err != nil { 142 | return err 143 | } 144 | return wal.file.Close() 145 | } 146 | 147 | // encodeEntry encodes a WriteAheadLogEntry into binary format. 148 | func encodeEntry(buf *bytes.Buffer, entry WriteAheadLogEntry) error { 149 | if err := binary.Write(buf, binary.LittleEndian, int32(len(entry.Action))); err != nil { 150 | return err 151 | } 152 | if _, err := buf.WriteString(entry.Action); err != nil { 153 | return err 154 | } 155 | if err := binary.Write(buf, binary.LittleEndian, int32(len(entry.Key))); err != nil { 156 | return err 157 | } 158 | if _, err := buf.WriteString(entry.Key); err != nil { 159 | return err 160 | } 161 | if err := binary.Write(buf, binary.LittleEndian, int32(len(entry.Value))); err != nil { 162 | return err 163 | } 164 | if _, err := buf.WriteString(entry.Value); err != nil { 165 | return err 166 | } 167 | if err := binary.Write(buf, binary.LittleEndian, entry.TTL); err != nil { 168 | return err 169 | } 170 | if err := binary.Write(buf, binary.LittleEndian, entry.Timestamp); err != nil { 171 | return err 172 | } 173 | return binary.Write(buf, binary.LittleEndian, entry.Checksum) 174 | } 175 | 176 | // decodeEntry decodes a binary WAL entry from the given reader. 177 | func decodeEntry(r io.Reader) (WriteAheadLogEntry, error) { 178 | var entry WriteAheadLogEntry 179 | 180 | var actionLen, keyLen, valueLen int32 181 | if err := binary.Read(r, binary.LittleEndian, &actionLen); err != nil { 182 | return entry, err 183 | } 184 | 185 | action := make([]byte, actionLen) 186 | if _, err := io.ReadFull(r, action); err != nil { 187 | return entry, err 188 | } 189 | entry.Action = string(action) 190 | 191 | if err := binary.Read(r, binary.LittleEndian, &keyLen); err != nil { 192 | return entry, err 193 | } 194 | 195 | key := make([]byte, keyLen) 196 | if _, err := io.ReadFull(r, key); err != nil { 197 | return entry, err 198 | } 199 | entry.Key = string(key) 200 | 201 | if err := binary.Read(r, binary.LittleEndian, &valueLen); err != nil { 202 | return entry, err 203 | } 204 | 205 | value := make([]byte, valueLen) 206 | if _, err := io.ReadFull(r, value); err != nil { 207 | return entry, err 208 | } 209 | entry.Value = string(value) 210 | 211 | if err := binary.Read(r, binary.LittleEndian, &entry.TTL); err != nil { 212 | return entry, err 213 | } 214 | 215 | if err := binary.Read(r, binary.LittleEndian, &entry.Timestamp); err != nil { 216 | return entry, err 217 | } 218 | 219 | if err := binary.Read(r, binary.LittleEndian, &entry.Checksum); err != nil { 220 | return entry, err 221 | } 222 | 223 | return entry, nil 224 | } 225 | 226 | // ShardedInMemoryStore represents a sharded in-memory key-value store with TTL. 227 | type ShardedInMemoryStore struct { 228 | shards []*mapShard 229 | numShards int 230 | wal WALInterface 231 | } 232 | 233 | // mapShard represents a single shard of the in-memory store. 234 | type mapShard struct { 235 | mu sync.RWMutex 236 | store map[string]ValueWithTTL 237 | heap MinHeap 238 | } 239 | 240 | type WALInterface interface { 241 | Log(WriteAheadLogEntry) error 242 | Close() error 243 | } 244 | 245 | // NewShardedInMemoryStore creates a new instance of ShardedInMemoryStore. 246 | func NewShardedInMemoryStore(numShards int, wal WALInterface) *ShardedInMemoryStore { 247 | shards := make([]*mapShard, numShards) 248 | for i := 0; i < numShards; i++ { 249 | shards[i] = &mapShard{ 250 | store: make(map[string]ValueWithTTL), 251 | heap: make(MinHeap, 0), 252 | } 253 | heap.Init(&shards[i].heap) 254 | } 255 | return &ShardedInMemoryStore{ 256 | shards: shards, 257 | numShards: numShards, 258 | wal: wal, 259 | } 260 | } 261 | 262 | // getShard returns the shard for a given key. 263 | func (s *ShardedInMemoryStore) getShard(key string) *mapShard { 264 | hash := crc32.ChecksumIEEE([]byte(key)) 265 | return s.shards[int(hash)%s.numShards] 266 | } 267 | 268 | // Set adds a key-value pair to the store with an optional TTL. 269 | func (s *ShardedInMemoryStore) Set(key, value string, ttl int64) { 270 | shard := s.getShard(key) 271 | shard.mu.Lock() 272 | defer shard.mu.Unlock() 273 | _, exists := shard.store[key] 274 | 275 | // delete the key from heap 276 | if exists { 277 | shard.heap.RemoveByKey(key) 278 | } 279 | 280 | var expiration int64 281 | if ttl == 0 { 282 | expiration = 0 283 | } else { 284 | expiration = time.Now().Add(time.Duration(ttl) * time.Second).Unix() 285 | } 286 | shard.store[key] = ValueWithTTL{Value: value, Expiration: expiration} 287 | 288 | // Update the min-heap 289 | heap.Push(&shard.heap, heapEntry{key: key, valueWithTTL: shard.store[key]}) 290 | // Log the operation 291 | entry := WriteAheadLogEntry{ 292 | Action: "set", 293 | Key: key, 294 | Value: value, 295 | TTL: ttl, 296 | Timestamp: time.Now().Unix(), 297 | } 298 | if !isWalRecovery { 299 | if err := s.wal.Log(entry); err != nil { 300 | fmt.Println("Error writing to WAL: ", err.Error()) 301 | } 302 | } 303 | } 304 | 305 | // Get retrieves a value by key from the store, checking for expiration. 306 | func (s *ShardedInMemoryStore) Get(key string) (string, bool) { 307 | shard := s.getShard(key) 308 | shard.mu.RLock() 309 | valueWithTTL, exists := shard.store[key] 310 | shard.mu.RUnlock() 311 | 312 | if !exists || (valueWithTTL.Expiration > 0 && time.Now().Unix() > valueWithTTL.Expiration) { 313 | if exists { 314 | s.Delete(key) 315 | } 316 | return "", false 317 | } 318 | return valueWithTTL.Value, true 319 | } 320 | 321 | // Delete removes a key-value pair from the store. 322 | func (s *ShardedInMemoryStore) Delete(key string) { 323 | shard := s.getShard(key) 324 | shard.mu.Lock() 325 | defer shard.mu.Unlock() 326 | delete(shard.store, key) 327 | 328 | shard.heap.RemoveByKey(key) 329 | // Log the delete operation 330 | entry := WriteAheadLogEntry{ 331 | Action: "delete", 332 | Key: key, 333 | Timestamp: time.Now().Unix(), 334 | } 335 | if !isWalRecovery { 336 | if err := s.wal.Log(entry); err != nil { 337 | fmt.Println("Error writing to WAL: ", err.Error()) 338 | } 339 | } 340 | } 341 | 342 | // Cleanup removes expired keys from the store using the min-heap. 343 | func (s *ShardedInMemoryStore) Cleanup() { 344 | for _, shard := range s.shards { 345 | shard.mu.Lock() 346 | now := time.Now().Unix() 347 | for shard.heap.Len() > 0 { 348 | // Get the entry with the smallest expiration time 349 | entry := heap.Pop(&shard.heap).(heapEntry) 350 | // If the smallest expiration time is in the future, stop the cleanup 351 | if entry.valueWithTTL.Expiration > now { 352 | heap.Push(&shard.heap, entry) 353 | // Push it back to the heap 354 | break 355 | } 356 | // Delete the expired entry from the store 357 | if entry.valueWithTTL.Expiration > 0 && now > entry.valueWithTTL.Expiration { 358 | delete(shard.store, entry.key) 359 | } 360 | } 361 | shard.mu.Unlock() 362 | } 363 | } 364 | 365 | // StartCleanupRoutine starts a background goroutine to periodically clean up expired keys. 366 | func (s *ShardedInMemoryStore) StartCleanupRoutine(interval time.Duration) { 367 | go func() { 368 | ticker := time.NewTicker(interval) 369 | defer ticker.Stop() 370 | for { 371 | <-ticker.C 372 | s.Cleanup() 373 | } 374 | }() 375 | } 376 | 377 | // RecoverFromWAL replays the WAL to restore the state of the store. 378 | func (s *ShardedInMemoryStore) RecoverFromWAL(filename string) error { 379 | file, err := os.Open(filename) 380 | if err != nil { 381 | return err 382 | } 383 | defer file.Close() 384 | 385 | isWalRecovery = true 386 | for { 387 | entry, err := decodeEntry(file) 388 | if err != nil { 389 | if err == io.EOF { 390 | break // End of file reached, exit the loop gracefully 391 | } 392 | return err // Return any other error 393 | } 394 | 395 | // Validate checksum to ensure entry integrity 396 | expectedChecksum := crc32.ChecksumIEEE([]byte(entry.Key + entry.Value)) 397 | if entry.Checksum != expectedChecksum { 398 | return fmt.Errorf("invalid checksum for entry: %v", entry) 399 | } 400 | 401 | if entry.TTL != 0 && entry.IsExpired() { 402 | continue 403 | } 404 | 405 | switch entry.Action { 406 | case "set": 407 | s.Set(entry.Key, entry.Value, entry.TTL) 408 | case "delete": 409 | s.Delete(entry.Key) 410 | } 411 | } 412 | isWalRecovery = false 413 | return nil 414 | } 415 | 416 | // LoadConfigAndCreateStore loads the config file and initializes the store. 417 | func LoadConfigAndCreateStore(configPath string) (*ShardedInMemoryStore, error) { 418 | cfg, err := config.LoadConfig(configPath) 419 | if err != nil { 420 | return nil, err 421 | } 422 | 423 | var wal WALInterface 424 | if cfg.WalEnabled { 425 | wal, err = NewWAL(cfg.WalPath, cfg.WalBufferSize, time.Duration(cfg.WalFlushInterval)*time.Second) 426 | if err != nil { 427 | return nil, err 428 | } 429 | } else { 430 | wal = &DummyWAL{} 431 | } 432 | 433 | store := NewShardedInMemoryStore(cfg.NumShards, wal) 434 | 435 | if cfg.WalEnabled { 436 | if err := store.RecoverFromWAL(cfg.WalPath); err != nil { 437 | return nil, err 438 | } 439 | } 440 | 441 | return store, nil 442 | } 443 | 444 | // Close cleans up resources, including closing the WAL. 445 | func (s *ShardedInMemoryStore) Close() error { 446 | s.Cleanup() 447 | return s.wal.Close() 448 | } 449 | 450 | // IsExpired checks if the entry has expired based on the current time. 451 | func (entry *WriteAheadLogEntry) IsExpired() bool { 452 | currentTime := time.Now().Unix() 453 | expirationTime := entry.Timestamp + entry.TTL 454 | return currentTime > expirationTime // Return true if current time is greater than expiration time 455 | } 456 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |

Memorandum

3 |

4 |

5 | Memorandum logo 6 |

7 |
8 | 9 | ## Overview 10 | **Memorandum** is an open-source, self-hosted, sharded in-memory key-value store written in Go, designed for efficient storage and retrieval of data with support for TTL (time-to-live) and Write-Ahead Logging (WAL) with clustering capabilities. It was developed in response to recent changes in popular database licensing models (read [this](https://www.theregister.com/2024/03/22/redis_changes_license/) for details). This project serves as a learning resource for building in-memory databases and understanding database internals. It also can be used in small to medium scale environments which need a light-weight IMDG. 11 | 12 | ## Background 13 | 14 | The recent shift towards more restrictive licensing models in some popular databases (more specifically redis) has led many developers to reconsider their approach to data storage. As a response to these changes, i've created Memorandum - a lightweight, easy-to-use key-value store that puts control firmly in the hands of its users. 15 | 16 | ## Features 17 | - **In-Memory Storage**: Fast access to key-value pairs stored in memory. 18 | - **Sharded Architecture**: Data is distributed across multiple shards to reduce contention and improve concurrency. 19 | - **TTL Support**: Optional time-to-live for each key to automatically expire data. 20 | - **Write-Ahead Logging (WAL)**: Logs write operations to ensure data durability and facilitate recovery. 21 | - **interfaces**: Implemented as a command-line interface and a network server with two http and RPC interfaces so far. 22 | - **clustering**: This project contains distributed clustering capabilities. Features include: Data Replication, Health Checks, Dynamic Node Management and Authentication. 23 | 24 | 25 | ## Usage as Standalone service 26 | 27 | ## Installation 28 | To get started with Memorandum, clone the repository and build the project using the simple script: 29 | 30 | ```sh 31 | curl -sSL https://raw.githubusercontent.com/shafigh75/Memorandum/main/build.sh | bash 32 | ``` 33 | ### NOTE: 34 | make sure golang is installed on your server or else the build script will not work for you. 35 | 36 | ### Running the Server 37 | To start the Memorandum server, run the following command: 38 | 39 | ```sh 40 | ./Memorandum 41 | ``` 42 | 43 | ### Running the cli 44 | use this command to start the CLI: 45 | ```sh 46 | ./Memorandum-cli 47 | ``` 48 | 49 | ### Configuration 50 | Memorandum uses a configuration file to set various parameters such as the number of shards, WAL file path, buffer size, and flush interval. Update the `config.json` file with your desired settings(detailed explanation later on). 51 | 52 | ```json 53 | # Example config/config.json 54 | { 55 | "http_port": ":6060", 56 | "rpc_port": ":1234", 57 | "cluster_port": ":5036", 58 | "WAL_path": "/home/test/Memorandum/data/wal.bin", 59 | "http_log_path": "/home/test/Memorandum/logs/http.log", 60 | "rpc_log_path": "/home/test/Memorandum/logs/rpc.log", 61 | "WAL_bufferSize": 4096, 62 | "WAL_flushInterval": 30, 63 | "cleanup_interval": 10, 64 | "heartbeat_interval": 10, 65 | "configCheck_interval": 10, 66 | "auth_enabled": true, 67 | "wal_enabled": true, 68 | "cluster_enabled": true, 69 | "shard_count": 32, 70 | "replica_count": 0, 71 | "auth_token": "f5e0c51b7f3c6e6b57deb13b3017c32e" 72 | } 73 | ``` 74 | **NOTE**: make sure to check the config file and set the values based on your requirements. 75 | **NOTE**: In cli there is a `passwd` command that will generate a new auth token for you :) 76 | 77 | ## Usage as module 78 | Here is an example of how to use the Memorandum library in your Go project: 79 | 80 | ### Installation 81 | To get started with Memorandum, you need to have Go installed on your machine. You can install Memorandum by running: 82 | ```bash 83 | go get -u github.com/shafigh75/Memorandum 84 | ``` 85 | 86 | ```go 87 | package main 88 | 89 | import ( 90 | "fmt" 91 | "github.com/shafigh75/Memorandum/server/db" 92 | ) 93 | 94 | func main() { 95 | // Load configuration and create store 96 | store, err := db.LoadConfigAndCreateStore("config.json") 97 | if err != nil { 98 | fmt.Println("Error:", err) 99 | return 100 | } 101 | 102 | // Set a key-value pair with TTL 103 | store.Set("key1", "value1", 60) // TTL in seconds 104 | 105 | // Retrieve the value 106 | value, exists := store.Get("key1") 107 | if exists { 108 | fmt.Println("Retrieved value:", value) 109 | } 110 | 111 | // Delete the key 112 | store.Delete("key1") 113 | 114 | // Close the store 115 | store.Close() 116 | } 117 | ``` 118 | 119 | ## API Reference 120 | 121 | ### Set 122 | Sets a key-value pair in the store with an optional TTL. 123 | ```go 124 | func (s *ShardedInMemoryStore) Set(key, value string, ttl int64) 125 | ``` 126 | - `key`: The key to store. 127 | - `value`: The value associated with the key. 128 | - `ttl`: Time-To-Live in seconds. If `0`, the key never expires. 129 | 130 | ### Get 131 | Retrieves the value for a given key, considering expiration. 132 | ```go 133 | func (s *ShardedInMemoryStore) Get(key string) (string, bool) 134 | ``` 135 | - `key`: The key to retrieve. 136 | - Returns the value and a boolean indicating if the key exists and is not expired. 137 | 138 | ### Delete 139 | Removes a key-value pair from the store. 140 | ```go 141 | func (s *ShardedInMemoryStore) Delete(key string) 142 | ``` 143 | - `key`: The key to delete. 144 | 145 | ### Cleanup 146 | Removes expired keys from the store. Can be run periodically. 147 | ```go 148 | func (s *ShardedInMemoryStore) Cleanup() 149 | ``` 150 | 151 | # Memorandum Configuration 152 | 153 | The `config.json` file is used to configure various aspects of the Memorandum in-memory data store. Below is a detailed description of each configuration parameter: 154 | 155 | ## Configuration Parameters 156 | 157 | ### Server Configuration 158 | - **http_port**: Specifies the port on which the HTTP server listens. 159 | - Example: `":6060"` 160 | 161 | - **rpc_port**: Specifies the port on which the RPC server listens. 162 | - Example: `":1234"` 163 | 164 | - **cluster_port**: Specifies the port on which the http cluster server listens. 165 | - Example: `":5036"` 166 | 167 | ### Paths 168 | - **WAL_path**: Specifies the path to the Write-Ahead Log (WAL) file. 169 | - Example: `"/home/test/Memorandum/data/wal.bin"` 170 | 171 | - **http_log_path**: Specifies the path to the HTTP log file. 172 | - Example: `"/home/test/Memorandum/logs/http.log"` 173 | 174 | - **rpc_log_path**: Specifies the path to the RPC log file. 175 | - Example: `"/home/test/Memorandum/logs/rpc.log"` 176 | 177 | ### WAL Configuration 178 | - **WAL_bufferSize**: Specifies the buffer size for the Write-Ahead Log (in bytes). 179 | - Example: `4096` 180 | 181 | - **WAL_flushInterval**: Specifies the interval (in seconds) at which the WAL is flushed to disk. 182 | - Example: `30` 183 | 184 | ### Cleanup Configuration 185 | - **cleanup_interval**: Specifies the interval (in seconds) at which expired keys are cleaned up. 186 | - Example: `10` 187 | 188 | ### heartbeat Configuration 189 | - **heartbeat_interval**: Specifies the interval (in seconds) at which the nodes in cluster will be checked. 190 | - Example: `100` 191 | 192 | ### re-add to cluster Configuration 193 | - **configCheck_interval**: Specifies the interval (in seconds) at which the disabled nodes in cluster will be checked and re-add to cluster if node is up again. 194 | - Example: `100` 195 | 196 | ### replication factor 197 | - **replica_count**: Specifies the number of nodes the data will be replicated to. starting from 0 (meaning no replication, data is stored on one node only) to n-1 (n is the total node count). 198 | - Example: `0` 199 | **Note**: here the replica means number of nodes other than the primary nodes so for example if you want to replicate to one more node other than the primary node (which is the result of key hashing), use 1. 200 | 201 | ### clustering enabled 202 | - **cluster_enabled**: Specifies whether clustering is enabled or is it running as standalone server with a single node. 203 | - Example: `true` 204 | 205 | ### Authentication 206 | - **auth_enabled**: Enables or disables authentication. 207 | - Example: `true` 208 | 209 | - **auth_token**: Specifies the authentication token required for accessing the service. 210 | - Example: `"f5e0c51b7f3c6e6b57deb13b3017c32e"` 211 | 212 | ### Sharding 213 | - **shard_count**: Specifies the number of shards to be used for the in-memory store. 214 | - Example: `32` 215 | 216 | ### WAL Enable 217 | - **wal_enabled**: Enables or disables the Write-Ahead Log. 218 | - Example: `true` 219 | 220 | ## Sample Configuration File 221 | 222 | ```json 223 | { 224 | "http_port": ":6060", 225 | "rpc_port": ":1234", 226 | "cluster_port": ":5036", 227 | "WAL_path": "/home/test/Memorandum/data/wal.bin", 228 | "http_log_path": "/home/test/Memorandum/logs/http.log", 229 | "rpc_log_path": "/home/test/Memorandum/logs/rpc.log", 230 | "WAL_bufferSize": 4096, 231 | "WAL_flushInterval": 30, 232 | "cleanup_interval": 10, 233 | "heartbeat_interval": 10, 234 | "configCheck_interval": 10, 235 | "auth_enabled": true, 236 | "wal_enabled": true, 237 | "cluster_enabled": true, 238 | "shard_count": 32, 239 | "replica_count": 0, 240 | "auth_token": "f5e0c51b7f3c6e6b57deb13b3017c32e" 241 | } 242 | ``` 243 | 244 | ## Loading Configuration 245 | 246 | To load the configuration and create the store, use the following code: 247 | 248 | ```go 249 | store, err := db.LoadConfigAndCreateStore("config.json") 250 | if err != nil { 251 | fmt.Println("Error loading configuration:", err) 252 | return 253 | } 254 | 255 | // Use the store for your operations 256 | // Example: Set a key-value pair 257 | store.Set("key1", "value1", 60) 258 | 259 | // Close the store when done 260 | defer store.Close() 261 | ``` 262 | 263 | ## Clustering Overview 264 | 265 | This project contains distributed clustering capabilities. Features include: 266 | - **Data Replication**: Uses consistent hashing to distribute keys across nodes. 267 | - **Health Checks**: Periodic node pinging to detect failures. 268 | - **Dynamic Node Management**: Nodes can be added via API or `nodes.json` updates. 269 | - **Authentication**: Optional token-based auth for API endpoints. 270 | 271 | 272 | ### Key Components 273 | 1. **ClusterManager** 274 | - Manages node lifecycle (add/remove). 275 | - Monitors `nodes.json` for changes. 276 | - Performs health checks. 277 | 2. **NodeService** 278 | - Handles RPC calls to nodes for `SET`, `GET`, and `DELETE` operations. 279 | - Uses replication (default: 1 replica) for fault tolerance. 280 | 3. **HTTP Server** 281 | - Exposes REST API for data operations and cluster management. 282 | 283 | --- 284 | 285 | **NOTE**: for adding nodes, we can modify the `cluster/nodes.json` file. example of this file: 286 | ```json 287 | // format of node address: IP + 288 | { 289 | "nodes": [ 290 | "127.0.0.1:1234", 291 | "1.1.1.1:1234", 292 | "2.2.2.2:1234" 293 | ] 294 | } 295 | ``` 296 | 297 | **NOTE**: always add the `127.0.0.1:` as this is crucial for your current node. 298 | **NOTE**: make sure nodes.json file has the same content on all nodes in the cluster. 299 | 300 | --- 301 | 302 | 303 | ## API Documentation 304 | 305 | ### Authentication 306 | If enabled in `config.json`, include the header: 307 | `Authorization: Bearer ` 308 | 309 | --- 310 | 311 | ### Endpoints 312 | 313 | #### 1. Set Key-Value Pair(s) 314 | - **Method**: `POST` 315 | - **URL**: `/set` 316 | - **Body**: 317 | 318 | ```json 319 | [ 320 | { 321 | "key": "name", 322 | "value": "mohammad", 323 | "ttl": 3600 324 | }, 325 | { 326 | "key": "age", 327 | "value": "28", 328 | "ttl": 1800 329 | } 330 | ] 331 | ``` 332 | 333 | Response: 334 | ```json 335 | { 336 | "success": true, 337 | "data": { 338 | "name": "mohammad", 339 | "age": "28" 340 | } 341 | } 342 | ``` 343 | 344 | #### 2. Get Key-Value Pair(s) 345 | - **Method**: `GET` 346 | - **URL**: `/get/` 347 | - **Body**: 348 | 349 | ```json 350 | THIS REQUEST HAS NO BODY :) 351 | ``` 352 | 353 | Response: 354 | ```json 355 | { 356 | "success": true, 357 | "data": "mohammad" 358 | } 359 | ``` 360 | 361 | #### 3. Delete Key 362 | - **Method**: `DELETE` 363 | - **URL**: `/delete/` 364 | - **Body**: 365 | 366 | ```json 367 | THIS REQUEST HAS NO BODY :) 368 | 369 | ``` 370 | 371 | Response: 372 | ```json 373 | { 374 | "success": true 375 | } 376 | ``` 377 | 378 | #### 4. List Active Nodes 379 | - **Method**: `GET` 380 | - **URL**: `/nodes` 381 | - **Body**: 382 | 383 | ```json 384 | THIS REQUEST HAS NO BODY :) 385 | ``` 386 | 387 | Response: 388 | ```json 389 | { 390 | "success": true, 391 | "data": ["127.0.0.1:1234", "1.1.1.1:1234"] 392 | } 393 | ``` 394 | 395 | #### 5. Add Node 396 | - **Method**: `POST` 397 | - **URL**: `/nodes/add` 398 | - **Body**: 399 | 400 | ```json 401 | { 402 | "address": "192.168.1.100:1234" 403 | } 404 | ``` 405 | 406 | Response: 407 | ```json 408 | { 409 | "success": true, 410 | "data": "192.168.1.100:1234" 411 | } 412 | ``` 413 | 414 | 415 | ## Benchmarks 416 | 417 | To measure the performance of the key operations, you can run the benchmark tests. These tests provide insights into the time taken for `Set`, `Get`, and `Delete` operations. 418 | 419 | ### Running Benchmarks 420 | Navigate to the directory containing the `db` package and run: 421 | 422 | ```sh 423 | go test -bench=. 424 | ``` 425 | 426 | ### example results of Running benchmarks WAL-enabled: 427 | ```sh 428 | goos: linux 429 | goarch: amd64 430 | pkg: github.com/shafigh75/Memorandum/server/db 431 | cpu: Intel(R) Xeon(R) Platinum 8280 CPU @ 2.70GHz 432 | BenchmarkSet-24 357301 2919 ns/op 433 | BenchmarkGet-24 4718535 273.0 ns/op 434 | BenchmarkDelete-24 557890 1911 ns/op 435 | PASS 436 | ok github.com/shafigh75/Memorandum/server/db 5.010s 437 | 438 | ``` 439 | 440 | ### example results of Running benchmarks WAL-disabled: 441 | ```sh 442 | goos: linux 443 | goarch: amd64 444 | pkg: github.com/shafigh75/Memorandum/server/db 445 | cpu: Intel(R) Xeon(R) Platinum 8280 CPU @ 2.70GHz 446 | BenchmarkSet-24 868538 1235 ns/op 447 | BenchmarkGet-24 4332234 282.9 ns/op 448 | BenchmarkDelete-24 5088898 253.6 ns/op 449 | PASS 450 | ok github.com/shafigh75/Memorandum/server/db 4.256s 451 | 452 | ``` 453 | **NOTE** : notice the huge write differnce when disabling WAL 454 | 455 | 456 | ## Contributing 457 | Contributions are welcome! If you have suggestions for improvements or new features, feel free to open an issue or submit a pull request. 458 | 459 | ## License 460 | This project is licensed under the GPL-V3 License. See the [LICENSE](LICENSE) file for details. 461 | 462 | ## Acknowledgments 463 | - Inspired by various in-memory database projects and resources. 464 | - Thanks to the Go community for their excellent documentation and support. 465 | 466 | --- 467 | 468 | 469 | ## Disclaimer 470 | This is a simple in-memory database implementation which was built as a hobby project and may not perform well under enterprise-level workload. 471 | 472 | 473 |
474 | 475 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------