Nostro/implementations/Nostro-Connector.cpp
2026-11-01 18:35:23 +01:00

145 lines
4.9 KiB
C++

// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
#include <cerrno>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
module Nostro:Connector_impl;
import std;
import :Connector;
import :Banks;
import :File;
import :Utils;
using namespace Nostro;
using namespace nlohmann;
namespace fs = std::filesystem;
namespace {
[[noreturn]] void ThrowErrno(std::string_view what, const fs::path& path) {
throw std::system_error(errno, std::generic_category(), std::format("cannot {} {}", what, path.string()));
}
// One nostro process at a time works on the connectors: two that each load, change and save the file would each
// write back their own view, and the later one would drop what the other added or renewed. The lock is taken by
// the first load or save and held until the process ends.
void LockConnectors() {
static std::int32_t lock = -1;
if(lock != -1) {
return;
}
const fs::path path = configPath/"connectors.lock";
CreatePrivateFile(path);
const std::int32_t fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
if(fd == -1) {
ThrowErrno("open", path);
}
// Remembered only once it is held: a failure here leaves the next call to try again, not to think it locked.
std::int32_t result = flock(fd, LOCK_EX | LOCK_NB);
if(result == -1 && errno == EWOULDBLOCK) {
Note("waiting for another nostro process to finish");
do {
result = flock(fd, LOCK_EX);
} while(result == -1 && errno == EINTR);
}
if(result == -1) {
const std::int32_t error = errno;
close(fd);
errno = error;
ThrowErrno("lock", path);
}
lock = fd;
}
void WriteAll(std::int32_t fd, std::string_view data, const fs::path& path) {
while(!data.empty()) {
const ssize_t written = write(fd, data.data(), data.size());
if(written >= 0) {
data.remove_prefix(static_cast<std::size_t>(written));
} else if(errno != EINTR) {
ThrowErrno("write", path);
}
}
}
}
void Connector::SaveConnectors() {
LockConnectors();
const fs::path path = configPath/"connectors.json";
const fs::path temporary = configPath/std::format("connectors.json.tmp-{}", getpid());
json jsonConnectors = json::object();
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
jsonConnectors[Bank::connectorId] = Bank::connectors;
});
const std::string text = jsonConnectors.dump(4);
// The file holds the only copy of each connector's private key. The new one is on the disk before it replaces the
// old one, and the rename after, so a crash or a power cut leaves one whole file or the other.
CreatePrivateFile(temporary);
const std::int32_t fd = open(temporary.c_str(), O_WRONLY | O_TRUNC | O_CLOEXEC);
if(fd == -1) {
ThrowErrno("open", temporary);
}
try {
WriteAll(fd, text, temporary);
if(fsync(fd) == -1) {
ThrowErrno("sync", temporary);
}
} catch(...) {
close(fd);
fs::remove(temporary);
throw;
}
close(fd);
fs::rename(temporary, path);
const std::int32_t directory = open(configPath.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(directory != -1) {
fsync(directory);
close(directory);
}
}
void Connector::LoadConnectors() {
LockConnectors();
const fs::path path = configPath/"connectors.json";
if(!fs::exists(path)) {
return;
}
std::ifstream f(path);
const json jsonConnectors = [&path, &f] {
try {
return json::parse(f);
} catch(const json::parse_error& e) {
// nlohmann's own message quotes the text it read last, which can be part of a private key: say where the
// file breaks, not what it holds.
throw std::runtime_error(std::format("{} is not valid JSON (it breaks at byte {})", path.string(), e.byte));
}
}();
// Every bank's list is in place before any refresh: a refresh can save, and a save writes all of them.
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
if(jsonConnectors.contains(Bank::connectorId)) {
Bank::connectors = jsonConnectors.at(Bank::connectorId).template get<std::remove_cvref_t<decltype(Bank::connectors)>>();
}
});
tuple_for<EnabledBanks>([]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
try {
bank.RefreshAccounts();
} catch(const std::exception& e) {
Note(std::format("{} connector '{}' is unavailable: {}", Bank::connectorId, bank.name, e.what()));
}
}
});
}