KeyValueContainer.hpp 18.7 KB
Newer Older
Matthieu Dorier's avatar
Matthieu Dorier committed
1 2 3 4 5
/*
 * (C) 2018 The University of Chicago
 * 
 * See COPYRIGHT in top-level directory.
 */
Matthieu Dorier's avatar
Matthieu Dorier committed
6 7 8 9 10
#ifndef __HEPNOS_KEYVAL_CONTAINER_H
#define __HEPNOS_KEYVAL_CONTAINER_H

#include <memory>
#include <string>
11
#include <sstream>
Matthieu Dorier's avatar
Matthieu Dorier committed
12 13 14
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/string.hpp>
15 16
#include <hepnos/InputArchive.hpp>
#include <hepnos/ProductID.hpp>
Matthieu Dorier's avatar
Matthieu Dorier committed
17 18
#include <hepnos/Demangle.hpp>
#include <hepnos/Exception.hpp>
19
#include <hepnos/DataStore.hpp>
Matthieu Dorier's avatar
Matthieu Dorier committed
20 21 22

namespace hepnos {

23
class WriteBatch;
24
class AsyncEngine;
25
class Prefetcher;
26

Matthieu Dorier's avatar
Matthieu Dorier committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
class KeyValueContainer {

    public:

    /**
     * @brief Default constructor.
     */
    KeyValueContainer() = default;

    /**
     * @brief Copy constructor.
     */
    KeyValueContainer(const KeyValueContainer& other) = default;

    /**
     * @brief Move constructor.
     */
    KeyValueContainer(KeyValueContainer&& other) = default;

    /**
     * @brief Copy-assignment operator.
     */
    KeyValueContainer& operator=(const KeyValueContainer& other) = default;

    /**
     * @brief Move-assignment operator.
     */
    KeyValueContainer& operator=(KeyValueContainer&& other) = default;

    /**
     * @brief Destructor.
     */
    virtual ~KeyValueContainer() = default;

61 62 63 64 65
    /**
     * @brief Gets the DataStore to which this instance of KeyValueContainer belongs.
     *
     * @return DataStore.
     */
66
    virtual DataStore datastore() const = 0;
67

Matthieu Dorier's avatar
Matthieu Dorier committed
68 69 70 71 72
    /**
     * @brief Stores raw key/value data in this KeyValueContainer.
     * This function is virtual and must be overloaded in the child class.
     *
     * @param key Key
73 74
     * @param value Value pointer
     * @param vsize Value size (in bytes)
Matthieu Dorier's avatar
Matthieu Dorier committed
75
     *
76
     * @return A valid ProductID if the key did not already exist, an invalid one otherwise.
Matthieu Dorier's avatar
Matthieu Dorier committed
77
     */
78
    virtual ProductID storeRawData(const std::string& key, const char* value, size_t vsize) = 0;
79

80 81 82 83 84 85 86 87 88 89 90 91
    /**
     * @brief Stores raw key/value data in a WriteBatch.
     * This function is virtual and must be overloaded in the child class.
     *
     * @param batch Batch in which to write.
     * @param key Key
     * @param value Value pointer
     * @param vsize Value size (in bytes)
     *
     * @return 
     */
    virtual ProductID storeRawData(WriteBatch& batch, const std::string& key, const char* value, size_t vsize) = 0;
Matthieu Dorier's avatar
Matthieu Dorier committed
92

93 94
    virtual ProductID storeRawData(AsyncEngine& async, const std::string& key, const char* value, size_t vsize) = 0;

Matthieu Dorier's avatar
Matthieu Dorier committed
95 96 97 98 99 100 101 102 103
    /**
     * @brief Loads raw key/value data from this KeyValueContainer.
     * This function is virtual and must be overloaded in the child class.
     *
     * @param key Key
     * @param buffer Buffer used to hold the value.
     *
     * @return true if the key exists, false otherwise.
     */
104
    virtual bool loadRawData(const std::string& key, std::string& buffer) const = 0;
Matthieu Dorier's avatar
Matthieu Dorier committed
105

106 107
    virtual bool loadRawData(const std::string& key, char* value, size_t* vsize) const = 0;

108 109 110 111
    virtual bool loadRawData(const Prefetcher& prefetcher, const std::string& key, std::string& buffer) const = 0;

    virtual bool loadRawData(const Prefetcher& prefetcher, const std::string& key, char* value, size_t* vsize) const = 0;

Matthieu Dorier's avatar
Matthieu Dorier committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    /**
     * @brief Stores a key/value pair into the KeyValueContainer.
     * The type of the key should have operator<< available
     * to stream it into a std::stringstream for the purpose
     * of converting it into an std::string. The resulting
     * string must not have the "/", or "%" characters. The
     * type of the value must be serializable using Boost.
     *
     * @tparam K type of the key.
     * @tparam V type of the value.
     * @param key Key to store.
     * @param value Value to store.
     *
     * @return true if the key was found. false otherwise.
     */
    template<typename K, typename V>
128
    ProductID store(const K& key, const V& value) {
129
        return storeImpl(key, value, std::is_pod<V>());
130 131
    }

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    /**
     * @brief Stores a key/value pair into the WriteBatch.
     * The type of the key should have operator<< available
     * to stream it into a std::stringstream for the purpose
     * of converting it into an std::string. The resulting
     * string must not have the "/", or "%" characters. The
     * type of the value must be serializable using Boost.
     *
     * @tparam K type of the key.
     * @tparam V type of the value.
     * @param key Key to store.
     * @param value Value to store.
     *
     * @return true if the key was found. false otherwise.
     */
147 148
    template<typename K, typename V>
    ProductID store(WriteBatch& batch, const K& key, const V& value) {
149
        return storeImpl(batch, key, value, std::is_pod<V>());
Matthieu Dorier's avatar
Matthieu Dorier committed
150 151
    }

152 153 154 155 156
    template<typename K, typename V>
    ProductID store(AsyncEngine& async, const K& key, const V& value) {
        return storeImpl(async, key, value, std::is_pod<V>());
    }

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    /**
     * @brief Version of store when the value is an std::vector.
     */
    template<typename K, typename V>
    ProductID store(const K& key, const std::vector<V>& value, int start=0, int end=-1) {
        std::string key_str, val_str;
        serializeKeyValueVector(std::is_pod<V>(), key, value, key_str, val_str, start, end);
        return storeRawData(key_str, val_str.data(), val_str.size());
    }

    /**
     * @brief Version of store when the value is an std::vector.
     */
    template<typename K, typename V>
    ProductID store(WriteBatch& batch, const K& key, const std::vector<V>& value, int start=0, int end=-1) {
        std::string key_str, val_str;
        serializeKeyValueVector(std::is_pod<V>(), key, value, key_str, val_str, start, end);
        return storeRawData(batch, key_str, val_str.data(), val_str.size());
    }

177 178 179 180 181 182 183 184 185 186
    /**
     * @brief Version of store when the value is an std::vector.
     */
    template<typename K, typename V>
    ProductID store(AsyncEngine& async, const K& key, const std::vector<V>& value, int start=0, int end=-1) {
        std::string key_str, val_str;
        serializeKeyValueVector(std::is_pod<V>(), key, value, key_str, val_str, start, end);
        return storeRawData(async, key_str, val_str.data(), val_str.size());
    }

Matthieu Dorier's avatar
Matthieu Dorier committed
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    /**
     * @brief Loads a value associated with a key from the 
     * KeyValueContainer. The type of the key should have 
     * operator<< available to stream it into a std::stringstream 
     * for the purpose of converting it into an std::string. 
     * The resulting string must not have the "/" or "%" characters.
     * The type of the value must be serializable using Boost.
     *
     * @tparam K type of the key.
     * @tparam V type of the value.
     * @param key Key to load.
     * @param value Value to load.
     *
     * @return true if the key exists and was loaded. False otherwise.
     */
    template<typename K, typename V>
    bool load(const K& key, V& value) const {
204 205 206
        return loadImpl(key, value, std::is_pod<V>());
    }

207 208 209 210 211 212 213 214
    /**
     * @brief Version of load for vectors.
     */
    template<typename K, typename V>
    bool load(const K& key, std::vector<V>& value) const {
        return loadVectorImpl(key, value, std::is_pod<V>());
    }

215 216 217 218 219 220 221 222 223 224
    template<typename K, typename V>
    bool load(const Prefetcher& prefetcher, const K& key, V& value) const {
        return loadImpl(prefetcher, key, value, std::is_pod<V>());
    }

    template<typename K, typename V>
    bool load(const Prefetcher& prefetcher, const K& key, std::vector<V>& value) const {
        return loadVectorImpl(prefetcher, key, value, std::is_pod<V>());
    }

225 226
    private:

227 228 229 230
    /**
     * @brief Implementation of the store function when the value is
     * not an std::vector and not a POD.
     */
231 232 233 234 235 236 237 238
    template<typename K, typename V>
    ProductID storeImpl(const K& key, const V& value,
            const std::integral_constant<bool, false>&) {
        std::string key_str, val_str;
        serializeKeyValue(key, value, key_str, val_str);
        return storeRawData(key_str, val_str.data(), val_str.size());
    }

239 240 241 242
    /**
     * @brief Implementation of the store function with WriteBatch
     * and the value type is not am std::vector and not a POD.
     */
243 244 245 246 247 248 249 250
    template<typename K, typename V>
    ProductID storeImpl(WriteBatch& batch, const K& key, const V& value,
            const std::integral_constant<bool, false>&) {
        std::string key_str, val_str;
        serializeKeyValue(key, value, key_str, val_str);
        return storeRawData(batch, key_str, val_str.data(), val_str.size());
    }

251 252 253 254 255 256 257 258 259 260 261 262
    /**
     * @brief Implementation of the store function with AsyncEngine
     * and the value type is not am std::vector and not a POD.
     */
    template<typename K, typename V>
    ProductID storeImpl(AsyncEngine& async, const K& key, const V& value,
            const std::integral_constant<bool, false>&) {
        std::string key_str, val_str;
        serializeKeyValue(key, value, key_str, val_str);
        return storeRawData(async, key_str, val_str.data(), val_str.size());
    }

263 264 265 266
    /**
     * @brief Implementation of the store function when the value
     * type is a POD.
     */
267 268 269 270 271 272 273 274
    template<typename K, typename V>
    ProductID storeImpl(const K& key, const V& value,
            const std::integral_constant<bool, true>&) {
        std::string key_str;
        serializeKeyValue(key, value, key_str);
        return storeRawData(key_str, reinterpret_cast<const char*>(&value), sizeof(value));
    }

275 276 277 278
    /**
     * @brief Implementation of the store function with WriteBatch
     * when the value type is a POD.
     */
279 280 281 282 283 284 285 286
    template<typename K, typename V>
    ProductID storeImpl(WriteBatch& batch, const K& key, const V& value,
            const std::integral_constant<bool, true>&) {
        std::string key_str;
        serializeKeyValue(key, value, key_str);
        return storeRawData(batch, key_str, reinterpret_cast<const char*>(&value), sizeof(value));
    }

287 288 289 290 291 292 293 294 295 296 297 298
    /**
     * @brief Implementation of the store function with AsyncEngine
     * when the value type is a POD.
     */
    template<typename K, typename V>
    ProductID storeImpl(AsyncEngine& async, const K& key, const V& value,
            const std::integral_constant<bool, true>&) {
        std::string key_str;
        serializeKeyValue(key, value, key_str);
        return storeRawData(async, key_str, reinterpret_cast<const char*>(&value), sizeof(value));
    }

299 300 301
    /**
     * @brief Implementation of the load function when the value type is a POD.
     */
302 303 304 305 306 307 308 309 310 311 312 313 314
    template<typename K, typename V>
    bool loadImpl(const K& key, V& value,
            const std::integral_constant<bool, true>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<V>();
        size_t vsize = sizeof(value);
        if(!loadRawData(ss_key.str(), reinterpret_cast<char*>(&value), &vsize)) {
            return false;
        }
        return vsize == sizeof(value);
    }

315 316 317 318 319 320 321 322 323 324 325 326 327
    template<typename K, typename V>
    bool loadImpl(const Prefetcher& prefetcher, const K& key, V& value,
            const std::integral_constant<bool, true>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<V>();
        size_t vsize = sizeof(value);
        if(!loadRawData(prefetcher, ss_key.str(), reinterpret_cast<char*>(&value), &vsize)) {
            return false;
        }
        return vsize == sizeof(value);
    }

328 329 330
    /**
     * @brief Implementation of the load function when the value type is not a POD.
     */
331 332 333
    template<typename K, typename V>
    bool loadImpl(const K& key, V& value,
            const std::integral_constant<bool, false>&) const {
334
        std::string buffer;
Matthieu Dorier's avatar
Matthieu Dorier committed
335 336 337 338 339 340
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<V>();
        if(!loadRawData(ss_key.str(), buffer)) {
            return false;
        }
        try {
341
            std::stringstream ss(buffer);
342
            InputArchive ia(datastore(), ss);
Matthieu Dorier's avatar
Matthieu Dorier committed
343 344 345 346 347 348
            ia >> value;
        } catch(...) {
            throw Exception("Exception occured during serialization");
        }
        return true;
    }
349

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
    template<typename K, typename V>
    bool loadImpl(const Prefetcher& prefetcher, const K& key, V& value,
            const std::integral_constant<bool, false>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<V>();
        if(!loadRawData(prefetcher, ss_key.str(), buffer)) {
            return false;
        }
        try {
            std::stringstream ss(buffer);
            InputArchive ia(datastore(), ss);
            ia >> value;
        } catch(...) {
            throw Exception("Exception occured during serialization");
        }
        return true;
    }

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    /**
     * @brief Implementation of the load function when the value type is a vector of POD.
     */
    template<typename K, typename V>
    bool loadVectorImpl(const K& key, std::vector<V>& value,
            const std::integral_constant<bool, true>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<std::vector<V>>();
        if(!loadRawData(ss_key.str(), buffer)) {
            return false;
        }
        size_t count = 0;
        if(buffer.size() < sizeof(count)) {
            return false;
        }
        std::memcpy(&count, buffer.data(), sizeof(count));
        if(buffer.size() != sizeof(count) + count*sizeof(V)) {
            return false;
        }
        value.resize(count);
        std::memcpy(value.data(), buffer.data()+sizeof(count), count*sizeof(V));
        return true;
    }

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    template<typename K, typename V>
    bool loadVectorImpl(const Prefetcher& prefetcher, const K& key, std::vector<V>& value,
            const std::integral_constant<bool, true>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<std::vector<V>>();
        if(!loadRawData(prefetcher, ss_key.str(), buffer)) {
            return false;
        }
        size_t count = 0;
        if(buffer.size() < sizeof(count)) {
            return false;
        }
        std::memcpy(&count, buffer.data(), sizeof(count));
        if(buffer.size() != sizeof(count) + count*sizeof(V)) {
            return false;
        }
        value.resize(count);
        std::memcpy(value.data(), buffer.data()+sizeof(count), count*sizeof(V));
        return true;
    }

416 417 418 419 420 421 422 423 424 425 426 427 428 429
    /**
     * @brief Implementation of the load function when the value type is a vector of non-POD.
     */
    template<typename K, typename V>
    bool loadVectorImpl(const K& key, std::vector<V>& value,
            const std::integral_constant<bool, false>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<std::vector<V>>();
        if(!loadRawData(ss_key.str(), buffer)) {
            return false;
        }
        try {
            std::stringstream ss(buffer);
430
            InputArchive ia(datastore(), ss);
431 432 433 434 435 436 437 438 439 440 441
            size_t count = 0;
            ia >> count;
            value.resize(count);
            for(unsigned i=0; i<count; i++) {
                ia >> value[i];
            }
        } catch(...) {
            throw Exception("Exception occured during serialization");
        }
        return true;
    }
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

    template<typename K, typename V>
    bool loadVectorImpl(const Prefetcher& prefetcher, const K& key, std::vector<V>& value,
            const std::integral_constant<bool, false>&) const {
        std::string buffer;
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<std::vector<V>>();
        if(!loadRawData(prefetcher, ss_key.str(), buffer)) {
            return false;
        }
        try {
            std::stringstream ss(buffer);
            InputArchive ia(datastore(), ss);
            size_t count = 0;
            ia >> count;
            value.resize(count);
            for(unsigned i=0; i<count; i++) {
                ia >> value[i];
            }
        } catch(...) {
            throw Exception("Exception occured during serialization");
        }
        return true;
    }

467 468 469 470
    /**
     * @brief Creates the string key based on the provided key
     * and the type of the value. Serializes the value into a string.
     */
471 472 473
    template<typename K, typename V>
    static void serializeKeyValue(const K& key, const V& value,
            std::string& key_str, std::string& value_str) {
474
        serializeKeyValue(key, value, key_str);
475
        std::stringstream ss_value;
476
        boost::archive::binary_oarchive oa(ss_value, boost::archive::archive_flags::no_header);
477 478 479 480 481 482 483
        try {
            oa << value;
        } catch(...) {
            throw Exception("Exception occured during serialization");
        }
        value_str = ss_value.str();
    }
484

485 486 487 488
    /**
     * @brief Creates the string key based on the provided key
     * and the type of the value.
     */
489 490 491 492 493 494
    template<typename K, typename V>
    static void serializeKeyValue(const K& key, const V& value, std::string& key_str) {
        std::stringstream ss_key;
        ss_key << key << "#" << demangle<V>();
        key_str = std::move(ss_key.str());
    }
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539

    /**
     * @brief Version of serializeKeyValue for vectors of non-POD datatypes.
     */
    template<typename K, typename V>
    static void serializeKeyValueVector(const std::integral_constant<bool, false>&,
            const K& key, const std::vector<V>& value,
            std::string& key_str, std::string& value_str,
            int start, int end) {
        if(end == -1)
            end = value.size();
        if(start < 0 || start > end || end > value.size())
            throw Exception("Invalid range when storing vector");
        serializeKeyValue(key, value, key_str);
        std::stringstream ss_value;
        boost::archive::binary_oarchive oa(ss_value, boost::archive::archive_flags::no_header);
        try {
            size_t count = end-start;
            oa << count;
            for(auto i = start; i < end; i++)
                oa << value[i];
        } catch(...) {
            throw Exception("Exception occured during serialization");
        }
        value_str = ss_value.str();
    }

    /**
     * @brief Version of serializeKeyValue for vectors of POD datatypes.
     */
    template<typename K, typename V>
    static void serializeKeyValueVector(const std::integral_constant<bool, true>&,
            const K& key, const std::vector<V>& value,
            std::string& key_str, std::string& value_str,
            int start, int end) {
        if(end == -1)
            end = value.size();
        if(start < 0 || start > end || end > value.size())
            throw Exception("Invalid range when storing vector");
        serializeKeyValue(key, value, key_str);
        size_t count = end-start;
        value_str.resize(sizeof(count) + count*sizeof(V));
        std::memcpy(const_cast<char*>(value_str.data()), &count, sizeof(count));
        std::memcpy(const_cast<char*>(value_str.data())+sizeof(count), &value[start], count*sizeof(V));
    }
Matthieu Dorier's avatar
Matthieu Dorier committed
540 541 542 543 544
};

}

#endif