epgsql_sock.erl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. %%% @doc GenServer holding all the connection state (including socket).
  2. %%%
  3. %%% See [https://www.postgresql.org/docs/current/static/protocol-flow.html]
  4. %%%
  5. %%% Commands in PostgreSQL protocol are pipelined: you don't have to wait for
  6. %%% reply to be able to send next command.
  7. %%% Commands are processed (and responses to them are generated) in FIFO order.
  8. %%% eg, if you execute 2 SimpleQuery: #1 and #2, first you get all response
  9. %%% packets for #1 and then all for #2:
  10. %%% ```
  11. %%% > SQuery #1
  12. %%% > SQuery #2
  13. %%% < RowDescription #1
  14. %%% < DataRow #1.1
  15. %%% < ...
  16. %%% < DataRow #1.N
  17. %%% < CommandComplete #1
  18. %%% < RowDescription #2
  19. %%% < DataRow #2.1
  20. %%% < ...
  21. %%% < DataRow #2.N
  22. %%% < CommandComplete #2
  23. %%% '''
  24. %%% `epgsql_sock' is capable of utilizing the pipelining feature - as soon as
  25. %%% it receives a new command, it sends it to the server immediately and then
  26. %%% it puts command's callbacks and state into internal queue of all the commands
  27. %%% which were sent to the server and waiting for response. So it knows in which
  28. %%% order it should call each pipelined command's `handle_message' callback.
  29. %%% But it can be easily broken if high-level command is poorly implemented or
  30. %%% some conflicting low-level commands (such as `parse', `bind', `execute') are
  31. %%% executed in a wrong order. In this case server and epgsql states become out of
  32. %%% sync and {@link epgsql_cmd_sync} have to be executed in order to recover.
  33. %%% @see epgsql_cmd_connect. epgsql_cmd_connect for network connection and authentication setup
  34. %%% @end
  35. %%% Copyright (C) 2009 - Will Glozer. All rights reserved.
  36. %%% Copyright (C) 2011 - Anton Lebedevich. All rights reserved.
  37. -module(epgsql_sock).
  38. -behavior(gen_server).
  39. -export([start_link/0,
  40. close/1,
  41. sync_command/3,
  42. async_command/4,
  43. get_parameter/2,
  44. set_notice_receiver/2,
  45. get_cmd_status/1,
  46. cancel/1]).
  47. -export([handle_call/3, handle_cast/2, handle_info/2]).
  48. -export([init/1, code_change/3, terminate/2]).
  49. %% loop callback
  50. -export([on_message/3, on_replication/3]).
  51. %% Comand's APIs
  52. -export([set_net_socket/3, init_replication_state/1, set_attr/3, get_codec/1,
  53. get_rows/1, get_results/1, notify/2, send/2, send/3, send_multi/2,
  54. get_parameter_internal/2,
  55. get_replication_state/1, set_packet_handler/2]).
  56. -export_type([transport/0, pg_sock/0, error/0]).
  57. -include("epgsql.hrl").
  58. -include("protocol.hrl").
  59. -include("epgsql_replication.hrl").
  60. -type transport() :: {call, any()}
  61. | {cast, pid(), reference()}
  62. | {incremental, pid(), reference()}.
  63. -type tcp_socket() :: port(). %gen_tcp:socket() isn't exported prior to erl 18
  64. -type repl_state() :: #repl{}.
  65. -type error() :: {error, sync_required | closed | sock_closed | sock_error}.
  66. -record(state, {mod :: gen_tcp | ssl | undefined,
  67. sock :: tcp_socket() | ssl:sslsocket() | undefined,
  68. data = <<>>,
  69. backend :: {Pid :: integer(), Key :: integer()} | undefined,
  70. handler = on_message :: on_message | on_replication | undefined,
  71. codec :: epgsql_binary:codec() | undefined,
  72. queue = queue:new() :: queue:queue({epgsql_command:command(), any(), transport()}),
  73. current_cmd :: epgsql_command:command() | undefined,
  74. current_cmd_state :: any() | undefined,
  75. current_cmd_transport :: transport() | undefined,
  76. async :: undefined | atom() | pid(),
  77. parameters = [] :: [{Key :: binary(), Value :: binary()}],
  78. rows = [] :: [tuple()],
  79. results = [],
  80. sync_required :: boolean() | undefined,
  81. txstatus :: byte() | undefined, % $I | $T | $E,
  82. complete_status :: atom() | {atom(), integer()} | undefined,
  83. repl :: repl_state() | undefined}).
  84. -opaque pg_sock() :: #state{}.
  85. %% -- client interface --
  86. start_link() ->
  87. gen_server:start_link(?MODULE, [], []).
  88. close(C) when is_pid(C) ->
  89. catch gen_server:cast(C, stop),
  90. ok.
  91. -spec sync_command(epgsql:connection(), epgsql_command:command(), any()) -> any().
  92. sync_command(C, Command, Args) ->
  93. gen_server:call(C, {command, Command, Args}, infinity).
  94. -spec async_command(epgsql:connection(), cast | incremental,
  95. epgsql_command:command(), any()) -> reference().
  96. async_command(C, Transport, Command, Args) ->
  97. Ref = make_ref(),
  98. Pid = self(),
  99. ok = gen_server:cast(C, {{Transport, Pid, Ref}, Command, Args}),
  100. Ref.
  101. get_parameter(C, Name) ->
  102. gen_server:call(C, {get_parameter, to_binary(Name)}, infinity).
  103. set_notice_receiver(C, PidOrName) when is_pid(PidOrName);
  104. is_atom(PidOrName) ->
  105. gen_server:call(C, {set_async_receiver, PidOrName}, infinity).
  106. get_cmd_status(C) ->
  107. gen_server:call(C, get_cmd_status, infinity).
  108. cancel(S) ->
  109. gen_server:cast(S, cancel).
  110. %% -- command APIs --
  111. %% send()
  112. %% send_many()
  113. -spec set_net_socket(gen_tcp | ssl, tcp_socket() | ssl:sslsocket(), pg_sock()) -> pg_sock().
  114. set_net_socket(Mod, Socket, State) ->
  115. State1 = State#state{mod = Mod, sock = Socket},
  116. setopts(State1, [{active, true}]),
  117. State1.
  118. -spec init_replication_state(pg_sock()) -> pg_sock().
  119. init_replication_state(State) ->
  120. State#state{repl = #repl{}}.
  121. -spec set_attr(atom(), any(), pg_sock()) -> pg_sock().
  122. set_attr(backend, {_Pid, _Key} = Backend, State) ->
  123. State#state{backend = Backend};
  124. set_attr(async, Async, State) ->
  125. State#state{async = Async};
  126. set_attr(txstatus, Status, State) ->
  127. State#state{txstatus = Status};
  128. set_attr(codec, Codec, State) ->
  129. State#state{codec = Codec};
  130. set_attr(sync_required, Value, State) ->
  131. State#state{sync_required = Value};
  132. set_attr(replication_state, Value, State) ->
  133. State#state{repl = Value}.
  134. %% XXX: be careful!
  135. -spec set_packet_handler(atom(), pg_sock()) -> pg_sock().
  136. set_packet_handler(Handler, State) ->
  137. State#state{handler = Handler}.
  138. -spec get_codec(pg_sock()) -> epgsql_binary:codec().
  139. get_codec(#state{codec = Codec}) ->
  140. Codec.
  141. -spec get_replication_state(pg_sock()) -> repl_state().
  142. get_replication_state(#state{repl = Repl}) ->
  143. Repl.
  144. -spec get_rows(pg_sock()) -> [tuple()].
  145. get_rows(#state{rows = Rows}) ->
  146. lists:reverse(Rows).
  147. -spec get_results(pg_sock()) -> [any()].
  148. get_results(#state{results = Results}) ->
  149. lists:reverse(Results).
  150. -spec get_parameter_internal(binary(), pg_sock()) -> binary() | undefined.
  151. get_parameter_internal(Name, #state{parameters = Parameters}) ->
  152. case lists:keysearch(Name, 1, Parameters) of
  153. {value, {Name, Value}} -> Value;
  154. false -> undefined
  155. end.
  156. %% -- gen_server implementation --
  157. init([]) ->
  158. {ok, #state{}}.
  159. handle_call({get_parameter, Name}, _From, State) ->
  160. {reply, {ok, get_parameter_internal(Name, State)}, State};
  161. handle_call({set_async_receiver, PidOrName}, _From, #state{async = Previous} = State) ->
  162. {reply, {ok, Previous}, State#state{async = PidOrName}};
  163. handle_call(get_cmd_status, _From, #state{complete_status = Status} = State) ->
  164. {reply, {ok, Status}, State};
  165. handle_call({standby_status_update, FlushedLSN, AppliedLSN}, _From,
  166. #state{handler = on_replication,
  167. repl = #repl{last_received_lsn = ReceivedLSN} = Repl} = State) ->
  168. send(State, ?COPY_DATA, epgsql_wire:encode_standby_status_update(ReceivedLSN, FlushedLSN, AppliedLSN)),
  169. Repl1 = Repl#repl{last_flushed_lsn = FlushedLSN,
  170. last_applied_lsn = AppliedLSN},
  171. {reply, ok, State#state{repl = Repl1}};
  172. handle_call({command, Command, Args}, From, State) ->
  173. Transport = {call, From},
  174. command_new(Transport, Command, Args, State).
  175. handle_cast({{Method, From, Ref} = Transport, Command, Args}, State)
  176. when ((Method == cast) or (Method == incremental)),
  177. is_pid(From),
  178. is_reference(Ref) ->
  179. command_new(Transport, Command, Args, State);
  180. handle_cast(stop, State) ->
  181. send(State, ?TERMINATE, []),
  182. {stop, normal, flush_queue(State, {error, closed})};
  183. handle_cast(cancel, State = #state{backend = {Pid, Key},
  184. sock = TimedOutSock}) ->
  185. {ok, {Addr, Port}} = case State#state.mod of
  186. gen_tcp -> inet:peername(TimedOutSock);
  187. ssl -> ssl:peername(TimedOutSock)
  188. end,
  189. SockOpts = [{active, false}, {packet, raw}, binary],
  190. %% TODO timeout
  191. {ok, Sock} = gen_tcp:connect(Addr, Port, SockOpts),
  192. Msg = <<16:?int32, 80877102:?int32, Pid:?int32, Key:?int32>>,
  193. ok = gen_tcp:send(Sock, Msg),
  194. gen_tcp:close(Sock),
  195. {noreply, State}.
  196. handle_info({Closed, Sock}, #state{sock = Sock} = State)
  197. when Closed == tcp_closed; Closed == ssl_closed ->
  198. {stop, sock_closed, flush_queue(State#state{sock = undefined}, {error, sock_closed})};
  199. handle_info({Error, Sock, Reason}, #state{sock = Sock} = State)
  200. when Error == tcp_error; Error == ssl_error ->
  201. Why = {sock_error, Reason},
  202. {stop, Why, flush_queue(State, {error, Why})};
  203. handle_info({inet_reply, _, ok}, State) ->
  204. {noreply, State};
  205. handle_info({inet_reply, _, Status}, State) ->
  206. {stop, Status, flush_queue(State, {error, Status})};
  207. handle_info({_, Sock, Data2}, #state{data = Data, sock = Sock} = State) ->
  208. loop(State#state{data = <<Data/binary, Data2/binary>>}).
  209. terminate(_Reason, #state{sock = undefined}) -> ok;
  210. terminate(_Reason, #state{mod = gen_tcp, sock = Sock}) -> gen_tcp:close(Sock);
  211. terminate(_Reason, #state{mod = ssl, sock = Sock}) -> ssl:close(Sock).
  212. code_change(_OldVsn, State, _Extra) ->
  213. {ok, State}.
  214. %% -- internal functions --
  215. -spec command_new(transport(), epgsql_command:command(), any(), pg_sock()) ->
  216. Result when
  217. Result :: {noreply, pg_sock()}
  218. | {stop, Reason :: any(), pg_sock()}.
  219. command_new(Transport, Command, Args, State) ->
  220. CmdState = epgsql_command:init(Command, Args),
  221. command_exec(Transport, Command, CmdState, State).
  222. -spec command_exec(transport(), epgsql_command:command(), any(), pg_sock()) ->
  223. Result when
  224. Result :: {noreply, pg_sock()}
  225. | {stop, Reason :: any(), pg_sock()}.
  226. command_exec(Transport, Command, _, State = #state{sync_required = true})
  227. when Command /= epgsql_cmd_sync ->
  228. {noreply,
  229. finish(State#state{current_cmd = Command,
  230. current_cmd_transport = Transport},
  231. {error, sync_required})};
  232. command_exec(Transport, Command, CmdState, State) ->
  233. case epgsql_command:execute(Command, State, CmdState) of
  234. {ok, State1, CmdState1} ->
  235. {noreply, command_enqueue(Transport, Command, CmdState1, State1)};
  236. {stop, StopReason, Response, State1} ->
  237. reply(Transport, Response, Response),
  238. {stop, StopReason, State1}
  239. end.
  240. -spec command_enqueue(transport(), epgsql_command:command(), epgsql_command:state(), pg_sock()) -> pg_sock().
  241. command_enqueue(Transport, Command, CmdState, #state{current_cmd = undefined} = State) ->
  242. State#state{current_cmd = Command,
  243. current_cmd_state = CmdState,
  244. current_cmd_transport = Transport,
  245. complete_status = undefined};
  246. command_enqueue(Transport, Command, CmdState, #state{queue = Q} = State) ->
  247. State#state{queue = queue:in({Command, CmdState, Transport}, Q),
  248. complete_status = undefined}.
  249. -spec command_handle_message(byte(), binary() | epgsql:query_error(), pg_sock()) ->
  250. {noreply, pg_sock()}
  251. | {stop, any(), pg_sock()}.
  252. command_handle_message(Msg, Payload,
  253. #state{current_cmd = Command,
  254. current_cmd_state = CmdState} = State) ->
  255. case epgsql_command:handle_message(Command, Msg, Payload, State, CmdState) of
  256. {add_row, Row, State1, CmdState1} ->
  257. {noreply, add_row(State1#state{current_cmd_state = CmdState1}, Row)};
  258. {add_result, Result, Notice, State1, CmdState1} ->
  259. {noreply,
  260. add_result(State1#state{current_cmd_state = CmdState1},
  261. Notice, Result)};
  262. {finish, Result, Notice, State1} ->
  263. {noreply, finish(State1, Notice, Result)};
  264. {noaction, State1} ->
  265. {noreply, State1};
  266. {noaction, State1, CmdState1} ->
  267. {noreply, State1#state{current_cmd_state = CmdState1}};
  268. {requeue, State1, CmdState1} ->
  269. Transport = State1#state.current_cmd_transport,
  270. command_exec(Transport, Command, CmdState1,
  271. State1#state{current_cmd = undefined});
  272. {stop, Reason, Response, State1} ->
  273. {stop, Reason, finish(State1, Response)};
  274. {sync_required, Why} ->
  275. %% Protocol error. Finish and flush all pending commands.
  276. {noreply, sync_required(finish(State#state{sync_required = true}, Why))};
  277. unknown ->
  278. {stop, {error, {unexpected_message, Msg, Command, CmdState}}, State}
  279. end.
  280. command_next(#state{current_cmd = PrevCmd,
  281. queue = Q} = State) when PrevCmd =/= undefined ->
  282. case queue:out(Q) of
  283. {empty, _} ->
  284. State#state{current_cmd = undefined,
  285. current_cmd_state = undefined,
  286. current_cmd_transport = undefined,
  287. rows = [],
  288. results = []};
  289. {{value, {Command, CmdState, Transport}}, Q1} ->
  290. State#state{current_cmd = Command,
  291. current_cmd_state = CmdState,
  292. current_cmd_transport = Transport,
  293. queue = Q1,
  294. rows = [],
  295. results = []}
  296. end.
  297. setopts(#state{mod = Mod, sock = Sock}, Opts) ->
  298. case Mod of
  299. gen_tcp -> inet:setopts(Sock, Opts);
  300. ssl -> ssl:setopts(Sock, Opts)
  301. end.
  302. %% This one only used in connection initiation to send client's
  303. %% `StartupMessage' and `SSLRequest' packets
  304. -spec send(pg_sock(), iodata()) -> ok | {error, any()}.
  305. send(#state{mod = Mod, sock = Sock}, Data) ->
  306. do_send(Mod, Sock, epgsql_wire:encode_command(Data)).
  307. -spec send(pg_sock(), byte(), iodata()) -> ok | {error, any()}.
  308. send(#state{mod = Mod, sock = Sock}, Type, Data) ->
  309. do_send(Mod, Sock, epgsql_wire:encode_command(Type, Data)).
  310. -spec send_multi(pg_sock(), [{byte(), iodata()}]) -> ok | {error, any()}.
  311. send_multi(#state{mod = Mod, sock = Sock}, List) ->
  312. do_send(Mod, Sock, lists:map(fun({Type, Data}) ->
  313. epgsql_wire:encode_command(Type, Data)
  314. end, List)).
  315. do_send(gen_tcp, Sock, Bin) ->
  316. %% Why not gen_tcp:send/2?
  317. %% See https://github.com/rabbitmq/rabbitmq-common/blob/v3.7.4/src/rabbit_writer.erl#L367-L384
  318. %% Because of that we also have `handle_info({inet_reply, ...`
  319. try erlang:port_command(Sock, Bin) of
  320. true ->
  321. ok
  322. catch
  323. error:_Error ->
  324. {error, einval}
  325. end;
  326. do_send(ssl, Sock, Bin) ->
  327. ssl:send(Sock, Bin).
  328. loop(#state{data = Data, handler = Handler, repl = Repl} = State) ->
  329. case epgsql_wire:decode_message(Data) of
  330. {Type, Payload, Tail} ->
  331. case ?MODULE:Handler(Type, Payload, State#state{data = Tail}) of
  332. {noreply, State2} ->
  333. loop(State2);
  334. R = {stop, _Reason2, _State2} ->
  335. R
  336. end;
  337. _ ->
  338. %% in replication mode send feedback after each batch of messages
  339. case (Repl =/= undefined) andalso (Repl#repl.feedback_required) of
  340. true ->
  341. #repl{last_received_lsn = LastReceivedLSN,
  342. last_flushed_lsn = LastFlushedLSN,
  343. last_applied_lsn = LastAppliedLSN} = Repl,
  344. send(State, ?COPY_DATA, epgsql_wire:encode_standby_status_update(
  345. LastReceivedLSN, LastFlushedLSN, LastAppliedLSN)),
  346. {noreply, State#state{repl = Repl#repl{feedback_required = false}}};
  347. _ ->
  348. {noreply, State}
  349. end
  350. end.
  351. finish(State, Result) ->
  352. finish(State, Result, Result).
  353. finish(State = #state{current_cmd_transport = Transport}, Notice, Result) ->
  354. reply(Transport, Notice, Result),
  355. command_next(State).
  356. reply({cast, From, Ref}, _, Result) ->
  357. From ! {self(), Ref, Result};
  358. reply({incremental, From, Ref}, Notice, _) ->
  359. From ! {self(), Ref, Notice};
  360. reply({call, From}, _, Result) ->
  361. gen_server:reply(From, Result).
  362. add_result(#state{results = Results, current_cmd_transport = Transport} = State, Notice, Result) ->
  363. Results2 = case Transport of
  364. {incremental, From, Ref} ->
  365. From ! {self(), Ref, Notice},
  366. Results;
  367. _ ->
  368. [Result | Results]
  369. end,
  370. State#state{rows = [],
  371. results = Results2}.
  372. add_row(#state{rows = Rows, current_cmd_transport = Transport} = State, Data) ->
  373. Rows2 = case Transport of
  374. {incremental, From, Ref} ->
  375. From ! {self(), Ref, {data, Data}},
  376. Rows;
  377. _ ->
  378. [Data | Rows]
  379. end,
  380. State#state{rows = Rows2}.
  381. notify(#state{current_cmd_transport = {incremental, From, Ref}} = State, Notice) ->
  382. From ! {self(), Ref, Notice},
  383. State;
  384. notify(State, _) ->
  385. State.
  386. %% Send asynchronous messages (notice / notification)
  387. notify_async(#state{async = undefined}, _) ->
  388. false;
  389. notify_async(#state{async = PidOrName}, Msg) ->
  390. try PidOrName ! {epgsql, self(), Msg} of
  391. _ -> true
  392. catch error:badarg ->
  393. %% no process registered under this name
  394. false
  395. end.
  396. sync_required(#state{current_cmd = epgsql_cmd_sync} = State) ->
  397. State;
  398. sync_required(#state{current_cmd = undefined} = State) ->
  399. State#state{sync_required = true};
  400. sync_required(State) ->
  401. sync_required(finish(State, {error, sync_required})).
  402. flush_queue(#state{current_cmd = undefined} = State, _) ->
  403. State;
  404. flush_queue(State, Error) ->
  405. flush_queue(finish(State, Error), Error).
  406. to_binary(B) when is_binary(B) -> B;
  407. to_binary(L) when is_list(L) -> list_to_binary(L).
  408. %% -- backend message handling --
  409. %% CommandComplete
  410. on_message(?COMMAND_COMPLETE = Msg, Bin, State) ->
  411. Complete = epgsql_wire:decode_complete(Bin),
  412. command_handle_message(Msg, Bin, State#state{complete_status = Complete});
  413. %% ReadyForQuery
  414. on_message(?READY_FOR_QUERY = Msg, <<Status:8>> = Bin, State) ->
  415. command_handle_message(Msg, Bin, State#state{txstatus = Status});
  416. %% Error
  417. on_message(?ERROR = Msg, Err, #state{current_cmd = CurrentCmd} = State) ->
  418. Reason = epgsql_wire:decode_error(Err),
  419. case CurrentCmd of
  420. undefined ->
  421. %% Message generated by server asynchronously
  422. {stop, {shutdown, Reason}, State};
  423. _ ->
  424. command_handle_message(Msg, Reason, State)
  425. end;
  426. %% NoticeResponse
  427. on_message(?NOTICE, Data, State) ->
  428. notify_async(State, {notice, epgsql_wire:decode_error(Data)}),
  429. {noreply, State};
  430. %% ParameterStatus
  431. on_message(?PARAMETER_STATUS, Data, State) ->
  432. [Name, Value] = epgsql_wire:decode_strings(Data),
  433. Parameters2 = lists:keystore(Name, 1, State#state.parameters,
  434. {Name, Value}),
  435. {noreply, State#state{parameters = Parameters2}};
  436. %% NotificationResponse
  437. on_message(?NOTIFICATION, <<Pid:?int32, Strings/binary>>, State) ->
  438. {Channel1, Payload1} = case epgsql_wire:decode_strings(Strings) of
  439. [Channel, Payload] -> {Channel, Payload};
  440. [Channel] -> {Channel, <<>>}
  441. end,
  442. notify_async(State, {notification, Channel1, Pid, Payload1}),
  443. {noreply, State};
  444. %% ParseComplete
  445. %% ParameterDescription
  446. %% RowDescription
  447. %% NoData
  448. %% BindComplete
  449. %% CloseComplete
  450. %% DataRow
  451. %% PortalSuspended
  452. %% EmptyQueryResponse
  453. %% CopyData
  454. %% CopyBothResponse
  455. on_message(Msg, Payload, State) ->
  456. command_handle_message(Msg, Payload, State).
  457. %% CopyData for Replication mode
  458. on_replication(?COPY_DATA, <<?PRIMARY_KEEPALIVE_MESSAGE:8, LSN:?int64, _Timestamp:?int64, ReplyRequired:8>>,
  459. #state{repl = #repl{last_flushed_lsn = LastFlushedLSN,
  460. last_applied_lsn = LastAppliedLSN,
  461. align_lsn = AlignLsn} = Repl} = State) ->
  462. Repl1 =
  463. case ReplyRequired of
  464. 1 when AlignLsn ->
  465. send(State, ?COPY_DATA,
  466. epgsql_wire:encode_standby_status_update(LSN, LSN, LSN)),
  467. Repl#repl{feedback_required = false,
  468. last_received_lsn = LSN, last_applied_lsn = LSN, last_flushed_lsn = LSN};
  469. 1 when not AlignLsn ->
  470. send(State, ?COPY_DATA,
  471. epgsql_wire:encode_standby_status_update(LSN, LastFlushedLSN, LastAppliedLSN)),
  472. Repl#repl{feedback_required = false,
  473. last_received_lsn = LSN};
  474. _ ->
  475. Repl#repl{feedback_required = true,
  476. last_received_lsn = LSN}
  477. end,
  478. {noreply, State#state{repl = Repl1}};
  479. %% CopyData for Replication mode
  480. on_replication(?COPY_DATA, <<?X_LOG_DATA, StartLSN:?int64, EndLSN:?int64,
  481. _Timestamp:?int64, WALRecord/binary>>,
  482. #state{repl = Repl} = State) ->
  483. Repl1 = handle_xlog_data(StartLSN, EndLSN, WALRecord, Repl),
  484. {noreply, State#state{repl = Repl1}};
  485. on_replication(?ERROR, Err, State) ->
  486. Reason = epgsql_wire:decode_error(Err),
  487. {stop, {error, Reason}, State};
  488. on_replication(M, Data, Sock) when M == ?NOTICE;
  489. M == ?NOTIFICATION;
  490. M == ?PARAMETER_STATUS ->
  491. on_message(M, Data, Sock).
  492. handle_xlog_data(StartLSN, EndLSN, WALRecord, #repl{cbmodule = undefined,
  493. receiver = Receiver} = Repl) ->
  494. %% with async messages
  495. Receiver ! {epgsql, self(), {x_log_data, StartLSN, EndLSN, WALRecord}},
  496. Repl#repl{feedback_required = true,
  497. last_received_lsn = EndLSN};
  498. handle_xlog_data(StartLSN, EndLSN, WALRecord,
  499. #repl{cbmodule = CbModule, cbstate = CbState, receiver = undefined} = Repl) ->
  500. %% with callback method
  501. {ok, LastFlushedLSN, LastAppliedLSN, NewCbState} =
  502. epgsql:handle_x_log_data(CbModule, StartLSN, EndLSN, WALRecord, CbState),
  503. Repl#repl{feedback_required = true,
  504. last_received_lsn = EndLSN,
  505. last_flushed_lsn = LastFlushedLSN,
  506. last_applied_lsn = LastAppliedLSN,
  507. cbstate = NewCbState}.