epgsql_sock.erl 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. connect_opts :: epgsql:connect_opts()}).
  85. -opaque pg_sock() :: #state{}.
  86. %% -- client interface --
  87. start_link() ->
  88. gen_server:start_link(?MODULE, [], []).
  89. close(C) when is_pid(C) ->
  90. catch gen_server:cast(C, stop),
  91. ok.
  92. -spec sync_command(epgsql:connection(), epgsql_command:command(), any()) -> any().
  93. sync_command(C, Command, Args) ->
  94. gen_server:call(C, {command, Command, Args}, infinity).
  95. -spec async_command(epgsql:connection(), cast | incremental,
  96. epgsql_command:command(), any()) -> reference().
  97. async_command(C, Transport, Command, Args) ->
  98. Ref = make_ref(),
  99. Pid = self(),
  100. ok = gen_server:cast(C, {{Transport, Pid, Ref}, Command, Args}),
  101. Ref.
  102. get_parameter(C, Name) ->
  103. gen_server:call(C, {get_parameter, to_binary(Name)}, infinity).
  104. set_notice_receiver(C, PidOrName) when is_pid(PidOrName);
  105. is_atom(PidOrName) ->
  106. gen_server:call(C, {set_async_receiver, PidOrName}, infinity).
  107. get_cmd_status(C) ->
  108. gen_server:call(C, get_cmd_status, infinity).
  109. cancel(S) ->
  110. gen_server:cast(S, cancel).
  111. %% -- command APIs --
  112. %% send()
  113. %% send_many()
  114. -spec set_net_socket(gen_tcp | ssl, tcp_socket() | ssl:sslsocket(), pg_sock()) -> pg_sock().
  115. set_net_socket(Mod, Socket, State) ->
  116. State1 = State#state{mod = Mod, sock = Socket},
  117. setopts(State1, [{active, true}]),
  118. State1.
  119. -spec init_replication_state(pg_sock()) -> pg_sock().
  120. init_replication_state(State) ->
  121. State#state{repl = #repl{}}.
  122. -spec set_attr(atom(), any(), pg_sock()) -> pg_sock().
  123. set_attr(backend, {_Pid, _Key} = Backend, State) ->
  124. State#state{backend = Backend};
  125. set_attr(async, Async, State) ->
  126. State#state{async = Async};
  127. set_attr(txstatus, Status, State) ->
  128. State#state{txstatus = Status};
  129. set_attr(codec, Codec, State) ->
  130. State#state{codec = Codec};
  131. set_attr(sync_required, Value, State) ->
  132. State#state{sync_required = Value};
  133. set_attr(replication_state, Value, State) ->
  134. State#state{repl = Value};
  135. set_attr(connect_opts, ConnectOpts, State) ->
  136. State#state{connect_opts = ConnectOpts}.
  137. %% XXX: be careful!
  138. -spec set_packet_handler(atom(), pg_sock()) -> pg_sock().
  139. set_packet_handler(Handler, State) ->
  140. State#state{handler = Handler}.
  141. -spec get_codec(pg_sock()) -> epgsql_binary:codec().
  142. get_codec(#state{codec = Codec}) ->
  143. Codec.
  144. -spec get_replication_state(pg_sock()) -> repl_state().
  145. get_replication_state(#state{repl = Repl}) ->
  146. Repl.
  147. -spec get_rows(pg_sock()) -> [tuple()].
  148. get_rows(#state{rows = Rows}) ->
  149. lists:reverse(Rows).
  150. -spec get_results(pg_sock()) -> [any()].
  151. get_results(#state{results = Results}) ->
  152. lists:reverse(Results).
  153. -spec get_parameter_internal(binary(), pg_sock()) -> binary() | undefined.
  154. get_parameter_internal(Name, #state{parameters = Parameters}) ->
  155. case lists:keysearch(Name, 1, Parameters) of
  156. {value, {Name, Value}} -> Value;
  157. false -> undefined
  158. end.
  159. %% -- gen_server implementation --
  160. init([]) ->
  161. {ok, #state{}}.
  162. handle_call({get_parameter, Name}, _From, State) ->
  163. {reply, {ok, get_parameter_internal(Name, State)}, State};
  164. handle_call({set_async_receiver, PidOrName}, _From, #state{async = Previous} = State) ->
  165. {reply, {ok, Previous}, State#state{async = PidOrName}};
  166. handle_call(get_cmd_status, _From, #state{complete_status = Status} = State) ->
  167. {reply, {ok, Status}, State};
  168. handle_call({standby_status_update, FlushedLSN, AppliedLSN}, _From,
  169. #state{handler = on_replication,
  170. repl = #repl{last_received_lsn = ReceivedLSN} = Repl} = State) ->
  171. send(State, ?COPY_DATA, epgsql_wire:encode_standby_status_update(ReceivedLSN, FlushedLSN, AppliedLSN)),
  172. Repl1 = Repl#repl{last_flushed_lsn = FlushedLSN,
  173. last_applied_lsn = AppliedLSN},
  174. {reply, ok, State#state{repl = Repl1}};
  175. handle_call({command, Command, Args}, From, State) ->
  176. Transport = {call, From},
  177. command_new(Transport, Command, Args, State).
  178. handle_cast({{Method, From, Ref} = Transport, Command, Args}, State)
  179. when ((Method == cast) or (Method == incremental)),
  180. is_pid(From),
  181. is_reference(Ref) ->
  182. command_new(Transport, Command, Args, State);
  183. handle_cast(stop, State) ->
  184. send(State, ?TERMINATE, []),
  185. {stop, normal, flush_queue(State, {error, closed})};
  186. handle_cast(cancel, State = #state{backend = {Pid, Key},
  187. connect_opts = ConnectOpts,
  188. mod = Mode}) ->
  189. SockOpts = [{active, false}, {packet, raw}, binary],
  190. Msg = <<16:?int32, 80877102:?int32, Pid:?int32, Key:?int32>>,
  191. case epgsql_cmd_connect:open_socket(SockOpts, ConnectOpts) of
  192. {ok, Mode, Sock} when Mode == gen_tcp ->
  193. ok = gen_tcp:send(Sock, Msg),
  194. gen_tcp:close(Sock);
  195. {ok, Mode, Sock} when Mode == ssl ->
  196. ok = ssl:send(Sock, Msg),
  197. ssl:close(Sock);
  198. {error, _Reason} ->
  199. noop
  200. end,
  201. {noreply, State}.
  202. handle_info({Closed, Sock}, #state{sock = Sock} = State)
  203. when Closed == tcp_closed; Closed == ssl_closed ->
  204. {stop, sock_closed, flush_queue(State#state{sock = undefined}, {error, sock_closed})};
  205. handle_info({Error, Sock, Reason}, #state{sock = Sock} = State)
  206. when Error == tcp_error; Error == ssl_error ->
  207. Why = {sock_error, Reason},
  208. {stop, Why, flush_queue(State, {error, Why})};
  209. handle_info({inet_reply, _, ok}, State) ->
  210. {noreply, State};
  211. handle_info({inet_reply, _, Status}, State) ->
  212. {stop, Status, flush_queue(State, {error, Status})};
  213. handle_info({_, Sock, Data2}, #state{data = Data, sock = Sock} = State) ->
  214. loop(State#state{data = <<Data/binary, Data2/binary>>}).
  215. terminate(_Reason, #state{sock = undefined}) -> ok;
  216. terminate(_Reason, #state{mod = gen_tcp, sock = Sock}) -> gen_tcp:close(Sock);
  217. terminate(_Reason, #state{mod = ssl, sock = Sock}) -> ssl:close(Sock).
  218. code_change(_OldVsn, State, _Extra) ->
  219. {ok, State}.
  220. %% -- internal functions --
  221. -spec command_new(transport(), epgsql_command:command(), any(), pg_sock()) ->
  222. Result when
  223. Result :: {noreply, pg_sock()}
  224. | {stop, Reason :: any(), pg_sock()}.
  225. command_new(Transport, Command, Args, State) ->
  226. CmdState = epgsql_command:init(Command, Args),
  227. command_exec(Transport, Command, CmdState, State).
  228. -spec command_exec(transport(), epgsql_command:command(), any(), pg_sock()) ->
  229. Result when
  230. Result :: {noreply, pg_sock()}
  231. | {stop, Reason :: any(), pg_sock()}.
  232. command_exec(Transport, Command, _, State = #state{sync_required = true})
  233. when Command /= epgsql_cmd_sync ->
  234. {noreply,
  235. finish(State#state{current_cmd = Command,
  236. current_cmd_transport = Transport},
  237. {error, sync_required})};
  238. command_exec(Transport, Command, CmdState, State) ->
  239. case epgsql_command:execute(Command, State, CmdState) of
  240. {ok, State1, CmdState1} ->
  241. {noreply, command_enqueue(Transport, Command, CmdState1, State1)};
  242. {stop, StopReason, Response, State1} ->
  243. reply(Transport, Response, Response),
  244. {stop, StopReason, State1}
  245. end.
  246. -spec command_enqueue(transport(), epgsql_command:command(), epgsql_command:state(), pg_sock()) -> pg_sock().
  247. command_enqueue(Transport, Command, CmdState, #state{current_cmd = undefined} = State) ->
  248. State#state{current_cmd = Command,
  249. current_cmd_state = CmdState,
  250. current_cmd_transport = Transport,
  251. complete_status = undefined};
  252. command_enqueue(Transport, Command, CmdState, #state{queue = Q} = State) ->
  253. State#state{queue = queue:in({Command, CmdState, Transport}, Q),
  254. complete_status = undefined}.
  255. -spec command_handle_message(byte(), binary() | epgsql:query_error(), pg_sock()) ->
  256. {noreply, pg_sock()}
  257. | {stop, any(), pg_sock()}.
  258. command_handle_message(Msg, Payload,
  259. #state{current_cmd = Command,
  260. current_cmd_state = CmdState} = State) ->
  261. case epgsql_command:handle_message(Command, Msg, Payload, State, CmdState) of
  262. {add_row, Row, State1, CmdState1} ->
  263. {noreply, add_row(State1#state{current_cmd_state = CmdState1}, Row)};
  264. {add_result, Result, Notice, State1, CmdState1} ->
  265. {noreply,
  266. add_result(State1#state{current_cmd_state = CmdState1},
  267. Notice, Result)};
  268. {finish, Result, Notice, State1} ->
  269. {noreply, finish(State1, Notice, Result)};
  270. {noaction, State1} ->
  271. {noreply, State1};
  272. {noaction, State1, CmdState1} ->
  273. {noreply, State1#state{current_cmd_state = CmdState1}};
  274. {requeue, State1, CmdState1} ->
  275. Transport = State1#state.current_cmd_transport,
  276. command_exec(Transport, Command, CmdState1,
  277. State1#state{current_cmd = undefined});
  278. {stop, Reason, Response, State1} ->
  279. {stop, Reason, finish(State1, Response)};
  280. {sync_required, Why} ->
  281. %% Protocol error. Finish and flush all pending commands.
  282. {noreply, sync_required(finish(State#state{sync_required = true}, Why))};
  283. unknown ->
  284. {stop, {error, {unexpected_message, Msg, Command, CmdState}}, State}
  285. end.
  286. command_next(#state{current_cmd = PrevCmd,
  287. queue = Q} = State) when PrevCmd =/= undefined ->
  288. case queue:out(Q) of
  289. {empty, _} ->
  290. State#state{current_cmd = undefined,
  291. current_cmd_state = undefined,
  292. current_cmd_transport = undefined,
  293. rows = [],
  294. results = []};
  295. {{value, {Command, CmdState, Transport}}, Q1} ->
  296. State#state{current_cmd = Command,
  297. current_cmd_state = CmdState,
  298. current_cmd_transport = Transport,
  299. queue = Q1,
  300. rows = [],
  301. results = []}
  302. end.
  303. setopts(#state{mod = Mod, sock = Sock}, Opts) ->
  304. case Mod of
  305. gen_tcp -> inet:setopts(Sock, Opts);
  306. ssl -> ssl:setopts(Sock, Opts)
  307. end.
  308. %% This one only used in connection initiation to send client's
  309. %% `StartupMessage' and `SSLRequest' packets
  310. -spec send(pg_sock(), iodata()) -> ok | {error, any()}.
  311. send(#state{mod = Mod, sock = Sock}, Data) ->
  312. do_send(Mod, Sock, epgsql_wire:encode_command(Data)).
  313. -spec send(pg_sock(), byte(), iodata()) -> ok | {error, any()}.
  314. send(#state{mod = Mod, sock = Sock}, Type, Data) ->
  315. do_send(Mod, Sock, epgsql_wire:encode_command(Type, Data)).
  316. -spec send_multi(pg_sock(), [{byte(), iodata()}]) -> ok | {error, any()}.
  317. send_multi(#state{mod = Mod, sock = Sock}, List) ->
  318. do_send(Mod, Sock, lists:map(fun({Type, Data}) ->
  319. epgsql_wire:encode_command(Type, Data)
  320. end, List)).
  321. do_send(gen_tcp, Sock, Bin) ->
  322. %% Why not gen_tcp:send/2?
  323. %% See https://github.com/rabbitmq/rabbitmq-common/blob/v3.7.4/src/rabbit_writer.erl#L367-L384
  324. %% Because of that we also have `handle_info({inet_reply, ...`
  325. try erlang:port_command(Sock, Bin) of
  326. true ->
  327. ok
  328. catch
  329. error:_Error ->
  330. {error, einval}
  331. end;
  332. do_send(ssl, Sock, Bin) ->
  333. ssl:send(Sock, Bin).
  334. loop(#state{data = Data, handler = Handler, repl = Repl} = State) ->
  335. case epgsql_wire:decode_message(Data) of
  336. {Type, Payload, Tail} ->
  337. case ?MODULE:Handler(Type, Payload, State#state{data = Tail}) of
  338. {noreply, State2} ->
  339. loop(State2);
  340. R = {stop, _Reason2, _State2} ->
  341. R
  342. end;
  343. _ ->
  344. %% in replication mode send feedback after each batch of messages
  345. case (Repl =/= undefined) andalso (Repl#repl.feedback_required) of
  346. true ->
  347. #repl{last_received_lsn = LastReceivedLSN,
  348. last_flushed_lsn = LastFlushedLSN,
  349. last_applied_lsn = LastAppliedLSN} = Repl,
  350. send(State, ?COPY_DATA, epgsql_wire:encode_standby_status_update(
  351. LastReceivedLSN, LastFlushedLSN, LastAppliedLSN)),
  352. {noreply, State#state{repl = Repl#repl{feedback_required = false}}};
  353. _ ->
  354. {noreply, State}
  355. end
  356. end.
  357. finish(State, Result) ->
  358. finish(State, Result, Result).
  359. finish(State = #state{current_cmd_transport = Transport}, Notice, Result) ->
  360. reply(Transport, Notice, Result),
  361. command_next(State).
  362. reply({cast, From, Ref}, _, Result) ->
  363. From ! {self(), Ref, Result};
  364. reply({incremental, From, Ref}, Notice, _) ->
  365. From ! {self(), Ref, Notice};
  366. reply({call, From}, _, Result) ->
  367. gen_server:reply(From, Result).
  368. add_result(#state{results = Results, current_cmd_transport = Transport} = State, Notice, Result) ->
  369. Results2 = case Transport of
  370. {incremental, From, Ref} ->
  371. From ! {self(), Ref, Notice},
  372. Results;
  373. _ ->
  374. [Result | Results]
  375. end,
  376. State#state{rows = [],
  377. results = Results2}.
  378. add_row(#state{rows = Rows, current_cmd_transport = Transport} = State, Data) ->
  379. Rows2 = case Transport of
  380. {incremental, From, Ref} ->
  381. From ! {self(), Ref, {data, Data}},
  382. Rows;
  383. _ ->
  384. [Data | Rows]
  385. end,
  386. State#state{rows = Rows2}.
  387. notify(#state{current_cmd_transport = {incremental, From, Ref}} = State, Notice) ->
  388. From ! {self(), Ref, Notice},
  389. State;
  390. notify(State, _) ->
  391. State.
  392. %% Send asynchronous messages (notice / notification)
  393. notify_async(#state{async = undefined}, _) ->
  394. false;
  395. notify_async(#state{async = PidOrName}, Msg) ->
  396. try PidOrName ! {epgsql, self(), Msg} of
  397. _ -> true
  398. catch error:badarg ->
  399. %% no process registered under this name
  400. false
  401. end.
  402. sync_required(#state{current_cmd = epgsql_cmd_sync} = State) ->
  403. State;
  404. sync_required(#state{current_cmd = undefined} = State) ->
  405. State#state{sync_required = true};
  406. sync_required(State) ->
  407. sync_required(finish(State, {error, sync_required})).
  408. flush_queue(#state{current_cmd = undefined} = State, _) ->
  409. State;
  410. flush_queue(State, Error) ->
  411. flush_queue(finish(State, Error), Error).
  412. to_binary(B) when is_binary(B) -> B;
  413. to_binary(L) when is_list(L) -> list_to_binary(L).
  414. %% -- backend message handling --
  415. %% CommandComplete
  416. on_message(?COMMAND_COMPLETE = Msg, Bin, State) ->
  417. Complete = epgsql_wire:decode_complete(Bin),
  418. command_handle_message(Msg, Bin, State#state{complete_status = Complete});
  419. %% ReadyForQuery
  420. on_message(?READY_FOR_QUERY = Msg, <<Status:8>> = Bin, State) ->
  421. command_handle_message(Msg, Bin, State#state{txstatus = Status});
  422. %% Error
  423. on_message(?ERROR = Msg, Err, #state{current_cmd = CurrentCmd} = State) ->
  424. Reason = epgsql_wire:decode_error(Err),
  425. case CurrentCmd of
  426. undefined ->
  427. %% Message generated by server asynchronously
  428. {stop, {shutdown, Reason}, State};
  429. _ ->
  430. command_handle_message(Msg, Reason, State)
  431. end;
  432. %% NoticeResponse
  433. on_message(?NOTICE, Data, State) ->
  434. notify_async(State, {notice, epgsql_wire:decode_error(Data)}),
  435. {noreply, State};
  436. %% ParameterStatus
  437. on_message(?PARAMETER_STATUS, Data, State) ->
  438. [Name, Value] = epgsql_wire:decode_strings(Data),
  439. Parameters2 = lists:keystore(Name, 1, State#state.parameters,
  440. {Name, Value}),
  441. {noreply, State#state{parameters = Parameters2}};
  442. %% NotificationResponse
  443. on_message(?NOTIFICATION, <<Pid:?int32, Strings/binary>>, State) ->
  444. {Channel1, Payload1} = case epgsql_wire:decode_strings(Strings) of
  445. [Channel, Payload] -> {Channel, Payload};
  446. [Channel] -> {Channel, <<>>}
  447. end,
  448. notify_async(State, {notification, Channel1, Pid, Payload1}),
  449. {noreply, State};
  450. %% ParseComplete
  451. %% ParameterDescription
  452. %% RowDescription
  453. %% NoData
  454. %% BindComplete
  455. %% CloseComplete
  456. %% DataRow
  457. %% PortalSuspended
  458. %% EmptyQueryResponse
  459. %% CopyData
  460. %% CopyBothResponse
  461. on_message(Msg, Payload, State) ->
  462. command_handle_message(Msg, Payload, State).
  463. %% CopyData for Replication mode
  464. on_replication(?COPY_DATA, <<?PRIMARY_KEEPALIVE_MESSAGE:8, LSN:?int64, _Timestamp:?int64, ReplyRequired:8>>,
  465. #state{repl = #repl{last_flushed_lsn = LastFlushedLSN,
  466. last_applied_lsn = LastAppliedLSN,
  467. align_lsn = AlignLsn} = Repl} = State) ->
  468. Repl1 =
  469. case ReplyRequired of
  470. 1 when AlignLsn ->
  471. send(State, ?COPY_DATA,
  472. epgsql_wire:encode_standby_status_update(LSN, LSN, LSN)),
  473. Repl#repl{feedback_required = false,
  474. last_received_lsn = LSN, last_applied_lsn = LSN, last_flushed_lsn = LSN};
  475. 1 when not AlignLsn ->
  476. send(State, ?COPY_DATA,
  477. epgsql_wire:encode_standby_status_update(LSN, LastFlushedLSN, LastAppliedLSN)),
  478. Repl#repl{feedback_required = false,
  479. last_received_lsn = LSN};
  480. _ ->
  481. Repl#repl{feedback_required = true,
  482. last_received_lsn = LSN}
  483. end,
  484. {noreply, State#state{repl = Repl1}};
  485. %% CopyData for Replication mode
  486. on_replication(?COPY_DATA, <<?X_LOG_DATA, StartLSN:?int64, EndLSN:?int64,
  487. _Timestamp:?int64, WALRecord/binary>>,
  488. #state{repl = Repl} = State) ->
  489. Repl1 = handle_xlog_data(StartLSN, EndLSN, WALRecord, Repl),
  490. {noreply, State#state{repl = Repl1}};
  491. on_replication(?ERROR, Err, State) ->
  492. Reason = epgsql_wire:decode_error(Err),
  493. {stop, {error, Reason}, State};
  494. on_replication(M, Data, Sock) when M == ?NOTICE;
  495. M == ?NOTIFICATION;
  496. M == ?PARAMETER_STATUS ->
  497. on_message(M, Data, Sock).
  498. handle_xlog_data(StartLSN, EndLSN, WALRecord, #repl{cbmodule = undefined,
  499. receiver = Receiver} = Repl) ->
  500. %% with async messages
  501. Receiver ! {epgsql, self(), {x_log_data, StartLSN, EndLSN, WALRecord}},
  502. Repl#repl{feedback_required = true,
  503. last_received_lsn = EndLSN};
  504. handle_xlog_data(StartLSN, EndLSN, WALRecord,
  505. #repl{cbmodule = CbModule, cbstate = CbState, receiver = undefined} = Repl) ->
  506. %% with callback method
  507. {ok, LastFlushedLSN, LastAppliedLSN, NewCbState} =
  508. epgsql:handle_x_log_data(CbModule, StartLSN, EndLSN, WALRecord, CbState),
  509. Repl#repl{feedback_required = true,
  510. last_received_lsn = EndLSN,
  511. last_flushed_lsn = LastFlushedLSN,
  512. last_applied_lsn = LastAppliedLSN,
  513. cbstate = NewCbState}.