summaryrefslogtreecommitdiff
path: root/datastore-leveldb/src/web.cpp
blob: 2adf8ebb821d8c7d6c4eb3cec079749cc8d85e18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include "web.h"
#include "db.h"
#include <algorithm>
#include <vector>
#include <leveldb/comparator.h>
#include <iomanip>

static const leveldb::Comparator *cmp = leveldb::BytewiseComparator();

static inline std::string make_key(uint64_t timestamp) {
    std::stringstream key;
    key << "ts-";
    key << std::setfill('0') << std::setw(20) << timestamp;
    return key.str();
}

static inline bool parse_key(leveldb::Slice &&key, uint64_t *value) {
    if (key.size() != 20+3) 
        return false;
    *value = std::stoul(key.data()+3);
    return true;
}


const boost::regex web_handle_api_value_R(
    "/api/value/([a-zA-Z0-9]+)/([0-9]+)");
void web_handle_api_value(const boost::cmatch &match, struct mg_connection *conn) {
    std::string sensor(match[1].str());
    uint64_t timestamp = std::stoul(match[2].str());
    char buf[1024];
    int count = mg_read(conn, buf, 1024);
    std::string value(buf, count);

    leveldb::DB *db = getDB(sensor);
    if (db == nullptr) {
        std::cout << "failed to get db for " << sensor << std::endl;
        mg_printf(conn, "HTTP/1.1 500 Internal Error\r\n\r\n");
        return;
    }

    db->Put(leveldb::WriteOptions(), make_key(timestamp), value);
    mg_printf(conn, "HTTP/1.1 200 Value received\r\n\r\n");
}

static inline void print_json_tuple(struct mg_connection *conn,
        std::ostringstream &outbuf,
        leveldb::Slice &&key,
        leveldb::Slice &&value) {

    size_t key_size =  key.size();
    if (key_size != 20+3) {
        std::cerr << "invalid key" << std::endl;
        return;
    }

    unsigned int offset = 3; // "ts-"
    // skip zeros in timestamp
    while (offset < key_size-1 and *(key.data()+offset) == '0')
        offset++;

    outbuf << '[';
    outbuf.write(key.data()+offset, key_size-offset);
    outbuf << ',';
    outbuf.write(value.data(), value.size());
    outbuf << ']';

    mg_write(conn, outbuf.str().c_str(), outbuf.tellp());
}


const boost::regex web_handle_api_range_R(
    "/api/range/([a-zA-Z0-9]+)/([0-9]+)/([0-9]+)");
void web_handle_api_range(const boost::cmatch &match, struct mg_connection *conn) {
    std::string sensor(match[1].str());
    uint64_t start = std::stoul(match[2].str());
    uint64_t end = std::stoul(match[3].str());
    std::string key_start(std::move(make_key(start)));
    std::string key_end(std::move(make_key(end)));

    leveldb::DB *db = getDB(sensor);
    if (db == nullptr) {
        mg_printf(conn, "HTTP/1.1 500 Internal Error\r\n"
                        "\r\n");
        return;
    }

    mg_printf(conn,
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: application/json; encoding=UTF-8\r\n"
            "\r\n");

    std::ostringstream out;
    out << "{'sensor':'" << sensor << "', 'error':null, 'data':[";
    mg_write(conn, out.str().c_str(), out.str().size());

    leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
    bool first = true;
    std::ostringstream outbuf;
    for (it->Seek(key_start); 
            it->Valid() && cmp->Compare(it->key(), key_end) < 0;
            it->Next()) {
        if (first) first = false;
        else outbuf << ",";
        print_json_tuple(conn, outbuf, it->key(), it->value());
        outbuf.seekp(0);
    }
    mg_printf(conn, "]}\r\n");
    delete it;
}

const boost::regex web_handle_api_range_size_R(
    "/api/range/([a-zA-Z0-9]+)/([0-9]+)/([0-9]+)/([0-9]+)");
void web_handle_api_range_size(const boost::cmatch &match, struct mg_connection *conn) {
    std::string sensor(match[1].str());
    uint64_t start = std::stoul(match[2].str());
    uint64_t end = std::stoul(match[3].str());
    uint64_t size = std::stoul(match[4].str());

    leveldb::DB *db = getDB(sensor);
    if (db == nullptr) {
        mg_printf(conn, "HTTP/1.1 500 Internal Error\r\n"
                        "\r\n");
        return;
    }

    mg_printf(conn,
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: application/json; encoding=UTF-8\r\n"
            "\r\n");

    uint64_t step = std::max((uint64_t)1, (end-start) / size);

    std::ostringstream out;
    out << "{'sensor':'" << sensor << "', "
        << "'error':null, "
        << "'size':" << size << ", "
        << "'step':" << step << ", "
        << "'data':[";
    mg_write(conn, out.str().c_str(), out.str().size());

    bool first = true;
    uint64_t actual_size = 0;
    std::ostringstream outbuf;
    leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
    for (uint64_t key = start; key <= end; key += step) {
        it->Seek(make_key(key));

        if (first) first = false;
        else outbuf << ",";

        print_json_tuple(conn, outbuf, it->key(), it->value());
        outbuf.seekp(0);
        actual_size++;
    }
    mg_printf(conn, "], 'actual_size':%ld}\r\n", actual_size);
    delete it;
}