Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
workspace_store.cpp
Go to the documentation of this file.
2#include <slick/logger.hpp>
3#include <filesystem>
4#include <fstream>
5#include <set>
6#include <string>
7#include <system_error>
8#include <utility>
9
10namespace slick::trader {
11
12using json = nlohmann::json;
13
14namespace {
15
16constexpr size_t MAX_NAME = 64;
17constexpr size_t MAX_TOOL = 32;
18constexpr size_t MAX_PARAM = 128;
19constexpr size_t MAX_WINDOWS = 128;
20
21// Blanks a name doesn't start or end with: ASCII ones, and no-break and ideographic spaces in UTF-8.
22constexpr std::string_view BLANKS[] = {" ", "\t", "\r", "\n", "\f", "\v", "\xC2\xA0", "\xE3\x80\x80"};
23
24// `name` without the blanks around it: "Morning " is Morning, as the dashboard trims it too.
25std::string_view trim(std::string_view name) {
26 for (bool cut = true; cut;) {
27 cut = false;
28 for (const auto blank : BLANKS) {
29 if (name.starts_with(blank)) {
30 name.remove_prefix(blank.size());
31 cut = true;
32 }
33 if (name.ends_with(blank)) {
34 name.remove_suffix(blank.size());
35 cut = true;
36 }
37 }
38 }
39 return name;
40}
41
42bool valid_name(std::string_view name) {
43 if (name.empty() || name.size() > MAX_NAME) {
44 return false;
45 }
46 for (const unsigned char c : name) {
47 if (c < 0x20 || c == 0x7f) {
48 return false;
49 }
50 }
51 return true;
52}
53
54// `windows` as kept: the fields a window reopens with and no others. Empty `error` when it is fine.
55json clean_windows(const json& windows, std::string& error) {
56 if (!windows.is_array() || windows.size() > MAX_WINDOWS) {
57 error = "windows must be an array of at most " + std::to_string(MAX_WINDOWS);
58 return {};
59 }
60 json out = json::array();
61 for (const auto& w : windows) {
62 const auto tool = w.is_object() ? w.find("tool") : w.end();
63 if (!w.is_object() || tool == w.end() || !tool->is_string() || tool->get_ref<const std::string&>().empty() ||
64 tool->get_ref<const std::string&>().size() > MAX_TOOL) {
65 error = "each window needs a tool name";
66 return {};
67 }
68 json kept = {{"tool", *tool}};
69 for (const char* key : {"left", "top", "width", "height"}) {
70 const auto value = w.find(key);
71 if (value == w.end() || !value->is_number_integer()) {
72 error = std::string("each window needs an integer ") + key;
73 return {};
74 }
75 kept[key] = *value;
76 }
77 if (const auto params = w.find("params"); params != w.end()) {
78 if (!params->is_object()) {
79 error = "params must be an object";
80 return {};
81 }
82 for (const auto& [key, value] : params->items()) {
83 if (!value.is_string() || key.size() > MAX_PARAM || value.get_ref<const std::string&>().size() > MAX_PARAM) {
84 error = "params must be short strings";
85 return {};
86 }
87 }
88 kept["params"] = *params;
89 }
90 out.push_back(std::move(kept));
91 }
92 return out;
93}
94
95json blank() {
96 const std::string name(WorkspaceStore::DEFAULT);
97 return {{"last", name}, {"workspaces", {{name, {{"windows", json::array()}}}}}};
98}
99
100bool is_last(const json& doc, const std::string& name) {
101 return doc["last"].get_ref<const std::string&>() == name;
102}
103
104} // namespace
105
106void WorkspaceStore::load(std::string path) {
107 path_ = std::move(path);
108 doc_ = blank();
109 std::error_code ec;
110 if (path_.empty() || !std::filesystem::exists(path_, ec)) {
111 return;
112 }
113 std::ifstream in(path_);
114 const json file = json::parse(in, nullptr, false);
115 if (!file.is_object() || !file.contains("workspaces") || !file["workspaces"].is_object()) {
116 LOG_WARN("WebServer: {} is not a workspaces file: starting with Default alone", path_);
117 return;
118 }
119 // A hand edit that broke one workspace loses that one only. A name is kept trimmed, so of
120 // "Morning" and "Morning " the first in the file stays.
121 auto& kept = doc_["workspaces"];
122 std::set<std::string> loaded;
123 for (const auto& [raw, workspace] : file["workspaces"].items()) {
124 const std::string name(trim(raw));
125 std::string error = loaded.contains(name) ? "another workspace has that name" : "";
126 json windows = error.empty() && valid_name(name) && workspace.is_object() && workspace.contains("windows")
127 ? clean_windows(workspace["windows"], error) : json();
128 if (windows.is_null()) {
129 LOG_WARN("WebServer: dropping workspace '{}' from {}: {}", raw, path_,
130 error.empty() ? "not a workspace" : error);
131 continue;
132 }
133 loaded.insert(name);
134 kept[name] = {{"windows", std::move(windows)}};
135 }
136 if (const auto last = file.find("last"); last != file.end() && last->is_string()) {
137 const std::string name(trim(last->get_ref<const std::string&>()));
138 if (kept.contains(name)) {
139 doc_["last"] = name;
140 }
141 }
142}
143
144WorkspaceStore::Result WorkspaceStore::save(std::string_view name, const json& windows) {
145 name = trim(name);
146 if (!valid_name(name)) {
147 return {400, "a workspace name is 1 to 64 characters, none of them control characters"};
148 }
149 std::string error;
150 json kept = clean_windows(windows, error);
151 if (!error.empty()) {
152 return {400, std::move(error)};
153 }
154 json before = doc_;
155 const std::string key(name);
156 doc_["workspaces"][key] = {{"windows", std::move(kept)}};
157 doc_["last"] = key;
158 return commit(std::move(before));
159}
160
162 name = trim(name);
163 if (name == DEFAULT) {
164 return {400, "Default can't be deleted"};
165 }
166 const std::string key(name);
167 if (!doc_["workspaces"].contains(key)) {
168 return {404, "no workspace " + key};
169 }
170 json before = doc_;
171 doc_["workspaces"].erase(key);
172 if (is_last(doc_, key)) {
173 doc_["last"] = std::string(DEFAULT);
174 }
175 return commit(std::move(before));
176}
177
179 const std::string key(trim(name));
180 if (!doc_["workspaces"].contains(key)) {
181 return {404, "no workspace " + key};
182 }
183 if (is_last(doc_, key)) {
184 return {};
185 }
186 json before = doc_;
187 doc_["last"] = key;
188 return commit(std::move(before));
189}
190
191WorkspaceStore::Result WorkspaceStore::commit(json before) {
192 if (path_.empty()) {
193 return {};
194 }
195 namespace fs = std::filesystem;
196 const fs::path file(path_);
197 fs::path temp = file;
198 temp += ".tmp";
199 std::error_code ec;
200 if (file.has_parent_path()) {
201 fs::create_directories(file.parent_path(), ec); // the write below reports a failure
202 }
203 bool written = false;
204 {
205 std::ofstream out(temp, std::ios::trunc);
206 out << doc_.dump(2) << '\n';
207 out.close();
208 written = static_cast<bool>(out);
209 }
210 if (written) {
211 fs::rename(temp, file, ec); // over the old one in one step: a crash leaves either whole
212 }
213 if (!written || ec) {
214 fs::remove(temp, ec);
215 doc_ = std::move(before);
216 LOG_ERROR("WebServer: cannot write workspaces to {}", path_);
217 return {500, "cannot write " + path_};
218 }
219 return {};
220}
221
222} // namespace slick::trader
static constexpr std::string_view DEFAULT
Result save(std::string_view name, const nlohmann::json &windows)
Result remove(std::string_view name)
Result use(std::string_view name)
nlohmann::json json