Skip to content

Open Source alternative to Algolia + Pinecone and an Easier-to-Use alternative to ElasticSearch ⚡ 🔍 ✨ Fast, typo tolerant, in-memory fuzzy Search Engine for building delightful search experiences

Allow collections to be symlinked by an alternative name.

Kishore Nallan13964b6a5756
diff --git a/include/collection_manager.h b/include/collection_manager.h
index dfcf9382..3c8e504a 100644
--- a/include/collection_manager.h
+++ b/include/collection_manager.h
@@ -16,6 +16,8 @@ private:
spp::sparse_hash_map<uint32_t, std::string> collection_id_names;
+ spp::sparse_hash_map<std::string, std::string> collection_symlinks;
+
// Auto incrementing ID assigned to each collection
// Using a ID instead of a collection's name makes renaming possible
uint32_t next_collection_id;
@@ -67,9 +69,21 @@ public:
uint32_t get_next_collection_id();
+ static std::string get_symlink_key(const std::string & symlink_name);
+
void set_next_collection_id(uint32_t next_id);
Store* get_store();
+ // symlinks
+ Option<std::string> resolve_symlink(const std::string & symlink_name);
+
+ spp::sparse_hash_map<std::string, std::string> get_symlinks();
+
+ bool upsert_symlink(const std::string & symlink_name, const std::string & collection_name);
+
+ bool delete_symlink(const std::string & symlink_name);
+
static constexpr const char* NEXT_COLLECTION_ID_KEY = "$CI";
+ static constexpr const char* SYMLINK_PREFIX = "$SL";
};
\ No newline at end of file
diff --git a/include/core_api.h b/include/core_api.h
index 3b711c59..89ef7d7a 100644
--- a/include/core_api.h
+++ b/include/core_api.h
@@ -31,4 +31,3 @@ void on_send_response(void *data);
void collection_export_handler(http_req* req, http_res* res, void* data);
static constexpr const char* SEND_RESPONSE_MSG = "send_response";
-static constexpr const char* REPLICATION_EVENT_MSG = "replication_event";
\ No newline at end of file
diff --git a/include/http_server.h b/include/http_server.h
index 101c02d1..9a563082 100644
--- a/include/http_server.h
+++ b/include/http_server.h
@@ -66,8 +66,6 @@ private:
static int send_401_unauthorized(h2o_req_t *req);
- static constexpr const char* SEND_RESPONSE_MSG = "send_response";
-
public:
HttpServer(std::string listen_address, uint32_t listen_port,
std::string ssl_cert_path, std::string ssl_cert_key_path, bool cors_enabled);
diff --git a/include/replicator.h b/include/replicator.h
index bc8b56c7..6a5bb94c 100644
--- a/include/replicator.h
+++ b/include/replicator.h
@@ -10,14 +10,15 @@
#include <iostream>
#include "logger.h"
+static constexpr const char* REPLICATION_EVENT_MSG = "replication_event";
+
struct ReplicationEvent {
std::string type;
std::string key;
std::string value;
ReplicationEvent(const std::string& type, const uint32_t collection_id,
- const std::string& key, const std::string& value):
- type(type), key(key), value(value) {
+ const std::string& key, const std::string& value): type(type), key(key), value(value) {
}
};
@@ -57,6 +58,12 @@ public:
key.ToString(), value.ToString());
server->send_message(REPLICATION_EVENT_MSG, replication_event);
}
+
+ if(parts.size() >= 2 && parts[0] == CollectionManager::SYMLINK_PREFIX) {
+ ReplicationEvent* replication_event = new ReplicationEvent("ADD_SYMLINK", 0,
+ key.ToString(), value.ToString());
+ server->send_message(REPLICATION_EVENT_MSG, replication_event);
+ }
}
void Delete(const rocksdb::Slice& key) {
@@ -73,6 +80,12 @@ public:
server->send_message(REPLICATION_EVENT_MSG, replication_event);
}
+ if(parts.size() >= 2 && parts[0] == CollectionManager::SYMLINK_PREFIX) {
+ ReplicationEvent* replication_event = new ReplicationEvent("REMOVE_SYMLINK", 0,
+ key.ToString(), "");
+ server->send_message(REPLICATION_EVENT_MSG, replication_event);
+ }
+
}
void Merge(const rocksdb::Slice& key, const rocksdb::Slice& value) {
@@ -180,6 +193,15 @@ public:
collection->index_in_memory(document, seq_id);
}
+ if(replication_event->type == "ADD_SYMLINK") {
+ CollectionManager & collection_manager = CollectionManager::get_instance();
+ std::vector<std::string> parts;
+ std::string symlink_prefix_key = std::string(CollectionManager::SYMLINK_PREFIX) + "_";
+ StringUtils::split(replication_event->key, parts, symlink_prefix_key); // symlink_prefix, symlink_name
+ std::string & symlink_name = parts[0];
+ collection_manager.upsert_symlink(symlink_name, replication_event->value);
+ }
+
if(replication_event->type == "INCR_COLLECTION_NEXT_SEQ") {
CollectionManager & collection_manager = CollectionManager::get_instance();
const std::string & collection_name = replication_event->key.substr(strlen(Collection::COLLECTION_NEXT_SEQ_PREFIX)+1);
@@ -195,6 +217,15 @@ public:
collection->remove(parts[2], false);
}
+ if(replication_event->type == "REMOVE_SYMLINK") {
+ CollectionManager & collection_manager = CollectionManager::get_instance();
+ std::vector<std::string> parts;
+ std::string symlink_prefix_key = std::string(CollectionManager::SYMLINK_PREFIX) + "_";
+ StringUtils::split(replication_event->key, parts, symlink_prefix_key); // symlink_prefix, symlink_name
+ std::string & symlink_name = parts[0];
+ collection_manager.delete_symlink(symlink_name);
+ }
+
if(replication_event->type == "DROP_COLLECTION") {
CollectionManager & collection_manager = CollectionManager::get_instance();
// <collection_meta_prefix>_<collection_name>
@@ -204,4 +235,4 @@ public:
delete replication_event;
}
-};
\ No newline at end of file
+};
diff --git a/include/topster.h b/include/topster.h
index 2f803c82..0e158c5b 100644
--- a/include/topster.h
+++ b/include/topster.h
@@ -81,7 +81,7 @@ struct Topster {
}
keys.erase(kvs[start]->key);
- keys.emplace(key, kvs[start]);
+ keys[key] = kvs[start];
kvs[start]->key = key;
kvs[start]->field_id = field_id;
@@ -130,7 +130,7 @@ struct Topster {
kvs[start]->primary_attr = primary_attr;
kvs[start]->secondary_attr = secondary_attr;
- keys.emplace(key, kvs[start]);
+ keys[key] = kvs[start];
if(key_found) {
// need to sift down if it's a replace
diff --git a/include/typesense_server.h b/include/typesense_server.h
new file mode 100644
index 00000000..8bcd356b
--- /dev/null
+++ b/include/typesense_server.h
@@ -0,0 +1,143 @@
+#pragma once
+
+#include <string>
+#include <iostream>
+#include <cmdline.h>
+#include "logger.h"
+#include "store.h"
+#include "collection_manager.h"
+#include "http_server.h"
+#include "replicator.h"
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+HttpServer* server;
+
+void catch_interrupt(int sig) {
+ LOG(INFO) << "Stopping Typesense server...";
+ signal(sig, SIG_IGN); // ignore for now as we want to shut down elegantly
+ server->stop();
+}
+
+bool directory_exists(const std::string & dir_path) {
+ struct stat info;
+ return stat(dir_path.c_str(), &info) == 0 && (info.st_mode & S_IFDIR);
+}
+
+void init_cmdline_options(cmdline::parser & options, int argc, char **argv) {
+ options.set_program_name("./typesense-server");
+
+ options.add<std::string>("data-dir", 'd', "Directory where data will be stored.", true);
+ options.add<std::string>("api-key", 'a', "API key that allows all operations.", true);
+ options.add<std::string>("search-only-api-key", 's', "API key that allows only searches.", false);
+
+ options.add<std::string>("listen-address", 'h', "Address to which Typesense server binds.", false, "0.0.0.0");
+ options.add<uint32_t>("listen-port", 'p', "Port on which Typesense server listens.", false, 8108);
+ options.add<std::string>("master", 'm', "Provide the master's address in http(s)://<master_address>:<master_port> "
+ "format to start the server as a read-only replica.", false, "");
+
+ options.add<std::string>("ssl-certificate", 'c', "Path to the SSL certificate file.", false, "");
+ options.add<std::string>("ssl-certificate-key", 'k', "Path to the SSL certificate key file.", false, "");
+
+ options.add("enable-cors", '\0', "Enable CORS requests.");
+ options.add<std::string>("log-dir", '\0', "Path to the log file.", false, "");
+}
+
+int init_logger(cmdline::parser & options, std::unique_ptr<g3::LogWorker> & log_worker) {
+ // remove SIGTERM since we handle it on our own
+ g3::overrideSetupSignals({{SIGABRT, "SIGABRT"}, {SIGFPE, "SIGFPE"},{SIGILL, "SIGILL"}, {SIGSEGV, "SIGSEGV"},});
+
+ // we can install new signal handlers only after overriding above
+ signal(SIGINT, catch_interrupt);
+ signal(SIGTERM, catch_interrupt);
+
+ std::string log_dir = options.get<std::string>("log-dir");
+
+ if(log_dir.empty()) {
+ // use console logger if log dir is not specified
+ log_worker->addSink(std2::make_unique<ConsoleLoggingSink>(),
+ &ConsoleLoggingSink::ReceiveLogMessage);
+ } else {
+ if(!directory_exists(log_dir)) {
+ std::cerr << "Typesense failed to start. " << "Log directory " << log_dir << " does not exist.";
+ return 1;
+ }
+
+ log_worker->addDefaultLogger("typesense", log_dir, "");
+
+ std::cout << "Starting Typesense " << TYPESENSE_VERSION << ". Log directory is configured as: "
+ << log_dir << std::endl;
+ }
+
+ g3::initializeLogging(log_worker.get());
+
+ return 0;
+}
+
+int run_server(cmdline::parser & options, void (*master_server_routes)(), void (*replica_server_routes)()) {
+ LOG(INFO) << "Starting Typesense " << TYPESENSE_VERSION << std::flush;
+
+ if(!directory_exists(options.get<std::string>("data-dir"))) {
+ LOG(ERR) << "Typesense failed to start. " << "Data directory " << options.get<std::string>("data-dir")
+ << " does not exist.";
+ return 1;
+ }
+
+ Store store(options.get<std::string>("data-dir"));
+
+ LOG(INFO) << "Loading collections from disk...";
+
+ CollectionManager & collectionManager = CollectionManager::get_instance();
+ Option<bool> init_op = collectionManager.init(&store, options.get<std::string>("api-key"),
+ options.get<std::string>("search-only-api-key"));
+
+ if(init_op.ok()) {
+ LOG(INFO) << "Finished loading collections from disk.";
+ } else {
+ LOG(ERR)<< "Typesense failed to start. " << "Could not load collections from disk: " << init_op.error();
+ return 1;
+ }
+
+ server = new HttpServer(
+ options.get<std::string>("listen-address"),
+ options.get<uint32_t>("listen-port"),
+ options.get<std::string>("ssl-certificate"),
+ options.get<std::string>("ssl-certificate-key"),
+ options.exist("enable-cors")
+ );
+
+ server->set_auth_handler(handle_authentication);
+
+ server->on(SEND_RESPONSE_MSG, on_send_response);
+ server->on(REPLICATION_EVENT_MSG, Replicator::on_replication_event);
+
+ if(options.get<std::string>("master").empty()) {
+ master_server_routes();
+ } else {
+ replica_server_routes();
+
+ const std::string & master_host_port = options.get<std::string>("master");
+ std::vector<std::string> parts;
+ StringUtils::split(master_host_port, parts, ":");
+ if(parts.size() != 3) {
+ LOG(ERR) << "Invalid value for --master option. Usage: http(s)://<master_address>:<master_port>";
+ return 1;
+ }
+
+ LOG(INFO) << "Typesense is starting as a read-only replica... Spawning replication thread...";
+ std::thread replication_thread([&master_host_port, &store, &options]() {
+ Replicator::start(::server, master_host_port, options.get<std::string>("api-key"), store);
+ });
+
+ replication_thread.detach();
+ }
+
+ int ret_code = server->run();
+
+ // we are out of the event loop here
+ delete server;
+ CollectionManager::get_instance().dispose();
+
+ return ret_code;
+}
\ No newline at end of file
diff --git a/src/collection_manager.cpp b/src/collection_manager.cpp
index 48e43849..4bafcbb6 100644
--- a/src/collection_manager.cpp
+++ b/src/collection_manager.cpp
@@ -1,4 +1,3 @@
-
#include <string>
#include <vector>
#include <json.hpp>
@@ -106,10 +105,10 @@ Option<bool> CollectionManager::init(Store *store, const std::string & auth_key,
Option<uint32_t> seq_id_op = collection->doc_id_to_seq_id(document["id"]);
if(!seq_id_op.ok()) {
- delete iter;
- return Option<bool>(500, std::string("Error while fetching sequence id of document id " +
- document["id"].get<std::string>() + " in collection `" +
- collection->get_name() + "`"));
+ delete iter;
+ return Option<bool>(500, std::string("Error while fetching sequence id of document id " +
+ document["id"].get<std::string>() + " in collection `" +
+ collection->get_name() + "`"));
}
collection->index_in_memory(document, seq_id_op.get());
@@ -121,6 +120,15 @@ Option<bool> CollectionManager::init(Store *store, const std::string & auth_key,
add_to_collections(collection);
}
+ std::string symlink_prefix_key = std::string(SYMLINK_PREFIX) + "_";
+ rocksdb::Iterator* iter = store->scan(symlink_prefix_key);
+ while(iter->Valid() && iter->key().starts_with(symlink_prefix_key)) {
+ std::vector<std::string> parts;
+ StringUtils::split(iter->key().ToString(), parts, symlink_prefix_key);
+ collection_symlinks[parts[0]] = iter->value().ToString();
+ iter->Next();
+ }
+
return Option<bool>(true);
}
@@ -159,8 +167,8 @@ Option<Collection*> CollectionManager::create_collection(const std::string name,
if(field.name == default_sorting_field && !(field.type == field_types::INT32 ||
field.type == field_types::FLOAT)) {
- return Option<Collection*>(400, "Default sorting field `" + default_sorting_field + "` must be of type int32 "
- "or float.");
+ return Option<Collection*>(400, "Default sorting field `" + default_sorting_field +
+ "` must be of type int32 or float.");
}
}
@@ -192,6 +200,14 @@ Collection* CollectionManager::get_collection(const std::string & collection_nam
return collections.at(collection_name);
}
+ // a symlink name takes lesser precedence over a real collection name
+ if(collection_symlinks.count(collection_name) != 0) {
+ const std::string & symlinked_name = collection_symlinks.at(collection_name);
+ if(collections.count(symlinked_name) != 0) {
+ return collections.at(symlinked_name);
+ }
+ }
+
return nullptr;
}
@@ -252,10 +268,44 @@ uint32_t CollectionManager::get_next_collection_id() {
return next_collection_id;
}
+std::string CollectionManager::get_symlink_key(const std::string & symlink_name) {
+ return std::string(SYMLINK_PREFIX) + "_" + symlink_name;
+}
+
void CollectionManager::set_next_collection_id(uint32_t next_id) {
next_collection_id = next_id;
}
+spp::sparse_hash_map<std::string, std::string> CollectionManager::get_symlinks() {
+ return collection_symlinks;
+}
+
+Option<std::string> CollectionManager::resolve_symlink(const std::string & symlink_name) {
+ if(collection_symlinks.count(symlink_name) != 0) {
+ return Option<std::string>(collection_symlinks.at(symlink_name));
+ }
+
+ return Option<std::string>(404, "Not found.");
+}
+
+bool CollectionManager::upsert_symlink(const std::string & symlink_name, const std::string & collection_name) {
+ bool inserted = store->insert(get_symlink_key(symlink_name), collection_name);
+ if(!inserted) {
+ return false;
+ }
+ collection_symlinks[symlink_name] = collection_name;
+ return true;
+}
+
+bool CollectionManager::delete_symlink(const std::string & symlink_name) {
+ bool removed = store->remove(get_symlink_key(symlink_name));
+ if(!removed) {
+ return false;
+ }
+ collection_symlinks.erase(symlink_name);
+ return true;
+}
+
Store* CollectionManager::get_store() {
return store;
-}
\ No newline at end of file
+}
diff --git a/src/main/typesense_server.cpp b/src/main/typesense_server.cpp
index 3095ac34..10bf456a 100644
--- a/src/main/typesense_server.cpp
+++ b/src/main/typesense_server.cpp
@@ -1,29 +1,5 @@
-#include <signal.h>
-#include <iostream>
-#include <vector>
-#include <string>
-#include <thread>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <cmdline.h>
-#include "http_server.h"
#include "core_api.h"
-#include "string_utils.h"
-#include "replicator.h"
-#include "logger.h"
-
-HttpServer* server;
-
-void catch_interrupt(int sig) {
- LOG(INFO) << "Stopping Typesense server...";
- signal(sig, SIG_IGN); // ignore for now as we want to shut down elegantly
- server->stop();
-}
-
-bool directory_exists(const std::string & dir_path) {
- struct stat info;
- return stat(dir_path.c_str(), &info) == 0 && (info.st_mode & S_IFDIR);
-}
+#include "typesense_server.h"
void master_server_routes() {
// collection management
@@ -64,115 +40,15 @@ void replica_server_routes() {
}
int main(int argc, char **argv) {
- // remove SIGTERM since we handle it on our own
- g3::overrideSetupSignals({{SIGABRT, "SIGABRT"}, {SIGFPE, "SIGFPE"},{SIGILL, "SIGILL"}, {SIGSEGV, "SIGSEGV"},});
-
- // we can install new signal handlers only after overriding above
- signal(SIGINT, catch_interrupt);
- signal(SIGTERM, catch_interrupt);
-
cmdline::parser options;
- options.set_program_name("./typesense-server");
-
- options.add<std::string>("data-dir", 'd', "Directory where data will be stored.", true);
- options.add<std::string>("api-key", 'a', "API key that allows all operations.", true);
- options.add<std::string>("search-only-api-key", 's', "API key that allows only searches.", false);
-
- options.add<std::string>("listen-address", 'h', "Address to which Typesense server binds.", false, "0.0.0.0");
- options.add<uint32_t>("listen-port", 'p', "Port on which Typesense server listens.", false, 8108);
- options.add<std::string>("master", 'm', "Provide the master's address in http(s)://<master_address>:<master_port> "
- "format to start the server as a read-only replica.", false, "");
-
- options.add<std::string>("ssl-certificate", 'c', "Path to the SSL certificate file.", false, "");
- options.add<std::string>("ssl-certificate-key", 'k', "Path to the SSL certificate key file.", false, "");
-
- options.add("enable-cors", '\0', "Enable CORS requests.");
- options.add<std::string>("log-dir", '\0', "Path to the log file.", false, "");
-
+ init_cmdline_options(options, argc, argv);
options.parse_check(argc, argv);
- auto log_worker = g3::LogWorker::createLogWorker();
- std::string log_dir = options.get<std::string>("log-dir");
-
- if(log_dir.empty()) {
- // use console logger if log dir is not specified
- log_worker->addSink(std2::make_unique<ConsoleLoggingSink>(),
- &ConsoleLoggingSink::ReceiveLogMessage);
- } else {
- if(!directory_exists(log_dir)) {
- std::cerr << "Typesense failed to start. " << "Log directory " << log_dir << " does not exist.";
- return 1;
- }
-
- log_worker->addDefaultLogger("typesense", log_dir, "");
-
- std::cout << "Starting Typesense " << TYPESENSE_VERSION << ". Log directory is configured as: "
- << log_dir << std::endl;
+ std::unique_ptr<g3::LogWorker> log_worker = g3::LogWorker::createLogWorker();
+ int ret_code = init_logger(options, log_worker);
+ if(ret_code != 0) {
+ return ret_code;
}
- g3::initializeLogging(log_worker.get());
-
- LOG(INFO) << "Starting Typesense " << TYPESENSE_VERSION;
-
- if(!directory_exists(options.get<std::string>("data-dir"))) {
- LOG(ERR) << "Typesense failed to start. " << "Data directory " << options.get<std::string>("data-dir")
- << " does not exist.";
- return 1;
- }
-
- LOG(INFO) << "Loading collections from disk...";
-
- Store store(options.get<std::string>("data-dir"));
- CollectionManager & collectionManager = CollectionManager::get_instance();
- Option<bool> init_op = collectionManager.init(&store, options.get<std::string>("api-key"),
- options.get<std::string>("search-only-api-key"));
-
- if(init_op.ok()) {
- LOG(INFO) << "Finished loading collections from disk.";
- } else {
- LOG(ERR)<< "Typesense failed to start. " << "Could not load collections from disk: " << init_op.error();
- return 1;
- }
-
- server = new HttpServer(
- options.get<std::string>("listen-address"),
- options.get<uint32_t>("listen-port"),
- options.get<std::string>("ssl-certificate"),
- options.get<std::string>("ssl-certificate-key"),
- options.exist("enable-cors")
- );
-
- server->set_auth_handler(handle_authentication);
-
- server->on(SEND_RESPONSE_MSG, on_send_response);
- server->on(REPLICATION_EVENT_MSG, Replicator::on_replication_event);
-
- if(options.get<std::string>("master").empty()) {
- master_server_routes();
- } else {
- replica_server_routes();
-
- const std::string & master_host_port = options.get<std::string>("master");
- std::vector<std::string> parts;
- StringUtils::split(master_host_port, parts, ":");
- if(parts.size() != 3) {
- LOG(ERR) << "Invalid value for --master option. Usage: http(s)://<master_address>:<master_port>";
- return 1;
- }
-
- LOG(INFO) << "Typesense is starting as a read-only replica... Spawning replication thread...";
- std::thread replication_thread([&master_host_port, &store, &options]() {
- Replicator::start(::server, master_host_port, options.get<std::string>("api-key"), store);
- });
-
- replication_thread.detach();
- }
-
- int return_code = server->run();
-
- // we are out of the event loop here
- delete server;
- CollectionManager::get_instance().dispose();
-
- return return_code;
+ return run_server(options, &master_server_routes, &replica_server_routes);
}
\ No newline at end of file
diff --git a/test/collection_manager_test.cpp b/test/collection_manager_test.cpp
index e101a56d..ef81bea4 100644
--- a/test/collection_manager_test.cpp
+++ b/test/collection_manager_test.cpp
@@ -81,10 +81,10 @@ TEST_F(CollectionManagerTest, CollectionCreation) {
// we already call `collection1->get_next_seq_id` above, which is side-effecting
ASSERT_EQ(1, StringUtils::deserialize_uint32_t(next_seq_id));
ASSERT_EQ("{\"default_sorting_field\":\"points\",\"fields\":[{\"facet\":false,\"name\":\"title\",\"type\":\"string\"},"
- "{\"facet\":false,\"name\":\"starring\",\"type\":\"string\"},"
- "{\"facet\":true,\"name\":\"cast\",\"type\":\"string[]\"},"
- "{\"facet\":false,\"name\":\"points\",\"type\":\"int32\"}"
- "],\"id\":0,\"name\":\"collection1\"}", collection_meta_json);
+ "{\"facet\":false,\"name\":\"starring\",\"type\":\"string\"},"
+ "{\"facet\":true,\"name\":\"cast\",\"type\":\"string[]\"},"
+ "{\"facet\":false,\"name\":\"points\",\"type\":\"int32\"}"
+ "],\"id\":0,\"name\":\"collection1\"}", collection_meta_json);
ASSERT_EQ("1", next_collection_id);
}
@@ -175,4 +175,69 @@ TEST_F(CollectionManagerTest, DropCollectionCleanly) {
ASSERT_EQ(1, collectionManager.get_next_collection_id());
delete it;
+}
+
+TEST_F(CollectionManagerTest, Symlinking) {
+ CollectionManager & cmanager = CollectionManager::get_instance();
+ std::string state_dir_path = "/tmp/typesense_test/cmanager_test_db";
+ system(("rm -rf "+state_dir_path+" && mkdir -p "+state_dir_path).c_str());
+ Store *store = new Store(state_dir_path);
+ cmanager.init(store, "auth_key", "search_auth_key");
+
+ // try resolving on a blank slate
+ Option<std::string> collection_option = cmanager.resolve_symlink("collection");
+
+ ASSERT_FALSE(collection_option.ok());
+ ASSERT_EQ(404, collection_option.code());
+
+ ASSERT_EQ(0, cmanager.get_symlinks().size());
+
+ // insert a symlink
+ bool inserted = cmanager.upsert_symlink("collection", "collection_2018");
+ ASSERT_TRUE(inserted);
+
+ collection_option = cmanager.resolve_symlink("collection");
+ ASSERT_TRUE(collection_option.ok());
+ ASSERT_EQ("collection_2018", collection_option.get());
+
+ // let's try inserting another symlink
+ cmanager.upsert_symlink("company", "company_2018");
+ collection_option = cmanager.resolve_symlink("company");
+ ASSERT_TRUE(collection_option.ok());
+ ASSERT_EQ("company_2018", collection_option.get());
+
+ ASSERT_EQ(2, cmanager.get_symlinks().size());
+
+ // update existing symlink
+ inserted = cmanager.upsert_symlink("company", "company_2019");
+ ASSERT_TRUE(inserted);
+ collection_option = cmanager.resolve_symlink("company");
+ ASSERT_TRUE(collection_option.ok());
+ ASSERT_EQ("company_2019", collection_option.get());
+
+ // remove link
+ cmanager.delete_symlink("collection");
+ collection_option = cmanager.resolve_symlink("collection");
+ ASSERT_FALSE(collection_option.ok());
+ ASSERT_EQ(404, collection_option.code());
+
+ // try adding a few more symlinks
+ cmanager.upsert_symlink("company_1", "company_2018");
+ cmanager.upsert_symlink("company_2", "company_2019");
+ cmanager.upsert_symlink("company_3", "company_2020");
+
+ // should be able to restore state on init
+ CollectionManager & cmanager2 = CollectionManager::get_instance();
+ cmanager2.init(store, "auth_key", "search_auth_key");
+ collection_option = cmanager2.resolve_symlink("company");
+ ASSERT_TRUE(collection_option.ok());
+ ASSERT_EQ("company_2019", collection_option.get());
+
+ collection_option = cmanager2.resolve_symlink("company_1");
+ ASSERT_TRUE(collection_option.ok());
+ ASSERT_EQ("company_2018", collection_option.get());
+
+ collection_option = cmanager2.resolve_symlink("company_3");
+ ASSERT_TRUE(collection_option.ok());
+ ASSERT_EQ("company_2020", collection_option.get());
}
\ No newline at end of file