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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#include <kooling/api/api.h>
#include <kooling/component/sensor/interface.h>
#include <kooling/database/database.h>
#include <kooling/datamodel/motion-type.h>
#include <kooling/datamodel/platform.h>
#include <kooling/datamodel/sensor.h>
#include <kooling/datamodel/speed.h>
#include <kooling/datamodel/user.h>
#include <kooling/json/json.h>
#include <kooling/system/sleep.h>
#include <kooling/system/workpool.h>

#include <plog/Log.h>

#include <chrono>
#include <cstddef>
#include <deque>
#include <future>
#include <sstream>
using namespace std::chrono_literals;

namespace kooling::component::sensor {

class database : public interface
{
    struct ctor_tag {};

public:
    explicit database(ctor_tag, const json_t&);

    ~database() override = default;

    static interface::pointer_type create(const json_t& config)
    {
        return std::make_unique<database>(ctor_tag{}, config);
    }

    static std::string name()
    {
        return "database";
    }

    void run() override;
    void stop() override;

private:
    using duration_t          = kooling::datamodel::timestamp::duration;
    using fingerprint_t       = kooling::datamodel::fingerprint;
    using platform_t          = kooling::datamodel::platform;
    using sensor_data_point_t = kooling::datamodel::sensor_data_point;
    using sensor_data_t       = kooling::datamodel::sensor_data;
    using speed_t             = kooling::datamodel::speed;
    using timestamp_t         = kooling::datamodel::timestamp;
    using user_t              = kooling::datamodel::user;

    std::optional<int> fetch_server_id();
    std::deque<user_t> fetch_users(int server_id) const;
    void handle_user(user_t) const;
    interface::per_device_t fetch_sensor_data(const user_t&) const;

private:
    struct server_conf
    {
        std::string host;
        std::string token;
        NLOHMANN_DEFINE_TYPE_INTRUSIVE(server_conf, host, token);
    };

    kooling::system::sleep d_sleep;
    const std::string d_instance;
    kooling::system::workpool d_workpool;
    const std::chrono::seconds d_seconds_between_batches;
    const server_conf d_server;
    const kooling::database::config d_prod_db_config;
    const kooling::database::config d_sensor_db_config;
};

static bool registered{ factory().register_component<database>() };

database::database(ctor_tag, const json_t& config)
    : d_instance{ config["instance"] }
    , d_workpool{ config["parallelism"] }
    , d_seconds_between_batches{ config["seconds_between_batches"] }
    , d_server{ config["server"].get<server_conf>() }
    , d_prod_db_config{ config["prod_database"].get<kooling::database::config>() }
    , d_sensor_db_config{ config["sensor_database"].get<kooling::database::config>() }
{}

std::optional<int> database::fetch_server_id()
{
    const kooling::api::api api{ d_server.host, d_server.token };

    constexpr const char *base_error_msg{ "Could not fetch server id: " };
    constexpr int max_attemps{ 10 };
    for (int attempt = 1; attempt != max_attemps; ++attempt)
    {
        if (const auto server_id{ api.get_server_id(d_instance) }; server_id)
        {
            PLOG_DEBUG << "Got server id: " << *server_id;
            return server_id;
        }

        PLOG_WARNING
            << base_error_msg
            << "tried " << attempt << " out of " << max_attemps << " times, "
            << "trying again in 1 minute";

        if (d_sleep(1min))
        {
            break;
        }
    }

    PLOG_ERROR << base_error_msg << "bailing out";
    return {};
}

auto database::fetch_users(int server_id) const -> std::deque<user_t>
{
    std::deque<user_t> users;
    const auto add_user{
        [&users](std::string user,
                 int platform,
                 std::string vehicle_type,
                 std::string company_id,
                 int review)
        {
            users.push_back(
                { std::move(user)
                , platform_t::_from_integral(platform)
                , std::move(vehicle_type)
                , std::move(company_id)
                , review == 1 });
        } };

    kooling::database::database db{ d_prod_db_config };

    const auto make_query = [&db, server_id](std::string_view table, platform_t platform)
    {
        // TODO - filter by lastdataprocessed bigger than something?
        std::stringstream ss;
        ss
            << "SELECT sa.userid, " << static_cast<int>(platform._to_integral()) << ", "
            << "COALESCE(acc.vehicletype, ''), "
            << "COALESCE(acc.companyid, ''), "
            << "acc.koolingreview "
            << "FROM " << db.quote_table(table) << " sa, accounts acc "
            << "WHERE sa.serverid = " << server_id << " "
            << "AND sa.userid = acc.userid "
            << "AND (sa.lastdataprocessed IS NULL OR sa.lastdatareceived > sa.lastdataprocessed)";
        return ss.str();
    };

    std::string query{
        make_query("serverassignments", platform_t::android)
        + " UNION "
        + make_query("serverassignments2", platform_t::ios) };
    if (db.query(query, add_user))
    {
        PLOG_DEBUG << "Got " << users.size() << " users";
    }
    else
    {
        PLOG_ERROR << "Error fetching users";
    }
    return users;
}

void database::handle_user(user_t user) const<--- Function parameter 'user' should be passed by const reference.
{
    if (d_sleep.stopped())
    {
        return;
    }

    std::stringstream log;
    log << "handling "
        << "user: '" << user.user_id << "', "
        << "platform: '" << user.platform._to_string() << "', "
        << "company_id: '" << user.company_id << "', "
        << "vehicle_type: '" << user.vehicle_type << "'";

    PLOG_DEBUG << "Begin " << log.str();
    dispatch(user, fetch_sensor_data(user));
    PLOG_DEBUG << "End " << log.str();
}

interface::per_device_t database::fetch_sensor_data(const user_t& user) const
{
    kooling::database::database db{ d_sensor_db_config };

    const std::string_view table_name{
        user.platform == +platform_t::android
        ? "koolingdata"
        : "koolingdata2" };

    std::stringstream ss;
    ss
        << "SELECT "
           "  sens.timestamp, "
           "  sens.motiontype, "
           "  sens.latitude, "
           "  sens.longitude, "
           "  sens.speed, "
           "  COALESCE(sens.steps, 0), "
           "  COALESCE(sens.accuracy, -1), "
           "  COALESCE(sens.bluetooth, '[]'), "
           "  phon.manufacturer, "
           "  phon.model, "
           "  phon.osversion "
           "FROM " << db.quote_table(table_name) << " sens, phoneconfiguration phon "
           "WHERE sens.userid = $1 "
           "  AND sens.motiontype IS NOT NULL "
           "  AND sens.latitude IS NOT NULL "
           "  AND sens.longitude IS NOT NULL "
           "  AND sens.deleted = 0 "
           "  AND sens.phoneconfigurationid = phon.id "
           "ORDER BY timestamp ASC";

    interface::ingester ingester;
    if (db.query(ss.str(), kooling::database::params{ user.user_id }, ingester))
    {
        auto data{ ingester.data() };
        for (const auto& [fingerprint, sensor_data] : data)
        {
            PLOG_DEBUG
                << "Retrieved user: '" << user.user_id << "', "
                   "configuration: " << fingerprint << ", "
                   "dps: " << sensor_data.size();
        }
        return data;
    }

    PLOG_ERROR
        << "Error fetching sensor data for user: '" << user.user_id << "'";
    return {};
}

void database::run()
{
    const auto server_id{ fetch_server_id() };
    if (!server_id)
    {
        return ;
    }

    while (true)
    {
        const auto users{ fetch_users(*server_id) };
        if (users.empty())
        {
            PLOG_DEBUG
                << "Nothing to do, waiting for "
                << d_seconds_between_batches.count()
                << " seconds until next run";
            if (d_sleep(d_seconds_between_batches))
            {
                PLOG_DEBUG << "Handling stop request";
                break;
            }
            continue;
        }

        std::vector<std::future<void>> futures;
        futures.reserve(users.size());

        PLOG_DEBUG << "Posting batch";
        for (auto user : users)
        {
            futures.push_back(<--- Consider using std::transform algorithm instead of a raw loop.
                d_workpool.post(
                    [this, user = std::move(user)]()
                    {
                        this->handle_user(std::move(user));
                    }));
        }

        PLOG_DEBUG << "Waiting for all threads to complete";
        for (auto& f : futures)
        {
            f.wait();
        }

        PLOG_DEBUG
            << "Batch completed, waiting for "
            << d_seconds_between_batches.count()
            << " seconds until next one";

        if (d_sleep(d_seconds_between_batches))
        {
            PLOG_DEBUG << "Handling stop request";
            break;
        }
    }
}

void database::stop()
{
    PLOG_DEBUG << "Stop requested";
    d_sleep.stop();
}

} // namespace kooling::component::sensor