-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 079ed2a
Showing
20 changed files
with
4,377 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
build* | ||
*.exe | ||
data/*.dat | ||
.env* | ||
.vscode/* | ||
*.pdb | ||
*.ilk |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
Copyright 2024 Gabriel Camargo | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
# 💾 CMR Cache - Servidor de Cache Alternativo ao Redis | ||
|
||
**CMR Cache** é um servidor de cache open-source projetado para oferecer uma solução rápida e leve para armazenamento temporário de dados em memória. Ele foi criado para ser uma alternativa ao Redis, com foco em simplicidade e flexibilidade, ideal para pequenos projetos ou comunidades que precisam de um cache eficiente, mas sem a complexidade do Redis. | ||
|
||
## 🚀 Funcionalidades | ||
|
||
- 🔥 **Alto desempenho**: Respostas rápidas para operações de leitura e escrita. | ||
- 📦 **Armazenamento em memória**: Dados mantidos em memória volátil para acesso ultrarrápido. | ||
- 🧩 **Comandos simples**: Suporte aos principais comandos de cache, como `SET`, `GET`, `DEL`. | ||
- 🔒 **Autenticação básica**: Controle de acesso via autenticação com usuário e senha. | ||
- 📜 **Persistência opcional**: Opção de persistir dados no disco para cenários de cache que exigem durabilidade. | ||
- 🌐 **Compatibilidade**: Suporte para integração com diversas linguagens. | ||
|
||
## 🛠️ Instalação | ||
|
||
### Pré-requisitos | ||
|
||
- [Clang++](https://clang.llvm.org/get_started.html) | ||
- [Boost C++ Libraries](https://www.boost.org/) | ||
|
||
### Clonando o repositório | ||
|
||
```bash | ||
git clone https://github.com/camargo2019/cmr-cache.git | ||
cd cmr-cache | ||
``` | ||
|
||
### Instalando dependências | ||
|
||
No Ubuntu, você pode instalar as dependências necessárias com: | ||
|
||
```bash | ||
sudo apt-get install libboost-all-dev | ||
``` | ||
|
||
### Compilando | ||
|
||
Para compilar o projeto no Ubuntu, use o seguinte comando: | ||
|
||
```bash | ||
clang++ -o cmr_cache main.cpp -I./vendor/yaml -I/usr/local/include/boost -L/usr/local/lib -lboost_system -lpthread -Wmissing-declarations | ||
``` | ||
|
||
## 🎮 Uso | ||
|
||
### Executando o servidor | ||
|
||
Para iniciar o servidor CMR Cache, basta rodar o seguinte comando: | ||
|
||
```bash | ||
./cmr_cache | ||
``` | ||
|
||
Por padrão, o servidor escutará na porta `6347` na sua máquina local. Se desejar, você pode alterar a porta e outras configurações em `config/host.yaml`. | ||
|
||
### Exemplo de uso com Python | ||
|
||
Aqui está um exemplo simples de como interagir com o servidor CMR Cache utilizando Python: | ||
|
||
```python | ||
import socket | ||
|
||
# Conectando ao servidor CMR Cache | ||
HOST = 'localhost' | ||
PORT = 6347 | ||
|
||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: | ||
sock.connect((HOST, PORT)) | ||
|
||
# Autenticando | ||
sock.sendall(b'AUTH admin admin\r\n') | ||
response = sock.recv(1024) | ||
print('Response:', response.decode()) | ||
|
||
# Definindo um valor no cache | ||
sock.sendall(b'SET mykey myvalue 3600\r\n') | ||
response = sock.recv(1024) | ||
print('Response:', response.decode()) | ||
|
||
# Obtendo um valor do cache | ||
sock.sendall(b'GET mykey\r\n') | ||
response = sock.recv(1024) | ||
print('Response:', response.decode()) | ||
``` | ||
|
||
## 📚 Comandos Suportados | ||
|
||
| Comando | Descrição | | ||
|------------------------|----------------------------------------------------------| | ||
| `SET key value` | Define um valor para a chave | | ||
| `SET key value expire` | Define um valor com tempo de expiração | | ||
| `GET key` | Retorna o valor associado à chave | | ||
| `DEL key` | Remove uma chave | | ||
| `AUTH user password` | Autentica o usuário com a senha | | ||
| `USE database` | Especifica qual banco de dados será utilizado | | ||
|
||
## 🌟 Contribuindo | ||
|
||
Contribuições são bem-vindas! Sinta-se à vontade para abrir issues ou enviar pull requests. Agradecemos qualquer tipo de contribuição para tornar o CMR Cache melhor para todos. | ||
|
||
### Como contribuir | ||
|
||
1. Faça um fork do repositório. | ||
2. Crie uma branch para sua feature (`git checkout -b feat/minha-feature`). | ||
3. Commit suas mudanças (`git commit -m 'feat: Adiciona nova feature'`). | ||
4. Envie seu código para o repositório (`git push origin feat/minha-feature`). | ||
5. Abra um Pull Request. | ||
|
||
## 📝 Licença | ||
|
||
Este projeto está licenciado sob a [MIT License](LICENSE). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
## 📌 Tarefas Pendentes | ||
|
||
### Funcionalidades | ||
- [ ] Implementar expiração dos valores ao utilizar o comando `SET key value expire`. | ||
|
||
### Melhorias | ||
- [ ] Melhorar o método de salvamento dos dados no arquivo `.dat`. | ||
- [ ] Criar um dashboard de monitoramento para o servidor. | ||
|
||
### Testes | ||
- [ ] Escrever testes unitários para os principais comandos (`SET`, `GET`, `DEL`). | ||
|
||
### Documentação | ||
- [ ] Criar documentação detalhada sobre a utilização do CMR Cache. | ||
|
||
### Outros | ||
- [ ] Adicionar logs detalhados para as operações do servidor. | ||
- [ ] Melhorar o tratamento de erros em operações que falharem. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
connect: | ||
max-clients: 100 # max clients | ||
auth: | ||
allow-ip: # Remove makes it accept all IPs | ||
- localhost | ||
- 127.0.0.1 | ||
|
||
basic: # Auth basic | ||
- user: admin | ||
pass: admin | ||
db: cache # "*" releases connection in all db |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
host: | ||
address: 0.0.0.0 | ||
port: 6347 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
/* | ||
* MIT License | ||
* | ||
* Copyright 2024 Gabriel Camargo | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated | ||
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the | ||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit | ||
* persons to whom the Software is furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the | ||
* Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO | ||
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
* | ||
* | ||
*/ | ||
|
||
#include "cache.h" | ||
|
||
Cache::Cache(){ | ||
std::ifstream file("data/databases.dat"); | ||
if (file.is_open()){ | ||
size_t cacheSize; | ||
file.read(reinterpret_cast<char*>(&cacheSize), sizeof(cacheSize)); | ||
|
||
for (size_t i = 0; i < cacheSize; ++i) { | ||
std::string key; | ||
size_t keySize; | ||
file.read(reinterpret_cast<char*>(&keySize), sizeof(keySize)); | ||
key.resize(keySize); | ||
file.read(&key[0], keySize); | ||
|
||
std::unordered_map<std::string, CacheStruct> map; | ||
|
||
size_t mapSize; | ||
file.read(reinterpret_cast<char*>(&mapSize), sizeof(mapSize)); | ||
|
||
for (size_t f = 0; f < mapSize; ++f) { | ||
std::string itemKey; | ||
size_t itemKeySize; | ||
file.read(reinterpret_cast<char*>(&itemKeySize), sizeof(itemKeySize)); | ||
itemKey.resize(itemKeySize); | ||
file.read(&itemKey[0], itemKeySize); | ||
|
||
CacheStruct cacheStruct; | ||
cacheStruct.deserialize(file); | ||
|
||
map[itemKey] = cacheStruct; | ||
} | ||
|
||
cache_[key] = map; | ||
} | ||
} | ||
} | ||
|
||
std::string Cache::get(std::string db, std::string key){ | ||
if (cache_.find(db) != cache_.end()) { | ||
if (cache_[db].find(key) != cache_[db].end()){ | ||
return cache_[db][key].value; | ||
} | ||
} | ||
|
||
return ""; | ||
} | ||
|
||
bool Cache::set(std::string db, std::string key, std::string value, int expire){ | ||
|
||
CacheStruct data; | ||
data.value = value; | ||
data.expire = expire; | ||
|
||
cache_[db][key] = data; | ||
save(); | ||
|
||
return true; | ||
} | ||
|
||
bool Cache::del(std::string db, std::string key){ | ||
if (cache_.find(db) != cache_.end()) { | ||
if (cache_[db].find(key) != cache_[db].end()){ | ||
cache_[db].erase(key); | ||
save(); | ||
|
||
return true; | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
|
||
void Cache::save(){ | ||
std::ofstream file("data/databases.dat"); | ||
|
||
size_t cacheSize = cache_.size(); | ||
file.write(reinterpret_cast<const char*>(&cacheSize), sizeof(cacheSize)); | ||
|
||
for (const auto& row: cache_) { | ||
const std::string& key = row.first; | ||
const std::unordered_map<std::string, CacheStruct>& map = row.second; | ||
|
||
size_t keySize = key.size(); | ||
file.write(reinterpret_cast<const char*>(&keySize), sizeof(keySize)); | ||
file.write(key.data(), keySize); | ||
|
||
size_t mapSize = map.size(); | ||
file.write(reinterpret_cast<const char*>(&mapSize), sizeof(mapSize)); | ||
|
||
for (const auto& rowPair: map) { | ||
const std::string& pairKey = rowPair.first; | ||
const CacheStruct& cachedata = rowPair.second; | ||
|
||
size_t pairKeySize = pairKey.size(); | ||
file.write(reinterpret_cast<const char*>(&pairKeySize), sizeof(pairKeySize)); | ||
file.write(pairKey.data(), pairKeySize); | ||
|
||
cachedata.serialize(file); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
/* | ||
* MIT License | ||
* | ||
* Copyright 2024 Gabriel Camargo | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated | ||
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the | ||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit | ||
* persons to whom the Software is furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the | ||
* Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO | ||
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
* | ||
* | ||
*/ | ||
|
||
#ifndef CORE_CACHE_H | ||
#define CORE_CACHE_H | ||
|
||
#include <string> | ||
#include <fstream> | ||
#include <unordered_map> | ||
|
||
typedef struct CacheStruct { | ||
std::string value; | ||
int expire; | ||
|
||
void serialize(std::ofstream& stream) const { | ||
size_t size = value.size(); | ||
stream.write(reinterpret_cast<const char*>(&size), sizeof(size)); | ||
stream.write(value.data(), size); | ||
stream.write(reinterpret_cast<const char*>(&expire), sizeof(expire)); | ||
} | ||
|
||
void deserialize(std::ifstream& stream) { | ||
size_t size; | ||
stream.read(reinterpret_cast<char*>(&size), sizeof(size)); | ||
value.resize(size); | ||
stream.read(&value[0], size); | ||
stream.read(reinterpret_cast<char*>(&expire), sizeof(expire)); | ||
} | ||
}; | ||
|
||
class Cache { | ||
public: | ||
Cache (); | ||
std::string get(std::string db, std::string key); | ||
bool set(std::string db, std::string key, std::string value, int expire = -1); | ||
bool del(std::string db, std::string key); | ||
void save(); | ||
|
||
private: | ||
std::unordered_map<std::string, std::unordered_map<std::string, CacheStruct>> cache_; | ||
}; | ||
|
||
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
* MIT License | ||
* | ||
* Copyright 2024 Gabriel Camargo | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated | ||
* documentation files (the “Software”), to deal in the Software without restriction, including without limitation the | ||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit | ||
* persons to whom the Software is furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the | ||
* Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO | ||
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | ||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
* | ||
* | ||
*/ | ||
|
||
#ifndef CORE_H | ||
#define CORE_H | ||
|
||
#include "cache/cache.cpp" | ||
#include "entities/config.h" | ||
#include "socket/socket.cpp" | ||
|
||
#endif |
Oops, something went wrong.