#include "dbms_pipe_queue.hpp" extern "C" { #include "miscadmin.h" #include "storage/dsm_registry.h" #include "utils/elog.h" #include "utils/timestamp.h" #include "utils/wait_classes.h" } static constexpr int32 DBMS_PIPE_DEFAULT_MAX_PIPE_SIZE = 65536; struct DbmsPipeMessage { dsa_pointer next; Size data_bytes; Size capacity_bytes; TimestampTz expires_at; char data[FLEXIBLE_ARRAY_MEMBER]; }; static dsa_area *dbms_pipe_message_area = nullptr; static dsa_area * dbms_pipe_get_message_area() { if (dbms_pipe_message_area == nullptr) { bool found; dbms_pipe_message_area = GetNamedDSA("dbms_pipe_messages", &found); } return dbms_pipe_message_area; } static void dbms_pipe_raise_privilege_error() { ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("ORA-23322: Privilege error accessing pipe"))); } static bool dbms_pipe_entry_access_allowed(const DbmsPipeRegistryEntry *entry) { return !entry->is_private || entry->owner_id == GetUserId(); } static Size dbms_pipe_message_capacity_bytes(const DbmsPipeSerializedMessage *message) { /* Даже пустое сообщение расходует ёмкость ограниченной очереди FIFO. */ return Max(message->accounted_bytes, static_cast(1)); } static Size dbms_pipe_max_pipe_size(const DbmsPipeRegistryEntry *entry) { return entry->max_pipe_size < 0 ? 0 : static_cast(entry->max_pipe_size); } static bool dbms_pipe_message_fits_capacity(const DbmsPipeRegistryEntry *entry, Size message_bytes) { return message_bytes <= dbms_pipe_max_pipe_size(entry); } static bool dbms_pipe_entry_has_capacity(const DbmsPipeRegistryEntry *entry, Size message_bytes) { const Size max_pipe_size = dbms_pipe_max_pipe_size(entry); return message_bytes <= max_pipe_size && entry->queued_bytes <= max_pipe_size - message_bytes; } static TimestampTz dbms_pipe_timestamp_after_seconds(int32 timeout_seconds) { const int64 timeout_ms = static_cast(timeout_seconds) * INT64CONST(1000); return TimestampTzPlusMilliseconds(GetCurrentTimestamp(), timeout_ms); } static long dbms_pipe_remaining_wait_ms(TimestampTz deadline) { return TimestampDifferenceMilliseconds(GetCurrentTimestamp(), deadline); } static dsa_pointer dbms_pipe_allocate_message(const DbmsPipeSerializedMessage *message, Size capacity_bytes, TimestampTz expires_at) { dsa_area *const area = dbms_pipe_get_message_area(); const Size allocation_size = offsetof(DbmsPipeMessage, data) + message->data_bytes; const dsa_pointer pointer = dsa_allocate(area, allocation_size); /* * До возврата узел принадлежит только этому вызову. При ошибке * обращения к сегменту не оставляем бесхозное выделение в DSA. */ PG_TRY(); { auto *const node = static_cast(dsa_get_address(area, pointer)); node->next = InvalidDsaPointer; node->data_bytes = message->data_bytes; node->capacity_bytes = capacity_bytes; node->expires_at = expires_at; if (message->data_bytes > 0) memcpy(node->data, message->data, message->data_bytes); } PG_CATCH(); { dsa_free(area, pointer); PG_RE_THROW(); } PG_END_TRY(); return pointer; } static void dbms_pipe_enqueue_locked(DbmsPipeRegistryEntry *entry, const DbmsPipeSerializedMessage *message, Size capacity_bytes, TimestampTz expires_at) { dsa_area *const area = dbms_pipe_get_message_area(); /* Получение адреса хвоста может вызвать ERROR: делаем это до allocation. */ DbmsPipeMessage *const tail = DsaPointerIsValid(entry->queue_tail) ? static_cast( dsa_get_address(area, entry->queue_tail)) : nullptr; const dsa_pointer pointer = dbms_pipe_allocate_message(message, capacity_bytes, expires_at); if (tail != nullptr) tail->next = pointer; else entry->queue_head = pointer; entry->queue_tail = pointer; entry->message_count++; entry->queued_bytes += capacity_bytes; } static void dbms_pipe_replace_singleton_locked(DbmsPipeRegistryEntry *entry, const DbmsPipeSerializedMessage *message, Size capacity_bytes, TimestampTz expires_at) { dsa_area *const area = dbms_pipe_get_message_area(); const dsa_pointer previous = entry->queue_head; Assert(entry->message_count <= 1); /* * Заранее подключаем старый сегмент: после allocation не должно * оставаться операций, способных выделять память до публикации. */ if (DsaPointerIsValid(previous)) (void) dsa_get_address(area, previous); const dsa_pointer new_pointer = dbms_pipe_allocate_message(message, capacity_bytes, expires_at); PG_TRY(); { if (DsaPointerIsValid(previous)) dsa_free(area, previous); } PG_CATCH(); { dsa_free(area, new_pointer); PG_RE_THROW(); } PG_END_TRY(); entry->queue_head = new_pointer; entry->queue_tail = new_pointer; entry->message_count = 1; entry->queued_bytes = capacity_bytes; } /* * Снимаем головной узел только после успешной десериализации. * До этого момента FIFO сохраняет сообщение. */ static void dbms_pipe_drop_head_locked(DbmsPipeRegistryEntry *entry) { dsa_area *const area = dbms_pipe_get_message_area(); const dsa_pointer pointer = entry->queue_head; auto *const node = static_cast(dsa_get_address(area, pointer)); entry->queue_head = node->next; if (!DsaPointerIsValid(entry->queue_head)) entry->queue_tail = InvalidDsaPointer; Assert(entry->message_count > 0); Assert(entry->queued_bytes >= node->capacity_bytes); entry->message_count--; entry->queued_bytes -= node->capacity_bytes; dsa_free(area, pointer); } static bool dbms_pipe_singleton_expired_locked(const DbmsPipeRegistryEntry *entry) { if (!DsaPointerIsValid(entry->queue_head)) return false; dsa_area *const area = dbms_pipe_get_message_area(); auto *const node = static_cast( dsa_get_address(area, entry->queue_head)); return node->expires_at != 0 && GetCurrentTimestamp() >= node->expires_at; } void dbms_pipe_queue_prepare() { (void) dbms_pipe_get_message_area(); dbms_pipe_registry_prepare_wait_conditions(); } void dbms_pipe_queue_convert_singleton_to_ordinary(DbmsPipeRegistryEntry *entry) { if (DsaPointerIsValid(entry->queue_head)) { dsa_area *const area = dbms_pipe_get_message_area(); auto *const node = static_cast( dsa_get_address(area, entry->queue_head)); /* Для обычных сообщений срок действия не ограничен. */ node->expires_at = 0; } entry->singleton = false; entry->shelf_life = 0; } void dbms_pipe_queue_purge(const DbmsPipeNameKey *key) { dbms_pipe_queue_prepare(); ConditionVariable *const wait_condition = dbms_pipe_registry_wait_condition(key); bool found; DbmsPipeRegistryEntry *const entry = dbms_pipe_registry_find_or_insert(key, &found); if (!found) dbms_pipe_registry_initialize_entry(entry, DBMS_PIPE_DEFAULT_MAX_PIPE_SIZE, false, false, 0); if (!dbms_pipe_entry_access_allowed(entry)) { dbms_pipe_registry_release(entry); dbms_pipe_raise_privilege_error(); } dbms_pipe_queue_discard_messages(entry); dbms_pipe_registry_release(entry); /* * PURGE освобождает место в очереди. Уведомление может разбудить * ожидающего получателя, но он повторно проверит очередь и продолжит ждать. */ ConditionVariableBroadcast(wait_condition); } void dbms_pipe_queue_discard_messages(DbmsPipeRegistryEntry *entry) { dsa_area *const area = dbms_pipe_get_message_area(); dsa_pointer pointer = entry->queue_head; while (DsaPointerIsValid(pointer)) { auto *const node = static_cast(dsa_get_address(area, pointer)); const dsa_pointer next = node->next; dsa_free(area, pointer); pointer = next; } entry->queue_head = InvalidDsaPointer; entry->queue_tail = InvalidDsaPointer; entry->message_count = 0; entry->queued_bytes = 0; } int32 dbms_pipe_queue_send(const DbmsPipeNameKey *key, const DbmsPipeSerializedMessage *message, int32 timeout_seconds, int32 max_pipe_size, bool singleton_requested, int32 shelf_life) { dbms_pipe_queue_prepare(); ConditionVariable *const wait_condition = dbms_pipe_registry_wait_condition(key); const Size capacity_bytes = dbms_pipe_message_capacity_bytes(message); const TimestampTz deadline = timeout_seconds == 0 ? 0 : dbms_pipe_timestamp_after_seconds(timeout_seconds); /* * Поколение связывает ожидание с конкретным экземпляром канала. REMOVE_PIPE * может удалить запись без пробуждения; новый канал с тем же именем * получает другое поколение и не завершает прежнее ожидание. */ uint64 generation = 0; bool waiting = false; while (true) { bool found = true; DbmsPipeRegistryEntry *entry = generation == 0 ? dbms_pipe_registry_find_or_insert(key, &found) : dbms_pipe_registry_find(key, true); if (generation == 0 && !found) { dbms_pipe_registry_initialize_entry(entry, max_pipe_size, false, singleton_requested, 0); generation = entry->generation; } if (entry != nullptr) { if (generation == 0) generation = entry->generation; else if (entry->generation != generation) { dbms_pipe_registry_release(entry); entry = nullptr; } } if (entry != nullptr) { if (!dbms_pipe_entry_access_allowed(entry)) { dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); dbms_pipe_raise_privilege_error(); } if (!entry->singleton && singleton_requested) { dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); return 6; } if (!entry->singleton && shelf_life > 0) { dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); return 7; } if (max_pipe_size > entry->max_pipe_size) entry->max_pipe_size = max_pipe_size; if (entry->singleton) { if (dbms_pipe_message_fits_capacity(entry, capacity_bytes)) { const int32 effective_shelf_life = shelf_life > 0 ? shelf_life : entry->shelf_life; const TimestampTz expires_at = effective_shelf_life > 0 ? dbms_pipe_timestamp_after_seconds(effective_shelf_life) : 0; dbms_pipe_replace_singleton_locked(entry, message, capacity_bytes, expires_at); dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); ConditionVariableBroadcast(wait_condition); return 0; } } else if (dbms_pipe_entry_has_capacity(entry, capacity_bytes)) { dbms_pipe_enqueue_locked(entry, message, capacity_bytes, 0); dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); ConditionVariableBroadcast(wait_condition); return 0; } if (timeout_seconds == 0) { dbms_pipe_registry_release(entry); return 1; } if (!waiting) { /* * Регистрируем ожидание до снятия блокировки, * чтобы не потерять уведомление. */ ConditionVariablePrepareToSleep(wait_condition); waiting = true; } dbms_pipe_registry_release(entry); } else if (!waiting) { ConditionVariablePrepareToSleep(wait_condition); waiting = true; } const long remaining_ms = dbms_pipe_remaining_wait_ms(deadline); if (remaining_ms == 0) { ConditionVariableCancelSleep(); return 1; } if (ConditionVariableTimedSleep(wait_condition, remaining_ms, PG_WAIT_EXTENSION) && dbms_pipe_remaining_wait_ms(deadline) == 0) { ConditionVariableCancelSleep(); return 1; } } } int32 dbms_pipe_queue_receive(const DbmsPipeNameKey *key, int32 timeout_seconds, DbmsPipeReceiveMode mode) { dbms_pipe_queue_prepare(); ConditionVariable *const wait_condition = dbms_pipe_registry_wait_condition(key); const TimestampTz deadline = timeout_seconds == 0 ? 0 : dbms_pipe_timestamp_after_seconds(timeout_seconds); /* * Поколение связывает ожидание с экземпляром канала. После пробуждения * запись dshash ищется заново; указатель на неё при ожидании не хранится. */ uint64 generation = 0; bool waiting = false; while (true) { bool found = true; DbmsPipeRegistryEntry *entry; if (generation != 0) entry = dbms_pipe_registry_find(key, true); else if (mode == DbmsPipeReceiveMode::NORMAL) entry = dbms_pipe_registry_find_or_insert(key, &found); else entry = dbms_pipe_registry_find(key, true); if (mode == DbmsPipeReceiveMode::NORMAL && generation == 0 && !found) { dbms_pipe_registry_initialize_entry(entry, DBMS_PIPE_DEFAULT_MAX_PIPE_SIZE, false, false, 0); generation = entry->generation; } if (entry != nullptr) { if (generation == 0) generation = entry->generation; else if (entry->generation != generation) { dbms_pipe_registry_release(entry); entry = nullptr; } } if (entry != nullptr) { if (!dbms_pipe_entry_access_allowed(entry)) { dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); dbms_pipe_raise_privilege_error(); } if (mode == DbmsPipeReceiveMode::SINGLETON_CACHE && !entry->singleton) { dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); return 8; } if (entry->singleton && dbms_pipe_singleton_expired_locked(entry)) dbms_pipe_queue_discard_messages(entry); if (DsaPointerIsValid(entry->queue_head)) { /* * Ошибка десериализации оставляет FIFO неизменной. * При ERROR PostgreSQL освобождает LWLock и снимает * регистрацию ConditionVariable во время abort/subabort; * явный release из PG_CATCH недопустим, поскольку * errfinish() сбрасывает InterruptHoldoffCount. */ dsa_area *const area = dbms_pipe_get_message_area(); auto *const node = static_cast( dsa_get_address(area, entry->queue_head)); dbms_pipe_buffer_receive_succeeded(node->data, node->data_bytes); if (!entry->singleton) dbms_pipe_drop_head_locked(entry); const bool freed_capacity = !entry->singleton; dbms_pipe_registry_release(entry); if (waiting) ConditionVariableCancelSleep(); if (freed_capacity) ConditionVariableBroadcast(wait_condition); return 0; } if (timeout_seconds == 0) { dbms_pipe_registry_release(entry); return 1; } if (!waiting) { /* * Регистрируем ожидание до снятия блокировки, * чтобы не потерять уведомление. */ ConditionVariablePrepareToSleep(wait_condition); waiting = true; } dbms_pipe_registry_release(entry); } else if (!waiting) { ConditionVariablePrepareToSleep(wait_condition); waiting = true; } const long remaining_ms = dbms_pipe_remaining_wait_ms(deadline); if (remaining_ms == 0) { ConditionVariableCancelSleep(); return 1; } if (ConditionVariableTimedSleep(wait_condition, remaining_ms, PG_WAIT_EXTENSION) && dbms_pipe_remaining_wait_ms(deadline) == 0) { ConditionVariableCancelSleep(); return 1; } } }