├── .gitignore ├── Src ├── Tools │ ├── Word.h │ ├── Word.cpp │ └── ClientProtocol.h ├── Client.h ├── Main.cpp └── Client.cpp ├── generate.bat ├── .gitmodules ├── NOTICE ├── Marefile └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | Build/ 2 | *.sdf 3 | *.opensdf 4 | *.suo 5 | *.vcxproj.user 6 | *.vcxproj 7 | *.vcxproj.filters 8 | *.sln 9 | -------------------------------------------------------------------------------- /Src/Tools/Word.h: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | #include 6 | 7 | class Word 8 | { 9 | public: 10 | static size_t split(const String& data, List& result); 11 | }; 12 | -------------------------------------------------------------------------------- /generate.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | if not exist Build\Debug\mare\mare.exe call Ext\mare\compile.bat --buildDir=Build/Debug/mare --outputDir=Build/Debug/mare --sourceDir=Ext/mare/src 4 | if not "%1"=="" (Build\Debug\mare\mare.exe %*) else Build\Debug\mare\mare.exe --vcxproj=2013 5 | 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "Ext/libnstd"] 2 | path = Ext/libnstd 3 | url = https://github.com/craflin/libnstd.git 4 | [submodule "Ext/mare"] 5 | path = Ext/mare 6 | url = https://github.com/craflin/mare.git 7 | [submodule "Ext/lz4"] 8 | path = Ext/lz4 9 | url = https://github.com/Cyan4973/lz4.git 10 | [submodule "Ext/libzlimdbclient"] 11 | path = Ext/libzlimdbclient 12 | url = https://github.com/craflin/libzlimdbclient.git 13 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | 2 | Copyright 2015 Colin Graf 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | -------------------------------------------------------------------------------- /Src/Tools/Word.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Word.h" 3 | 4 | size_t Word::split(const String& data, List& result) 5 | { 6 | const char_t* start = data; 7 | const char_t* str = start; 8 | for(;;) 9 | { 10 | while(String::isSpace(*str)) 11 | ++str; 12 | if(!*str) 13 | break; 14 | if(*str == _T('"')) 15 | { 16 | ++str; 17 | const char* end = str; 18 | for(; *end; ++end) 19 | if(*end == _T('\\') && end[1] == _T('"')) 20 | ++end; 21 | else if(*end == _T('"')) 22 | break; 23 | if(end > str) // TODO: read escaped spaces as ordinary spaces? 24 | result.append(data.substr(str - start, end - str)); 25 | str = end; 26 | if(*str) 27 | ++str; // skip closing '"' 28 | } 29 | else 30 | { 31 | const char* end = str; 32 | for(; *end; ++end) 33 | if(String::isSpace(*end)) 34 | break; 35 | // TODO: read escaped spaces as ordinary spaces 36 | result.append(data.substr(str - start, end - str)); 37 | str = end; 38 | } 39 | } 40 | return result.size(); 41 | } 42 | -------------------------------------------------------------------------------- /Src/Tools/ClientProtocol.h: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | 6 | #include 7 | 8 | class ClientProtocol 9 | { 10 | public: 11 | static bool_t getString(const zlimdb_entity& entity, size_t offset, size_t length, String& result) 12 | { 13 | if(offset + length > entity.size) 14 | return false; 15 | result.attach((const char_t*)&entity + offset, length); 16 | return true; 17 | } 18 | 19 | //static void_t setHeader(Header& header, MessageType type, size_t size, uint32_t requestId, uint8_t flags = 0) 20 | //{ 21 | // header.size = size; 22 | // header.messageType = type; 23 | // header.requestId = requestId; 24 | // header.flags = flags; 25 | //} 26 | // 27 | static void_t setEntityHeader(zlimdb_entity& entity, uint64_t id, uint64_t time, uint16_t size) 28 | { 29 | entity.id = id; 30 | entity.time = time; 31 | entity.size = size; 32 | } 33 | 34 | static void_t setString(zlimdb_entity& entity, uint16_t& length, size_t offset, const String& str) 35 | { 36 | length = str.length(); 37 | Memory::copy((byte_t*)&entity + offset, (const char_t*)str, str.length()); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /Marefile: -------------------------------------------------------------------------------- 1 | 2 | buildDir = "Build/$(configuration)/$(target)" 3 | 4 | targets = { 5 | 6 | zlimdbclient = cppApplication + { 7 | dependencies = { "libnstd", "liblz4", "libzlimdbclient" } 8 | includePaths = { "Ext/libnstd/include", "Ext/lz4", "Ext/libzlimdbclient/include" } 9 | libPaths = { "$(dir $(buildDir))/libnstd", "$(dir $(buildDir))/liblz4", "$(dir $(buildDir))/libzlimdbclient" } 10 | libs = { "nstd", "zlimdbclient", "lz4" } 11 | root = "Src" 12 | files = { 13 | "Src/**.cpp" = cppSource 14 | "Src/**.h" 15 | } 16 | if tool == "vcxproj" { 17 | libs += { "ws2_32" } 18 | linkFlags += { "/SUBSYSTEM:CONSOLE" } 19 | } 20 | if platform == "Linux" { 21 | libs += { "pthread", "rt" } 22 | cppFlags += { "-Wno-delete-non-virtual-dtor" } 23 | } 24 | } 25 | 26 | include "Ext/libnstd/libnstd.mare" 27 | libnstd += { 28 | folder = "Ext" 29 | } 30 | 31 | include "Ext/libzlimdbclient/libzlimdbclient.mare" 32 | libzlimdbclient += { 33 | folder = "Ext" 34 | } 35 | 36 | liblz4 = cppStaticLibrary + { 37 | folder = "Ext" 38 | includePaths = { "Ext/lz4" } 39 | root = { "Ext/lz4" } 40 | files = { 41 | "Ext/lz4/lz4.c" = cSource, 42 | "Ext/lz4/lz4.h" 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Src/Client.h: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | typedef struct _zlimdb_ zlimdb; 11 | 12 | class Client 13 | { 14 | public: 15 | Client(); 16 | ~Client(); 17 | 18 | String getLastError() const {return error;} 19 | 20 | bool_t connect(const String& userName, const String& password, const String& address); 21 | 22 | void_t disconnect(); 23 | 24 | void_t listUsers() {enqueueAction(listUsersAction);} 25 | void_t addUser(const String& userName, const String& password) {enqueueAction(addUserAction, userName, password);} 26 | void_t listTables() {enqueueAction(listTablesAction);} 27 | void_t createTable(const String& name) {enqueueAction(createTableAction, name);} 28 | void_t removeTable() {enqueueAction(removeTableAction);} 29 | void_t clearTable() {enqueueAction(clearTableAction);} 30 | void_t copyTable(const String& newName) {enqueueAction(copyTableAction, newName);} 31 | void_t findTable(const String& name) {enqueueAction(findTableAction, name);} 32 | void_t selectTable(uint32_t tableId) {enqueueAction(selectTableAction, tableId);} 33 | void_t query() {enqueueAction(queryAction);} 34 | void_t query(uint64_t sinceId) {enqueueAction(queryAction, sinceId);} 35 | void_t add(const String& value) {enqueueAction(addAction, value);} 36 | void_t subscribe() {enqueueAction(subscribeAction);} 37 | void_t sync() {enqueueAction(syncAction);} 38 | 39 | private: 40 | enum ActionType 41 | { 42 | quitAction, 43 | listUsersAction, 44 | addUserAction, 45 | listTablesAction, 46 | createTableAction, 47 | removeTableAction, 48 | clearTableAction, 49 | copyTableAction, 50 | findTableAction, 51 | selectTableAction, 52 | queryAction, 53 | addAction, 54 | subscribeAction, 55 | syncAction, 56 | }; 57 | struct Action 58 | { 59 | ActionType type; 60 | Variant param1; 61 | Variant param2; 62 | }; 63 | 64 | private: 65 | static uint_t threadProc(void_t* param); 66 | static void_t zlimdbCallback(void_t* userData, const void_t* data) {((Client*)userData)->zlimdbCallback(data);} 67 | 68 | void_t enqueueAction(ActionType type, const Variant& param1 = Variant(), const Variant& param2 = Variant()); 69 | 70 | void_t zlimdbCallback(const void_t* data); 71 | 72 | uint8_t process(); 73 | 74 | void_t handleAction(const Action& action); 75 | 76 | private: 77 | String error; 78 | zlimdb* zdb; 79 | volatile bool keepRunning; 80 | Thread thread; 81 | Mutex actionMutex; 82 | List actions; 83 | uint32_t selectedTable; 84 | 85 | private: 86 | static String getZlimdbError(); 87 | }; 88 | -------------------------------------------------------------------------------- /Src/Main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | #include "Tools/Word.h" 6 | 7 | #include "Client.h" 8 | 9 | void_t help() 10 | { 11 | Console::printf("listUsers - Show list of users.\n"); 12 | Console::printf("addUser - Add a new user.\n"); 13 | Console::printf("list - Show list of tables.\n"); 14 | Console::printf("create - Create a new table.\n"); 15 | Console::printf("find - Find table id by name.\n"); 16 | Console::printf("remove - Remove selected table.\n"); 17 | Console::printf("clear - Clear selected table.\n"); 18 | Console::printf("copy - Create copy of selected table.\n"); 19 | Console::printf("query [] - Query data from selected table.\n"); 20 | Console::printf("select - Select a table for further requests.\n"); 21 | //Console::printf("add - Add string data to selected table.\n"); 22 | //Console::printf("addData - Add bytes to selected table.\n"); 23 | Console::printf("subscribe - Subscribe to selected table.\n"); 24 | Console::printf("sync - Get time synchronization data of the selected table.\n"); 25 | Console::printf("exit - Quit the session.\n"); 26 | } 27 | 28 | int_t main(int_t argc, char_t* argv[]) 29 | { 30 | String password("root"); 31 | String user("root"); 32 | String address("127.0.0.1:13211"); 33 | { 34 | Process::Option options[] = { 35 | {'p', "password", Process::argumentFlag}, 36 | {'u', "user", Process::argumentFlag}, 37 | {'h', "help", Process::optionFlag}, 38 | }; 39 | Process::Arguments arguments(argc, argv, options); 40 | int_t character; 41 | String argument; 42 | while(arguments.read(character, argument)) 43 | switch(character) 44 | { 45 | case 'p': 46 | password = argument; 47 | break; 48 | case 'u': 49 | user = argument; 50 | break; 51 | case 0: 52 | address = argument; 53 | break; 54 | case '?': 55 | Console::errorf("Unknown option: %s.\n", (const char_t*)argument); 56 | return 1; 57 | case ':': 58 | Console::errorf("Option %s required an argument.\n", (const char_t*)argument); 59 | return 1; 60 | default: 61 | Console::errorf("Usage: %s [-u ] [-p ] [
]\n", argv[0]); 62 | return 1; 63 | } 64 | } 65 | 66 | Console::Prompt prompt; 67 | Client client; 68 | if(!client.connect(user, password, address)) 69 | return Console::errorf("error: Could not establish connection: %s\n", (const char_t*)client.getLastError()), 1; 70 | for(;;) 71 | { 72 | String result = prompt.getLine("zlimdb> "); 73 | Console::printf(String("zlimdb> ") + result + "\n"); 74 | 75 | List args; 76 | Word::split(result, args); 77 | String cmd = args.isEmpty() ? String() : args.front(); 78 | 79 | if(cmd == "exit" || cmd == "quit") 80 | break; 81 | else if(cmd == "help") 82 | help(); 83 | else if(cmd == "listUsers") 84 | client.listUsers(); 85 | else if(cmd == "addUser") 86 | { 87 | if(args.size() < 3) 88 | Console::errorf("error: Missing arguments: addUser \n"); 89 | else 90 | { 91 | String name = *(++args.begin()); 92 | String password = *(++(++args.begin())); 93 | client.addUser(name, password); 94 | } 95 | } 96 | else if(cmd == "list") 97 | client.listTables(); 98 | else if(cmd == "create") 99 | { 100 | if(args.size() < 2) 101 | Console::errorf("error: Missing argument: create \n"); 102 | else 103 | { 104 | String name = *(++args.begin()); 105 | client.createTable(name); 106 | } 107 | } 108 | else if(cmd == "remove") 109 | { 110 | client.removeTable(); 111 | } 112 | else if(cmd == "clear") 113 | { 114 | client.clearTable(); 115 | } 116 | else if(cmd == "copy") 117 | { 118 | if(args.size() < 2) 119 | Console::errorf("error: Missing argument: copy \n"); 120 | else 121 | { 122 | String name = *(++args.begin()); 123 | client.copyTable(name); 124 | } 125 | } 126 | else if(cmd == "find") 127 | { 128 | if(args.size() < 2) 129 | Console::errorf("error: Missing argument: find \n"); 130 | else 131 | { 132 | String name = *(++args.begin()); 133 | client.findTable(name); 134 | } 135 | } 136 | else if(cmd == "select") 137 | { 138 | if(args.size() < 2) 139 | Console::errorf("error: Missing argument: select \n"); 140 | else 141 | { 142 | String num = *(++args.begin()); 143 | client.selectTable(num.toUInt()); 144 | } 145 | } 146 | else if(cmd == "query") 147 | { 148 | if(args.size() >= 2) 149 | { 150 | uint64_t id = (++args.begin())->toUInt64(); 151 | client.query(id); 152 | } 153 | else 154 | client.query(); 155 | } 156 | //else if(cmd == "add") 157 | //{ 158 | // if(args.size() < 2) 159 | // Console::errorf("error: Missing argument: add \n"); 160 | // else 161 | // { 162 | // String value = *(++args.begin()); 163 | // client.add(value); 164 | // } 165 | //} 166 | //else if(cmd == "addData") 167 | //{ 168 | // if(args.size() < 2) 169 | // Console::errorf("error: Missing argument: addData \n"); 170 | // else 171 | // { 172 | // size_t len = (++args.begin())->toUInt(); 173 | // size_t count = args.size() < 3 ? 1 : (++(++args.begin()))->toUInt(); 174 | // String value; 175 | // value.resize(len); 176 | // Memory::fill((char_t*)value, 'a', len); 177 | // for(size_t i = 0; i < count; ++i) 178 | // client.add(value); 179 | // } 180 | //} 181 | else if(cmd == "subscribe") 182 | { 183 | client.subscribe(); 184 | } 185 | else if(cmd == "sync") 186 | { 187 | client.sync(); 188 | } 189 | else if(!cmd.isEmpty()) 190 | Console::errorf("error: Unknown command: %s\n", (const char_t*)cmd); 191 | } 192 | client.disconnect(); 193 | return 0; 194 | } 195 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Src/Client.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | #include "Tools/ClientProtocol.h" 11 | 12 | #include "Client.h" 13 | 14 | Client::Client() : zdb(0), selectedTable(0) 15 | { 16 | VERIFY(zlimdb_init() == 0); 17 | } 18 | 19 | Client::~Client() 20 | { 21 | disconnect(); 22 | VERIFY(zlimdb_cleanup() == 0); 23 | } 24 | 25 | bool_t Client::connect(const String& user, const String& password, const String& address) 26 | { 27 | disconnect(); 28 | 29 | // create connection 30 | zdb = zlimdb_create((void (*)(void*, const zlimdb_header*))(void (*)(void*, const void*))zlimdbCallback, this); 31 | if(!zdb) 32 | return error = getZlimdbError(), false; 33 | uint16_t port = 0; 34 | String host = address; 35 | const char_t* colon = address.find(':'); 36 | if(colon) 37 | { 38 | port = String::toUInt(colon + 1); 39 | host = address.substr(0, colon - (const char_t*)address); 40 | } 41 | if(zlimdb_connect(zdb, host, port, user, password) != 0) 42 | return error = getZlimdbError(), false; 43 | 44 | // start receive thread 45 | keepRunning = true; 46 | if(!thread.start(threadProc, this)) 47 | return error = Error::getErrorString(), false; 48 | return true; 49 | } 50 | 51 | void_t Client::disconnect() 52 | { 53 | if(zdb) 54 | { 55 | keepRunning = false; 56 | zlimdb_interrupt(zdb); 57 | } 58 | thread.join(); 59 | actions.clear(); 60 | selectedTable = 0; 61 | } 62 | 63 | uint_t Client::threadProc(void_t* param) 64 | { 65 | Client* client = (Client*)param; 66 | return client->process();; 67 | } 68 | 69 | uint8_t Client::process() 70 | { 71 | while(keepRunning && zlimdb_is_connected(zdb) == 0) 72 | if(zlimdb_exec(zdb, 5 * 60 * 1000) != 0) 73 | switch(zlimdb_errno()) 74 | { 75 | case zlimdb_local_error_interrupted: 76 | { 77 | Action action = {quitAction}; 78 | bool actionEmpty = true; 79 | do 80 | { 81 | actionMutex.lock(); 82 | if(!actions.isEmpty()) 83 | { 84 | action = actions.front(); 85 | actions.removeFront(); 86 | actionEmpty = actions.isEmpty(); 87 | } 88 | actionMutex.unlock(); 89 | handleAction(action); 90 | } while(!actionEmpty); 91 | } 92 | break; 93 | case zlimdb_local_error_timeout: 94 | break; 95 | default: 96 | return Console::errorf("error: Could not receive data: %s\n", (const char_t*)getZlimdbError()), 1; 97 | } 98 | return 0; 99 | } 100 | 101 | void_t Client::handleAction(const Action& action) 102 | { 103 | switch(action.type) 104 | { 105 | case listUsersAction: 106 | { 107 | if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0) 108 | return Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()), (void)0; 109 | char_t buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 110 | while(zlimdb_get_response(zdb, (zlimdb_header*)buffer, ZLIMDB_MAX_MESSAGE_SIZE) == 0) 111 | for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)zlimdb_get_first_entity((zlimdb_header*)buffer, sizeof(zlimdb_table_entity)); 112 | table; 113 | table = (const zlimdb_table_entity*)zlimdb_get_next_entity((zlimdb_header*)buffer, sizeof(zlimdb_table_entity), &table->entity)) 114 | { 115 | String tableName; 116 | if(!ClientProtocol::getString(table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName)) 117 | continue; 118 | if(!tableName.startsWith("users/")) 119 | continue; 120 | tableName.resize(tableName.length()); // enfore NULL termination 121 | Console::printf("%6llu: %s\n", table->entity.id, (const char_t*)File::basename(File::dirname(tableName))); 122 | } 123 | if(zlimdb_errno() != zlimdb_local_error_none) 124 | return Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()), (void)0; 125 | } 126 | break; 127 | case addUserAction: 128 | { 129 | const String userName = action.param1.toString(); 130 | const String password = action.param2.toString(); 131 | if(zlimdb_add_user(zdb, userName, password) != 0) 132 | return Console::errorf("error: Could not send add user request: %s\n", (const char_t*)getZlimdbError()), (void)0; 133 | } 134 | break; 135 | case listTablesAction: 136 | { 137 | if(zlimdb_query(zdb, zlimdb_table_tables, zlimdb_query_type_all, 0) != 0) 138 | return Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()), (void)0; 139 | char_t buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 140 | while(zlimdb_get_response(zdb, (zlimdb_header*)buffer, ZLIMDB_MAX_MESSAGE_SIZE) == 0) 141 | for(const zlimdb_table_entity* table = (const zlimdb_table_entity*)zlimdb_get_first_entity((zlimdb_header*)buffer, sizeof(zlimdb_table_entity)); 142 | table; 143 | table = (const zlimdb_table_entity*)zlimdb_get_next_entity((zlimdb_header*)buffer, sizeof(zlimdb_table_entity), &table->entity)) 144 | { 145 | String tableName; 146 | if(!ClientProtocol::getString(table->entity, sizeof(zlimdb_table_entity), table->name_size, tableName)) 147 | continue; 148 | tableName.resize(tableName.length()); // enfore NULL termination 149 | Console::printf("%6llu: %s\n", table->entity.id, (const char_t*)tableName); 150 | } 151 | if(zlimdb_errno() != zlimdb_local_error_none) 152 | return Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()), (void)0; 153 | } 154 | break; 155 | case selectTableAction: 156 | selectedTable = action.param1.toUInt(); 157 | //Console::printf("selected table %u\n", action.param); 158 | break; 159 | case createTableAction: 160 | { 161 | const String tableName = action.param1.toString(); 162 | uint32_t tableId; 163 | if(zlimdb_add_table(zdb, tableName, &tableId) != 0) 164 | return Console::errorf("error: Could not send add request: %s\n", (const char_t*)getZlimdbError()), (void)0; 165 | Console::printf("%6u: %s\n", tableId, (const char_t*)tableName); 166 | } 167 | break; 168 | case removeTableAction: 169 | { 170 | if(zlimdb_remove(zdb, zlimdb_table_tables, selectedTable) != 0) 171 | return Console::errorf("error: Could not send remove request: %s\n", (const char_t*)getZlimdbError()), (void)0; 172 | } 173 | break; 174 | case clearTableAction: 175 | { 176 | if(zlimdb_clear(zdb, selectedTable) != 0) 177 | return Console::errorf("error: Could not send clear request: %s\n", (const char_t*)getZlimdbError()), (void)0; 178 | } 179 | break; 180 | case copyTableAction: 181 | { 182 | const String tableName = action.param1.toString(); 183 | uint32_t tableId; 184 | if(zlimdb_copy_table(zdb, selectedTable, tableName, &tableId) != 0) 185 | return Console::errorf("error: Could not send copy request: %s\n", (const char_t*)getZlimdbError()), (void)0; 186 | Console::printf("%6u: %s\n", tableId, (const char_t*)tableName); 187 | } 188 | break; 189 | case findTableAction: 190 | { 191 | const String tableName = action.param1.toString(); 192 | uint32_t tableId; 193 | if(zlimdb_find_table(zdb, tableName, &tableId) != 0) 194 | return Console::errorf("error: Could not send find request: %s\n", (const char_t*)getZlimdbError()), (void)0; 195 | Console::printf("%6u: %s\n", tableId, (const char_t*)tableName); 196 | } 197 | break; 198 | case queryAction: 199 | { 200 | zlimdb_query_type queryType = zlimdb_query_type_all; 201 | uint64_t param = 0; 202 | if(!action.param1.isNull()) 203 | { 204 | queryType = zlimdb_query_type_since_id; 205 | param = action.param1.toUInt64(); 206 | } 207 | if(zlimdb_query(zdb, selectedTable, queryType, param) != 0) 208 | return Console::errorf("error: Could not send query: %s\n", (const char_t*)getZlimdbError()), (void)0; 209 | char_t buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 210 | while(zlimdb_get_response(zdb, (zlimdb_header*)buffer, ZLIMDB_MAX_MESSAGE_SIZE) == 0) 211 | for(const zlimdb_entity* entity = zlimdb_get_first_entity((zlimdb_header*)buffer, sizeof(zlimdb_entity)); 212 | entity; 213 | entity = zlimdb_get_next_entity((zlimdb_header*)buffer, sizeof(zlimdb_entity), entity)) 214 | Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); 215 | if(zlimdb_errno() != zlimdb_local_error_none) 216 | return Console::errorf("error: Could not receive query response: %s\n", (const char_t*)getZlimdbError()), (void)0; 217 | } 218 | break; 219 | case subscribeAction: 220 | { 221 | if(zlimdb_subscribe(zdb, selectedTable, zlimdb_query_type_all, 0, zlimdb_subscribe_flag_none) != 0) 222 | return Console::errorf("error: Could not send subscribe request: %s\n", (const char_t*)getZlimdbError()), (void)0; 223 | char_t buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 224 | uint32_t size = sizeof(buffer); 225 | while(zlimdb_get_response(zdb, (zlimdb_header*)buffer, ZLIMDB_MAX_MESSAGE_SIZE) == 0) 226 | for(const zlimdb_entity* entity = zlimdb_get_first_entity((zlimdb_header*)buffer, sizeof(zlimdb_entity)); 227 | entity; 228 | entity = zlimdb_get_next_entity((zlimdb_header*)buffer, sizeof(zlimdb_entity), entity)) 229 | Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); 230 | if(zlimdb_errno() != zlimdb_local_error_none) 231 | return Console::errorf("error: Could not receive subscribe response: %s\n", (const char_t*)getZlimdbError()), (void)0; 232 | } 233 | break; 234 | case addAction: 235 | { 236 | const String value = action.param1.toString(); 237 | Buffer buffer; 238 | buffer.resize(sizeof(zlimdb_table_entity) + value.length()); 239 | zlimdb_table_entity* entity = (zlimdb_table_entity*)(const byte_t*)buffer; 240 | ClientProtocol::setEntityHeader(entity->entity, 0, Time::time(), sizeof(zlimdb_table_entity) + value.length()); 241 | ClientProtocol::setString(entity->entity, entity->name_size, sizeof(*entity), value); 242 | if(zlimdb_add(zdb, selectedTable, &entity->entity, &entity->entity.id)) 243 | return Console::errorf("error: Could not send add request: %s\n", (const char_t*)getZlimdbError()), (void)0; 244 | } 245 | break; 246 | case syncAction: 247 | { 248 | int64_t serverTime, tableTime; 249 | if(zlimdb_sync(zdb, selectedTable, &serverTime, &tableTime)) 250 | return Console::errorf("error: Could not send sync request: %s\n", (const char_t*)getZlimdbError()), (void)0; 251 | Console::printf("serverTime=%llu, tableTime=%llu, offset=%lld\n", serverTime, tableTime, serverTime - tableTime); 252 | } 253 | break; 254 | case quitAction: 255 | break; 256 | } 257 | } 258 | 259 | void_t Client::enqueueAction(ActionType type, const Variant& param1, const Variant& param2) 260 | { 261 | if(!zdb) 262 | return; 263 | actionMutex.lock(); 264 | Action& action = actions.append(Action()); 265 | action.type = type; 266 | action.param1 = param1; 267 | action.param2 = param2; 268 | actionMutex.unlock(); 269 | zlimdb_interrupt(zdb); 270 | } 271 | 272 | void_t Client::zlimdbCallback(const void_t* data) 273 | { 274 | const zlimdb_header* header = (const zlimdb_header*)data; 275 | // todo: check sizes 276 | switch(header->message_type) 277 | { 278 | case zlimdb_message_error_response: 279 | { 280 | const zlimdb_error_response* errorResponse = (const zlimdb_error_response*)header; 281 | Console::printf("subscribe: errorResponse=%s (%d)\n", (const char_t*)getZlimdbError(), (int)errorResponse->error); 282 | } 283 | break; 284 | default: 285 | Console::printf("subscribe: messageType=%u\n", (uint_t)header->message_type); 286 | break; 287 | } 288 | } 289 | 290 | String Client::getZlimdbError() 291 | { 292 | int err = zlimdb_errno(); 293 | if(err == zlimdb_local_error_system) 294 | return Error::getErrorString(); 295 | else 296 | { 297 | const char* errstr = zlimdb_strerror(err); 298 | return String(errstr, String::length(errstr)); 299 | } 300 | } 301 | --------------------------------------------------------------------------------