From 9b1b06fa5541aa643fcb8133bdd1e1bf4c433949 Mon Sep 17 00:00:00 2001
From: root <root@vm-pgsrc.voh31zlp2kzufgr23fvzpey3uf.xx.internal.cloudapp.net>
Date: Thu, 23 Dec 2021 21:43:56 +0000
Subject: [PATCH] Add xlog_insert_hook to give control to the plugins on the
 WAL write actions. This helps solve scenarios like WAL rate governance,
 throttling the writes based on the policies defined by the plugin owners.

---
 src/backend/access/transam/xloginsert.c | 9 +++++++++
 src/include/access/xlog.h               | 5 +++++
 2 files changed, 14 insertions(+)

diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 689384a411..c9c5bb4f1d 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -128,6 +128,9 @@ static XLogRecData *XLogRecordAssemble(RmgrId rmid, uint8 info,
 static bool XLogCompressBackupBlock(char *page, uint16 hole_offset,
 									uint16 hole_length, char *dest, uint16 *dlen);
 
+/* Hook for plugins to get control in xlog_insert() */
+xlog_insert_hook_type xlog_insert_hook = NULL;
+
 /*
  * Begin constructing a WAL record. This must be called before the
  * XLogRegister* functions and XLogInsert().
@@ -456,6 +459,12 @@ XLogInsert(RmgrId rmid, uint8 info)
 		return EndPos;
 	}
 
+	/*
+	 * Allow a plugin to take action on inserting a new WAL record.
+	 */
+	if (xlog_insert_hook)
+		(*xlog_insert_hook)();
+
 	do
 	{
 		XLogRecPtr	RedoRecPtr;
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index 34f6c89f06..cf761fbc1c 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -299,6 +299,7 @@ extern void BootStrapXLOG(void);
 extern void LocalProcessControlFile(bool reset);
 extern void StartupXLOG(void);
 extern void ShutdownXLOG(int code, Datum arg);
+extern void InitXLOGAccess(void);
 extern void CreateCheckPoint(int flags);
 extern bool CreateRestartPoint(int flags);
 extern WALAvailability GetWALAvailability(XLogRecPtr targetLSN);
@@ -367,4 +368,8 @@ extern SessionBackupState get_backup_status(void);
 /* files to signal promotion to primary */
 #define PROMOTE_SIGNAL_FILE		"promote"
 
+/* hook for plugins to get control in XlogInsert */
+typedef void (*xlog_insert_hook_type) (void);
+extern PGDLLIMPORT xlog_insert_hook_type xlog_insert_hook;
+
 #endif							/* XLOG_H */
-- 
2.17.1

