summaryrefslogtreecommitdiff
path: root/lib/mu-config.hh
blob: bf461d85f5ea81cdb534e536205661a3a82cb003 (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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*
** Copyright (C) 2023-2025 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU General Public License as published by the
** Free Software Foundation; either version 3, or (at your option) any
** later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation,
** Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**
*/

#ifndef MU_CONFIG_HH__
#define MU_CONFIG_HH__

#include <cstdint>
#include <cinttypes>
#include <string_view>
#include <string>
#include <array>
#include <vector>
#include <variant>
#include <unordered_map>

#include "mu-xapian-db.hh"

#include <utils/mu-utils.hh>
#include <utils/mu-result.hh>
#include <utils/mu-option.hh>

namespace Mu {

struct Property {
	enum struct Id {
		BatchSize,		/**< Xapian batch-size */
		Contacts,		/**< Cache of contact information */
		Created,		/**< Time of creation */
		IgnoredAddresses,	/**< Email addresses ignored for the contacts-cache */
		Labels,                 /**< Serialized label information. */
		LastChange,		/**< Time of last change */
		LastIndex,		/**< Time of last index */
		MaxMessageSize,		/**< Maximum message size (in bytes) */
		PersonalAddresses,	/**< List of personal e-mail addresses */
		RootMaildir,		/**< Root maildir path */
		SchemaVersion,		/**< Xapian DB schema version */
		SupportNgrams,		/**< Support ngrams for indexing & querying
					 *  for e.g. CJK languages */
		/* <private> */
		_count_		/* Number of Ids */
	};

	static constexpr size_t id_size = static_cast<size_t>(Id::_count_);
	/**< Number of Property::Ids */

	enum struct Flags {
		None	     = 0,	/**< Nothing in particular */
		ReadOnly     = 1 << 0, /**< Property is read-only for external use
					* (but can change from within the store) */
		Configurable = 1 << 1,	/**< A user-configurable parameter; name
					 * starts with 'conf-' */
		Internal     = 1 << 2,	/**< Mu-internal field */
		Runtime      = 1 << 3,  /**< May change at runtime */
	};
	enum struct Type {
		Boolean,        /**< Some boolean value */
		Number,		/**< Some number */
		Timestamp,      /**< Timestamp number */
		Path,           /**< Path string */
		String,		/**< A string */
		StringList,	/**< A list of strings */
	};

	using Value = std::variant<int64_t, std::string, std::vector<std::string> >;

	Id			id;
	Type			type;
	Flags			flags;
	std::string_view	name;
	std::string_view        default_val;
	std::string_view	description;
};

MU_ENABLE_BITOPS(Property::Flags);

class Config {
public:
	using	Id    = Property::Id;
	using	Type  = Property::Type;
	using	Flags = Property::Flags;
	using	Value = Property::Value;

	static constexpr std::array<Property, Property::id_size>
	properties    = {{
		{
			Id::BatchSize,
			Type::Number,
			Flags::Configurable,
			"batch-size",
			"50000",
			"Maximum number of changes in a database transaction"
		},
		{
			Id::Contacts,
			Type::String,
			Flags::Internal,
			"contacts",
			{},
			"Serialized contact information"
		},
		{
			Id::Created,
			Type::Timestamp,
			Flags::ReadOnly,
			MetadataIface::created_key,
			{},
			"Database creation time"
		},
		{
			Id::IgnoredAddresses,
			Type::StringList,
			Flags::Configurable,
			"ignored-addresses",
			{},
			"E-mail addresses ignored  for the contacts-cache, "
			"literal or /regexp/"
		},

		{
			Id::Labels,
			Type::String,
			Flags::Internal,
			"labels",
			{},
			"Serialized labels information"
		},

		{
			Id::LastChange,
			Type::Timestamp,
			Flags::ReadOnly | Flags::Runtime,
			MetadataIface::last_change_key,
			{},
			"Time when last change occurred"
		},
		{
			Id::LastIndex,
			Type::Timestamp,
			Flags::ReadOnly | Flags::Runtime,
			"last-index",
			{},
			"Time when last indexing operation was completed"
		},
		{
			Id::MaxMessageSize,
			Type::Number,
			Flags::Configurable,
			"max-message-size",
			"100000000", // default max: 100M bytes
			"Maximum message size (in bytes); bigger messages are skipped"
		},
		{
			Id::PersonalAddresses,
			Type::StringList,
			Flags::Configurable,
			"personal-addresses",
			{},
			"Personal e-mail addresses, literal or /regexp/"
		},
		{
			Id::RootMaildir,
			Type::Path,
			Flags::ReadOnly,
			"root-maildir",
			{},
			"Absolute path of the top of the Maildir tree"
		},
		{
			Id::SchemaVersion,
			Type::Number,
			Flags::ReadOnly,
			"schema-version",
			{},
			"Version of the Xapian database schema"
		},
		{
			Id::SupportNgrams,
			Type::Boolean,
			Flags::Configurable,
			"support-ngrams",
			{},
			"Support n-grams for working with CJK and other languages"
		},
	}};

	/**
	 * Construct a new Config object.
	 *
	 * @param db The config-store (database); must stay valid for the
	 * lifetime of this config.
	 */
	Config(MetadataIface& cstore): cstore_{cstore}{}

	/**
	 * Get the property by its id
	 *
	 * @param id a property id (!= Id::_count_)
	 *
	 * @return the property
	 */
	template <Id ID>
	constexpr static const Property& property() {
		return properties[static_cast<size_t>(ID)];
	}

	/**
	 * Get a Property by its name.
	 *
	 * @param name The name
	 *
	 * @return the property or Nothing if not found
	 */
	static Option<const Property&> property(const std::string& name) {
		const auto pname{std::string_view(name.data(), name.size())};
		for (auto&& prop: properties)
			if (prop.name == pname)
				return prop;
		return Nothing;
	}


	/**
	 * Get the string-value for prop.
	 *
	 * For internal use
	 *
	 * @param prop some property
	 *
	 * @return a string
	 */
	std::string get_str(const Property& prop) const {
		const auto str = cstore_.metadata(std::string{prop.name});
		return str.empty() ? std::string{prop.default_val} : str;
	}


	/**
	 * Get the property value decoded based on the type
	 *
	 * @param prop_id a property id
	 *
	 * @return the value or Nothing
	 */
	template<Type type>
	static constexpr auto decode(const std::string& str)  {
		if constexpr (type == Type::Number)
			return static_cast<size_t>(str.empty() ? 0 : std::atoll(str.c_str()));
		if constexpr (type == Type::Boolean)
			return static_cast<size_t>(str.empty() ? false :
						   std::atol(str.c_str()) != 0);
		else if constexpr (type == Type::Timestamp)
			return static_cast<int64_t>(str.empty() ? 0 : std::atoll(str.c_str()));
		else if constexpr (type == Type::Path || type == Type::String)
			return str;
		else if constexpr (type == Type::StringList)
			return split(str, SepaChar1);
		throw std::logic_error("invalid type");
	}



	/**
	 * Get the property value of the correct type
	 *
	 * @param prop_id a property id
	 *
	 * @return the value or Nothing
	 */
	template<Id ID>
	auto get() const {
		constexpr auto& prop{property<ID>()};
		return decode<prop.type>(get_str(prop));
	}

	/**
	 * Set a new value for some property
	 *
	 * @param prop_id property-id
	 * @param val the new value (of the correct type)
	 *
	 * @return Ok() or some error
	 */
	template<Id ID, typename T>
	Result<void> set(const T& val) {
		constexpr auto&& prop{property<ID>()};
		if (read_only())
			return Err(Error::Code::AccessDenied,
				   "cannot write to read-only db");

		const auto strval = std::invoke([&]{
			if constexpr (prop.type == Type::Number || prop.type == Type::Timestamp)
				return mu_format("{}", static_cast<int64_t>(val));
			if constexpr (prop.type == Type::Boolean)
				return val ? "1" : "0";
			else if constexpr (prop.type == Type::Path || prop.type == Type::String)
				return std::string{val};
			else if constexpr (prop.type == Type::StringList)
				return join(val, SepaChar1);
			else
				throw std::logic_error("invalid prop " + std::string{prop.name});
		});

		cstore_.set_metadata(std::string{prop.name}, strval);
		return Ok();
	}

	/**
	 * Is this a read-only Config?
	 *
	 *
	 * @return true or false
	 */
	bool read_only() const { return cstore_.read_only();};

	/**
	 * Import configurable settings to some other MetadataIface
	 *
	 * @param target some other metadata interface
	 */
	void import_configurable(const Config& src) const {
		for (auto&& prop: properties) {
			if (any_of(prop.flags & Flags::Configurable)) {
				const auto&& key{std::string{prop.name}};
				if (auto&& val{src.cstore_.metadata(key)}; !val.empty())
					cstore_.set_metadata(key, std::string{val});
			}
		}
	}

private:
	MetadataIface& cstore_;
};


} // namespace Mu

#endif /* MU_CONFIG_DB_HH__ */