mirror of
https://github.com/FerretDB/documentdb.git
synced 2026-11-25 19:59:54 -05:00
Merged PR 1668237: [Livesite] Handle default_readonly_transaction more gracefully
### Does this PR have any customer impact? Yes ### Type (Feature, Refactoring, Bugfix, DevOps, Testing, Perf, etc) Bugfix ### Does it involve schema level changes? (Table, Column, Index, UDF, etc level changes) No ### Are you introducing any new config? If yes, do you have tests with and without them being set? Yes ### ChangeLog (Refer [Template](../oss/CHANGELOG.md)) ### Description When servers have default_readonly_transaction set, the current behavior is wonky - it will cause failures in underlying queries and pollute the errors, and it will go through a bunch of work only to fail. Additionally, background jobs like TTL will fail ungracefully. Handle this GUC by failing write commands early with a more useful error message. Additionally, in cases like TTL, add an opt-in way to prune rows even in the presence of this GUC if it's opted into. ---- #### AI description (iteration 1) #### PR Classification This pull request is a bug fix that improves error handling for write operations attempted during default read-only transactions. #### PR Summary The changes introduce a unified mechanism to check and enforce read-only transaction restrictions, ensuring graceful errors when write operations are attempted while in a read-only state. Key changes include: - **`include/commands/commands_common.h`**: Added the inline function `ThrowIfServerOrTransactionReadOnly` to validate transaction state and throw appropriate errors. - **Test files**: New regression tests under `/oss/pg_documentdb/src/test/regress/expected/` and `/oss/pg_documentdb/src/test/regress/sql/readonly_transaction_tests.sql` validate the expected error responses under read-only conditions. - **`ttl_index.c`**: Modified TTL job logic to handle read-only transactions, allowing jobs to commit and restart when the corresponding flag is enabled. - **Gateway and error handling**: Updated configuration in `TenantConfigurationBase.cs`, error augmentation in `PostgresMongoResultExtensions.cs`, and error mappings (e.g., adding error code 10107 for `NotWritablePrimary`) to propagate clear error messages. - **Command modules**: Added calls to `ThrowIfServerOrTransactionReadOnly` in several command implementations (e.g., in `insert.c`, `update.c`, `delete.c`, `create_indexes.c`) to enforce read-only restrictions uniformly. <!-- GitOpsUserAgent=GitOps.Apps.Server.pullrequestcopilot -->
This commit is contained in:
1 parent
047561b03e
commit
c5bbda3241
24 files changed
+269
-3
No files matched your search
@@ -1334,6 +1334,7 @@ GenerateAggregationQuery(text *database, pgbson *aggregationSpec, QueryData *que
|
||||
else if (query->commandType == CMD_MERGE)
|
||||
{
|
||||
/* CMD_MERGE is case when pipeline has output stage ($merge or $out) result will be always single batch. */
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
queryData->cursorKind = QueryCursorType_SingleBatch;
|
||||
}
|
||||
else if (queryData->cursorKind == QueryCursorType_Unspecified)
|
||||
|
||||
@@ -126,6 +126,7 @@ command_create_collection_view(PG_FUNCTION_ARGS)
|
||||
GetMongoCollectionOrViewByNameDatum(
|
||||
databaseDatum, createDatum, NoLock);
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
if (collection != NULL)
|
||||
{
|
||||
/* Collection exists validate options */
|
||||
|
||||
@@ -441,6 +441,7 @@ command_create_indexes_non_concurrently(PG_FUNCTION_ARGS)
|
||||
skip_check_collection_create = PG_GETARG_BOOL(2);
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
pgbson *arg = PgbsonDeduplicateFields(PG_GETARG_PGBSON(1));
|
||||
CreateIndexesArg createIndexesArg = ParseCreateIndexesArg(dbNameDatum,
|
||||
arg);
|
||||
|
||||
@@ -580,6 +580,8 @@ command_create_indexes_background(PG_FUNCTION_ARGS)
|
||||
text *databaseDatum = PG_GETARG_TEXT_P(0);
|
||||
pgbson *indexSpec = PG_GETARG_PGBSON(1);
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
|
||||
StringInfo submitIndexBuildRequestQuery = makeStringInfo();
|
||||
appendStringInfo(submitIndexBuildRequestQuery,
|
||||
"SELECT %s.create_indexes_background_internal(%s,%s)",
|
||||
|
||||
@@ -184,6 +184,8 @@ command_delete(PG_FUNCTION_ARGS)
|
||||
ereport(ERROR, (errmsg("return type must be a row type")));
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
|
||||
bson_iter_t deleteCommandIter;
|
||||
PgbsonInitIterator(deleteSpec, &deleteCommandIter);
|
||||
|
||||
@@ -995,6 +997,7 @@ command_delete_worker(PG_FUNCTION_ARGS)
|
||||
pgbsonsequence *specDocuments = PG_GETARG_MAYBE_NULL_PGBSON_SEQUENCE(4);
|
||||
text *transactionId = PG_ARGISNULL(5) ? NULL : PG_GETARG_TEXT_PP(5);
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
AllowNestedDistributionInCurrentTransaction();
|
||||
pgbsonelement commandElement;
|
||||
PgbsonToSinglePgbsonElement(deleteInternalSpec, &commandElement);
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
#include "utils/index_utils.h"
|
||||
#include "utils/guc_utils.h"
|
||||
#include "utils/version_utils.h"
|
||||
#include "commands/commands_common.h"
|
||||
|
||||
#include "api_hooks.h"
|
||||
|
||||
@@ -49,6 +50,7 @@ command_drop_collection(PG_FUNCTION_ARGS)
|
||||
PG_RETURN_BOOL(false);
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
Datum databaseNameDatum = PG_GETARG_DATUM(0);
|
||||
Datum collectionNameDatum = PG_GETARG_DATUM(1);
|
||||
|
||||
|
||||
@@ -160,6 +160,7 @@ command_find_and_modify(PG_FUNCTION_ARGS)
|
||||
ereport(ERROR, (errmsg("return type must be a row type")));
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
FindAndModifySpec spec = ParseFindAndModifyMessage(message);
|
||||
|
||||
Datum collectionNameDatum = CStringGetTextDatum(spec.collectionName);
|
||||
|
||||
@@ -907,6 +907,8 @@ CommandInsertCore(PG_FUNCTION_ARGS, bool isTransactional, MemoryContext allocCon
|
||||
ereport(ERROR, (errmsg("insert document cannot be NULL")));
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
|
||||
Datum databaseNameDatum = PG_GETARG_DATUM(0);
|
||||
pgbson *insertSpec = PG_GETARG_PGBSON(1);
|
||||
|
||||
@@ -1098,6 +1100,7 @@ command_insert_worker(PG_FUNCTION_ARGS)
|
||||
"Explicit shardOid must be set - this is a server bug")));
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
AllowNestedDistributionInCurrentTransaction();
|
||||
pgbsonelement element = { 0 };
|
||||
PgbsonToSinglePgbsonElement(insertInternalSpec, &element);
|
||||
|
||||
@@ -499,6 +499,7 @@ PerformUpdateCore(Datum databaseNameDatum, pgbson *updateSpec,
|
||||
TupleDesc resultTupDesc, bool isTransactional,
|
||||
MemoryContext allocContext)
|
||||
{
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
bson_iter_t updateCommandIter;
|
||||
PgbsonInitIterator(updateSpec, &updateCommandIter);
|
||||
|
||||
@@ -2119,6 +2120,8 @@ command_update_worker(PG_FUNCTION_ARGS)
|
||||
"update spec or update documents argument must be not null.")));
|
||||
}
|
||||
|
||||
ThrowIfServerOrTransactionReadOnly();
|
||||
|
||||
WorkerUpdateParam params;
|
||||
memset(¶ms, 0, sizeof(WorkerUpdateParam));
|
||||
DeserializeUpdateWorkerSpec(updateInternalSpec, ¶ms);
|
||||
|
||||
@@ -155,6 +155,9 @@ bool AlterCreationTimeInCompleteUpgrade = ALTER_CREATION_TIME_IN_COMPLETE_UPGRAD
|
||||
#define DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS true
|
||||
bool EnableUsernamePasswordConstraints = DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS;
|
||||
|
||||
#define DEFAULT_SKIP_ENFORCE_TRANSACTION_READ_ONLY false
|
||||
bool SkipEnforceTransactionReadOnly = DEFAULT_SKIP_ENFORCE_TRANSACTION_READ_ONLY;
|
||||
|
||||
/* FEATURE FLAGS END */
|
||||
|
||||
void
|
||||
@@ -443,4 +446,12 @@ InitializeFeatureFlagConfigurations(const char *prefix, const char *newGucPrefix
|
||||
NULL, &EnableUsernamePasswordConstraints,
|
||||
DEFAULT_ENABLE_USERNAME_PASSWORD_CONSTRAINTS,
|
||||
PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
|
||||
DefineCustomBoolVariable(
|
||||
psprintf("%s.skipEnforceTransactionReadOnly", newGucPrefix),
|
||||
gettext_noop(
|
||||
"Whether or not to skip enforcing transaction read only."),
|
||||
NULL, &SkipEnforceTransactionReadOnly,
|
||||
DEFAULT_SKIP_ENFORCE_TRANSACTION_READ_ONLY,
|
||||
PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
}
|
||||
@@ -125,6 +125,15 @@ bool EnableUserCrud = DEFAULT_ENABLE_USER_CRUD;
|
||||
#define DEFAULT_VECTOR_ITERATIVE_SCAN_MODE VectorIterativeScan_RELAXED_ORDER
|
||||
int VectorPreFilterIterativeScanMode = DEFAULT_VECTOR_ITERATIVE_SCAN_MODE;
|
||||
|
||||
/* Note that this is explicitly left disabled
|
||||
* This is primarily because the operator that sets default_transaction_readonly
|
||||
* would want to avoid new writes (perhaps due to high disk usage) and a background
|
||||
* job that can go and delete documents can produce WAL files and can exacerbate
|
||||
* the issue by putting disk load. Make this explicitly opt-in.
|
||||
*/
|
||||
#define DEFAULT_ENABLE_TTL_JOBS_ON_READ_ONLY false
|
||||
bool EnableTtlJobsOnReadOnly = DEFAULT_ENABLE_TTL_JOBS_ON_READ_ONLY;
|
||||
|
||||
void
|
||||
InitializeSystemConfigurations(const char *prefix, const char *newGucPrefix)
|
||||
{
|
||||
@@ -341,6 +350,14 @@ InitializeSystemConfigurations(const char *prefix, const char *newGucPrefix)
|
||||
NULL, &EnableUserCrud, DEFAULT_ENABLE_USER_CRUD,
|
||||
PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
|
||||
DefineCustomBoolVariable(
|
||||
psprintf("%s.enableTTLJobsOnReadOnly", newGucPrefix),
|
||||
gettext_noop(
|
||||
"Enables TTL jobs on read-only nodes. This will override"
|
||||
" the default_transaction_readonly on the TTL job only."),
|
||||
NULL, &EnableTtlJobsOnReadOnly, DEFAULT_ENABLE_TTL_JOBS_ON_READ_ONLY,
|
||||
PGC_USERSET, 0, NULL, NULL, NULL);
|
||||
|
||||
DefineCustomEnumVariable(
|
||||
psprintf("%s.vectorPreFilterIterativeScanMode", newGucPrefix),
|
||||
gettext_noop(
|
||||
|
||||
@@ -13,7 +13,7 @@ test: bson_aggregation_pipeline_tests_facet_group_explain_pg!MAJOR_VERSION! bson
|
||||
# Cannot run this concurrently due to currentOp tests
|
||||
test: bson_aggregation_pipeline_tests_coll_agnostic
|
||||
test: bson_aggregation_pipeline_tests_merge_objects_group bson_aggregation_cursor_tests
|
||||
test: bson_aggregation_pipeline_tests_stddevpopsamp_group
|
||||
test: bson_aggregation_pipeline_tests_stddevpopsamp_group readonly_transaction_tests
|
||||
test: commands_create_indexes_background commands_create_view_tests
|
||||
test: collection_management bson_aggregation_cursor_tests_txn
|
||||
test: bson_aggregation_object_operators_tests bson_aggregation_pipeline_diagnostic_command_tests bson_aggregation_functions_nested_tests
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
SET search_path TO documentdb_api,documentdb_core,documentdb_api_catalog;
|
||||
SET documentdb.next_collection_id TO 2100;
|
||||
SET documentdb.next_collection_index_id TO 2100;
|
||||
SELECT documentdb_api.create_collection_view('db', '{ "create": "test" }');
|
||||
NOTICE: creating collection
|
||||
create_collection_view
|
||||
----------------------------------------
|
||||
{ "ok" : { "$numberDouble" : "1.0" } }
|
||||
(1 row)
|
||||
|
||||
SELECT documentdb_api.insert_one('db', 'test', '{ "_id": 1, "a": 1, "ttl": 0 }');
|
||||
insert_one
|
||||
----------------------------------------------------------------------
|
||||
{ "n" : { "$numberInt" : "1" }, "ok" : { "$numberDouble" : "1.0" } }
|
||||
(1 row)
|
||||
|
||||
SELECT documentdb_api_internal.create_indexes_non_concurrently('db', '{ "createIndexes": "test", "indexes": [ { "key": { "ttl": 1 }, "name": "ttlIndex", "expireAfterSeconds": 300 } ] }', TRUE);
|
||||
create_indexes_non_concurrently
|
||||
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
{ "raw" : { "defaultShard" : { "numIndexesBefore" : { "$numberInt" : "1" }, "numIndexesAfter" : { "$numberInt" : "2" }, "createdCollectionAutomatically" : false, "ok" : { "$numberInt" : "1" } } }, "ok" : { "$numberInt" : "1" } }
|
||||
(1 row)
|
||||
|
||||
-- set the default transaction mode.
|
||||
set default_transaction_read_only = on;
|
||||
-- should fail gracefully.
|
||||
SELECT documentdb_api.create_collection_view('db', '{ "create": "collection" }');
|
||||
ERROR: cannot execute write operations when the server is in a read-only state.
|
||||
DETAIL: the default transaction is read-only
|
||||
SELECT documentdb_api.insert('db', '{ "insert": "test", "documents": [ { "a": 1 }] }');
|
||||
ERROR: cannot execute write operations when the server is in a read-only state.
|
||||
DETAIL: the default transaction is read-only
|
||||
SELECT documentdb_api.update('db', '{ "update": "test", "updates": [ { "q": { "a": 1 }, "u": { "$set": { "b": 1 }} }] }');
|
||||
ERROR: cannot execute write operations when the server is in a read-only state.
|
||||
DETAIL: the default transaction is read-only
|
||||
SELECT documentdb_api.delete('db', '{ "delete": "test", "deletes": [ { "q": { "a": 1 } }] }');
|
||||
ERROR: cannot execute write operations when the server is in a read-only state.
|
||||
DETAIL: the default transaction is read-only
|
||||
SELECT document FROM documentdb_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "test", "pipeline": [ { "$merge": { "into": "test" } } ] }');
|
||||
ERROR: cannot execute write operations when the server is in a read-only state.
|
||||
DETAIL: the default transaction is read-only
|
||||
SELECT documentdb_api.drop_collection('db', 'collection');
|
||||
ERROR: cannot execute write operations when the server is in a read-only state.
|
||||
DETAIL: the default transaction is read-only
|
||||
-- same command works when transaction explicitly read-write.
|
||||
BEGIN;
|
||||
SET TRANSACTION READ WRITE;
|
||||
SELECT documentdb_api.create_collection_view('db', '{ "create": "collection" }');
|
||||
NOTICE: creating collection
|
||||
create_collection_view
|
||||
----------------------------------------
|
||||
{ "ok" : { "$numberDouble" : "1.0" } }
|
||||
(1 row)
|
||||
|
||||
SELECT documentdb_api.insert('db', '{ "insert": "collection", "documents": [ { "a": 1 }] }');
|
||||
insert
|
||||
----------------------------------------------------------------------------------------
|
||||
("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t)
|
||||
(1 row)
|
||||
|
||||
SELECT documentdb_api.update('db', '{ "update": "collection", "updates": [ { "q": { "a": 1 }, "u": { "$set": { "b": 1 }} }] }');
|
||||
update
|
||||
--------------------------------------------------------------------------------------------------------------------------------------
|
||||
("{ ""ok"" : { ""$numberDouble"" : ""1.0"" }, ""nModified"" : { ""$numberLong"" : ""1"" }, ""n"" : { ""$numberLong"" : ""1"" } }",t)
|
||||
(1 row)
|
||||
|
||||
SELECT documentdb_api.delete('db', '{ "delete": "collection", "deletes": [ { "q": { "a": 1 }, "limit": 1 }] }');
|
||||
delete
|
||||
----------------------------------------------------------------------------------------
|
||||
("{ ""n"" : { ""$numberInt"" : ""1"" }, ""ok"" : { ""$numberDouble"" : ""1.0"" } }",t)
|
||||
(1 row)
|
||||
|
||||
SELECT documentdb_api.drop_collection('db', 'collection');
|
||||
drop_collection
|
||||
-----------------
|
||||
t
|
||||
(1 row)
|
||||
|
||||
ROLLBACK;
|
||||
-- fails gracefully when transaction is read-only.
|
||||
CALL documentdb_api_internal.delete_expired_rows();
|
||||
INFO: TTL job skipping because transaction is read-only.
|
||||
set documentdb.enableTTLJobsOnReadOnly to on;
|
||||
CALL documentdb_api_internal.delete_expired_rows();
|
||||
@@ -0,0 +1,36 @@
|
||||
SET search_path TO documentdb_api,documentdb_core,documentdb_api_catalog;
|
||||
SET documentdb.next_collection_id TO 2100;
|
||||
SET documentdb.next_collection_index_id TO 2100;
|
||||
|
||||
SELECT documentdb_api.create_collection_view('db', '{ "create": "test" }');
|
||||
SELECT documentdb_api.insert_one('db', 'test', '{ "_id": 1, "a": 1, "ttl": 0 }');
|
||||
|
||||
SELECT documentdb_api_internal.create_indexes_non_concurrently('db', '{ "createIndexes": "test", "indexes": [ { "key": { "ttl": 1 }, "name": "ttlIndex", "expireAfterSeconds": 300 } ] }', TRUE);
|
||||
|
||||
-- set the default transaction mode.
|
||||
set default_transaction_read_only = on;
|
||||
|
||||
-- should fail gracefully.
|
||||
SELECT documentdb_api.create_collection_view('db', '{ "create": "collection" }');
|
||||
SELECT documentdb_api.insert('db', '{ "insert": "test", "documents": [ { "a": 1 }] }');
|
||||
SELECT documentdb_api.update('db', '{ "update": "test", "updates": [ { "q": { "a": 1 }, "u": { "$set": { "b": 1 }} }] }');
|
||||
SELECT documentdb_api.delete('db', '{ "delete": "test", "deletes": [ { "q": { "a": 1 } }] }');
|
||||
|
||||
SELECT document FROM documentdb_api_catalog.bson_aggregation_pipeline('db', '{ "aggregate": "test", "pipeline": [ { "$merge": { "into": "test" } } ] }');
|
||||
SELECT documentdb_api.drop_collection('db', 'collection');
|
||||
|
||||
-- same command works when transaction explicitly read-write.
|
||||
BEGIN;
|
||||
SET TRANSACTION READ WRITE;
|
||||
SELECT documentdb_api.create_collection_view('db', '{ "create": "collection" }');
|
||||
SELECT documentdb_api.insert('db', '{ "insert": "collection", "documents": [ { "a": 1 }] }');
|
||||
SELECT documentdb_api.update('db', '{ "update": "collection", "updates": [ { "q": { "a": 1 }, "u": { "$set": { "b": 1 }} }] }');
|
||||
SELECT documentdb_api.delete('db', '{ "delete": "collection", "deletes": [ { "q": { "a": 1 }, "limit": 1 }] }');
|
||||
SELECT documentdb_api.drop_collection('db', 'collection');
|
||||
ROLLBACK;
|
||||
|
||||
-- fails gracefully when transaction is read-only.
|
||||
CALL documentdb_api_internal.delete_expired_rows();
|
||||
|
||||
set documentdb.enableTTLJobsOnReadOnly to on;
|
||||
CALL documentdb_api_internal.delete_expired_rows();
|
||||
@@ -32,6 +32,7 @@ extern int MaxTTLDeleteBatchSize;
|
||||
extern int TTLPurgerLockTimeout;
|
||||
extern char *ApiGucPrefix;
|
||||
extern int SingleTTLTaskTimeBudget;
|
||||
extern bool EnableTtlJobsOnReadOnly;
|
||||
|
||||
bool UseV2TTLIndexPurger = true;
|
||||
|
||||
@@ -370,6 +371,35 @@ delete_expired_rows(PG_FUNCTION_ARGS)
|
||||
continue;
|
||||
}
|
||||
|
||||
/*
|
||||
* Before we begin the actual deletions, check if we need
|
||||
* to handle if the transaction is read-only.
|
||||
*/
|
||||
if (XactReadOnly)
|
||||
{
|
||||
if (EnableTtlJobsOnReadOnly)
|
||||
{
|
||||
/* To enable read-write we need to be the first query
|
||||
* in the transaction. Process_utility will have already
|
||||
* set a snapshot on this transaction so we can't reset
|
||||
* the transaction read-only flag.
|
||||
* Consequently, commit this transaction that's read-only
|
||||
* and start a new one so we can mark the read-only flag
|
||||
* as false.
|
||||
*/
|
||||
PopAllActiveSnapshots();
|
||||
CommitTransactionCommand();
|
||||
StartTransactionCommand();
|
||||
SetGUCLocally("transaction_read_only", "false");
|
||||
}
|
||||
else
|
||||
{
|
||||
ereport(INFO, errmsg(
|
||||
"TTL job skipping because transaction is read-only."));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
volatile bool shouldStop = false;
|
||||
|
||||
/* Delete records on all tables for this collection */
|
||||
@@ -426,6 +456,12 @@ delete_expired_rows(PG_FUNCTION_ARGS)
|
||||
{
|
||||
goto end;
|
||||
}
|
||||
|
||||
/* Before starting the next loop, set the transaction characteristics */
|
||||
if (XactReadOnly && EnableTtlJobsOnReadOnly)
|
||||
{
|
||||
SetGUCLocally("transaction_read_only", "false");
|
||||
}
|
||||
}
|
||||
|
||||
if (IsTaskTimeBudgetExceeded(startTime, NULL))
|
||||
|
||||
Reference in new issue
Block a user