aboutsummaryrefslogtreecommitdiff
path: root/umosapi.cpp
blob: f6f0cddee085e9e2de35d301d6f05c5159203422 (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
158
159
160
161
162
163
164
165
166
167
168
169
#include <string.h>
#include <filesystem>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

#include <pistache/http.h>
#include <pistache/description.h>
#include <pistache/endpoint.h>

#include <pistache/serializer/rapidjson.h>

#include <json-c/json.h>

#include "clara.hpp"

using namespace std;
using namespace Pistache;


using namespace clara;

namespace Generic {
    void handleReady(const Rest::Request&, Http::ResponseWriter response) {
        response.send(Http::Code::Ok, "1");
    }
}

class UmosapiService {
    public:

        UmosapiService(Address addr)
            : httpEndpoint(std::make_shared<Http::Endpoint>(addr))
            , desc("Unity Mongo Save API", "0.1")
        { }

        void init(size_t thr = 2) {
            auto opts = Http::Endpoint::options()
                .threads(thr);
            httpEndpoint->init(opts);
            createDescription();
        }

        void start(std::string swaggerui) {
            router.initFromDescription(desc);

            Rest::Swagger swagger(desc);
            swagger
                .uiPath("/doc")
                .uiDirectory(swaggerui)
                .apiPath("/api")
                .serializer(&Rest::Serializer::rapidJson)
                .install(router);

            httpEndpoint->setHandler(router.handler());
            httpEndpoint->serve();
        }

    private:
        void createDescription() {
            desc
                .info()
                .license("Apache", "https://neodarz.net");

            auto backendErrorResponse =
                desc.response(Http::Code::Internal_Server_Error, "Backend is dead, it's the end of the world");

            desc
                .schemes(Rest::Scheme::Http)
                .basePath("/v1")
                .produces(MIME(Application, Json))
                .consumes(MIME(Application, Json));

            desc
                .route(desc.get("/ready"))
                .bind(&Generic::handleReady)
                .response(Http::Code::Ok, "Api started")
                .response(backendErrorResponse);

            auto versionPath = desc.path("/v1");

            versionPath
                .route(desc.get("/:collections"))
                .bind(&UmosapiService::retrieveAll, this)
                .produces(MIME(Application, Json))
                .parameter<Rest::Type::String>("collection", "Name of the collection where the uobjects are located")
                .response(Http::Code::Ok, "List of uobjects")
                .response(backendErrorResponse);

        }

        void retrieveAll(const Rest::Request&, Http::ResponseWriter response) {
            response.send(Http::Code::Ok, "No fucking objects");
        }

        std::shared_ptr<Http::Endpoint> httpEndpoint;
        Rest::Description desc;
        Rest::Router router;
};

std::string get_value(struct json_object *jobj, const char *key) {
    struct json_object *tmp;


    json_object_object_get_ex(jobj, key, &tmp);

    if (jobj == NULL) {
        cout << "get_value: Json object is null" << endl;
        return "";
    } else {
        return json_object_get_string(tmp);
    }
}

int main(int argc, char *argv[]) {

    string config_path = "";
    const char *homedir;

    if ((homedir = getenv("XDG_CONFIG_HOME")) == NULL || (homedir = getenv("HOME")) == NULL) {
        homedir = getpwuid(getuid())->pw_dir;
    }

    config_path.append(homedir);
    config_path.append("/.config/umosapi/config.json");

    bool showHelp = false;
    int config_port = 9080;
    int thr = 2;
    auto cli = clara::detail::Help(showHelp)
             | clara::detail::Opt( config_path, "config" )["-c"]["--config"]("Config file path. Default ")
             | clara::detail::Opt( config_port, "port" )["-p"]["--port"]("Port to listen.")
             | clara::detail::Opt( thr, "treads" )["-t"]["--threads"]("Number of threads.");
    auto result = cli.parse( clara::detail::Args( argc, argv ) );
    if( !result )
    {
        std::cerr << "Error in command line: " << result.errorMessage() << std::endl;
        std::cerr << cli << std::endl;
        exit(1);
    }

    if ( showHelp ) {
        std::cerr << cli << std::endl;
        exit(1);
    }

    Address addr(Ipv4::any(), Port(config_port));

    cout << "Using " << hardware_concurrency() << " cores";
    cout << " - " << thr << " threads" << endl;
    cout << "Listen on 0.0.0.0:" << config_port << endl;

    cout << "Using config file '" << config_path << "'" << endl;

    if (!std::filesystem::exists(config_path)) {
        cout << "Error fatal : config file '" << config_path << "' not found" << endl;
        cout << "config.json is search here: ~/.config/umosapi/config.json" << endl;
        exit (EXIT_FAILURE);
    }

    auto config = json_object_from_file(config_path.c_str());

    //cout << get_value(config, "swaggerui") << endl;

    UmosapiService umosapi(addr);

    umosapi.init(thr);
    umosapi.start(get_value(config, "swaggerui"));
}