@@ -4,11 +4,14 @@ import (
4
4
"context"
5
5
"encoding/base64"
6
6
"fmt"
7
+ "log"
7
8
"os"
9
+ "time"
8
10
9
11
"github.com/fly-apps/postgres-flex/internal/flypg"
10
12
"github.com/fly-apps/postgres-flex/internal/flypg/admin"
11
13
"github.com/fly-apps/postgres-flex/internal/utils"
14
+ "github.com/jackc/pgx/v5"
12
15
)
13
16
14
17
func main () {
@@ -49,20 +52,43 @@ func processUnregistration(ctx context.Context) error {
49
52
return fmt .Errorf ("failed to unregister member: %v" , err )
50
53
}
51
54
52
- slots , err := admin . ListReplicationSlots ( ctx , conn )
53
- if err != nil {
54
- return fmt . Errorf ( "failed to list replication slots: %v" , err )
55
+ slotName := fmt . Sprintf ( "repmgr_slot_%d" , member . ID )
56
+ if err := removeReplicationSlot ( ctx , conn , slotName ); err != nil {
57
+ return err
55
58
}
56
59
57
- targetSlot := fmt .Sprintf ("repmgr_slot_%d" , member .ID )
58
- for _ , slot := range slots {
59
- if slot .Name == targetSlot {
60
- if err := admin .DropReplicationSlot (ctx , conn , targetSlot ); err != nil {
61
- return fmt .Errorf ("failed to drop replication slot: %v" , err )
60
+ return nil
61
+ }
62
+
63
+ func removeReplicationSlot (ctx context.Context , conn * pgx.Conn , slotName string ) error {
64
+ ticker := time .NewTicker (1 * time .Second )
65
+ timeout := time .After (10 * time .Second )
66
+ defer ticker .Stop ()
67
+ for {
68
+ select {
69
+ case <- ctx .Done ():
70
+ return ctx .Err ()
71
+ case <- timeout :
72
+ return fmt .Errorf ("timed out trying to drop replication slot" )
73
+ case <- ticker .C :
74
+ slot , err := admin .GetReplicationSlot (ctx , conn , slotName )
75
+ if err != nil {
76
+ if err == pgx .ErrNoRows {
77
+ return nil
78
+ }
79
+ return fmt .Errorf ("failed to get replication slot %s: %v" , slotName , err )
80
+ }
81
+
82
+ if slot .Active {
83
+ log .Printf ("Slot %s is still active, waiting..." , slotName )
84
+ continue
62
85
}
63
- break
86
+
87
+ if err := admin .DropReplicationSlot (ctx , conn , slotName ); err != nil {
88
+ return fmt .Errorf ("failed to drop replication slot %s: %v" , slotName , err )
89
+ }
90
+
91
+ return nil
64
92
}
65
93
}
66
-
67
- return nil
68
94
}
0 commit comments