|
|
@@ -10,6 +10,7 @@
|
|
|
#include "json_parse.hpp"
|
|
|
#include "persistence/wal.hpp"
|
|
|
#include "views/projection.hpp"
|
|
|
+#include "storage/secondary_index.hpp"
|
|
|
|
|
|
#include <spdlog/spdlog.h>
|
|
|
#include <nlohmann/json.hpp>
|
|
|
@@ -20,6 +21,7 @@
|
|
|
#include <memory>
|
|
|
#include <mutex>
|
|
|
#include <queue>
|
|
|
+#include <unordered_set>
|
|
|
#include <utility>
|
|
|
#include <vector>
|
|
|
|
|
|
@@ -29,9 +31,60 @@ namespace smartbotic::database {
|
|
|
namespace pb = smartbotic::databasepb;
|
|
|
|
|
|
namespace {
|
|
|
+// v2.12.0 — refusal detail. See the comment above `service DatabaseService` in
|
|
|
+// database.proto for the key and its JSON shape. Attached to the call's
|
|
|
+// trailing metadata, so it accompanies an error status AND an in-band refusal
|
|
|
+// (status OK, success=false) alike.
|
|
|
+constexpr const char* kErrorDetailKey = "sbdb-error-detail-bin";
|
|
|
+
|
|
|
+void attachErrorDetail(grpc::ServerContext* context, const nlohmann::json& detail) {
|
|
|
+ if (context != nullptr) {
|
|
|
+ context->AddTrailingMetadata(kErrorDetailKey, detail.dump());
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+grpc::Status uniqueViolationStatus(grpc::ServerContext* context,
|
|
|
+ const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
+ attachErrorDetail(context, {{"reason", "unique_violation"},
|
|
|
+ {"fields", e.fields},
|
|
|
+ {"values", e.values},
|
|
|
+ {"conflicting_id", e.existing_id}});
|
|
|
+ return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+}
|
|
|
+
|
|
|
+grpc::Status missingParentStatus(grpc::ServerContext* context,
|
|
|
+ const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
+ attachErrorDetail(context, {{"reason", "missing_parent"},
|
|
|
+ {"fields", nlohmann::json::array({e.childField})},
|
|
|
+ {"values", {{e.childField, e.parentId}}},
|
|
|
+ {"relation", e.relation}});
|
|
|
+ return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+}
|
|
|
+
|
|
|
+// An in-band refusal: status OK, success=false, as these RPCs have always
|
|
|
+// answered - so a pre-2.12 client sees exactly what it always saw - plus the
|
|
|
+// code it would carry as a status, and the detail.
|
|
|
+template <typename Response>
|
|
|
+grpc::Status refuseInBand(grpc::ServerContext* context, Response* response,
|
|
|
+ grpc::StatusCode code, const std::string& reason,
|
|
|
+ const std::string& message,
|
|
|
+ nlohmann::json extra = nlohmann::json::object()) {
|
|
|
+ response->set_success(false);
|
|
|
+ response->set_error(message);
|
|
|
+ response->set_error_code(static_cast<int32_t>(code));
|
|
|
+ extra["reason"] = reason;
|
|
|
+ extra["code"] = static_cast<int>(code);
|
|
|
+ attachErrorDetail(context, extra);
|
|
|
+ return grpc::Status::OK;
|
|
|
+}
|
|
|
+
|
|
|
// Returns a Status that should be returned when the DB is read-only.
|
|
|
// Used by write handlers whose responses don't have set_success/set_error fields.
|
|
|
-grpc::Status readOnlyStatus(const std::string& rpcName, const DatabaseService& svc) {
|
|
|
+grpc::Status readOnlyStatus(grpc::ServerContext* context, const std::string& rpcName,
|
|
|
+ const DatabaseService& svc) {
|
|
|
+ // v2.12.0 — reason "read_only": FAILED_PRECONDITION alone is ambiguous with
|
|
|
+ // a relation refusal, which uses the same code.
|
|
|
+ attachErrorDetail(context, {{"reason", "read_only"}});
|
|
|
return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
|
|
|
rpcName + " rejected: database is in read-only mode. " + svc.readOnlyReason());
|
|
|
}
|
|
|
@@ -39,7 +92,9 @@ grpc::Status readOnlyStatus(const std::string& rpcName, const DatabaseService& s
|
|
|
// Returns a Status for rejecting writes when memory pressure is EMERGENCY.
|
|
|
// Shares the RESOURCE_EXHAUSTED code with gRPC concurrency cap so clients
|
|
|
// can reuse the same retry path.
|
|
|
-grpc::Status memoryEmergencyStatus(const std::string& rpcName, const MemoryStore& store) {
|
|
|
+grpc::Status memoryEmergencyStatus(grpc::ServerContext* context, const std::string& rpcName,
|
|
|
+ const MemoryStore& store) {
|
|
|
+ attachErrorDetail(context, {{"reason", "memory_pressure"}});
|
|
|
return grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED,
|
|
|
rpcName + " rejected: memory pressure emergency (" +
|
|
|
std::to_string(store.pressurePercent()) + "% of max, threshold " +
|
|
|
@@ -354,10 +409,10 @@ grpc::Status DatabaseGrpcImpl::Insert(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("Insert", service_);
|
|
|
+ return readOnlyStatus(context, "Insert", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("Insert", store_);
|
|
|
+ return memoryEmergencyStatus(context, "Insert", store_);
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
|
|
|
@@ -418,13 +473,13 @@ grpc::Status DatabaseGrpcImpl::Insert(
|
|
|
// v2.11.0 T11 — a duplicate is the caller's mistake, not a server
|
|
|
// fault. MemoryStore has already undone its own mutation by the
|
|
|
// time this propagates here (see mirrorDocOrUndo).
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
// v2.11.0 T13 — a validate_on_write rejection: the referenced
|
|
|
// parent does not exist. Not a server fault either, and not
|
|
|
// ALREADY_EXISTS - FAILED_PRECONDITION is the right status for "the
|
|
|
// system is not in a state this write requires".
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -544,21 +599,20 @@ grpc::Status DatabaseGrpcImpl::Update(
|
|
|
return st;
|
|
|
}
|
|
|
|
|
|
+ // v2.12.0 — still in-band (status OK) so older clients see what they always
|
|
|
+ // saw, now with error_code and a reason in the refusal detail.
|
|
|
if (service_.isReadOnly()) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("database is in read-only mode: " + service_.readOnlyReason());
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::FAILED_PRECONDITION, "read_only",
|
|
|
+ "database is in read-only mode: " + service_.readOnlyReason());
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("memory pressure emergency (" +
|
|
|
- std::to_string(store_.pressurePercent()) + "%); retry after backoff");
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::RESOURCE_EXHAUSTED, "memory_pressure",
|
|
|
+ "memory pressure emergency (" +
|
|
|
+ std::to_string(store_.pressurePercent()) + "%); retry after backoff");
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("cannot write to view '" + request->collection() + "': views are read-only");
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::INVALID_ARGUMENT, "view_write",
|
|
|
+ "cannot write to view '" + request->collection() + "': views are read-only");
|
|
|
}
|
|
|
try {
|
|
|
nlohmann::json data = smartbotic::db::parse_to_nlohmann(request->data());
|
|
|
@@ -583,16 +637,24 @@ grpc::Status DatabaseGrpcImpl::Update(
|
|
|
expiryOverrideFrom(*request)
|
|
|
);
|
|
|
if (!success) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("Version conflict");
|
|
|
- return grpc::Status::OK;
|
|
|
+ // v2.12.0 — updateIfVersion answers false for a missing
|
|
|
+ // document AND a stale version, and both used to be reported
|
|
|
+ // as "Version conflict". The message stays (older clients may
|
|
|
+ // match it); the code and detail now tell them apart.
|
|
|
+ auto current = store_.get(request->collection(), request->id());
|
|
|
+ if (!current) {
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
|
|
|
+ "not_found", "Version conflict");
|
|
|
+ }
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::ABORTED,
|
|
|
+ "version_conflict", "Version conflict",
|
|
|
+ {{"current_version", current->version}});
|
|
|
}
|
|
|
} else {
|
|
|
success = store_.update(request->collection(), request->id(), doc);
|
|
|
if (!success) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("Document not found");
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
|
|
|
+ "not_found", "Document not found");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -620,10 +682,10 @@ grpc::Status DatabaseGrpcImpl::Update(
|
|
|
"Invalid JSON: " + std::string(e.what()));
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
// v2.11.0 T11 — see the Insert handler's note.
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
// v2.11.0 T13 — see the Insert handler's note.
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -640,37 +702,72 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
|
|
|
return st;
|
|
|
}
|
|
|
|
|
|
+ // v2.12.0 — still in-band (status OK) so older clients see what they always
|
|
|
+ // saw, now with error_code and a reason in the refusal detail.
|
|
|
if (service_.isReadOnly()) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("database is in read-only mode: " + service_.readOnlyReason());
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::FAILED_PRECONDITION, "read_only",
|
|
|
+ "database is in read-only mode: " + service_.readOnlyReason());
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("memory pressure emergency (" +
|
|
|
- std::to_string(store_.pressurePercent()) + "%); retry after backoff");
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::RESOURCE_EXHAUSTED, "memory_pressure",
|
|
|
+ "memory pressure emergency (" +
|
|
|
+ std::to_string(store_.pressurePercent()) + "%); retry after backoff");
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("cannot write to view '" + request->collection() + "': views are read-only");
|
|
|
- return grpc::Status::OK;
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::INVALID_ARGUMENT, "view_write",
|
|
|
+ "cannot write to view '" + request->collection() + "': views are read-only");
|
|
|
}
|
|
|
try {
|
|
|
- nlohmann::json patch = smartbotic::db::parse_to_nlohmann(request->patch_json());
|
|
|
+ // v2.12.0 — an increment-only request may send no merge patch at all.
|
|
|
+ nlohmann::json patch = request->patch_json().empty()
|
|
|
+ ? nlohmann::json::object()
|
|
|
+ : smartbotic::db::parse_to_nlohmann(request->patch_json());
|
|
|
+
|
|
|
+ std::optional<nlohmann::json> increments;
|
|
|
+ if (!request->increments_json().empty()) {
|
|
|
+ increments = smartbotic::db::parse_to_nlohmann(request->increments_json());
|
|
|
+ }
|
|
|
+ std::optional<uint64_t> expectedVersion;
|
|
|
+ if (request->has_expected_version()) {
|
|
|
+ expectedVersion = request->expected_version();
|
|
|
+ }
|
|
|
|
|
|
+ nlohmann::json incremented = nlohmann::json::object();
|
|
|
+ MemoryStore::PatchRefusal refusal;
|
|
|
uint64_t newVersion = store_.patchDocument(
|
|
|
request->collection(),
|
|
|
request->id(),
|
|
|
patch,
|
|
|
request->actor(),
|
|
|
- expiryOverrideFrom(*request)
|
|
|
+ expiryOverrideFrom(*request),
|
|
|
+ expectedVersion,
|
|
|
+ increments ? &*increments : nullptr,
|
|
|
+ &incremented,
|
|
|
+ &refusal
|
|
|
);
|
|
|
|
|
|
if (newVersion == 0) {
|
|
|
- response->set_success(false);
|
|
|
- response->set_error("Document not found");
|
|
|
- return grpc::Status::OK;
|
|
|
+ using Kind = MemoryStore::PatchRefusal::Kind;
|
|
|
+ if (refusal.kind == Kind::VersionConflict) {
|
|
|
+ // A real status: only a caller that SENT expected_version can
|
|
|
+ // get here, so no pre-2.12 client ever sees it.
|
|
|
+ attachErrorDetail(context, {{"reason", "version_conflict"},
|
|
|
+ {"current_version", refusal.currentVersion}});
|
|
|
+ return grpc::Status(grpc::StatusCode::ABORTED,
|
|
|
+ "version conflict: document is at version " +
|
|
|
+ std::to_string(refusal.currentVersion) + ", expected " +
|
|
|
+ std::to_string(*expectedVersion));
|
|
|
+ }
|
|
|
+ if (refusal.kind == Kind::InvalidIncrement) {
|
|
|
+ attachErrorDetail(context, {{"reason", "invalid_increment"},
|
|
|
+ {"fields", nlohmann::json::array({refusal.field})}});
|
|
|
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, refusal.message);
|
|
|
+ }
|
|
|
+ return refuseInBand(context, response, grpc::StatusCode::NOT_FOUND,
|
|
|
+ "not_found", "Document not found");
|
|
|
+ }
|
|
|
+ if (increments) {
|
|
|
+ response->set_incremented_json(incremented.dump());
|
|
|
}
|
|
|
|
|
|
// Persist vector changes (store_.patchDocument handles WAL for the document itself
|
|
|
@@ -692,10 +789,10 @@ grpc::Status DatabaseGrpcImpl::PatchDocument(
|
|
|
"Invalid JSON: " + std::string(e.what()));
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
// v2.11.0 T11 — see the Insert handler's note.
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
// v2.11.0 T13 — see the Insert handler's note.
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -713,10 +810,10 @@ grpc::Status DatabaseGrpcImpl::Upsert(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("Upsert", service_);
|
|
|
+ return readOnlyStatus(context, "Upsert", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("Upsert", store_);
|
|
|
+ return memoryEmergencyStatus(context, "Upsert", store_);
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
|
|
|
@@ -794,10 +891,10 @@ grpc::Status DatabaseGrpcImpl::Upsert(
|
|
|
"Invalid JSON: " + std::string(e.what()));
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
// v2.11.0 T11 — see the Insert handler's note.
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
// v2.11.0 T13 — see the Insert handler's note.
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -827,10 +924,10 @@ grpc::Status DatabaseGrpcImpl::Delete(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("Delete", service_);
|
|
|
+ return readOnlyStatus(context, "Delete", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("Delete", store_);
|
|
|
+ return memoryEmergencyStatus(context, "Delete", store_);
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
|
|
|
@@ -846,13 +943,19 @@ grpc::Status DatabaseGrpcImpl::Delete(
|
|
|
// checkRelationDeleteAllowed()/performRelationCascade() so that
|
|
|
// BatchDelete enforces identically instead of bypassing all of it.
|
|
|
if (auto st = checkRelationDeleteAllowed(request->collection(), request->id()); !st.ok()) {
|
|
|
+ if (st.error_code() == grpc::StatusCode::FAILED_PRECONDITION) {
|
|
|
+ attachErrorDetail(context, {{"reason", "delete_restricted"}});
|
|
|
+ }
|
|
|
return st;
|
|
|
}
|
|
|
{
|
|
|
bool handled = false;
|
|
|
bool parentExisted = false;
|
|
|
if (auto st = performRelationCascade(request->collection(), request->id(),
|
|
|
- handled, parentExisted); !st.ok()) {
|
|
|
+ request->actor(), handled, parentExisted); !st.ok()) {
|
|
|
+ if (st.error_code() == grpc::StatusCode::FAILED_PRECONDITION) {
|
|
|
+ attachErrorDetail(context, {{"reason", "delete_restricted"}});
|
|
|
+ }
|
|
|
return st;
|
|
|
}
|
|
|
if (handled) {
|
|
|
@@ -871,7 +974,7 @@ grpc::Status DatabaseGrpcImpl::Delete(
|
|
|
hadVector = vectors->count(request->id()) > 0;
|
|
|
}
|
|
|
|
|
|
- bool deleted = store_.remove(request->collection(), request->id());
|
|
|
+ bool deleted = store_.remove(request->collection(), request->id(), request->actor());
|
|
|
|
|
|
if (deleted && hadVector) {
|
|
|
persistence_.logVecDelete(request->collection(), request->id());
|
|
|
@@ -1093,9 +1196,9 @@ grpc::Status DatabaseGrpcImpl::RestoreVersion(
|
|
|
response->set_success(true);
|
|
|
return grpc::Status::OK;
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -1141,9 +1244,9 @@ grpc::Status DatabaseGrpcImpl::RestoreToDate(
|
|
|
response->set_success(true);
|
|
|
return grpc::Status::OK;
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -1163,10 +1266,10 @@ grpc::Status DatabaseGrpcImpl::BatchInsert(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("BatchInsert", service_);
|
|
|
+ return readOnlyStatus(context, "BatchInsert", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("BatchInsert", store_);
|
|
|
+ return memoryEmergencyStatus(context, "BatchInsert", store_);
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
|
|
|
@@ -1244,10 +1347,10 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("BatchDelete", service_);
|
|
|
+ return readOnlyStatus(context, "BatchDelete", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("BatchDelete", store_);
|
|
|
+ return memoryEmergencyStatus(context, "BatchDelete", store_);
|
|
|
}
|
|
|
if (view_manager_.isView(request->collection())) {
|
|
|
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
|
|
|
@@ -1287,6 +1390,7 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
|
|
|
}
|
|
|
}
|
|
|
if (blockedCount > 0) {
|
|
|
+ attachErrorDetail(context, {{"reason", "delete_restricted"}});
|
|
|
return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION,
|
|
|
"batch delete refused: " + std::to_string(blockedCount) + " of " +
|
|
|
std::to_string(ids.size()) + " document(s) are protected by a relation, "
|
|
|
@@ -1299,6 +1403,7 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
|
|
|
uint64_t deleted = 0;
|
|
|
std::vector<std::string> plain; // ids with no destructive relation
|
|
|
plain.reserve(ids.size());
|
|
|
+ std::unordered_set<std::string> gone; // v2.12.0 — for deleted_ids
|
|
|
for (const auto& id : ids) {
|
|
|
bool handled = false;
|
|
|
bool parentExisted = false;
|
|
|
@@ -1308,20 +1413,31 @@ grpc::Status DatabaseGrpcImpl::BatchDelete(
|
|
|
// cascade fault the WAL may already hold durable entries (see
|
|
|
// performRelationCascade's INTERNAL branch), and pressing on would make
|
|
|
// the reported count meaningless.
|
|
|
- if (auto st = performRelationCascade(request->collection(), id,
|
|
|
+ if (auto st = performRelationCascade(request->collection(), id, request->actor(),
|
|
|
handled, parentExisted); !st.ok()) {
|
|
|
+ if (st.error_code() == grpc::StatusCode::FAILED_PRECONDITION) {
|
|
|
+ attachErrorDetail(context, {{"reason", "delete_restricted"}});
|
|
|
+ }
|
|
|
return st;
|
|
|
}
|
|
|
if (handled) {
|
|
|
- if (parentExisted) ++deleted;
|
|
|
+ if (parentExisted) { ++deleted; gone.insert(id); }
|
|
|
} else {
|
|
|
plain.push_back(id);
|
|
|
}
|
|
|
}
|
|
|
- if (!plain.empty()) {
|
|
|
- deleted += store_.bulkDelete(request->collection(), plain);
|
|
|
+ // v2.12.0 — one remove() per id rather than bulkDelete(), which is the same
|
|
|
+ // loop but reports only a count: the caller now learns WHICH ids existed.
|
|
|
+ for (const auto& id : plain) {
|
|
|
+ if (store_.remove(request->collection(), id, request->actor())) {
|
|
|
+ ++deleted;
|
|
|
+ gone.insert(id);
|
|
|
+ }
|
|
|
}
|
|
|
response->set_deleted_count(deleted);
|
|
|
+ for (const auto& id : ids) {
|
|
|
+ if (gone.erase(id) > 0) response->add_deleted_ids(id); // request order, once each
|
|
|
+ }
|
|
|
return grpc::Status::OK;
|
|
|
}
|
|
|
|
|
|
@@ -1715,10 +1831,10 @@ grpc::Status DatabaseGrpcImpl::SetAdd(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("SetAdd", service_);
|
|
|
+ return readOnlyStatus(context, "SetAdd", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("SetAdd", store_);
|
|
|
+ return memoryEmergencyStatus(context, "SetAdd", store_);
|
|
|
}
|
|
|
// v2.11.0 T11 — setAdd can raise UniqueViolation if a unique field is
|
|
|
// declared over this collection; without this, an uncaught exception
|
|
|
@@ -1728,9 +1844,9 @@ grpc::Status DatabaseGrpcImpl::SetAdd(
|
|
|
response->set_added(added);
|
|
|
return grpc::Status::OK;
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -1748,10 +1864,10 @@ grpc::Status DatabaseGrpcImpl::SetRemove(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("SetRemove", service_);
|
|
|
+ return readOnlyStatus(context, "SetRemove", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("SetRemove", store_);
|
|
|
+ return memoryEmergencyStatus(context, "SetRemove", store_);
|
|
|
}
|
|
|
// v2.11.0 T11 — setRemove bumps _version/_updated_at, which are
|
|
|
// index-declarable metadata fields, so it can raise UniqueViolation the
|
|
|
@@ -1761,9 +1877,9 @@ grpc::Status DatabaseGrpcImpl::SetRemove(
|
|
|
response->set_removed(removed);
|
|
|
return grpc::Status::OK;
|
|
|
} catch (const smartbotic::db::storage::UniqueViolation& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::ALREADY_EXISTS, e.what());
|
|
|
+ return uniqueViolationStatus(context, e);
|
|
|
} catch (const smartbotic::db::storage::MissingParentReference& e) {
|
|
|
- return grpc::Status(grpc::StatusCode::FAILED_PRECONDITION, e.what());
|
|
|
+ return missingParentStatus(context, e);
|
|
|
} catch (const std::exception& e) {
|
|
|
return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
}
|
|
|
@@ -1817,10 +1933,10 @@ grpc::Status DatabaseGrpcImpl::CreateCollection(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("CreateCollection", service_);
|
|
|
+ return readOnlyStatus(context, "CreateCollection", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("CreateCollection", store_);
|
|
|
+ return memoryEmergencyStatus(context, "CreateCollection", store_);
|
|
|
}
|
|
|
CollectionOptions opts;
|
|
|
// Proto3 defaults bools to false, but we want autoCreateId to default to true
|
|
|
@@ -1857,10 +1973,10 @@ grpc::Status DatabaseGrpcImpl::DropCollection(
|
|
|
}
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("DropCollection", service_);
|
|
|
+ return readOnlyStatus(context, "DropCollection", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("DropCollection", store_);
|
|
|
+ return memoryEmergencyStatus(context, "DropCollection", store_);
|
|
|
}
|
|
|
|
|
|
// v2.11.0 final review (finding 1, from the "audit every other RPC that can
|
|
|
@@ -2045,7 +2161,7 @@ grpc::Status DatabaseGrpcImpl::CreateProject(
|
|
|
if (auto st = requireAnyAdmin(context, "CreateProject"); !st.ok()) return st;
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("CreateProject", service_);
|
|
|
+ return readOnlyStatus(context, "CreateProject", service_);
|
|
|
}
|
|
|
std::string error;
|
|
|
bool created = service_.createProject(request->name(), error);
|
|
|
@@ -2065,7 +2181,7 @@ grpc::Status DatabaseGrpcImpl::DropProject(
|
|
|
if (auto st = requireAnyAdmin(context, "DropProject"); !st.ok()) return st;
|
|
|
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("DropProject", service_);
|
|
|
+ return readOnlyStatus(context, "DropProject", service_);
|
|
|
}
|
|
|
std::string error;
|
|
|
bool dropped = service_.dropProject(request->name(), error);
|
|
|
@@ -2091,10 +2207,10 @@ grpc::Status DatabaseGrpcImpl::UploadFile(
|
|
|
std::to_string(maxFileStreams_) + " reached)");
|
|
|
}
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("UploadFile", service_);
|
|
|
+ return readOnlyStatus(context, "UploadFile", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("UploadFile", store_);
|
|
|
+ return memoryEmergencyStatus(context, "UploadFile", store_);
|
|
|
}
|
|
|
pb::FileChunk chunk;
|
|
|
std::vector<uint8_t> fileData;
|
|
|
@@ -2232,10 +2348,10 @@ grpc::Status DatabaseGrpcImpl::DeleteFile(
|
|
|
pb::DeleteFileResponse* response
|
|
|
) {
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("DeleteFile", service_);
|
|
|
+ return readOnlyStatus(context, "DeleteFile", service_);
|
|
|
}
|
|
|
if (store_.pressure() == MemoryPressure::Emergency) {
|
|
|
- return memoryEmergencyStatus("DeleteFile", store_);
|
|
|
+ return memoryEmergencyStatus(context, "DeleteFile", store_);
|
|
|
}
|
|
|
// v2.8.0 — gate the delete on the record's file type. Resolve first so we
|
|
|
// know the type; report a denial as "not deleted" rather than distinguishing
|
|
|
@@ -2300,7 +2416,7 @@ grpc::Status DatabaseGrpcImpl::SetFileTtl(
|
|
|
pb::SetFileTtlResponse* response
|
|
|
) {
|
|
|
if (service_.isReadOnly()) {
|
|
|
- return readOnlyStatus("SetFileTtl", service_);
|
|
|
+ return readOnlyStatus(context, "SetFileTtl", service_);
|
|
|
}
|
|
|
|
|
|
// Changing retention is a WRITE, gated on the record's own file type - which
|
|
|
@@ -2489,6 +2605,10 @@ grpc::Status DatabaseGrpcImpl::Subscribe(
|
|
|
protoEvent.set_document_id(event.documentId);
|
|
|
protoEvent.set_timestamp(event.timestamp);
|
|
|
protoEvent.set_node_id(event.nodeId);
|
|
|
+ // v2.12.0 - sent whether or not the subscriber asked for data: it is
|
|
|
+ // provenance, not document content, and a loop guard needs it on
|
|
|
+ // every event.
|
|
|
+ protoEvent.set_actor(event.actor);
|
|
|
|
|
|
if (includeData && event.data) {
|
|
|
// Masked columns must not ride out through the event stream - that
|
|
|
@@ -3062,6 +3182,7 @@ grpc::Status DatabaseGrpcImpl::checkRelationDeleteAllowed(const std::string& col
|
|
|
|
|
|
grpc::Status DatabaseGrpcImpl::performRelationCascade(const std::string& collection,
|
|
|
const std::string& id,
|
|
|
+ const std::string& actor,
|
|
|
bool& handled,
|
|
|
bool& parentExisted) {
|
|
|
handled = false;
|
|
|
@@ -3099,10 +3220,15 @@ grpc::Status DatabaseGrpcImpl::performRelationCascade(const std::string& collect
|
|
|
// MemoryStore apply. See relation_cascade.hpp's file header for why
|
|
|
// executeCascade() cannot go back through the ordinary
|
|
|
// persistCallback_ path itself.
|
|
|
- auto notify = [this](const std::string& coll, const std::string& docId,
|
|
|
- const std::optional<smartbotic::database::Document>& doc,
|
|
|
- smartbotic::database::EventType eventType) {
|
|
|
- service_.notifyReplicationAndEvents(coll, docId, doc, eventType);
|
|
|
+ //
|
|
|
+ // v2.12.0 - every event here carries the DELETING caller's actor,
|
|
|
+ // explicitly. The parent is gone so there is nothing to derive it
|
|
|
+ // from, and a child this cascade nulled still has its previous
|
|
|
+ // writer in updatedBy - deriving would blame them for our delete.
|
|
|
+ auto notify = [this, actor](const std::string& coll, const std::string& docId,
|
|
|
+ const std::optional<smartbotic::database::Document>& doc,
|
|
|
+ smartbotic::database::EventType eventType) {
|
|
|
+ service_.notifyReplicationAndEvents(coll, docId, doc, eventType, actor);
|
|
|
};
|
|
|
try {
|
|
|
parentExisted = smartbotic::database::executeCascade(
|
|
|
@@ -3746,6 +3872,98 @@ grpc::Status DatabaseReplicationGrpcImpl::GetNodeState(
|
|
|
// error.
|
|
|
// -------------------------------------------------------------------------
|
|
|
|
|
|
+// v2.12.0 — CreateIndex with `fields` set: a COMPOSITE unique constraint. See
|
|
|
+// CreateIndexRequest.fields in database.proto for the contract.
|
|
|
+grpc::Status DatabaseGrpcImpl::createCompositeUnique(
|
|
|
+ grpc::ServerContext* /*context*/,
|
|
|
+ const pb::CreateIndexRequest* request,
|
|
|
+ pb::CreateIndexResponse* response,
|
|
|
+ const smartbotic::database::Decision& dec) {
|
|
|
+ auto refuse = [&](const std::string& msg) {
|
|
|
+ response->set_success(false);
|
|
|
+ response->set_error(msg);
|
|
|
+ return grpc::Status::OK;
|
|
|
+ };
|
|
|
+ const std::vector<std::string> fields(request->fields().begin(), request->fields().end());
|
|
|
+ if (!request->field().empty()) return refuse("set either field or fields, not both");
|
|
|
+ if (fields.size() < 2) {
|
|
|
+ return refuse("a composite unique constraint needs two or more fields; "
|
|
|
+ "for one field use `field` with unique=true");
|
|
|
+ }
|
|
|
+ if (!request->unique()) {
|
|
|
+ return refuse("a composite index is only a unique constraint - it backs no "
|
|
|
+ "query - so unique must be true");
|
|
|
+ }
|
|
|
+ for (size_t i = 0; i < fields.size(); ++i) {
|
|
|
+ if (fields[i].empty()) return refuse("field names must not be empty");
|
|
|
+ for (size_t j = i + 1; j < fields.size(); ++j) {
|
|
|
+ if (fields[i] == fields[j]) return refuse("field '" + fields[i] + "' is listed twice");
|
|
|
+ }
|
|
|
+ if (!dec.mask.empty() &&
|
|
|
+ std::find(dec.mask.begin(), dec.mask.end(), fields[i]) != dec.mask.end()) {
|
|
|
+ return refuse("cannot constrain a masked field");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // Same gate and reason as a single-field unique constraint (see CreateIndex).
|
|
|
+ if (!service_.mirrorHealthy() || service_.mirrorDriftSinceReady() != 0) {
|
|
|
+ return refuse("cannot declare a unique constraint while the LMDB mirror is "
|
|
|
+ "unhealthy or has drifted since startup: the duplicate check "
|
|
|
+ "only consults LMDB, and MemoryStore may be ahead of it right now");
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ const auto rc = smartbotic::database::resolveCollection(request->collection());
|
|
|
+ auto* lmdb = dynamic_cast<smartbotic::db::storage::LmdbDocumentStore*>(
|
|
|
+ service_.docStore(rc.project));
|
|
|
+ if (lmdb == nullptr) return refuse("unique constraints require the LMDB substrate");
|
|
|
+
|
|
|
+ CollectionCfg cfg = config_manager_.configFor(request->collection());
|
|
|
+ const bool existed = std::find(cfg.compositeUniques.begin(), cfg.compositeUniques.end(),
|
|
|
+ fields) != cfg.compositeUniques.end();
|
|
|
+ // ARM FIRST, then build in one write transaction (see
|
|
|
+ // build_composite_unique): writes from here on maintain the constraint,
|
|
|
+ // and the build sees every row committed before it, so nothing slips
|
|
|
+ // between the two.
|
|
|
+ auto armed = cfg.compositeUniques;
|
|
|
+ if (!existed) armed.push_back(fields);
|
|
|
+ lmdb->set_composite_uniques(rc.collection, armed);
|
|
|
+
|
|
|
+ uint64_t rows = 0;
|
|
|
+ auto dupes = lmdb->build_composite_unique(rc.collection, fields, rows);
|
|
|
+ if (!dupes.empty()) {
|
|
|
+ // Disarm: the constraint is refused, so it must not enforce anything.
|
|
|
+ lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
|
|
|
+ std::string msg = "cannot declare " + request->collection() + "#(" +
|
|
|
+ smartbotic::db::storage::composite_display_name(fields) + ") unique: " +
|
|
|
+ std::to_string(dupes.size()) + " duplicate value combination(s) found, e.g. ";
|
|
|
+ for (size_t i = 0; i < dupes.size(); ++i) {
|
|
|
+ if (i) msg += ", ";
|
|
|
+ msg += dupes[i].sample_id + " (x" + std::to_string(dupes[i].count) + ")";
|
|
|
+ response->add_duplicate_examples(dupes[i].sample_id);
|
|
|
+ }
|
|
|
+ return refuse(msg);
|
|
|
+ }
|
|
|
+ if (!existed) {
|
|
|
+ cfg.compositeUniques.push_back(fields);
|
|
|
+ std::string err;
|
|
|
+ if (!config_manager_.setConfig(request->collection(), cfg, err)) {
|
|
|
+ lmdb->set_composite_uniques(rc.collection, armed); // keep enforcing what was built
|
|
|
+ return refuse("constraint built but could not be recorded: " + err);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ response->set_success(true);
|
|
|
+ response->set_rows_indexed(rows);
|
|
|
+ response->set_already_existed(existed);
|
|
|
+ spdlog::info("v2.12 composite unique created coll={} fields=({}) rows={} (already_existed={})",
|
|
|
+ request->collection(), smartbotic::db::storage::composite_display_name(fields),
|
|
|
+ rows, existed);
|
|
|
+ return grpc::Status::OK;
|
|
|
+ } catch (const std::invalid_argument& e) {
|
|
|
+ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, e.what());
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ return grpc::Status(grpc::StatusCode::INTERNAL, e.what());
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
grpc::Status DatabaseGrpcImpl::CreateIndex(
|
|
|
grpc::ServerContext* context,
|
|
|
const pb::CreateIndexRequest* request,
|
|
|
@@ -3763,6 +3981,9 @@ grpc::Status DatabaseGrpcImpl::CreateIndex(
|
|
|
response->set_error("database is in read-only mode: " + service_.readOnlyReason());
|
|
|
return grpc::Status::OK;
|
|
|
}
|
|
|
+ if (request->fields_size() > 0) {
|
|
|
+ return createCompositeUnique(context, request, response, dec);
|
|
|
+ }
|
|
|
if (request->field().empty()) {
|
|
|
response->set_success(false);
|
|
|
response->set_error("field is required");
|
|
|
@@ -3931,6 +4152,33 @@ grpc::Status DatabaseGrpcImpl::DropIndex(
|
|
|
return grpc::Status::OK;
|
|
|
}
|
|
|
|
|
|
+ // v2.12.0 — a composite unique constraint, named by its exact field list.
|
|
|
+ if (request->fields_size() > 0) {
|
|
|
+ if (!request->field().empty()) {
|
|
|
+ response->set_success(false);
|
|
|
+ response->set_error("set either field or fields, not both");
|
|
|
+ return grpc::Status::OK;
|
|
|
+ }
|
|
|
+ const std::vector<std::string> fields(request->fields().begin(),
|
|
|
+ request->fields().end());
|
|
|
+ CollectionCfg cfg = config_manager_.configFor(request->collection());
|
|
|
+ auto cit = std::find(cfg.compositeUniques.begin(), cfg.compositeUniques.end(), fields);
|
|
|
+ if (cit != cfg.compositeUniques.end()) {
|
|
|
+ cfg.compositeUniques.erase(cit);
|
|
|
+ std::string err;
|
|
|
+ if (!config_manager_.setConfig(request->collection(), cfg, err)) {
|
|
|
+ response->set_success(false);
|
|
|
+ response->set_error(err);
|
|
|
+ return grpc::Status::OK;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // Undeclare first, then drop - same order and reason as below.
|
|
|
+ lmdb->set_composite_uniques(rc.collection, cfg.compositeUniques);
|
|
|
+ lmdb->drop_composite_unique(rc.collection, fields);
|
|
|
+ response->set_success(true);
|
|
|
+ return grpc::Status::OK;
|
|
|
+ }
|
|
|
+
|
|
|
// Undeclare FIRST. While the declaration stands, writes maintain the
|
|
|
// index; dropping the sub-db first would leave a window where writes
|
|
|
// recreate entries in a half-dropped index.
|
|
|
@@ -4011,6 +4259,26 @@ grpc::Status DatabaseGrpcImpl::ListIndexes(
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
+ // v2.12.0 — composite unique constraints. Hidden when ANY of their
|
|
|
+ // fields is masked, for the same reason a masked field's index is.
|
|
|
+ for (const auto& cf : cfg.compositeUniques) {
|
|
|
+ bool masked = false;
|
|
|
+ for (const auto& f : cf) {
|
|
|
+ masked = masked || (!dec.mask.empty() &&
|
|
|
+ std::find(dec.mask.begin(), dec.mask.end(), f) != dec.mask.end());
|
|
|
+ }
|
|
|
+ if (masked) continue;
|
|
|
+ auto* info = response->add_indexes();
|
|
|
+ info->set_field(smartbotic::db::storage::composite_display_name(cf));
|
|
|
+ info->set_unique(true);
|
|
|
+ for (const auto& f : cf) info->add_fields(f);
|
|
|
+ if (lmdb != nullptr) {
|
|
|
+ const uint64_t n = lmdb->composite_unique_entries(rc.collection, cf);
|
|
|
+ // Every recorded tuple is distinct by construction.
|
|
|
+ info->set_distinct_values(n);
|
|
|
+ info->set_entries(n);
|
|
|
+ }
|
|
|
+ }
|
|
|
response->set_success(true);
|
|
|
return grpc::Status::OK;
|
|
|
} catch (const std::invalid_argument& e) {
|