LCOV - code coverage report
Current view: top level - src/backend/replication/logical - logical.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 92.8 % 777 721
Test Date: 2026-08-11 01:15:52 Functions: 97.6 % 41 40
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 63.6 % 346 220

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  * logical.c
       3                 :             :  *     PostgreSQL logical decoding coordination
       4                 :             :  *
       5                 :             :  * Copyright (c) 2012-2026, PostgreSQL Global Development Group
       6                 :             :  *
       7                 :             :  * IDENTIFICATION
       8                 :             :  *    src/backend/replication/logical/logical.c
       9                 :             :  *
      10                 :             :  * NOTES
      11                 :             :  *    This file coordinates interaction between the various modules that
      12                 :             :  *    together provide logical decoding, primarily by providing so
      13                 :             :  *    called LogicalDecodingContexts. The goal is to encapsulate most of the
      14                 :             :  *    internal complexity for consumers of logical decoding, so they can
      15                 :             :  *    create and consume a changestream with a low amount of code. Builtin
      16                 :             :  *    consumers are the walsender and SQL SRF interface, but it's possible to
      17                 :             :  *    add further ones without changing core code, e.g. to consume changes in
      18                 :             :  *    a bgworker.
      19                 :             :  *
      20                 :             :  *    The idea is that a consumer provides three callbacks, one to read WAL,
      21                 :             :  *    one to prepare a data write, and a final one for actually writing since
      22                 :             :  *    their implementation depends on the type of consumer.  Check
      23                 :             :  *    logicalfuncs.c for an example implementation of a fairly simple consumer
      24                 :             :  *    and an implementation of a WAL reading callback that's suitable for
      25                 :             :  *    simple consumers.
      26                 :             :  *-------------------------------------------------------------------------
      27                 :             :  */
      28                 :             : 
      29                 :             : #include "postgres.h"
      30                 :             : 
      31                 :             : #include "access/xact.h"
      32                 :             : #include "access/xlog_internal.h"
      33                 :             : #include "access/xlogutils.h"
      34                 :             : #include "commands/repack.h"
      35                 :             : #include "fmgr.h"
      36                 :             : #include "miscadmin.h"
      37                 :             : #include "pgstat.h"
      38                 :             : #include "replication/decode.h"
      39                 :             : #include "replication/logical.h"
      40                 :             : #include "replication/reorderbuffer.h"
      41                 :             : #include "replication/slotsync.h"
      42                 :             : #include "replication/snapbuild.h"
      43                 :             : #include "storage/proc.h"
      44                 :             : #include "storage/procarray.h"
      45                 :             : #include "utils/builtins.h"
      46                 :             : #include "utils/guc.h"
      47                 :             : #include "utils/injection_point.h"
      48                 :             : #include "utils/inval.h"
      49                 :             : #include "utils/memutils.h"
      50                 :             : #include "utils/varlena.h"
      51                 :             : 
      52                 :             : /* data for errcontext callback */
      53                 :             : typedef struct LogicalErrorCallbackState
      54                 :             : {
      55                 :             :     LogicalDecodingContext *ctx;
      56                 :             :     const char *callback_name;
      57                 :             :     XLogRecPtr  report_location;
      58                 :             : } LogicalErrorCallbackState;
      59                 :             : 
      60                 :             : /* GUC variables */
      61                 :             : char       *output_plugin_libraries_string;
      62                 :             : 
      63                 :             : /* wrappers around output plugin callbacks */
      64                 :             : static void output_plugin_error_callback(void *arg);
      65                 :             : static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
      66                 :             :                                bool is_init);
      67                 :             : static void shutdown_cb_wrapper(LogicalDecodingContext *ctx);
      68                 :             : static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn);
      69                 :             : static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      70                 :             :                               XLogRecPtr commit_lsn);
      71                 :             : static void begin_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn);
      72                 :             : static void prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      73                 :             :                                XLogRecPtr prepare_lsn);
      74                 :             : static void commit_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      75                 :             :                                        XLogRecPtr commit_lsn);
      76                 :             : static void rollback_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      77                 :             :                                          XLogRecPtr prepare_end_lsn, TimestampTz prepare_time);
      78                 :             : static void change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      79                 :             :                               Relation relation, ReorderBufferChange *change);
      80                 :             : static void truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      81                 :             :                                 int nrelations, Relation relations[], ReorderBufferChange *change);
      82                 :             : static void message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      83                 :             :                                XLogRecPtr message_lsn, bool transactional,
      84                 :             :                                const char *prefix, Size message_size, const char *message);
      85                 :             : 
      86                 :             : /* streaming callbacks */
      87                 :             : static void stream_start_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      88                 :             :                                     XLogRecPtr first_lsn);
      89                 :             : static void stream_stop_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      90                 :             :                                    XLogRecPtr last_lsn);
      91                 :             : static void stream_abort_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      92                 :             :                                     XLogRecPtr abort_lsn);
      93                 :             : static void stream_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      94                 :             :                                       XLogRecPtr prepare_lsn);
      95                 :             : static void stream_commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      96                 :             :                                      XLogRecPtr commit_lsn);
      97                 :             : static void stream_change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
      98                 :             :                                      Relation relation, ReorderBufferChange *change);
      99                 :             : static void stream_message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
     100                 :             :                                       XLogRecPtr message_lsn, bool transactional,
     101                 :             :                                       const char *prefix, Size message_size, const char *message);
     102                 :             : static void stream_truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
     103                 :             :                                        int nrelations, Relation relations[], ReorderBufferChange *change);
     104                 :             : 
     105                 :             : /* callback to update txn's progress */
     106                 :             : static void update_progress_txn_cb_wrapper(ReorderBuffer *cache,
     107                 :             :                                            ReorderBufferTXN *txn,
     108                 :             :                                            XLogRecPtr lsn);
     109                 :             : 
     110                 :             : static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, const char *plugin);
     111                 :             : 
     112                 :             : /*
     113                 :             :  * Make sure the current settings & environment are capable of doing logical
     114                 :             :  * decoding.
     115                 :             :  */
     116                 :             : void
     117                 :        1768 : CheckLogicalDecodingRequirements(bool repack)
     118                 :             : {
     119                 :        1768 :     CheckSlotRequirements(repack);
     120                 :             : 
     121                 :             :     /*
     122                 :             :      * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
     123                 :             :      * needs the same check.
     124                 :             :      */
     125                 :             : 
     126         [ +  + ]:        1768 :     if (MyDatabaseId == InvalidOid)
     127         [ +  - ]:           1 :         ereport(ERROR,
     128                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     129                 :             :                  errmsg("logical decoding requires a database connection")));
     130                 :             : 
     131                 :             :     /* CheckSlotRequirements() has already checked if wal_level >= 'replica' */
     132                 :             :     Assert(wal_level >= WAL_LEVEL_REPLICA);
     133                 :             : 
     134                 :             :     /* Check if logical decoding is available on standby */
     135   [ +  +  +  + ]:        1767 :     if (RecoveryInProgress() && !IsLogicalDecodingEnabled())
     136         [ +  - ]:           2 :         ereport(ERROR,
     137                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     138                 :             :                  errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"),
     139                 :             :                  errhint("Set \"wal_level\" >= \"logical\" or create at least one logical slot when \"wal_level\" = \"replica\".")));
     140                 :        1765 : }
     141                 :             : 
     142                 :             : /*
     143                 :             :  * Helper function for CreateInitDecodingContext() and
     144                 :             :  * CreateDecodingContext() performing common tasks.
     145                 :             :  */
     146                 :             : static LogicalDecodingContext *
     147                 :        1245 : StartupDecodingContext(List *output_plugin_options,
     148                 :             :                        XLogRecPtr start_lsn,
     149                 :             :                        TransactionId xmin_horizon,
     150                 :             :                        bool need_full_snapshot,
     151                 :             :                        bool fast_forward,
     152                 :             :                        bool in_create,
     153                 :             :                        bool for_repack,
     154                 :             :                        XLogReaderRoutine *xl_routine,
     155                 :             :                        LogicalOutputPluginWriterPrepareWrite prepare_write,
     156                 :             :                        LogicalOutputPluginWriterWrite do_write,
     157                 :             :                        LogicalOutputPluginWriterUpdateProgress update_progress)
     158                 :             : {
     159                 :             :     ReplicationSlot *slot;
     160                 :             :     MemoryContext context,
     161                 :             :                 old_context;
     162                 :             :     LogicalDecodingContext *ctx;
     163                 :             : 
     164                 :             :     /* shorter lines... */
     165                 :        1245 :     slot = MyReplicationSlot;
     166                 :             : 
     167                 :        1245 :     context = AllocSetContextCreate(CurrentMemoryContext,
     168                 :             :                                     "Logical decoding context",
     169                 :             :                                     ALLOCSET_DEFAULT_SIZES);
     170                 :        1245 :     old_context = MemoryContextSwitchTo(context);
     171                 :        1245 :     ctx = palloc0_object(LogicalDecodingContext);
     172                 :             : 
     173                 :        1245 :     ctx->context = context;
     174                 :             : 
     175                 :             :     /*
     176                 :             :      * (re-)load output plugins, so we detect a bad (removed) output plugin
     177                 :             :      * now.
     178                 :             :      */
     179         [ +  + ]:        1245 :     if (!fast_forward)
     180                 :             :     {
     181                 :             :         /*
     182                 :             :          * Before loading this library, make sure it's been blessed for
     183                 :             :          * logical decoding.
     184                 :             :          */
     185                 :        1219 :         const char *plugin = NameStr(slot->data.plugin);
     186                 :        1219 :         bool        plugin_allowed = false;
     187                 :             : 
     188         [ +  + ]:        1219 :         if (strcmp(plugin, "pgrepack") == 0)
     189                 :             :         {
     190                 :             :             /*
     191                 :             :              * REPACK is a special case -- print a more helpful error message
     192                 :             :              * here if we're not being called in the correct context.
     193                 :             :              */
     194   [ +  +  -  + ]:           8 :             if (!for_repack || !AmRepackWorker())
     195         [ +  - ]:           1 :                 ereport(ERROR,
     196                 :             :                         errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     197                 :             :                         errmsg("unsupported use of logical decoding plugin \"%s\"",
     198                 :             :                                "pgrepack"),
     199                 :             :                         errdetail("This plugin can only be used by %s.",
     200                 :             :                                   "REPACK (CONCURRENTLY)"));
     201                 :             : 
     202                 :           7 :             plugin_allowed = true;
     203                 :             :         }
     204         [ +  - ]:        1211 :         else if (output_plugin_libraries_string &&
     205         [ +  - ]:        1211 :                  output_plugin_libraries_string[0])
     206                 :             :         {
     207                 :             :             /* Check this plugin against output_plugin_libraries. */
     208                 :             :             char       *rawstring;
     209                 :        1211 :             List       *elemlist = NIL;
     210                 :             : 
     211                 :             :             /* Need a modifiable copy */
     212                 :        1211 :             rawstring = pstrdup(output_plugin_libraries_string);
     213                 :             : 
     214         [ -  + ]:        1211 :             if (!SplitGUCList(rawstring, ',', &elemlist))
     215                 :             :             {
     216                 :             :                 /* syntax error in list */
     217         [ #  # ]:           0 :                 ereport(LOG,
     218                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     219                 :             :                          errmsg("invalid list syntax in parameter \"%s\"",
     220                 :             :                                 "output_plugin_libraries")));
     221                 :             : 
     222                 :           0 :                 list_free(elemlist);
     223                 :           0 :                 elemlist = NIL;
     224                 :             :             }
     225                 :             : 
     226   [ +  -  +  +  :        2798 :             foreach_ptr(char, allowed, elemlist)
                   +  + ]
     227                 :             :             {
     228         [ +  + ]:        1584 :                 if (strcmp(allowed, plugin) == 0)
     229                 :             :                 {
     230                 :        1208 :                     plugin_allowed = true;
     231                 :        1208 :                     break;
     232                 :             :                 }
     233                 :             :             }
     234                 :             : 
     235                 :        1211 :             list_free(elemlist);
     236                 :        1211 :             pfree(rawstring);
     237                 :             :         }
     238                 :             : 
     239         [ +  + ]:        1218 :         if (!plugin_allowed)
     240                 :             :         {
     241                 :             :             /*
     242                 :             :              * Use the same error message as check_restricted_library_name(),
     243                 :             :              * but provide additional context for the DBA in the logs. (The
     244                 :             :              * HINT will be sent to the client, but that's not a secret.)
     245                 :             :              */
     246         [ +  - ]:           3 :             ereport(ERROR,
     247                 :             :                     errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     248                 :             :                     errmsg("library \"%s\" may not be used as an output plugin",
     249                 :             :                            plugin),
     250                 :             :             /*- translator: The second %s is the value of the output_plugin_libraries GUC, which may contain whitespace, commas, and double-quotes (") */
     251                 :             :                     errdetail_log("The configuration parameter \"%s\" (currently '%s') does not name this library as a trusted output plugin.",
     252                 :             :                                   "output_plugin_libraries",
     253                 :             :                                   output_plugin_libraries_string),
     254                 :             :                     errhint("If it is safe for all REPLICATION users to use this library as an output plugin, add it to \"%s\" and reload the server configuration.",
     255                 :             :                             "output_plugin_libraries"));
     256                 :             :         }
     257                 :             : 
     258                 :        1215 :         LoadOutputPlugin(&ctx->callbacks, plugin);
     259                 :             :     }
     260                 :             : 
     261                 :             :     /*
     262                 :             :      * Now that the slot's xmin has been set, we can announce ourselves as a
     263                 :             :      * logical decoding backend which doesn't need to be checked individually
     264                 :             :      * when computing the xmin horizon because the xmin is enforced via
     265                 :             :      * replication slots.
     266                 :             :      *
     267                 :             :      * We can only do so if we're outside of a transaction (i.e. the case when
     268                 :             :      * streaming changes via walsender), otherwise an already setup
     269                 :             :      * snapshot/xid would end up being ignored. That's not a particularly
     270                 :             :      * bothersome restriction since the SQL interface can't be used for
     271                 :             :      * streaming anyway.
     272                 :             :      */
     273         [ +  + ]:        1240 :     if (!IsTransactionOrTransactionBlock())
     274                 :             :     {
     275                 :         631 :         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     276                 :         631 :         MyProc->statusFlags |= PROC_IN_LOGICAL_DECODING;
     277                 :         631 :         ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
     278                 :         631 :         LWLockRelease(ProcArrayLock);
     279                 :             :     }
     280                 :             : 
     281                 :        1240 :     ctx->slot = slot;
     282                 :             : 
     283                 :        1240 :     ctx->reader = XLogReaderAllocate(wal_segment_size, NULL, xl_routine, ctx);
     284         [ -  + ]:        1240 :     if (!ctx->reader)
     285         [ #  # ]:           0 :         ereport(ERROR,
     286                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
     287                 :             :                  errmsg("out of memory"),
     288                 :             :                  errdetail("Failed while allocating a WAL reading processor.")));
     289                 :             : 
     290                 :        1240 :     ctx->reorder = ReorderBufferAllocate();
     291                 :        1240 :     ctx->snapshot_builder =
     292                 :        1240 :         AllocateSnapshotBuilder(ctx->reorder, xmin_horizon, start_lsn,
     293                 :             :                                 need_full_snapshot, in_create, slot->data.two_phase_at);
     294                 :             : 
     295                 :        1240 :     ctx->reorder->private_data = ctx;
     296                 :             : 
     297                 :             :     /* wrap output plugin callbacks, so we can add error context information */
     298                 :        1240 :     ctx->reorder->begin = begin_cb_wrapper;
     299                 :        1240 :     ctx->reorder->apply_change = change_cb_wrapper;
     300                 :        1240 :     ctx->reorder->apply_truncate = truncate_cb_wrapper;
     301                 :        1240 :     ctx->reorder->commit = commit_cb_wrapper;
     302                 :        1240 :     ctx->reorder->message = message_cb_wrapper;
     303                 :             : 
     304                 :             :     /*
     305                 :             :      * To support streaming, we require start/stop/abort/commit/change
     306                 :             :      * callbacks. The message and truncate callbacks are optional, similar to
     307                 :             :      * regular output plugins. We however enable streaming when at least one
     308                 :             :      * of the methods is enabled so that we can easily identify missing
     309                 :             :      * methods.
     310                 :             :      *
     311                 :             :      * We decide it here, but only check it later in the wrappers.
     312                 :             :      */
     313                 :        2513 :     ctx->streaming = (ctx->callbacks.stream_start_cb != NULL) ||
     314         [ +  - ]:          33 :         (ctx->callbacks.stream_stop_cb != NULL) ||
     315         [ +  - ]:          33 :         (ctx->callbacks.stream_abort_cb != NULL) ||
     316         [ +  - ]:          33 :         (ctx->callbacks.stream_commit_cb != NULL) ||
     317         [ +  - ]:          33 :         (ctx->callbacks.stream_change_cb != NULL) ||
     318   [ +  +  +  - ]:        1306 :         (ctx->callbacks.stream_message_cb != NULL) ||
     319         [ -  + ]:          33 :         (ctx->callbacks.stream_truncate_cb != NULL);
     320                 :             : 
     321                 :             :     /*
     322                 :             :      * streaming callbacks
     323                 :             :      *
     324                 :             :      * stream_message and stream_truncate callbacks are optional, so we do not
     325                 :             :      * fail with ERROR when missing, but the wrappers simply do nothing. We
     326                 :             :      * must set the ReorderBuffer callbacks to something, otherwise the calls
     327                 :             :      * from there will crash (we don't want to move the checks there).
     328                 :             :      */
     329                 :        1240 :     ctx->reorder->stream_start = stream_start_cb_wrapper;
     330                 :        1240 :     ctx->reorder->stream_stop = stream_stop_cb_wrapper;
     331                 :        1240 :     ctx->reorder->stream_abort = stream_abort_cb_wrapper;
     332                 :        1240 :     ctx->reorder->stream_prepare = stream_prepare_cb_wrapper;
     333                 :        1240 :     ctx->reorder->stream_commit = stream_commit_cb_wrapper;
     334                 :        1240 :     ctx->reorder->stream_change = stream_change_cb_wrapper;
     335                 :        1240 :     ctx->reorder->stream_message = stream_message_cb_wrapper;
     336                 :        1240 :     ctx->reorder->stream_truncate = stream_truncate_cb_wrapper;
     337                 :             : 
     338                 :             : 
     339                 :             :     /*
     340                 :             :      * To support two-phase logical decoding, we require
     341                 :             :      * begin_prepare/prepare/commit-prepare/abort-prepare callbacks. The
     342                 :             :      * filter_prepare callback is optional. We however enable two-phase
     343                 :             :      * logical decoding when at least one of the methods is enabled so that we
     344                 :             :      * can easily identify missing methods.
     345                 :             :      *
     346                 :             :      * We decide it here, but only check it later in the wrappers.
     347                 :             :      */
     348                 :        2513 :     ctx->twophase = (ctx->callbacks.begin_prepare_cb != NULL) ||
     349         [ +  - ]:          33 :         (ctx->callbacks.prepare_cb != NULL) ||
     350         [ +  - ]:          33 :         (ctx->callbacks.commit_prepared_cb != NULL) ||
     351         [ +  - ]:          33 :         (ctx->callbacks.rollback_prepared_cb != NULL) ||
     352   [ +  +  +  - ]:        1306 :         (ctx->callbacks.stream_prepare_cb != NULL) ||
     353         [ -  + ]:          33 :         (ctx->callbacks.filter_prepare_cb != NULL);
     354                 :             : 
     355                 :             :     /*
     356                 :             :      * Callback to support decoding at prepare time.
     357                 :             :      */
     358                 :        1240 :     ctx->reorder->begin_prepare = begin_prepare_cb_wrapper;
     359                 :        1240 :     ctx->reorder->prepare = prepare_cb_wrapper;
     360                 :        1240 :     ctx->reorder->commit_prepared = commit_prepared_cb_wrapper;
     361                 :        1240 :     ctx->reorder->rollback_prepared = rollback_prepared_cb_wrapper;
     362                 :             : 
     363                 :             :     /*
     364                 :             :      * Callback to support updating progress during sending data of a
     365                 :             :      * transaction (and its subtransactions) to the output plugin.
     366                 :             :      */
     367                 :        1240 :     ctx->reorder->update_progress_txn = update_progress_txn_cb_wrapper;
     368                 :             : 
     369                 :        1240 :     ctx->out = makeStringInfo();
     370                 :        1240 :     ctx->prepare_write = prepare_write;
     371                 :        1240 :     ctx->write = do_write;
     372                 :        1240 :     ctx->update_progress = update_progress;
     373                 :             : 
     374                 :        1240 :     ctx->output_plugin_options = output_plugin_options;
     375                 :             : 
     376                 :        1240 :     ctx->fast_forward = fast_forward;
     377                 :             : 
     378                 :        1240 :     MemoryContextSwitchTo(old_context);
     379                 :             : 
     380                 :        1240 :     return ctx;
     381                 :             : }
     382                 :             : 
     383                 :             : /*
     384                 :             :  * Create a new decoding context, for a new logical slot.
     385                 :             :  *
     386                 :             :  * plugin -- contains the name of the output plugin
     387                 :             :  * output_plugin_options -- contains options passed to the output plugin
     388                 :             :  * need_full_snapshot -- if true, must obtain a snapshot able to read all
     389                 :             :  *      tables; if false, one that can read only catalogs is acceptable.
     390                 :             :  * for_repack -- if true, we're going to be decoding for REPACK.
     391                 :             :  * restart_lsn -- if given as invalid, it's this routine's responsibility to
     392                 :             :  *      mark WAL as reserved by setting a convenient restart_lsn for the slot.
     393                 :             :  *      Otherwise, we set for decoding to start from the given LSN without
     394                 :             :  *      marking WAL reserved beforehand.  In that scenario, it's up to the
     395                 :             :  *      caller to guarantee that WAL remains available.
     396                 :             :  * xl_routine -- XLogReaderRoutine for underlying XLogReader
     397                 :             :  * prepare_write, do_write, update_progress --
     398                 :             :  *      callbacks that perform the use-case dependent, actual, work.
     399                 :             :  *
     400                 :             :  * Needs to be called while in a memory context that's at least as long lived
     401                 :             :  * as the decoding context because further memory contexts will be created
     402                 :             :  * inside it.
     403                 :             :  *
     404                 :             :  * Returns an initialized decoding context after calling the output plugin's
     405                 :             :  * startup function.
     406                 :             :  */
     407                 :             : LogicalDecodingContext *
     408                 :         522 : CreateInitDecodingContext(const char *plugin,
     409                 :             :                           List *output_plugin_options,
     410                 :             :                           bool need_full_snapshot,
     411                 :             :                           bool for_repack,
     412                 :             :                           XLogRecPtr restart_lsn,
     413                 :             :                           XLogReaderRoutine *xl_routine,
     414                 :             :                           LogicalOutputPluginWriterPrepareWrite prepare_write,
     415                 :             :                           LogicalOutputPluginWriterWrite do_write,
     416                 :             :                           LogicalOutputPluginWriterUpdateProgress update_progress)
     417                 :             : {
     418                 :         522 :     TransactionId xmin_horizon = InvalidTransactionId;
     419                 :             :     ReplicationSlot *slot;
     420                 :             :     NameData    plugin_name;
     421                 :             :     LogicalDecodingContext *ctx;
     422                 :             :     MemoryContext old_context;
     423                 :             : 
     424                 :             :     /*
     425                 :             :      * On a standby, this check is also required while creating the slot.
     426                 :             :      * Check the comments in the function.
     427                 :             :      */
     428                 :         522 :     CheckLogicalDecodingRequirements(for_repack);
     429                 :             : 
     430                 :             :     /* shorter lines... */
     431                 :         522 :     slot = MyReplicationSlot;
     432                 :             : 
     433                 :             :     /* first some sanity checks that are unlikely to be violated */
     434         [ -  + ]:         522 :     if (slot == NULL)
     435         [ #  # ]:           0 :         elog(ERROR, "cannot perform logical decoding without an acquired slot");
     436                 :             : 
     437         [ -  + ]:         522 :     if (plugin == NULL)
     438         [ #  # ]:           0 :         elog(ERROR, "cannot initialize logical decoding without a specified plugin");
     439                 :             : 
     440                 :             :     /* Make sure the passed slot is suitable. These are user facing errors. */
     441         [ -  + ]:         522 :     if (SlotIsPhysical(slot))
     442         [ #  # ]:           0 :         ereport(ERROR,
     443                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     444                 :             :                  errmsg("cannot use physical replication slot for logical decoding")));
     445                 :             : 
     446         [ -  + ]:         522 :     if (slot->data.database != MyDatabaseId)
     447         [ #  # ]:           0 :         ereport(ERROR,
     448                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     449                 :             :                  errmsg("replication slot \"%s\" was not created in this database",
     450                 :             :                         NameStr(slot->data.name))));
     451                 :             : 
     452   [ +  +  +  + ]:         890 :     if (IsTransactionState() &&
     453                 :         368 :         GetTopTransactionIdIfAny() != InvalidTransactionId)
     454         [ +  - ]:           2 :         ereport(ERROR,
     455                 :             :                 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
     456                 :             :                  errmsg("cannot create logical replication slot in transaction that has performed writes")));
     457                 :             : 
     458                 :             :     /*
     459                 :             :      * Register output plugin name with slot.  We need the mutex to avoid
     460                 :             :      * concurrent reading of a partially copied string.  But we don't want any
     461                 :             :      * complicated code while holding a spinlock, so do namestrcpy() outside.
     462                 :             :      */
     463                 :         520 :     namestrcpy(&plugin_name, plugin);
     464                 :         520 :     SpinLockAcquire(&slot->mutex);
     465                 :         520 :     slot->data.plugin = plugin_name;
     466                 :         520 :     SpinLockRelease(&slot->mutex);
     467                 :             : 
     468         [ +  + ]:         520 :     if (!XLogRecPtrIsValid(restart_lsn))
     469                 :         513 :         ReplicationSlotReserveWal();
     470                 :             :     else
     471                 :             :     {
     472                 :           7 :         SpinLockAcquire(&slot->mutex);
     473                 :           7 :         slot->data.restart_lsn = restart_lsn;
     474                 :           7 :         SpinLockRelease(&slot->mutex);
     475                 :             :     }
     476                 :             : 
     477                 :             :     /* ----
     478                 :             :      * This is a bit tricky: We need to determine a safe xmin horizon to start
     479                 :             :      * decoding from, to avoid starting from a running xacts record referring
     480                 :             :      * to xids whose rows have been vacuumed or pruned
     481                 :             :      * already. GetOldestSafeDecodingTransactionId() returns such a value, but
     482                 :             :      * without further interlock its return value might immediately be out of
     483                 :             :      * date.
     484                 :             :      *
     485                 :             :      * So we have to acquire both the ReplicationSlotControlLock and the
     486                 :             :      * ProcArrayLock to prevent concurrent computation and update of new xmin
     487                 :             :      * horizons by other backends, get the safe decoding xid, and inform the
     488                 :             :      * slot machinery about the new limit. Once that's done both locks can be
     489                 :             :      * released as the slot machinery now is protecting against vacuum.
     490                 :             :      *
     491                 :             :      * Note that, temporarily, the data, not just the catalog, xmin has to be
     492                 :             :      * reserved if a data snapshot is to be exported.  Otherwise the initial
     493                 :             :      * data snapshot created here is not guaranteed to be valid. After that
     494                 :             :      * the data xmin doesn't need to be managed anymore and the global xmin
     495                 :             :      * should be recomputed. As we are fine with losing the pegged data xmin
     496                 :             :      * after crash - no chance a snapshot would get exported anymore - we can
     497                 :             :      * get away with just setting the slot's
     498                 :             :      * effective_xmin. ReplicationSlotRelease will reset it again.
     499                 :             :      *
     500                 :             :      * ----
     501                 :             :      */
     502                 :         520 :     LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
     503                 :         520 :     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
     504                 :             : 
     505                 :         520 :     xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
     506                 :             : 
     507                 :         520 :     SpinLockAcquire(&slot->mutex);
     508                 :         520 :     slot->effective_catalog_xmin = xmin_horizon;
     509                 :         520 :     slot->data.catalog_xmin = xmin_horizon;
     510         [ +  + ]:         520 :     if (need_full_snapshot)
     511                 :         224 :         slot->effective_xmin = xmin_horizon;
     512                 :         520 :     SpinLockRelease(&slot->mutex);
     513                 :             : 
     514                 :         520 :     ReplicationSlotsComputeRequiredXmin(true);
     515                 :             : 
     516                 :         520 :     LWLockRelease(ProcArrayLock);
     517                 :         520 :     LWLockRelease(ReplicationSlotControlLock);
     518                 :             : 
     519                 :         520 :     ReplicationSlotMarkDirty();
     520                 :         520 :     ReplicationSlotSave();
     521                 :             : 
     522                 :         520 :     ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
     523                 :             :                                  need_full_snapshot, false, true, for_repack,
     524                 :             :                                  xl_routine, prepare_write, do_write,
     525                 :             :                                  update_progress);
     526                 :             : 
     527                 :             :     /* call output plugin initialization callback */
     528                 :         515 :     old_context = MemoryContextSwitchTo(ctx->context);
     529         [ +  - ]:         515 :     if (ctx->callbacks.startup_cb != NULL)
     530                 :         515 :         startup_cb_wrapper(ctx, &ctx->options, true);
     531                 :         515 :     MemoryContextSwitchTo(old_context);
     532                 :             : 
     533                 :             :     /*
     534                 :             :      * We allow decoding of prepared transactions when the two_phase is
     535                 :             :      * enabled at the time of slot creation, or when the two_phase option is
     536                 :             :      * given at the streaming start, provided the plugin supports all the
     537                 :             :      * callbacks for two-phase.
     538                 :             :      */
     539                 :         515 :     ctx->twophase &= slot->data.two_phase;
     540                 :             : 
     541                 :         515 :     ctx->reorder->output_rewrites = ctx->options.receive_rewrites;
     542                 :             : 
     543                 :         515 :     return ctx;
     544                 :             : }
     545                 :             : 
     546                 :             : /*
     547                 :             :  * Create a new decoding context, for a logical slot that has previously been
     548                 :             :  * used already.
     549                 :             :  *
     550                 :             :  * start_lsn
     551                 :             :  *      The LSN at which to start decoding.  If InvalidXLogRecPtr, restart
     552                 :             :  *      from the slot's confirmed_flush; otherwise, start from the specified
     553                 :             :  *      location (but move it forwards to confirmed_flush if it's older than
     554                 :             :  *      that, see below).
     555                 :             :  *
     556                 :             :  * output_plugin_options
     557                 :             :  *      options passed to the output plugin.
     558                 :             :  *
     559                 :             :  * fast_forward
     560                 :             :  *      bypass the generation of logical changes.
     561                 :             :  *
     562                 :             :  * xl_routine
     563                 :             :  *      XLogReaderRoutine used by underlying xlogreader
     564                 :             :  *
     565                 :             :  * prepare_write, do_write, update_progress
     566                 :             :  *      callbacks that have to be filled to perform the use-case dependent,
     567                 :             :  *      actual work.
     568                 :             :  *
     569                 :             :  * Needs to be called while in a memory context that's at least as long lived
     570                 :             :  * as the decoding context because further memory contexts will be created
     571                 :             :  * inside it.
     572                 :             :  *
     573                 :             :  * Returns an initialized decoding context after calling the output plugin's
     574                 :             :  * startup function.
     575                 :             :  */
     576                 :             : LogicalDecodingContext *
     577                 :         730 : CreateDecodingContext(XLogRecPtr start_lsn,
     578                 :             :                       List *output_plugin_options,
     579                 :             :                       bool fast_forward,
     580                 :             :                       XLogReaderRoutine *xl_routine,
     581                 :             :                       LogicalOutputPluginWriterPrepareWrite prepare_write,
     582                 :             :                       LogicalOutputPluginWriterWrite do_write,
     583                 :             :                       LogicalOutputPluginWriterUpdateProgress update_progress)
     584                 :             : {
     585                 :             :     LogicalDecodingContext *ctx;
     586                 :             :     ReplicationSlot *slot;
     587                 :             :     MemoryContext old_context;
     588                 :             : 
     589                 :             :     /* shorter lines... */
     590                 :         730 :     slot = MyReplicationSlot;
     591                 :             : 
     592                 :             :     /* first some sanity checks that are unlikely to be violated */
     593         [ -  + ]:         730 :     if (slot == NULL)
     594         [ #  # ]:           0 :         elog(ERROR, "cannot perform logical decoding without an acquired slot");
     595                 :             : 
     596                 :             :     /* make sure the passed slot is suitable, these are user facing errors */
     597         [ +  + ]:         730 :     if (SlotIsPhysical(slot))
     598         [ +  - ]:           1 :         ereport(ERROR,
     599                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     600                 :             :                  errmsg("cannot use physical replication slot for logical decoding")));
     601                 :             : 
     602                 :             :     /*
     603                 :             :      * We need to access the system tables during decoding to build the
     604                 :             :      * logical changes unless we are in fast_forward mode where no changes are
     605                 :             :      * generated.
     606                 :             :      */
     607   [ +  +  +  + ]:         729 :     if (slot->data.database != MyDatabaseId && !fast_forward)
     608         [ +  - ]:           3 :         ereport(ERROR,
     609                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     610                 :             :                  errmsg("replication slot \"%s\" was not created in this database",
     611                 :             :                         NameStr(slot->data.name))));
     612                 :             : 
     613                 :             :     /*
     614                 :             :      * The slots being synced from the primary can't be used for decoding as
     615                 :             :      * they are used after failover. However, we do allow advancing the LSNs
     616                 :             :      * during the synchronization of slots. See update_local_synced_slot.
     617                 :             :      */
     618   [ +  +  +  +  :         726 :     if (RecoveryInProgress() && slot->data.synced && !IsSyncingReplicationSlots())
                   +  + ]
     619         [ +  - ]:           1 :         ereport(ERROR,
     620                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     621                 :             :                 errmsg("cannot use replication slot \"%s\" for logical decoding",
     622                 :             :                        NameStr(slot->data.name)),
     623                 :             :                 errdetail("This replication slot is being synchronized from the primary server."),
     624                 :             :                 errhint("Specify another replication slot."));
     625                 :             : 
     626                 :             :     /* slot must be valid to allow decoding */
     627                 :             :     Assert(slot->data.invalidated == RS_INVAL_NONE);
     628                 :             :     Assert(XLogRecPtrIsValid(slot->data.restart_lsn));
     629                 :             : 
     630         [ +  + ]:         725 :     if (!XLogRecPtrIsValid(start_lsn))
     631                 :             :     {
     632                 :             :         /* continue from last position */
     633                 :         403 :         start_lsn = slot->data.confirmed_flush;
     634                 :             :     }
     635         [ +  + ]:         322 :     else if (start_lsn < slot->data.confirmed_flush)
     636                 :             :     {
     637                 :             :         /*
     638                 :             :          * It might seem like we should error out in this case, but it's
     639                 :             :          * pretty common for a client to acknowledge a LSN it doesn't have to
     640                 :             :          * do anything for, and thus didn't store persistently, because the
     641                 :             :          * xlog records didn't result in anything relevant for logical
     642                 :             :          * decoding. Clients have to be able to do that to support synchronous
     643                 :             :          * replication.
     644                 :             :          *
     645                 :             :          * Starting at a different LSN than requested might not catch certain
     646                 :             :          * kinds of client errors; so the client may wish to check that
     647                 :             :          * confirmed_flush_lsn matches its expectations.
     648                 :             :          */
     649         [ +  - ]:          62 :         elog(LOG, "%X/%08X has been already streamed, forwarding to %X/%08X",
     650                 :             :              LSN_FORMAT_ARGS(start_lsn),
     651                 :             :              LSN_FORMAT_ARGS(slot->data.confirmed_flush));
     652                 :             : 
     653                 :          62 :         start_lsn = slot->data.confirmed_flush;
     654                 :             :     }
     655                 :             : 
     656                 :         725 :     ctx = StartupDecodingContext(output_plugin_options,
     657                 :             :                                  start_lsn, InvalidTransactionId, false,
     658                 :             :                                  fast_forward, false, false,
     659                 :             :                                  xl_routine, prepare_write,
     660                 :             :                                  do_write, update_progress);
     661                 :             : 
     662                 :             :     /* call output plugin initialization callback */
     663                 :         725 :     old_context = MemoryContextSwitchTo(ctx->context);
     664         [ +  + ]:         725 :     if (ctx->callbacks.startup_cb != NULL)
     665                 :         699 :         startup_cb_wrapper(ctx, &ctx->options, false);
     666                 :         721 :     MemoryContextSwitchTo(old_context);
     667                 :             : 
     668                 :             :     /*
     669                 :             :      * We allow decoding of prepared transactions when the two_phase is
     670                 :             :      * enabled at the time of slot creation, or when the two_phase option is
     671                 :             :      * given at the streaming start, provided the plugin supports all the
     672                 :             :      * callbacks for two-phase.
     673                 :             :      */
     674   [ +  +  +  + ]:         721 :     ctx->twophase &= (slot->data.two_phase || ctx->twophase_opt_given);
     675                 :             : 
     676                 :             :     /* Mark slot to allow two_phase decoding if not already marked */
     677   [ +  +  +  + ]:         721 :     if (ctx->twophase && !slot->data.two_phase)
     678                 :             :     {
     679                 :           8 :         SpinLockAcquire(&slot->mutex);
     680                 :           8 :         slot->data.two_phase = true;
     681                 :           8 :         slot->data.two_phase_at = start_lsn;
     682                 :           8 :         SpinLockRelease(&slot->mutex);
     683                 :           8 :         ReplicationSlotMarkDirty();
     684                 :           8 :         ReplicationSlotSave();
     685                 :           8 :         SnapBuildSetTwoPhaseAt(ctx->snapshot_builder, start_lsn);
     686                 :             :     }
     687                 :             : 
     688                 :         721 :     ctx->reorder->output_rewrites = ctx->options.receive_rewrites;
     689                 :             : 
     690   [ +  +  +  + ]:         721 :     ereport(LogicalDecodingLogLevel(),
     691                 :             :             (errmsg("starting logical decoding for slot \"%s\"",
     692                 :             :                     NameStr(slot->data.name)),
     693                 :             :              errdetail("Streaming transactions committing after %X/%08X, reading WAL from %X/%08X.",
     694                 :             :                        LSN_FORMAT_ARGS(slot->data.confirmed_flush),
     695                 :             :                        LSN_FORMAT_ARGS(slot->data.restart_lsn))));
     696                 :             : 
     697                 :         721 :     return ctx;
     698                 :             : }
     699                 :             : 
     700                 :             : /*
     701                 :             :  * Returns true if a consistent initial decoding snapshot has been built.
     702                 :             :  */
     703                 :             : bool
     704                 :         549 : DecodingContextReady(LogicalDecodingContext *ctx)
     705                 :             : {
     706                 :         549 :     return SnapBuildCurrentState(ctx->snapshot_builder) == SNAPBUILD_CONSISTENT;
     707                 :             : }
     708                 :             : 
     709                 :             : /*
     710                 :             :  * Read from the decoding slot, until it is ready to start extracting changes.
     711                 :             :  */
     712                 :             : void
     713                 :         508 : DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
     714                 :             : {
     715                 :         508 :     ReplicationSlot *slot = ctx->slot;
     716                 :             : 
     717                 :             :     /* Initialize from where to start reading WAL. */
     718                 :         508 :     XLogBeginRead(ctx->reader, slot->data.restart_lsn);
     719                 :             : 
     720         [ +  + ]:         508 :     elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%08X",
     721                 :             :          LSN_FORMAT_ARGS(slot->data.restart_lsn));
     722                 :             : 
     723                 :             :     /* Wait for a consistent starting point */
     724                 :             :     for (;;)
     725                 :          32 :     {
     726                 :             :         XLogRecord *record;
     727                 :         540 :         char       *err = NULL;
     728                 :             : 
     729                 :             :         /* the read_page callback waits for new WAL */
     730                 :         540 :         record = XLogReadRecord(ctx->reader, &err);
     731         [ -  + ]:         540 :         if (err)
     732         [ #  # ]:           0 :             elog(ERROR, "could not find logical decoding starting point: %s", err);
     733         [ -  + ]:         540 :         if (!record)
     734         [ #  # ]:           0 :             elog(ERROR, "could not find logical decoding starting point");
     735                 :             : 
     736                 :         540 :         LogicalDecodingProcessRecord(ctx, ctx->reader);
     737                 :             : 
     738                 :             :         /* only continue till we found a consistent spot */
     739         [ +  + ]:         538 :         if (DecodingContextReady(ctx))
     740                 :         506 :             break;
     741                 :             : 
     742         [ -  + ]:          32 :         CHECK_FOR_INTERRUPTS();
     743                 :             :     }
     744                 :             : 
     745                 :         506 :     SpinLockAcquire(&slot->mutex);
     746                 :         506 :     slot->data.confirmed_flush = ctx->reader->EndRecPtr;
     747         [ +  + ]:         506 :     if (slot->data.two_phase)
     748                 :           9 :         slot->data.two_phase_at = ctx->reader->EndRecPtr;
     749                 :         506 :     SpinLockRelease(&slot->mutex);
     750                 :         506 : }
     751                 :             : 
     752                 :             : /*
     753                 :             :  * Free a previously allocated decoding context, invoking the shutdown
     754                 :             :  * callback if necessary.
     755                 :             :  */
     756                 :             : void
     757                 :         966 : FreeDecodingContext(LogicalDecodingContext *ctx)
     758                 :             : {
     759         [ +  + ]:         966 :     if (ctx->callbacks.shutdown_cb != NULL)
     760                 :         940 :         shutdown_cb_wrapper(ctx);
     761                 :             : 
     762                 :         966 :     ReorderBufferFree(ctx->reorder);
     763                 :         966 :     FreeSnapshotBuilder(ctx->snapshot_builder);
     764                 :         966 :     XLogReaderFree(ctx->reader);
     765                 :         966 :     MemoryContextDelete(ctx->context);
     766                 :         966 : }
     767                 :             : 
     768                 :             : /*
     769                 :             :  * Prepare a write using the context's output routine.
     770                 :             :  */
     771                 :             : void
     772                 :      360241 : OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write)
     773                 :             : {
     774         [ -  + ]:      360241 :     if (!ctx->accept_writes)
     775         [ #  # ]:           0 :         elog(ERROR, "writes are only accepted in commit, begin and change callbacks");
     776                 :             : 
     777                 :      360241 :     ctx->prepare_write(ctx, ctx->write_location, ctx->write_xid, last_write);
     778                 :      360241 :     ctx->prepared_write = true;
     779                 :      360241 : }
     780                 :             : 
     781                 :             : /*
     782                 :             :  * Perform a write using the context's output routine.
     783                 :             :  */
     784                 :             : void
     785                 :      360241 : OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write)
     786                 :             : {
     787         [ -  + ]:      360241 :     if (!ctx->prepared_write)
     788         [ #  # ]:           0 :         elog(ERROR, "OutputPluginPrepareWrite needs to be called before OutputPluginWrite");
     789                 :             : 
     790                 :      360241 :     ctx->write(ctx, ctx->write_location, ctx->write_xid, last_write);
     791                 :      360226 :     ctx->prepared_write = false;
     792                 :      360226 : }
     793                 :             : 
     794                 :             : /*
     795                 :             :  * Update progress tracking (if supported).
     796                 :             :  */
     797                 :             : void
     798                 :        4845 : OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx,
     799                 :             :                            bool skipped_xact)
     800                 :             : {
     801         [ +  + ]:        4845 :     if (!ctx->update_progress)
     802                 :        1594 :         return;
     803                 :             : 
     804                 :        3251 :     ctx->update_progress(ctx, ctx->write_location, ctx->write_xid,
     805                 :             :                          skipped_xact);
     806                 :             : }
     807                 :             : 
     808                 :             : /*
     809                 :             :  * Load the output plugin, lookup its output plugin init function, and check
     810                 :             :  * that it provides the required callbacks. The caller must have checked that
     811                 :             :  * the current user has the necessary privileges to load the given plugin;
     812                 :             :  * standard LOAD restrictions are not applied here.
     813                 :             :  */
     814                 :             : static void
     815                 :        1215 : LoadOutputPlugin(OutputPluginCallbacks *callbacks, const char *plugin)
     816                 :             : {
     817                 :             :     LogicalOutputPluginInit plugin_init;
     818                 :             : 
     819                 :        1214 :     plugin_init = (LogicalOutputPluginInit)
     820                 :        1215 :         load_external_function(plugin, "_PG_output_plugin_init", false, NULL);
     821                 :             : 
     822         [ -  + ]:        1214 :     if (plugin_init == NULL)
     823         [ #  # ]:           0 :         elog(ERROR, "output plugins have to declare the _PG_output_plugin_init symbol");
     824                 :             : 
     825                 :             :     /* ask the output plugin to fill the callback struct */
     826                 :        1214 :     plugin_init(callbacks);
     827                 :             : 
     828         [ -  + ]:        1214 :     if (callbacks->begin_cb == NULL)
     829         [ #  # ]:           0 :         elog(ERROR, "output plugins have to register a begin callback");
     830         [ -  + ]:        1214 :     if (callbacks->change_cb == NULL)
     831         [ #  # ]:           0 :         elog(ERROR, "output plugins have to register a change callback");
     832         [ -  + ]:        1214 :     if (callbacks->commit_cb == NULL)
     833         [ #  # ]:           0 :         elog(ERROR, "output plugins have to register a commit callback");
     834                 :        1214 : }
     835                 :             : 
     836                 :             : static void
     837                 :         485 : output_plugin_error_callback(void *arg)
     838                 :             : {
     839                 :         485 :     LogicalErrorCallbackState *state = (LogicalErrorCallbackState *) arg;
     840                 :             : 
     841                 :             :     /* not all callbacks have an associated LSN  */
     842         [ +  + ]:         485 :     if (XLogRecPtrIsValid(state->report_location))
     843                 :         481 :         errcontext("slot \"%s\", output plugin \"%s\", in the %s callback, associated LSN %X/%08X",
     844                 :         481 :                    NameStr(state->ctx->slot->data.name),
     845                 :         481 :                    NameStr(state->ctx->slot->data.plugin),
     846                 :             :                    state->callback_name,
     847                 :         481 :                    LSN_FORMAT_ARGS(state->report_location));
     848                 :             :     else
     849                 :           4 :         errcontext("slot \"%s\", output plugin \"%s\", in the %s callback",
     850                 :           4 :                    NameStr(state->ctx->slot->data.name),
     851                 :           4 :                    NameStr(state->ctx->slot->data.plugin),
     852                 :             :                    state->callback_name);
     853                 :         485 : }
     854                 :             : 
     855                 :             : static void
     856                 :        1214 : startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
     857                 :             : {
     858                 :             :     LogicalErrorCallbackState state;
     859                 :             :     ErrorContextCallback errcallback;
     860                 :             : 
     861                 :             :     Assert(!ctx->fast_forward);
     862                 :             : 
     863                 :             :     /* Push callback + info on the error context stack */
     864                 :        1214 :     state.ctx = ctx;
     865                 :        1214 :     state.callback_name = "startup";
     866                 :        1214 :     state.report_location = InvalidXLogRecPtr;
     867                 :        1214 :     errcallback.callback = output_plugin_error_callback;
     868                 :        1214 :     errcallback.arg = &state;
     869                 :        1214 :     errcallback.previous = error_context_stack;
     870                 :        1214 :     error_context_stack = &errcallback;
     871                 :             : 
     872                 :             :     /* set output state */
     873                 :        1214 :     ctx->accept_writes = false;
     874                 :        1214 :     ctx->end_xact = false;
     875                 :             : 
     876                 :             :     /* do the actual work: call callback */
     877                 :        1214 :     ctx->callbacks.startup_cb(ctx, opt, is_init);
     878                 :             : 
     879                 :             :     /* Pop the error context stack */
     880                 :        1210 :     error_context_stack = errcallback.previous;
     881                 :        1210 : }
     882                 :             : 
     883                 :             : static void
     884                 :         940 : shutdown_cb_wrapper(LogicalDecodingContext *ctx)
     885                 :             : {
     886                 :             :     LogicalErrorCallbackState state;
     887                 :             :     ErrorContextCallback errcallback;
     888                 :             : 
     889                 :             :     Assert(!ctx->fast_forward);
     890                 :             : 
     891                 :             :     /* Push callback + info on the error context stack */
     892                 :         940 :     state.ctx = ctx;
     893                 :         940 :     state.callback_name = "shutdown";
     894                 :         940 :     state.report_location = InvalidXLogRecPtr;
     895                 :         940 :     errcallback.callback = output_plugin_error_callback;
     896                 :         940 :     errcallback.arg = &state;
     897                 :         940 :     errcallback.previous = error_context_stack;
     898                 :         940 :     error_context_stack = &errcallback;
     899                 :             : 
     900                 :             :     /* set output state */
     901                 :         940 :     ctx->accept_writes = false;
     902                 :         940 :     ctx->end_xact = false;
     903                 :             : 
     904                 :             :     /* do the actual work: call callback */
     905                 :         940 :     ctx->callbacks.shutdown_cb(ctx);
     906                 :             : 
     907                 :             :     /* Pop the error context stack */
     908                 :         940 :     error_context_stack = errcallback.previous;
     909                 :         940 : }
     910                 :             : 
     911                 :             : 
     912                 :             : /*
     913                 :             :  * Callbacks for ReorderBuffer which add in some more information and then call
     914                 :             :  * output_plugin.h plugins.
     915                 :             :  */
     916                 :             : static void
     917                 :        1841 : begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
     918                 :             : {
     919                 :        1841 :     LogicalDecodingContext *ctx = cache->private_data;
     920                 :             :     LogicalErrorCallbackState state;
     921                 :             :     ErrorContextCallback errcallback;
     922                 :             : 
     923                 :             :     Assert(!ctx->fast_forward);
     924                 :             : 
     925                 :             :     /* Push callback + info on the error context stack */
     926                 :        1841 :     state.ctx = ctx;
     927                 :        1841 :     state.callback_name = "begin";
     928                 :        1841 :     state.report_location = txn->first_lsn;
     929                 :        1841 :     errcallback.callback = output_plugin_error_callback;
     930                 :        1841 :     errcallback.arg = &state;
     931                 :        1841 :     errcallback.previous = error_context_stack;
     932                 :        1841 :     error_context_stack = &errcallback;
     933                 :             : 
     934                 :             :     /* set output state */
     935                 :        1841 :     ctx->accept_writes = true;
     936                 :        1841 :     ctx->write_xid = txn->xid;
     937                 :        1841 :     ctx->write_location = txn->first_lsn;
     938                 :        1841 :     ctx->end_xact = false;
     939                 :             : 
     940                 :             :     /* do the actual work: call callback */
     941                 :        1841 :     ctx->callbacks.begin_cb(ctx, txn);
     942                 :             : 
     943                 :             :     /* Pop the error context stack */
     944                 :        1841 :     error_context_stack = errcallback.previous;
     945                 :        1841 : }
     946                 :             : 
     947                 :             : static void
     948                 :        1835 : commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
     949                 :             :                   XLogRecPtr commit_lsn)
     950                 :             : {
     951                 :        1835 :     LogicalDecodingContext *ctx = cache->private_data;
     952                 :             :     LogicalErrorCallbackState state;
     953                 :             :     ErrorContextCallback errcallback;
     954                 :             : 
     955                 :             :     Assert(!ctx->fast_forward);
     956                 :             : 
     957                 :             :     /* Push callback + info on the error context stack */
     958                 :        1835 :     state.ctx = ctx;
     959                 :        1835 :     state.callback_name = "commit";
     960                 :        1835 :     state.report_location = txn->final_lsn; /* beginning of commit record */
     961                 :        1835 :     errcallback.callback = output_plugin_error_callback;
     962                 :        1835 :     errcallback.arg = &state;
     963                 :        1835 :     errcallback.previous = error_context_stack;
     964                 :        1835 :     error_context_stack = &errcallback;
     965                 :             : 
     966                 :             :     /* set output state */
     967                 :        1835 :     ctx->accept_writes = true;
     968                 :        1835 :     ctx->write_xid = txn->xid;
     969                 :        1835 :     ctx->write_location = txn->end_lsn; /* points to the end of the record */
     970                 :        1835 :     ctx->end_xact = true;
     971                 :             : 
     972                 :             :     /* do the actual work: call callback */
     973                 :        1835 :     ctx->callbacks.commit_cb(ctx, txn, commit_lsn);
     974                 :             : 
     975                 :             :     /* Pop the error context stack */
     976                 :        1823 :     error_context_stack = errcallback.previous;
     977                 :        1823 : }
     978                 :             : 
     979                 :             : /*
     980                 :             :  * The functionality of begin_prepare is quite similar to begin with the
     981                 :             :  * exception that this will have gid (global transaction id) information which
     982                 :             :  * can be used by plugin. Now, we thought about extending the existing begin
     983                 :             :  * but that would break the replication protocol and additionally this looks
     984                 :             :  * cleaner.
     985                 :             :  */
     986                 :             : static void
     987                 :          26 : begin_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
     988                 :             : {
     989                 :          26 :     LogicalDecodingContext *ctx = cache->private_data;
     990                 :             :     LogicalErrorCallbackState state;
     991                 :             :     ErrorContextCallback errcallback;
     992                 :             : 
     993                 :             :     Assert(!ctx->fast_forward);
     994                 :             : 
     995                 :             :     /* We're only supposed to call this when two-phase commits are supported */
     996                 :             :     Assert(ctx->twophase);
     997                 :             : 
     998                 :             :     /* Push callback + info on the error context stack */
     999                 :          26 :     state.ctx = ctx;
    1000                 :          26 :     state.callback_name = "begin_prepare";
    1001                 :          26 :     state.report_location = txn->first_lsn;
    1002                 :          26 :     errcallback.callback = output_plugin_error_callback;
    1003                 :          26 :     errcallback.arg = &state;
    1004                 :          26 :     errcallback.previous = error_context_stack;
    1005                 :          26 :     error_context_stack = &errcallback;
    1006                 :             : 
    1007                 :             :     /* set output state */
    1008                 :          26 :     ctx->accept_writes = true;
    1009                 :          26 :     ctx->write_xid = txn->xid;
    1010                 :          26 :     ctx->write_location = txn->first_lsn;
    1011                 :          26 :     ctx->end_xact = false;
    1012                 :             : 
    1013                 :             :     /*
    1014                 :             :      * If the plugin supports two-phase commits then begin prepare callback is
    1015                 :             :      * mandatory
    1016                 :             :      */
    1017         [ -  + ]:          26 :     if (ctx->callbacks.begin_prepare_cb == NULL)
    1018         [ #  # ]:           0 :         ereport(ERROR,
    1019                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1020                 :             :                  errmsg("logical replication at prepare time requires a %s callback",
    1021                 :             :                         "begin_prepare_cb")));
    1022                 :             : 
    1023                 :             :     /* do the actual work: call callback */
    1024                 :          26 :     ctx->callbacks.begin_prepare_cb(ctx, txn);
    1025                 :             : 
    1026                 :             :     /* Pop the error context stack */
    1027                 :          26 :     error_context_stack = errcallback.previous;
    1028                 :          26 : }
    1029                 :             : 
    1030                 :             : static void
    1031                 :          26 : prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1032                 :             :                    XLogRecPtr prepare_lsn)
    1033                 :             : {
    1034                 :          26 :     LogicalDecodingContext *ctx = cache->private_data;
    1035                 :             :     LogicalErrorCallbackState state;
    1036                 :             :     ErrorContextCallback errcallback;
    1037                 :             : 
    1038                 :             :     Assert(!ctx->fast_forward);
    1039                 :             : 
    1040                 :             :     /* We're only supposed to call this when two-phase commits are supported */
    1041                 :             :     Assert(ctx->twophase);
    1042                 :             : 
    1043                 :             :     /* Push callback + info on the error context stack */
    1044                 :          26 :     state.ctx = ctx;
    1045                 :          26 :     state.callback_name = "prepare";
    1046                 :          26 :     state.report_location = txn->final_lsn; /* beginning of prepare record */
    1047                 :          26 :     errcallback.callback = output_plugin_error_callback;
    1048                 :          26 :     errcallback.arg = &state;
    1049                 :          26 :     errcallback.previous = error_context_stack;
    1050                 :          26 :     error_context_stack = &errcallback;
    1051                 :             : 
    1052                 :             :     /* set output state */
    1053                 :          26 :     ctx->accept_writes = true;
    1054                 :          26 :     ctx->write_xid = txn->xid;
    1055                 :          26 :     ctx->write_location = txn->end_lsn; /* points to the end of the record */
    1056                 :          26 :     ctx->end_xact = true;
    1057                 :             : 
    1058                 :             :     /*
    1059                 :             :      * If the plugin supports two-phase commits then prepare callback is
    1060                 :             :      * mandatory
    1061                 :             :      */
    1062         [ -  + ]:          26 :     if (ctx->callbacks.prepare_cb == NULL)
    1063         [ #  # ]:           0 :         ereport(ERROR,
    1064                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1065                 :             :                  errmsg("logical replication at prepare time requires a %s callback",
    1066                 :             :                         "prepare_cb")));
    1067                 :             : 
    1068                 :             :     /* do the actual work: call callback */
    1069                 :          26 :     ctx->callbacks.prepare_cb(ctx, txn, prepare_lsn);
    1070                 :             : 
    1071                 :             :     /* Pop the error context stack */
    1072                 :          26 :     error_context_stack = errcallback.previous;
    1073                 :          26 : }
    1074                 :             : 
    1075                 :             : static void
    1076                 :          32 : commit_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1077                 :             :                            XLogRecPtr commit_lsn)
    1078                 :             : {
    1079                 :          32 :     LogicalDecodingContext *ctx = cache->private_data;
    1080                 :             :     LogicalErrorCallbackState state;
    1081                 :             :     ErrorContextCallback errcallback;
    1082                 :             : 
    1083                 :             :     Assert(!ctx->fast_forward);
    1084                 :             : 
    1085                 :             :     /* We're only supposed to call this when two-phase commits are supported */
    1086                 :             :     Assert(ctx->twophase);
    1087                 :             : 
    1088                 :             :     /* Push callback + info on the error context stack */
    1089                 :          32 :     state.ctx = ctx;
    1090                 :          32 :     state.callback_name = "commit_prepared";
    1091                 :          32 :     state.report_location = txn->final_lsn; /* beginning of commit record */
    1092                 :          32 :     errcallback.callback = output_plugin_error_callback;
    1093                 :          32 :     errcallback.arg = &state;
    1094                 :          32 :     errcallback.previous = error_context_stack;
    1095                 :          32 :     error_context_stack = &errcallback;
    1096                 :             : 
    1097                 :             :     /* set output state */
    1098                 :          32 :     ctx->accept_writes = true;
    1099                 :          32 :     ctx->write_xid = txn->xid;
    1100                 :          32 :     ctx->write_location = txn->end_lsn; /* points to the end of the record */
    1101                 :          32 :     ctx->end_xact = true;
    1102                 :             : 
    1103                 :             :     /*
    1104                 :             :      * If the plugin support two-phase commits then commit prepared callback
    1105                 :             :      * is mandatory
    1106                 :             :      */
    1107         [ -  + ]:          32 :     if (ctx->callbacks.commit_prepared_cb == NULL)
    1108         [ #  # ]:           0 :         ereport(ERROR,
    1109                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1110                 :             :                  errmsg("logical replication at prepare time requires a %s callback",
    1111                 :             :                         "commit_prepared_cb")));
    1112                 :             : 
    1113                 :             :     /* do the actual work: call callback */
    1114                 :          32 :     ctx->callbacks.commit_prepared_cb(ctx, txn, commit_lsn);
    1115                 :             : 
    1116                 :             :     /* Pop the error context stack */
    1117                 :          32 :     error_context_stack = errcallback.previous;
    1118                 :          32 : }
    1119                 :             : 
    1120                 :             : static void
    1121                 :           8 : rollback_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1122                 :             :                              XLogRecPtr prepare_end_lsn,
    1123                 :             :                              TimestampTz prepare_time)
    1124                 :             : {
    1125                 :           8 :     LogicalDecodingContext *ctx = cache->private_data;
    1126                 :             :     LogicalErrorCallbackState state;
    1127                 :             :     ErrorContextCallback errcallback;
    1128                 :             : 
    1129                 :             :     Assert(!ctx->fast_forward);
    1130                 :             : 
    1131                 :             :     /* We're only supposed to call this when two-phase commits are supported */
    1132                 :             :     Assert(ctx->twophase);
    1133                 :             : 
    1134                 :             :     /* Push callback + info on the error context stack */
    1135                 :           8 :     state.ctx = ctx;
    1136                 :           8 :     state.callback_name = "rollback_prepared";
    1137                 :           8 :     state.report_location = txn->final_lsn; /* beginning of commit record */
    1138                 :           8 :     errcallback.callback = output_plugin_error_callback;
    1139                 :           8 :     errcallback.arg = &state;
    1140                 :           8 :     errcallback.previous = error_context_stack;
    1141                 :           8 :     error_context_stack = &errcallback;
    1142                 :             : 
    1143                 :             :     /* set output state */
    1144                 :           8 :     ctx->accept_writes = true;
    1145                 :           8 :     ctx->write_xid = txn->xid;
    1146                 :           8 :     ctx->write_location = txn->end_lsn; /* points to the end of the record */
    1147                 :           8 :     ctx->end_xact = true;
    1148                 :             : 
    1149                 :             :     /*
    1150                 :             :      * If the plugin support two-phase commits then rollback prepared callback
    1151                 :             :      * is mandatory
    1152                 :             :      */
    1153         [ -  + ]:           8 :     if (ctx->callbacks.rollback_prepared_cb == NULL)
    1154         [ #  # ]:           0 :         ereport(ERROR,
    1155                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1156                 :             :                  errmsg("logical replication at prepare time requires a %s callback",
    1157                 :             :                         "rollback_prepared_cb")));
    1158                 :             : 
    1159                 :             :     /* do the actual work: call callback */
    1160                 :           8 :     ctx->callbacks.rollback_prepared_cb(ctx, txn, prepare_end_lsn,
    1161                 :             :                                         prepare_time);
    1162                 :             : 
    1163                 :             :     /* Pop the error context stack */
    1164                 :           8 :     error_context_stack = errcallback.previous;
    1165                 :           8 : }
    1166                 :             : 
    1167                 :             : static void
    1168                 :      190624 : change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1169                 :             :                   Relation relation, ReorderBufferChange *change)
    1170                 :             : {
    1171                 :      190624 :     LogicalDecodingContext *ctx = cache->private_data;
    1172                 :             :     LogicalErrorCallbackState state;
    1173                 :             :     ErrorContextCallback errcallback;
    1174                 :             : 
    1175                 :             :     Assert(!ctx->fast_forward);
    1176                 :             : 
    1177                 :             :     /* Push callback + info on the error context stack */
    1178                 :      190624 :     state.ctx = ctx;
    1179                 :      190624 :     state.callback_name = "change";
    1180                 :      190624 :     state.report_location = change->lsn;
    1181                 :      190624 :     errcallback.callback = output_plugin_error_callback;
    1182                 :      190624 :     errcallback.arg = &state;
    1183                 :      190624 :     errcallback.previous = error_context_stack;
    1184                 :      190624 :     error_context_stack = &errcallback;
    1185                 :             : 
    1186                 :             :     /* set output state */
    1187                 :      190624 :     ctx->accept_writes = true;
    1188                 :      190624 :     ctx->write_xid = txn->xid;
    1189                 :             : 
    1190                 :             :     /*
    1191                 :             :      * Report this change's lsn so replies from clients can give an up-to-date
    1192                 :             :      * answer. This won't ever be enough (and shouldn't be!) to confirm
    1193                 :             :      * receipt of this transaction, but it might allow another transaction's
    1194                 :             :      * commit to be confirmed with one message.
    1195                 :             :      */
    1196                 :      190624 :     ctx->write_location = change->lsn;
    1197                 :             : 
    1198                 :      190624 :     ctx->end_xact = false;
    1199                 :             : 
    1200                 :      190624 :     ctx->callbacks.change_cb(ctx, txn, relation, change);
    1201                 :             : 
    1202                 :             :     /* Pop the error context stack */
    1203                 :      190618 :     error_context_stack = errcallback.previous;
    1204                 :      190618 : }
    1205                 :             : 
    1206                 :             : static void
    1207                 :          34 : truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1208                 :             :                     int nrelations, Relation relations[], ReorderBufferChange *change)
    1209                 :             : {
    1210                 :          34 :     LogicalDecodingContext *ctx = cache->private_data;
    1211                 :             :     LogicalErrorCallbackState state;
    1212                 :             :     ErrorContextCallback errcallback;
    1213                 :             : 
    1214                 :             :     Assert(!ctx->fast_forward);
    1215                 :             : 
    1216         [ -  + ]:          34 :     if (!ctx->callbacks.truncate_cb)
    1217                 :           0 :         return;
    1218                 :             : 
    1219                 :             :     /* Push callback + info on the error context stack */
    1220                 :          34 :     state.ctx = ctx;
    1221                 :          34 :     state.callback_name = "truncate";
    1222                 :          34 :     state.report_location = change->lsn;
    1223                 :          34 :     errcallback.callback = output_plugin_error_callback;
    1224                 :          34 :     errcallback.arg = &state;
    1225                 :          34 :     errcallback.previous = error_context_stack;
    1226                 :          34 :     error_context_stack = &errcallback;
    1227                 :             : 
    1228                 :             :     /* set output state */
    1229                 :          34 :     ctx->accept_writes = true;
    1230                 :          34 :     ctx->write_xid = txn->xid;
    1231                 :             : 
    1232                 :             :     /*
    1233                 :             :      * Report this change's lsn so replies from clients can give an up-to-date
    1234                 :             :      * answer. This won't ever be enough (and shouldn't be!) to confirm
    1235                 :             :      * receipt of this transaction, but it might allow another transaction's
    1236                 :             :      * commit to be confirmed with one message.
    1237                 :             :      */
    1238                 :          34 :     ctx->write_location = change->lsn;
    1239                 :             : 
    1240                 :          34 :     ctx->end_xact = false;
    1241                 :             : 
    1242                 :          34 :     ctx->callbacks.truncate_cb(ctx, txn, nrelations, relations, change);
    1243                 :             : 
    1244                 :             :     /* Pop the error context stack */
    1245                 :          34 :     error_context_stack = errcallback.previous;
    1246                 :             : }
    1247                 :             : 
    1248                 :             : bool
    1249                 :         170 : filter_prepare_cb_wrapper(LogicalDecodingContext *ctx, TransactionId xid,
    1250                 :             :                           const char *gid)
    1251                 :             : {
    1252                 :             :     LogicalErrorCallbackState state;
    1253                 :             :     ErrorContextCallback errcallback;
    1254                 :             :     bool        ret;
    1255                 :             : 
    1256                 :             :     Assert(!ctx->fast_forward);
    1257                 :             : 
    1258                 :             :     /* Push callback + info on the error context stack */
    1259                 :         170 :     state.ctx = ctx;
    1260                 :         170 :     state.callback_name = "filter_prepare";
    1261                 :         170 :     state.report_location = InvalidXLogRecPtr;
    1262                 :         170 :     errcallback.callback = output_plugin_error_callback;
    1263                 :         170 :     errcallback.arg = &state;
    1264                 :         170 :     errcallback.previous = error_context_stack;
    1265                 :         170 :     error_context_stack = &errcallback;
    1266                 :             : 
    1267                 :             :     /* set output state */
    1268                 :         170 :     ctx->accept_writes = false;
    1269                 :         170 :     ctx->end_xact = false;
    1270                 :             : 
    1271                 :             :     /* do the actual work: call callback */
    1272                 :         170 :     ret = ctx->callbacks.filter_prepare_cb(ctx, xid, gid);
    1273                 :             : 
    1274                 :             :     /* Pop the error context stack */
    1275                 :         170 :     error_context_stack = errcallback.previous;
    1276                 :             : 
    1277                 :         170 :     return ret;
    1278                 :             : }
    1279                 :             : 
    1280                 :             : bool
    1281                 :     1531121 : filter_by_origin_cb_wrapper(LogicalDecodingContext *ctx, ReplOriginId origin_id)
    1282                 :             : {
    1283                 :             :     LogicalErrorCallbackState state;
    1284                 :             :     ErrorContextCallback errcallback;
    1285                 :             :     bool        ret;
    1286                 :             : 
    1287                 :             :     Assert(!ctx->fast_forward);
    1288                 :             : 
    1289                 :             :     /* Push callback + info on the error context stack */
    1290                 :     1531121 :     state.ctx = ctx;
    1291                 :     1531121 :     state.callback_name = "filter_by_origin";
    1292                 :     1531121 :     state.report_location = InvalidXLogRecPtr;
    1293                 :     1531121 :     errcallback.callback = output_plugin_error_callback;
    1294                 :     1531121 :     errcallback.arg = &state;
    1295                 :     1531121 :     errcallback.previous = error_context_stack;
    1296                 :     1531121 :     error_context_stack = &errcallback;
    1297                 :             : 
    1298                 :             :     /* set output state */
    1299                 :     1531121 :     ctx->accept_writes = false;
    1300                 :     1531121 :     ctx->end_xact = false;
    1301                 :             : 
    1302                 :             :     /* do the actual work: call callback */
    1303                 :     1531121 :     ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
    1304                 :             : 
    1305                 :             :     /* Pop the error context stack */
    1306                 :     1531121 :     error_context_stack = errcallback.previous;
    1307                 :             : 
    1308                 :     1531121 :     return ret;
    1309                 :             : }
    1310                 :             : 
    1311                 :             : static void
    1312                 :          16 : message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1313                 :             :                    XLogRecPtr message_lsn, bool transactional,
    1314                 :             :                    const char *prefix, Size message_size, const char *message)
    1315                 :             : {
    1316                 :          16 :     LogicalDecodingContext *ctx = cache->private_data;
    1317                 :             :     LogicalErrorCallbackState state;
    1318                 :             :     ErrorContextCallback errcallback;
    1319                 :             : 
    1320                 :             :     Assert(!ctx->fast_forward);
    1321                 :             : 
    1322         [ -  + ]:          16 :     if (ctx->callbacks.message_cb == NULL)
    1323                 :           0 :         return;
    1324                 :             : 
    1325                 :             :     /* Push callback + info on the error context stack */
    1326                 :          16 :     state.ctx = ctx;
    1327                 :          16 :     state.callback_name = "message";
    1328                 :          16 :     state.report_location = message_lsn;
    1329                 :          16 :     errcallback.callback = output_plugin_error_callback;
    1330                 :          16 :     errcallback.arg = &state;
    1331                 :          16 :     errcallback.previous = error_context_stack;
    1332                 :          16 :     error_context_stack = &errcallback;
    1333                 :             : 
    1334                 :             :     /* set output state */
    1335                 :          16 :     ctx->accept_writes = true;
    1336         [ +  + ]:          16 :     ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
    1337                 :          16 :     ctx->write_location = message_lsn;
    1338                 :          16 :     ctx->end_xact = false;
    1339                 :             : 
    1340                 :             :     /* do the actual work: call callback */
    1341                 :          16 :     ctx->callbacks.message_cb(ctx, txn, message_lsn, transactional, prefix,
    1342                 :             :                               message_size, message);
    1343                 :             : 
    1344                 :             :     /* Pop the error context stack */
    1345                 :          16 :     error_context_stack = errcallback.previous;
    1346                 :             : }
    1347                 :             : 
    1348                 :             : static void
    1349                 :         655 : stream_start_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1350                 :             :                         XLogRecPtr first_lsn)
    1351                 :             : {
    1352                 :         655 :     LogicalDecodingContext *ctx = cache->private_data;
    1353                 :             :     LogicalErrorCallbackState state;
    1354                 :             :     ErrorContextCallback errcallback;
    1355                 :             : 
    1356                 :             :     Assert(!ctx->fast_forward);
    1357                 :             : 
    1358                 :             :     /* We're only supposed to call this when streaming is supported. */
    1359                 :             :     Assert(ctx->streaming);
    1360                 :             : 
    1361                 :             :     /* Push callback + info on the error context stack */
    1362                 :         655 :     state.ctx = ctx;
    1363                 :         655 :     state.callback_name = "stream_start";
    1364                 :         655 :     state.report_location = first_lsn;
    1365                 :         655 :     errcallback.callback = output_plugin_error_callback;
    1366                 :         655 :     errcallback.arg = &state;
    1367                 :         655 :     errcallback.previous = error_context_stack;
    1368                 :         655 :     error_context_stack = &errcallback;
    1369                 :             : 
    1370                 :             :     /* set output state */
    1371                 :         655 :     ctx->accept_writes = true;
    1372                 :         655 :     ctx->write_xid = txn->xid;
    1373                 :             : 
    1374                 :             :     /*
    1375                 :             :      * Report this message's lsn so replies from clients can give an
    1376                 :             :      * up-to-date answer. This won't ever be enough (and shouldn't be!) to
    1377                 :             :      * confirm receipt of this transaction, but it might allow another
    1378                 :             :      * transaction's commit to be confirmed with one message.
    1379                 :             :      */
    1380                 :         655 :     ctx->write_location = first_lsn;
    1381                 :             : 
    1382                 :         655 :     ctx->end_xact = false;
    1383                 :             : 
    1384                 :             :     /* in streaming mode, stream_start_cb is required */
    1385         [ -  + ]:         655 :     if (ctx->callbacks.stream_start_cb == NULL)
    1386         [ #  # ]:           0 :         ereport(ERROR,
    1387                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1388                 :             :                  errmsg("logical streaming requires a %s callback",
    1389                 :             :                         "stream_start_cb")));
    1390                 :             : 
    1391                 :         655 :     ctx->callbacks.stream_start_cb(ctx, txn);
    1392                 :             : 
    1393                 :             :     /* Pop the error context stack */
    1394                 :         655 :     error_context_stack = errcallback.previous;
    1395                 :         655 : }
    1396                 :             : 
    1397                 :             : static void
    1398                 :         655 : stream_stop_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1399                 :             :                        XLogRecPtr last_lsn)
    1400                 :             : {
    1401                 :         655 :     LogicalDecodingContext *ctx = cache->private_data;
    1402                 :             :     LogicalErrorCallbackState state;
    1403                 :             :     ErrorContextCallback errcallback;
    1404                 :             : 
    1405                 :             :     Assert(!ctx->fast_forward);
    1406                 :             : 
    1407                 :             :     /* We're only supposed to call this when streaming is supported. */
    1408                 :             :     Assert(ctx->streaming);
    1409                 :             : 
    1410                 :             :     /* Push callback + info on the error context stack */
    1411                 :         655 :     state.ctx = ctx;
    1412                 :         655 :     state.callback_name = "stream_stop";
    1413                 :         655 :     state.report_location = last_lsn;
    1414                 :         655 :     errcallback.callback = output_plugin_error_callback;
    1415                 :         655 :     errcallback.arg = &state;
    1416                 :         655 :     errcallback.previous = error_context_stack;
    1417                 :         655 :     error_context_stack = &errcallback;
    1418                 :             : 
    1419                 :             :     /* set output state */
    1420                 :         655 :     ctx->accept_writes = true;
    1421                 :         655 :     ctx->write_xid = txn->xid;
    1422                 :             : 
    1423                 :             :     /*
    1424                 :             :      * Report this message's lsn so replies from clients can give an
    1425                 :             :      * up-to-date answer. This won't ever be enough (and shouldn't be!) to
    1426                 :             :      * confirm receipt of this transaction, but it might allow another
    1427                 :             :      * transaction's commit to be confirmed with one message.
    1428                 :             :      */
    1429                 :         655 :     ctx->write_location = last_lsn;
    1430                 :             : 
    1431                 :         655 :     ctx->end_xact = false;
    1432                 :             : 
    1433                 :             :     /* in streaming mode, stream_stop_cb is required */
    1434         [ -  + ]:         655 :     if (ctx->callbacks.stream_stop_cb == NULL)
    1435         [ #  # ]:           0 :         ereport(ERROR,
    1436                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1437                 :             :                  errmsg("logical streaming requires a %s callback",
    1438                 :             :                         "stream_stop_cb")));
    1439                 :             : 
    1440                 :         655 :     ctx->callbacks.stream_stop_cb(ctx, txn);
    1441                 :             : 
    1442                 :             :     /* Pop the error context stack */
    1443                 :         655 :     error_context_stack = errcallback.previous;
    1444                 :         655 : }
    1445                 :             : 
    1446                 :             : static void
    1447                 :          30 : stream_abort_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1448                 :             :                         XLogRecPtr abort_lsn)
    1449                 :             : {
    1450                 :          30 :     LogicalDecodingContext *ctx = cache->private_data;
    1451                 :             :     LogicalErrorCallbackState state;
    1452                 :             :     ErrorContextCallback errcallback;
    1453                 :             : 
    1454                 :             :     Assert(!ctx->fast_forward);
    1455                 :             : 
    1456                 :             :     /* We're only supposed to call this when streaming is supported. */
    1457                 :             :     Assert(ctx->streaming);
    1458                 :             : 
    1459                 :             :     /* Push callback + info on the error context stack */
    1460                 :          30 :     state.ctx = ctx;
    1461                 :          30 :     state.callback_name = "stream_abort";
    1462                 :          30 :     state.report_location = abort_lsn;
    1463                 :          30 :     errcallback.callback = output_plugin_error_callback;
    1464                 :          30 :     errcallback.arg = &state;
    1465                 :          30 :     errcallback.previous = error_context_stack;
    1466                 :          30 :     error_context_stack = &errcallback;
    1467                 :             : 
    1468                 :             :     /* set output state */
    1469                 :          30 :     ctx->accept_writes = true;
    1470                 :          30 :     ctx->write_xid = txn->xid;
    1471                 :          30 :     ctx->write_location = abort_lsn;
    1472                 :          30 :     ctx->end_xact = true;
    1473                 :             : 
    1474                 :             :     /* in streaming mode, stream_abort_cb is required */
    1475         [ -  + ]:          30 :     if (ctx->callbacks.stream_abort_cb == NULL)
    1476         [ #  # ]:           0 :         ereport(ERROR,
    1477                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1478                 :             :                  errmsg("logical streaming requires a %s callback",
    1479                 :             :                         "stream_abort_cb")));
    1480                 :             : 
    1481                 :          30 :     ctx->callbacks.stream_abort_cb(ctx, txn, abort_lsn);
    1482                 :             : 
    1483                 :             :     /* Pop the error context stack */
    1484                 :          30 :     error_context_stack = errcallback.previous;
    1485                 :          30 : }
    1486                 :             : 
    1487                 :             : static void
    1488                 :          14 : stream_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1489                 :             :                           XLogRecPtr prepare_lsn)
    1490                 :             : {
    1491                 :          14 :     LogicalDecodingContext *ctx = cache->private_data;
    1492                 :             :     LogicalErrorCallbackState state;
    1493                 :             :     ErrorContextCallback errcallback;
    1494                 :             : 
    1495                 :             :     Assert(!ctx->fast_forward);
    1496                 :             : 
    1497                 :             :     /*
    1498                 :             :      * We're only supposed to call this when streaming and two-phase commits
    1499                 :             :      * are supported.
    1500                 :             :      */
    1501                 :             :     Assert(ctx->streaming);
    1502                 :             :     Assert(ctx->twophase);
    1503                 :             : 
    1504                 :             :     /* Push callback + info on the error context stack */
    1505                 :          14 :     state.ctx = ctx;
    1506                 :          14 :     state.callback_name = "stream_prepare";
    1507                 :          14 :     state.report_location = txn->final_lsn;
    1508                 :          14 :     errcallback.callback = output_plugin_error_callback;
    1509                 :          14 :     errcallback.arg = &state;
    1510                 :          14 :     errcallback.previous = error_context_stack;
    1511                 :          14 :     error_context_stack = &errcallback;
    1512                 :             : 
    1513                 :             :     /* set output state */
    1514                 :          14 :     ctx->accept_writes = true;
    1515                 :          14 :     ctx->write_xid = txn->xid;
    1516                 :          14 :     ctx->write_location = txn->end_lsn;
    1517                 :          14 :     ctx->end_xact = true;
    1518                 :             : 
    1519                 :             :     /* in streaming mode with two-phase commits, stream_prepare_cb is required */
    1520         [ -  + ]:          14 :     if (ctx->callbacks.stream_prepare_cb == NULL)
    1521         [ #  # ]:           0 :         ereport(ERROR,
    1522                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1523                 :             :                  errmsg("logical streaming at prepare time requires a %s callback",
    1524                 :             :                         "stream_prepare_cb")));
    1525                 :             : 
    1526                 :          14 :     ctx->callbacks.stream_prepare_cb(ctx, txn, prepare_lsn);
    1527                 :             : 
    1528                 :             :     /* Pop the error context stack */
    1529                 :          14 :     error_context_stack = errcallback.previous;
    1530                 :          14 : }
    1531                 :             : 
    1532                 :             : static void
    1533                 :          47 : stream_commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1534                 :             :                          XLogRecPtr commit_lsn)
    1535                 :             : {
    1536                 :          47 :     LogicalDecodingContext *ctx = cache->private_data;
    1537                 :             :     LogicalErrorCallbackState state;
    1538                 :             :     ErrorContextCallback errcallback;
    1539                 :             : 
    1540                 :             :     Assert(!ctx->fast_forward);
    1541                 :             : 
    1542                 :             :     /* We're only supposed to call this when streaming is supported. */
    1543                 :             :     Assert(ctx->streaming);
    1544                 :             : 
    1545                 :             :     /* Push callback + info on the error context stack */
    1546                 :          47 :     state.ctx = ctx;
    1547                 :          47 :     state.callback_name = "stream_commit";
    1548                 :          47 :     state.report_location = txn->final_lsn;
    1549                 :          47 :     errcallback.callback = output_plugin_error_callback;
    1550                 :          47 :     errcallback.arg = &state;
    1551                 :          47 :     errcallback.previous = error_context_stack;
    1552                 :          47 :     error_context_stack = &errcallback;
    1553                 :             : 
    1554                 :             :     /* set output state */
    1555                 :          47 :     ctx->accept_writes = true;
    1556                 :          47 :     ctx->write_xid = txn->xid;
    1557                 :          47 :     ctx->write_location = txn->end_lsn;
    1558                 :          47 :     ctx->end_xact = true;
    1559                 :             : 
    1560                 :             :     /* in streaming mode, stream_commit_cb is required */
    1561         [ -  + ]:          47 :     if (ctx->callbacks.stream_commit_cb == NULL)
    1562         [ #  # ]:           0 :         ereport(ERROR,
    1563                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1564                 :             :                  errmsg("logical streaming requires a %s callback",
    1565                 :             :                         "stream_commit_cb")));
    1566                 :             : 
    1567                 :          47 :     ctx->callbacks.stream_commit_cb(ctx, txn, commit_lsn);
    1568                 :             : 
    1569                 :             :     /* Pop the error context stack */
    1570                 :          47 :     error_context_stack = errcallback.previous;
    1571                 :          47 : }
    1572                 :             : 
    1573                 :             : static void
    1574                 :      170928 : stream_change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1575                 :             :                          Relation relation, ReorderBufferChange *change)
    1576                 :             : {
    1577                 :      170928 :     LogicalDecodingContext *ctx = cache->private_data;
    1578                 :             :     LogicalErrorCallbackState state;
    1579                 :             :     ErrorContextCallback errcallback;
    1580                 :             : 
    1581                 :             :     Assert(!ctx->fast_forward);
    1582                 :             : 
    1583                 :             :     /* We're only supposed to call this when streaming is supported. */
    1584                 :             :     Assert(ctx->streaming);
    1585                 :             : 
    1586                 :             :     /* Push callback + info on the error context stack */
    1587                 :      170928 :     state.ctx = ctx;
    1588                 :      170928 :     state.callback_name = "stream_change";
    1589                 :      170928 :     state.report_location = change->lsn;
    1590                 :      170928 :     errcallback.callback = output_plugin_error_callback;
    1591                 :      170928 :     errcallback.arg = &state;
    1592                 :      170928 :     errcallback.previous = error_context_stack;
    1593                 :      170928 :     error_context_stack = &errcallback;
    1594                 :             : 
    1595                 :             :     /* set output state */
    1596                 :      170928 :     ctx->accept_writes = true;
    1597                 :      170928 :     ctx->write_xid = txn->xid;
    1598                 :             : 
    1599                 :             :     /*
    1600                 :             :      * Report this change's lsn so replies from clients can give an up-to-date
    1601                 :             :      * answer. This won't ever be enough (and shouldn't be!) to confirm
    1602                 :             :      * receipt of this transaction, but it might allow another transaction's
    1603                 :             :      * commit to be confirmed with one message.
    1604                 :             :      */
    1605                 :      170928 :     ctx->write_location = change->lsn;
    1606                 :             : 
    1607                 :      170928 :     ctx->end_xact = false;
    1608                 :             : 
    1609                 :             :     /* in streaming mode, stream_change_cb is required */
    1610         [ -  + ]:      170928 :     if (ctx->callbacks.stream_change_cb == NULL)
    1611         [ #  # ]:           0 :         ereport(ERROR,
    1612                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1613                 :             :                  errmsg("logical streaming requires a %s callback",
    1614                 :             :                         "stream_change_cb")));
    1615                 :             : 
    1616                 :      170928 :     ctx->callbacks.stream_change_cb(ctx, txn, relation, change);
    1617                 :             : 
    1618                 :             :     /* Pop the error context stack */
    1619                 :      170928 :     error_context_stack = errcallback.previous;
    1620                 :      170928 : }
    1621                 :             : 
    1622                 :             : static void
    1623                 :           3 : stream_message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1624                 :             :                           XLogRecPtr message_lsn, bool transactional,
    1625                 :             :                           const char *prefix, Size message_size, const char *message)
    1626                 :             : {
    1627                 :           3 :     LogicalDecodingContext *ctx = cache->private_data;
    1628                 :             :     LogicalErrorCallbackState state;
    1629                 :             :     ErrorContextCallback errcallback;
    1630                 :             : 
    1631                 :             :     Assert(!ctx->fast_forward);
    1632                 :             : 
    1633                 :             :     /* We're only supposed to call this when streaming is supported. */
    1634                 :             :     Assert(ctx->streaming);
    1635                 :             : 
    1636                 :             :     /* this callback is optional */
    1637         [ -  + ]:           3 :     if (ctx->callbacks.stream_message_cb == NULL)
    1638                 :           0 :         return;
    1639                 :             : 
    1640                 :             :     /* Push callback + info on the error context stack */
    1641                 :           3 :     state.ctx = ctx;
    1642                 :           3 :     state.callback_name = "stream_message";
    1643                 :           3 :     state.report_location = message_lsn;
    1644                 :           3 :     errcallback.callback = output_plugin_error_callback;
    1645                 :           3 :     errcallback.arg = &state;
    1646                 :           3 :     errcallback.previous = error_context_stack;
    1647                 :           3 :     error_context_stack = &errcallback;
    1648                 :             : 
    1649                 :             :     /* set output state */
    1650                 :           3 :     ctx->accept_writes = true;
    1651         [ +  - ]:           3 :     ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
    1652                 :           3 :     ctx->write_location = message_lsn;
    1653                 :           3 :     ctx->end_xact = false;
    1654                 :             : 
    1655                 :             :     /* do the actual work: call callback */
    1656                 :           3 :     ctx->callbacks.stream_message_cb(ctx, txn, message_lsn, transactional, prefix,
    1657                 :             :                                      message_size, message);
    1658                 :             : 
    1659                 :             :     /* Pop the error context stack */
    1660                 :           3 :     error_context_stack = errcallback.previous;
    1661                 :             : }
    1662                 :             : 
    1663                 :             : static void
    1664                 :           0 : stream_truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1665                 :             :                            int nrelations, Relation relations[],
    1666                 :             :                            ReorderBufferChange *change)
    1667                 :             : {
    1668                 :           0 :     LogicalDecodingContext *ctx = cache->private_data;
    1669                 :             :     LogicalErrorCallbackState state;
    1670                 :             :     ErrorContextCallback errcallback;
    1671                 :             : 
    1672                 :             :     Assert(!ctx->fast_forward);
    1673                 :             : 
    1674                 :             :     /* We're only supposed to call this when streaming is supported. */
    1675                 :             :     Assert(ctx->streaming);
    1676                 :             : 
    1677                 :             :     /* this callback is optional */
    1678         [ #  # ]:           0 :     if (!ctx->callbacks.stream_truncate_cb)
    1679                 :           0 :         return;
    1680                 :             : 
    1681                 :             :     /* Push callback + info on the error context stack */
    1682                 :           0 :     state.ctx = ctx;
    1683                 :           0 :     state.callback_name = "stream_truncate";
    1684                 :           0 :     state.report_location = change->lsn;
    1685                 :           0 :     errcallback.callback = output_plugin_error_callback;
    1686                 :           0 :     errcallback.arg = &state;
    1687                 :           0 :     errcallback.previous = error_context_stack;
    1688                 :           0 :     error_context_stack = &errcallback;
    1689                 :             : 
    1690                 :             :     /* set output state */
    1691                 :           0 :     ctx->accept_writes = true;
    1692                 :           0 :     ctx->write_xid = txn->xid;
    1693                 :             : 
    1694                 :             :     /*
    1695                 :             :      * Report this change's lsn so replies from clients can give an up-to-date
    1696                 :             :      * answer. This won't ever be enough (and shouldn't be!) to confirm
    1697                 :             :      * receipt of this transaction, but it might allow another transaction's
    1698                 :             :      * commit to be confirmed with one message.
    1699                 :             :      */
    1700                 :           0 :     ctx->write_location = change->lsn;
    1701                 :             : 
    1702                 :           0 :     ctx->end_xact = false;
    1703                 :             : 
    1704                 :           0 :     ctx->callbacks.stream_truncate_cb(ctx, txn, nrelations, relations, change);
    1705                 :             : 
    1706                 :             :     /* Pop the error context stack */
    1707                 :           0 :     error_context_stack = errcallback.previous;
    1708                 :             : }
    1709                 :             : 
    1710                 :             : static void
    1711                 :        3379 : update_progress_txn_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
    1712                 :             :                                XLogRecPtr lsn)
    1713                 :             : {
    1714                 :        3379 :     LogicalDecodingContext *ctx = cache->private_data;
    1715                 :             :     LogicalErrorCallbackState state;
    1716                 :             :     ErrorContextCallback errcallback;
    1717                 :             : 
    1718                 :             :     Assert(!ctx->fast_forward);
    1719                 :             : 
    1720                 :             :     /* Push callback + info on the error context stack */
    1721                 :        3379 :     state.ctx = ctx;
    1722                 :        3379 :     state.callback_name = "update_progress_txn";
    1723                 :        3379 :     state.report_location = lsn;
    1724                 :        3379 :     errcallback.callback = output_plugin_error_callback;
    1725                 :        3379 :     errcallback.arg = &state;
    1726                 :        3379 :     errcallback.previous = error_context_stack;
    1727                 :        3379 :     error_context_stack = &errcallback;
    1728                 :             : 
    1729                 :             :     /* set output state */
    1730                 :        3379 :     ctx->accept_writes = false;
    1731                 :        3379 :     ctx->write_xid = txn->xid;
    1732                 :             : 
    1733                 :             :     /*
    1734                 :             :      * Report this change's lsn so replies from clients can give an up-to-date
    1735                 :             :      * answer. This won't ever be enough (and shouldn't be!) to confirm
    1736                 :             :      * receipt of this transaction, but it might allow another transaction's
    1737                 :             :      * commit to be confirmed with one message.
    1738                 :             :      */
    1739                 :        3379 :     ctx->write_location = lsn;
    1740                 :             : 
    1741                 :        3379 :     ctx->end_xact = false;
    1742                 :             : 
    1743                 :        3379 :     OutputPluginUpdateProgress(ctx, false);
    1744                 :             : 
    1745                 :             :     /* Pop the error context stack */
    1746                 :        3379 :     error_context_stack = errcallback.previous;
    1747                 :        3379 : }
    1748                 :             : 
    1749                 :             : /*
    1750                 :             :  * Set the required catalog xmin horizon for historic snapshots in the current
    1751                 :             :  * replication slot.
    1752                 :             :  *
    1753                 :             :  * Note that in the most cases, we won't be able to immediately use the xmin
    1754                 :             :  * to increase the xmin horizon: we need to wait till the client has confirmed
    1755                 :             :  * receiving current_lsn with LogicalConfirmReceivedLocation().
    1756                 :             :  */
    1757                 :             : void
    1758                 :         549 : LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
    1759                 :             : {
    1760                 :         549 :     bool        updated_xmin = false;
    1761                 :             :     ReplicationSlot *slot;
    1762                 :         549 :     bool        got_new_xmin = false;
    1763                 :             : 
    1764                 :         549 :     slot = MyReplicationSlot;
    1765                 :             : 
    1766                 :             :     Assert(slot != NULL);
    1767                 :             : 
    1768                 :         549 :     SpinLockAcquire(&slot->mutex);
    1769                 :             : 
    1770                 :             :     /*
    1771                 :             :      * don't overwrite if we already have a newer xmin. This can happen if we
    1772                 :             :      * restart decoding in a slot.
    1773                 :             :      */
    1774         [ +  + ]:         549 :     if (TransactionIdPrecedesOrEquals(xmin, slot->data.catalog_xmin))
    1775                 :             :     {
    1776                 :             :     }
    1777                 :             : 
    1778                 :             :     /*
    1779                 :             :      * If the client has already confirmed up to this lsn, we directly can
    1780                 :             :      * mark this as accepted. This can happen if we restart decoding in a
    1781                 :             :      * slot.
    1782                 :             :      */
    1783         [ +  + ]:         195 :     else if (current_lsn <= slot->data.confirmed_flush)
    1784                 :             :     {
    1785                 :          65 :         slot->candidate_catalog_xmin = xmin;
    1786                 :          65 :         slot->candidate_xmin_lsn = current_lsn;
    1787                 :             : 
    1788                 :             :         /* our candidate can directly be used */
    1789                 :          65 :         updated_xmin = true;
    1790                 :             :     }
    1791                 :             : 
    1792                 :             :     /*
    1793                 :             :      * Only increase if the previous values have been applied, otherwise we
    1794                 :             :      * might never end up updating if the receiver acks too slowly.
    1795                 :             :      */
    1796         [ +  + ]:         130 :     else if (!XLogRecPtrIsValid(slot->candidate_xmin_lsn))
    1797                 :             :     {
    1798                 :          24 :         slot->candidate_catalog_xmin = xmin;
    1799                 :          24 :         slot->candidate_xmin_lsn = current_lsn;
    1800                 :             : 
    1801                 :             :         /*
    1802                 :             :          * Log new xmin at an appropriate log level after releasing the
    1803                 :             :          * spinlock.
    1804                 :             :          */
    1805                 :          24 :         got_new_xmin = true;
    1806                 :             :     }
    1807                 :         549 :     SpinLockRelease(&slot->mutex);
    1808                 :             : 
    1809         [ +  + ]:         549 :     if (got_new_xmin)
    1810         [ +  + ]:          24 :         elog(DEBUG1, "got new catalog xmin %u at %X/%08X", xmin,
    1811                 :             :              LSN_FORMAT_ARGS(current_lsn));
    1812                 :             : 
    1813                 :             :     /* candidate already valid with the current flush position, apply */
    1814         [ +  + ]:         549 :     if (updated_xmin)
    1815                 :          65 :         LogicalConfirmReceivedLocation(slot->data.confirmed_flush);
    1816                 :         549 : }
    1817                 :             : 
    1818                 :             : /*
    1819                 :             :  * Mark the minimal LSN (restart_lsn) we need to read to replay all
    1820                 :             :  * transactions that have not yet committed at current_lsn.
    1821                 :             :  *
    1822                 :             :  * Just like LogicalIncreaseXminForSlot this only takes effect when the
    1823                 :             :  * client has confirmed to have received current_lsn.
    1824                 :             :  */
    1825                 :             : void
    1826                 :         496 : LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
    1827                 :             : {
    1828                 :         496 :     bool        updated_lsn = false;
    1829                 :             :     ReplicationSlot *slot;
    1830                 :             : 
    1831                 :         496 :     slot = MyReplicationSlot;
    1832                 :             : 
    1833                 :             :     Assert(slot != NULL);
    1834                 :             :     Assert(XLogRecPtrIsValid(restart_lsn));
    1835                 :             :     Assert(XLogRecPtrIsValid(current_lsn));
    1836                 :             : 
    1837                 :         496 :     SpinLockAcquire(&slot->mutex);
    1838                 :             : 
    1839                 :             :     /* don't overwrite if have a newer restart lsn */
    1840         [ +  + ]:         496 :     if (restart_lsn <= slot->data.restart_lsn)
    1841                 :             :     {
    1842                 :          11 :         SpinLockRelease(&slot->mutex);
    1843                 :             :     }
    1844                 :             : 
    1845                 :             :     /*
    1846                 :             :      * We might have already flushed far enough to directly accept this lsn,
    1847                 :             :      * in this case there is no need to check for existing candidate LSNs
    1848                 :             :      */
    1849         [ +  + ]:         485 :     else if (current_lsn <= slot->data.confirmed_flush)
    1850                 :             :     {
    1851                 :         326 :         slot->candidate_restart_valid = current_lsn;
    1852                 :         326 :         slot->candidate_restart_lsn = restart_lsn;
    1853                 :         326 :         SpinLockRelease(&slot->mutex);
    1854                 :             : 
    1855                 :             :         /* our candidate can directly be used */
    1856                 :         326 :         updated_lsn = true;
    1857                 :             :     }
    1858                 :             : 
    1859                 :             :     /*
    1860                 :             :      * Only increase if the previous values have been applied, otherwise we
    1861                 :             :      * might never end up updating if the receiver acks too slowly. A missed
    1862                 :             :      * value here will just cause some extra effort after reconnecting.
    1863                 :             :      */
    1864         [ +  + ]:         159 :     else if (!XLogRecPtrIsValid(slot->candidate_restart_valid))
    1865                 :             :     {
    1866                 :          44 :         slot->candidate_restart_valid = current_lsn;
    1867                 :          44 :         slot->candidate_restart_lsn = restart_lsn;
    1868                 :          44 :         SpinLockRelease(&slot->mutex);
    1869                 :             : 
    1870         [ +  + ]:          44 :         elog(DEBUG1, "got new restart lsn %X/%08X at %X/%08X",
    1871                 :             :              LSN_FORMAT_ARGS(restart_lsn),
    1872                 :             :              LSN_FORMAT_ARGS(current_lsn));
    1873                 :             :     }
    1874                 :             :     else
    1875                 :             :     {
    1876                 :             :         XLogRecPtr  candidate_restart_lsn;
    1877                 :             :         XLogRecPtr  candidate_restart_valid;
    1878                 :             :         XLogRecPtr  confirmed_flush;
    1879                 :             : 
    1880                 :         115 :         candidate_restart_lsn = slot->candidate_restart_lsn;
    1881                 :         115 :         candidate_restart_valid = slot->candidate_restart_valid;
    1882                 :         115 :         confirmed_flush = slot->data.confirmed_flush;
    1883                 :         115 :         SpinLockRelease(&slot->mutex);
    1884                 :             : 
    1885         [ +  + ]:         115 :         elog(DEBUG1, "failed to increase restart lsn: proposed %X/%08X, after %X/%08X, current candidate %X/%08X, current after %X/%08X, flushed up to %X/%08X",
    1886                 :             :              LSN_FORMAT_ARGS(restart_lsn),
    1887                 :             :              LSN_FORMAT_ARGS(current_lsn),
    1888                 :             :              LSN_FORMAT_ARGS(candidate_restart_lsn),
    1889                 :             :              LSN_FORMAT_ARGS(candidate_restart_valid),
    1890                 :             :              LSN_FORMAT_ARGS(confirmed_flush));
    1891                 :             :     }
    1892                 :             : 
    1893                 :             :     /* candidates are already valid with the current flush position, apply */
    1894         [ +  + ]:         496 :     if (updated_lsn)
    1895                 :         326 :         LogicalConfirmReceivedLocation(slot->data.confirmed_flush);
    1896                 :         496 : }
    1897                 :             : 
    1898                 :             : /*
    1899                 :             :  * Handle a consumer's confirmation having received all changes up to lsn.
    1900                 :             :  */
    1901                 :             : void
    1902                 :       21745 : LogicalConfirmReceivedLocation(XLogRecPtr lsn)
    1903                 :             : {
    1904                 :             :     Assert(XLogRecPtrIsValid(lsn));
    1905                 :             : 
    1906                 :             :     /* Do an unlocked check for candidate_lsn first. */
    1907         [ +  + ]:       21745 :     if (XLogRecPtrIsValid(MyReplicationSlot->candidate_xmin_lsn) ||
    1908         [ +  + ]:       21599 :         XLogRecPtrIsValid(MyReplicationSlot->candidate_restart_valid))
    1909                 :         491 :     {
    1910                 :         491 :         bool        updated_xmin = false;
    1911                 :         491 :         bool        updated_restart = false;
    1912                 :             :         XLogRecPtr  restart_lsn pg_attribute_unused();
    1913                 :             : 
    1914                 :         491 :         SpinLockAcquire(&MyReplicationSlot->mutex);
    1915                 :             : 
    1916                 :             :         /* remember the old restart lsn */
    1917                 :         491 :         restart_lsn = MyReplicationSlot->data.restart_lsn;
    1918                 :             : 
    1919                 :             :         /*
    1920                 :             :          * Prevent moving the confirmed_flush backwards, as this could lead to
    1921                 :             :          * data duplication issues caused by replicating already replicated
    1922                 :             :          * changes.
    1923                 :             :          *
    1924                 :             :          * This can happen when a client acknowledges an LSN it doesn't have
    1925                 :             :          * to do anything for, and thus didn't store persistently. After a
    1926                 :             :          * restart, the client can send the prior LSN that it stored
    1927                 :             :          * persistently as an acknowledgement, but we need to ignore such an
    1928                 :             :          * LSN. See similar case handling in CreateDecodingContext.
    1929                 :             :          */
    1930         [ +  + ]:         491 :         if (lsn > MyReplicationSlot->data.confirmed_flush)
    1931                 :          40 :             MyReplicationSlot->data.confirmed_flush = lsn;
    1932                 :             : 
    1933                 :             :         /* if we're past the location required for bumping xmin, do so */
    1934         [ +  + ]:         491 :         if (XLogRecPtrIsValid(MyReplicationSlot->candidate_xmin_lsn) &&
    1935         [ +  + ]:         146 :             MyReplicationSlot->candidate_xmin_lsn <= lsn)
    1936                 :             :         {
    1937                 :             :             /*
    1938                 :             :              * We have to write the changed xmin to disk *before* we change
    1939                 :             :              * the in-memory value, otherwise after a crash we wouldn't know
    1940                 :             :              * that some catalog tuples might have been removed already.
    1941                 :             :              *
    1942                 :             :              * Ensure that by first writing to ->xmin and only update
    1943                 :             :              * ->effective_xmin once the new state is synced to disk. After a
    1944                 :             :              * crash ->effective_xmin is set to ->xmin.
    1945                 :             :              */
    1946         [ +  - ]:          84 :             if (TransactionIdIsValid(MyReplicationSlot->candidate_catalog_xmin) &&
    1947         [ +  - ]:          84 :                 MyReplicationSlot->data.catalog_xmin != MyReplicationSlot->candidate_catalog_xmin)
    1948                 :             :             {
    1949                 :          84 :                 MyReplicationSlot->data.catalog_xmin = MyReplicationSlot->candidate_catalog_xmin;
    1950                 :          84 :                 MyReplicationSlot->candidate_catalog_xmin = InvalidTransactionId;
    1951                 :          84 :                 MyReplicationSlot->candidate_xmin_lsn = InvalidXLogRecPtr;
    1952                 :          84 :                 updated_xmin = true;
    1953                 :             :             }
    1954                 :             :         }
    1955                 :             : 
    1956         [ +  + ]:         491 :         if (XLogRecPtrIsValid(MyReplicationSlot->candidate_restart_valid) &&
    1957         [ +  + ]:         426 :             MyReplicationSlot->candidate_restart_valid <= lsn)
    1958                 :             :         {
    1959                 :             :             Assert(XLogRecPtrIsValid(MyReplicationSlot->candidate_restart_lsn));
    1960                 :             : 
    1961                 :         364 :             MyReplicationSlot->data.restart_lsn = MyReplicationSlot->candidate_restart_lsn;
    1962                 :         364 :             MyReplicationSlot->candidate_restart_lsn = InvalidXLogRecPtr;
    1963                 :         364 :             MyReplicationSlot->candidate_restart_valid = InvalidXLogRecPtr;
    1964                 :         364 :             updated_restart = true;
    1965                 :             :         }
    1966                 :             : 
    1967                 :         491 :         SpinLockRelease(&MyReplicationSlot->mutex);
    1968                 :             : 
    1969                 :             :         /* first write new xmin to disk, so we know what's up after a crash */
    1970   [ +  +  +  + ]:         491 :         if (updated_xmin || updated_restart)
    1971                 :             :         {
    1972                 :             : #ifdef USE_INJECTION_POINTS
    1973                 :             :             XLogSegNo   seg1,
    1974                 :             :                         seg2;
    1975                 :             : 
    1976                 :         429 :             XLByteToSeg(restart_lsn, seg1, wal_segment_size);
    1977                 :         429 :             XLByteToSeg(MyReplicationSlot->data.restart_lsn, seg2, wal_segment_size);
    1978                 :             : 
    1979                 :             :             /* trigger injection point, but only if segment changes */
    1980         [ +  + ]:         429 :             if (seg1 != seg2)
    1981                 :          17 :                 INJECTION_POINT("logical-replication-slot-advance-segment", NULL);
    1982                 :             : #endif
    1983                 :             : 
    1984                 :         429 :             ReplicationSlotMarkDirty();
    1985                 :         429 :             ReplicationSlotSave();
    1986         [ +  + ]:         429 :             elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
    1987                 :             :         }
    1988                 :             : 
    1989                 :             :         /*
    1990                 :             :          * Now the new xmin is safely on disk, we can let the global value
    1991                 :             :          * advance. We do not take ProcArrayLock or similar since we only
    1992                 :             :          * advance xmin here and there's not much harm done by a concurrent
    1993                 :             :          * computation missing that.
    1994                 :             :          */
    1995         [ +  + ]:         491 :         if (updated_xmin)
    1996                 :             :         {
    1997                 :          84 :             SpinLockAcquire(&MyReplicationSlot->mutex);
    1998                 :          84 :             MyReplicationSlot->effective_catalog_xmin = MyReplicationSlot->data.catalog_xmin;
    1999                 :          84 :             SpinLockRelease(&MyReplicationSlot->mutex);
    2000                 :             : 
    2001                 :          84 :             ReplicationSlotsComputeRequiredXmin(false);
    2002                 :             :         }
    2003                 :             : 
    2004                 :             :         /*
    2005                 :             :          * Now that the new restart_lsn is safely on disk, recompute the
    2006                 :             :          * global WAL retention requirement.
    2007                 :             :          */
    2008         [ +  + ]:         491 :         if (updated_restart)
    2009                 :         364 :             ReplicationSlotsComputeRequiredLSN();
    2010                 :             :     }
    2011                 :             :     else
    2012                 :             :     {
    2013                 :       21254 :         SpinLockAcquire(&MyReplicationSlot->mutex);
    2014                 :             : 
    2015                 :             :         /*
    2016                 :             :          * Prevent moving the confirmed_flush backwards. See comments above
    2017                 :             :          * for the details.
    2018                 :             :          */
    2019         [ +  + ]:       21254 :         if (lsn > MyReplicationSlot->data.confirmed_flush)
    2020                 :       20434 :             MyReplicationSlot->data.confirmed_flush = lsn;
    2021                 :             : 
    2022                 :       21254 :         SpinLockRelease(&MyReplicationSlot->mutex);
    2023                 :             :     }
    2024                 :       21745 : }
    2025                 :             : 
    2026                 :             : /*
    2027                 :             :  * Clear logical streaming state during (sub)transaction abort.
    2028                 :             :  */
    2029                 :             : void
    2030                 :       41595 : ResetLogicalStreamingState(void)
    2031                 :             : {
    2032                 :       41595 :     CheckXidAlive = InvalidTransactionId;
    2033                 :       41595 :     bsysscan = false;
    2034                 :       41595 : }
    2035                 :             : 
    2036                 :             : /*
    2037                 :             :  * Report stats for a slot.
    2038                 :             :  */
    2039                 :             : void
    2040                 :        6801 : UpdateDecodingStats(LogicalDecodingContext *ctx)
    2041                 :             : {
    2042                 :        6801 :     ReorderBuffer *rb = ctx->reorder;
    2043                 :             :     PgStat_StatReplSlotEntry repSlotStat;
    2044                 :             : 
    2045                 :             :     /* Nothing to do if we don't have any replication stats to be sent. */
    2046   [ +  +  +  +  :        6801 :     if (rb->spillBytes <= 0 && rb->streamBytes <= 0 && rb->totalBytes <= 0 &&
                   +  + ]
    2047         [ +  + ]:         460 :         rb->memExceededCount <= 0)
    2048                 :         451 :         return;
    2049                 :             : 
    2050         [ +  + ]:        6350 :     elog(DEBUG2, "UpdateDecodingStats: updating stats %p %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64,
    2051                 :             :          rb,
    2052                 :             :          rb->spillTxns,
    2053                 :             :          rb->spillCount,
    2054                 :             :          rb->spillBytes,
    2055                 :             :          rb->streamTxns,
    2056                 :             :          rb->streamCount,
    2057                 :             :          rb->streamBytes,
    2058                 :             :          rb->memExceededCount,
    2059                 :             :          rb->totalTxns,
    2060                 :             :          rb->totalBytes);
    2061                 :             : 
    2062                 :        6350 :     repSlotStat.spill_txns = rb->spillTxns;
    2063                 :        6350 :     repSlotStat.spill_count = rb->spillCount;
    2064                 :        6350 :     repSlotStat.spill_bytes = rb->spillBytes;
    2065                 :        6350 :     repSlotStat.stream_txns = rb->streamTxns;
    2066                 :        6350 :     repSlotStat.stream_count = rb->streamCount;
    2067                 :        6350 :     repSlotStat.stream_bytes = rb->streamBytes;
    2068                 :        6350 :     repSlotStat.mem_exceeded_count = rb->memExceededCount;
    2069                 :        6350 :     repSlotStat.total_txns = rb->totalTxns;
    2070                 :        6350 :     repSlotStat.total_bytes = rb->totalBytes;
    2071                 :             : 
    2072                 :        6350 :     pgstat_report_replslot(ctx->slot, &repSlotStat);
    2073                 :             : 
    2074                 :        6350 :     rb->spillTxns = 0;
    2075                 :        6350 :     rb->spillCount = 0;
    2076                 :        6350 :     rb->spillBytes = 0;
    2077                 :        6350 :     rb->streamTxns = 0;
    2078                 :        6350 :     rb->streamCount = 0;
    2079                 :        6350 :     rb->streamBytes = 0;
    2080                 :        6350 :     rb->memExceededCount = 0;
    2081                 :        6350 :     rb->totalTxns = 0;
    2082                 :        6350 :     rb->totalBytes = 0;
    2083                 :             : }
    2084                 :             : 
    2085                 :             : /*
    2086                 :             :  * Read up to the end of WAL starting from the decoding slot's restart_lsn
    2087                 :             :  * to end_of_wal in order to check if any meaningful/decodable WAL records
    2088                 :             :  * are encountered. scan_cutoff_lsn is the LSN, where we can terminate the
    2089                 :             :  * WAL scan early if we find a decodable WAL record after this LSN.
    2090                 :             :  *
    2091                 :             :  * Returns the last LSN decodable WAL record's LSN if found, otherwise
    2092                 :             :  * returns InvalidXLogRecPtr.
    2093                 :             :  */
    2094                 :             : XLogRecPtr
    2095                 :           4 : LogicalReplicationSlotCheckPendingWal(XLogRecPtr end_of_wal,
    2096                 :             :                                       XLogRecPtr scan_cutoff_lsn)
    2097                 :             : {
    2098                 :           4 :     XLogRecPtr  last_pending_wal = InvalidXLogRecPtr;
    2099                 :             : 
    2100                 :             :     Assert(MyReplicationSlot);
    2101                 :             :     Assert(end_of_wal >= scan_cutoff_lsn);
    2102                 :             : 
    2103         [ +  - ]:           4 :     PG_TRY();
    2104                 :             :     {
    2105                 :             :         LogicalDecodingContext *ctx;
    2106                 :             : 
    2107                 :             :         /*
    2108                 :             :          * Create our decoding context in fast_forward mode, passing start_lsn
    2109                 :             :          * as InvalidXLogRecPtr, so that we start processing from the slot's
    2110                 :             :          * confirmed_flush.
    2111                 :             :          */
    2112                 :           8 :         ctx = CreateDecodingContext(InvalidXLogRecPtr,
    2113                 :             :                                     NIL,
    2114                 :             :                                     true,   /* fast_forward */
    2115                 :           4 :                                     XL_ROUTINE(.page_read = read_local_xlog_page,
    2116                 :             :                                                .segment_open = wal_segment_open,
    2117                 :             :                                                .segment_close = wal_segment_close),
    2118                 :             :                                     NULL, NULL, NULL);
    2119                 :             : 
    2120                 :             :         /*
    2121                 :             :          * Start reading at the slot's restart_lsn, which we know points to a
    2122                 :             :          * valid record.
    2123                 :             :          */
    2124                 :           4 :         XLogBeginRead(ctx->reader, MyReplicationSlot->data.restart_lsn);
    2125                 :             : 
    2126                 :             :         /* Invalidate non-timetravel entries */
    2127                 :           4 :         InvalidateSystemCaches();
    2128                 :             : 
    2129         [ +  + ]:          88 :         while (ctx->reader->EndRecPtr < end_of_wal)
    2130                 :             :         {
    2131                 :             :             XLogRecord *record;
    2132                 :          84 :             char       *errm = NULL;
    2133                 :             : 
    2134                 :          84 :             record = XLogReadRecord(ctx->reader, &errm);
    2135                 :             : 
    2136         [ -  + ]:          84 :             if (errm)
    2137         [ #  # ]:           0 :                 elog(ERROR, "could not find record for logical decoding: %s", errm);
    2138                 :             : 
    2139         [ +  - ]:          84 :             if (record != NULL)
    2140                 :          84 :                 LogicalDecodingProcessRecord(ctx, ctx->reader);
    2141                 :             : 
    2142         [ +  + ]:          84 :             if (ctx->processing_required)
    2143                 :             :             {
    2144                 :           2 :                 last_pending_wal = ctx->reader->ReadRecPtr;
    2145                 :             : 
    2146                 :             :                 /*
    2147                 :             :                  * If we find a decodable WAL after the scan_cutoff_lsn point,
    2148                 :             :                  * we can terminate the scan early.
    2149                 :             :                  */
    2150         [ -  + ]:           2 :                 if (last_pending_wal >= scan_cutoff_lsn)
    2151                 :           0 :                     break;
    2152                 :             : 
    2153                 :             :                 /* Reset the flag and continue checking */
    2154                 :           2 :                 ctx->processing_required = false;
    2155                 :             :             }
    2156                 :             : 
    2157         [ -  + ]:          84 :             CHECK_FOR_INTERRUPTS();
    2158                 :             :         }
    2159                 :             : 
    2160                 :             :         /* Clean up */
    2161                 :           4 :         FreeDecodingContext(ctx);
    2162                 :           4 :         InvalidateSystemCaches();
    2163                 :             :     }
    2164                 :           0 :     PG_CATCH();
    2165                 :             :     {
    2166                 :             :         /* clear all timetravel entries */
    2167                 :           0 :         InvalidateSystemCaches();
    2168                 :             : 
    2169                 :           0 :         PG_RE_THROW();
    2170                 :             :     }
    2171         [ -  + ]:           4 :     PG_END_TRY();
    2172                 :             : 
    2173                 :           4 :     return last_pending_wal;
    2174                 :             : }
    2175                 :             : 
    2176                 :             : /*
    2177                 :             :  * Helper function for advancing our logical replication slot forward.
    2178                 :             :  *
    2179                 :             :  * The slot's restart_lsn is used as start point for reading records, while
    2180                 :             :  * confirmed_flush is used as base point for the decoding context.
    2181                 :             :  *
    2182                 :             :  * We cannot just do LogicalConfirmReceivedLocation to update confirmed_flush,
    2183                 :             :  * because we need to digest WAL to advance restart_lsn allowing to recycle
    2184                 :             :  * WAL and removal of old catalog tuples.  As decoding is done in fast_forward
    2185                 :             :  * mode, no changes are generated anyway.
    2186                 :             :  *
    2187                 :             :  * *found_consistent_snapshot will be true if the initial decoding snapshot has
    2188                 :             :  * been built; Otherwise, it will be false.
    2189                 :             :  */
    2190                 :             : XLogRecPtr
    2191                 :          22 : LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto,
    2192                 :             :                                     bool *found_consistent_snapshot)
    2193                 :             : {
    2194                 :             :     LogicalDecodingContext *ctx;
    2195                 :             :     XLogRecPtr  retlsn;
    2196                 :             : 
    2197                 :             :     Assert(XLogRecPtrIsValid(moveto));
    2198                 :             : 
    2199         [ +  + ]:          22 :     if (found_consistent_snapshot)
    2200                 :          11 :         *found_consistent_snapshot = false;
    2201                 :             : 
    2202         [ +  - ]:          22 :     PG_TRY();
    2203                 :             :     {
    2204                 :             :         /*
    2205                 :             :          * Create our decoding context in fast_forward mode, passing start_lsn
    2206                 :             :          * as InvalidXLogRecPtr, so that we start processing from my slot's
    2207                 :             :          * confirmed_flush.
    2208                 :             :          */
    2209                 :          44 :         ctx = CreateDecodingContext(InvalidXLogRecPtr,
    2210                 :             :                                     NIL,
    2211                 :             :                                     true,   /* fast_forward */
    2212                 :          22 :                                     XL_ROUTINE(.page_read = read_local_xlog_page,
    2213                 :             :                                                .segment_open = wal_segment_open,
    2214                 :             :                                                .segment_close = wal_segment_close),
    2215                 :             :                                     NULL, NULL, NULL);
    2216                 :             : 
    2217                 :             :         /*
    2218                 :             :          * Wait for specified streaming replication standby servers (if any)
    2219                 :             :          * to confirm receipt of WAL up to moveto lsn.
    2220                 :             :          */
    2221                 :          22 :         WaitForStandbyConfirmation(moveto);
    2222                 :             : 
    2223                 :             :         /*
    2224                 :             :          * Start reading at the slot's restart_lsn, which we know to point to
    2225                 :             :          * a valid record.
    2226                 :             :          */
    2227                 :          22 :         XLogBeginRead(ctx->reader, MyReplicationSlot->data.restart_lsn);
    2228                 :             : 
    2229                 :             :         /* invalidate non-timetravel entries */
    2230                 :          22 :         InvalidateSystemCaches();
    2231                 :             : 
    2232                 :             :         /* Decode records until we reach the requested target */
    2233         [ +  + ]:        2943 :         while (ctx->reader->EndRecPtr < moveto)
    2234                 :             :         {
    2235                 :        2921 :             char       *errm = NULL;
    2236                 :             :             XLogRecord *record;
    2237                 :             : 
    2238                 :             :             /*
    2239                 :             :              * Read records.  No changes are generated in fast_forward mode,
    2240                 :             :              * but snapbuilder/slot statuses are updated properly.
    2241                 :             :              */
    2242                 :        2921 :             record = XLogReadRecord(ctx->reader, &errm);
    2243         [ -  + ]:        2921 :             if (errm)
    2244         [ #  # ]:           0 :                 elog(ERROR, "could not find record while advancing replication slot: %s",
    2245                 :             :                      errm);
    2246                 :             : 
    2247                 :             :             /*
    2248                 :             :              * Process the record.  Storage-level changes are ignored in
    2249                 :             :              * fast_forward mode, but other modules (such as snapbuilder)
    2250                 :             :              * might still have critical updates to do.
    2251                 :             :              */
    2252         [ +  - ]:        2921 :             if (record)
    2253                 :        2921 :                 LogicalDecodingProcessRecord(ctx, ctx->reader);
    2254                 :             : 
    2255         [ -  + ]:        2921 :             CHECK_FOR_INTERRUPTS();
    2256                 :             :         }
    2257                 :             : 
    2258   [ +  +  +  - ]:          22 :         if (found_consistent_snapshot && DecodingContextReady(ctx))
    2259                 :          11 :             *found_consistent_snapshot = true;
    2260                 :             : 
    2261         [ +  - ]:          22 :         if (XLogRecPtrIsValid(ctx->reader->EndRecPtr))
    2262                 :             :         {
    2263                 :          22 :             LogicalConfirmReceivedLocation(moveto);
    2264                 :             : 
    2265                 :             :             /*
    2266                 :             :              * If only the confirmed_flush LSN has changed the slot won't get
    2267                 :             :              * marked as dirty by the above. Callers on the walsender
    2268                 :             :              * interface are expected to keep track of their own progress and
    2269                 :             :              * don't need it written out. But SQL-interface users cannot
    2270                 :             :              * specify their own start positions and it's harder for them to
    2271                 :             :              * keep track of their progress, so we should make more of an
    2272                 :             :              * effort to save it for them.
    2273                 :             :              *
    2274                 :             :              * Dirty the slot so it is written out at the next checkpoint. The
    2275                 :             :              * LSN position advanced to may still be lost on a crash but this
    2276                 :             :              * makes the data consistent after a clean shutdown.
    2277                 :             :              */
    2278                 :          22 :             ReplicationSlotMarkDirty();
    2279                 :             :         }
    2280                 :             : 
    2281                 :          22 :         retlsn = MyReplicationSlot->data.confirmed_flush;
    2282                 :             : 
    2283                 :             :         /* free context, call shutdown callback */
    2284                 :          22 :         FreeDecodingContext(ctx);
    2285                 :             : 
    2286                 :          22 :         InvalidateSystemCaches();
    2287                 :             :     }
    2288                 :           0 :     PG_CATCH();
    2289                 :             :     {
    2290                 :             :         /* clear all timetravel entries */
    2291                 :           0 :         InvalidateSystemCaches();
    2292                 :             : 
    2293                 :           0 :         PG_RE_THROW();
    2294                 :             :     }
    2295         [ -  + ]:          22 :     PG_END_TRY();
    2296                 :             : 
    2297                 :          22 :     return retlsn;
    2298                 :             : }
        

Generated by: LCOV version 2.0-1