feat(archive): month snapshots on the same node, drop extra-node and HTML /view.
Fixes EventHub/EventHubBack#76 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,164 +0,0 @@
|
||||
%%%-------------------------------------------------------------------
|
||||
%%% @doc Обработчик календарного представления (HTML-календарь).
|
||||
%%%
|
||||
%%% GET – возвращает HTML-страницу с календарём на указанный месяц.
|
||||
%%% Требует параметр `month` в формате YYYY-MM.
|
||||
%%% Доступно только владельцу календаря.
|
||||
%%% @end
|
||||
%%%-------------------------------------------------------------------
|
||||
-module(handler_calendar_view).
|
||||
-behaviour(cowboy_handler).
|
||||
|
||||
-export([init/2]).
|
||||
-export([trails/0]).
|
||||
|
||||
-include("records.hrl").
|
||||
|
||||
-define(ARCHIVE_CALL_TIMEOUT, 8000).
|
||||
|
||||
%%% cowboy_handler callback
|
||||
-spec init(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
|
||||
init(Req, Opts) ->
|
||||
handle(Req, Opts).
|
||||
|
||||
%%% Swagger metadata
|
||||
-spec trails() -> [map()].
|
||||
trails() ->
|
||||
[
|
||||
#{
|
||||
path => <<"/v1/calendars/:calendar_id/view">>,
|
||||
method => <<"GET">>,
|
||||
description => <<"Get calendar HTML view for a specific month">>,
|
||||
tags => [<<"Calendars">>],
|
||||
parameters => [
|
||||
#{
|
||||
name => <<"calendar_id">>,
|
||||
in => <<"path">>,
|
||||
description => <<"Calendar ID">>,
|
||||
required => true,
|
||||
schema => #{type => string}
|
||||
},
|
||||
#{
|
||||
name => <<"month">>,
|
||||
in => <<"query">>,
|
||||
description => <<"Month in YYYY-MM format">>,
|
||||
required => true,
|
||||
schema => #{type => string, pattern => <<"^\\d{4}-\\d{2}$">>}
|
||||
}
|
||||
],
|
||||
responses => #{
|
||||
200 => #{
|
||||
description => <<"HTML calendar page">>,
|
||||
content => #{<<"text/html">> => #{schema => #{type => string}}}
|
||||
},
|
||||
400 => #{description => <<"Missing or invalid 'month' parameter">>},
|
||||
401 => #{description => <<"Unauthorized">>},
|
||||
403 => #{description => <<"Access denied">>}
|
||||
}
|
||||
}
|
||||
].
|
||||
|
||||
%%%===================================================================
|
||||
%%% Внутренние функции
|
||||
%%%===================================================================
|
||||
|
||||
%% @private Основной обработчик запроса.
|
||||
-spec handle(cowboy_req:req(), any()) -> {ok, cowboy_req:req(), any()}.
|
||||
handle(Req, _Opts) ->
|
||||
CalendarId = cowboy_req:binding(calendar_id, Req),
|
||||
case handler_utils:auth_user(Req) of
|
||||
{ok, UserId, Req1} ->
|
||||
case is_owner(UserId, CalendarId) of
|
||||
true -> process_view(Req1, CalendarId);
|
||||
false -> handler_utils:send_error(Req1, 403, <<"Access denied">>)
|
||||
end;
|
||||
{error, _Code, _Msg, Req1} ->
|
||||
handler_utils:send_error(Req1, 401, <<"Unauthorized">>)
|
||||
end.
|
||||
|
||||
%% @private Проверяет, является ли пользователь владельцем календаря.
|
||||
-spec is_owner(binary(), binary()) -> boolean().
|
||||
is_owner(UserId, CalendarId) ->
|
||||
case mnesia:dirty_read({calendar, CalendarId}) of
|
||||
[#calendar{owner_id = UserId}] -> true;
|
||||
_ -> false
|
||||
end.
|
||||
|
||||
%% @private Обрабатывает запрос на отображение календаря.
|
||||
-spec process_view(cowboy_req:req(), binary()) -> {ok, cowboy_req:req(), any()}.
|
||||
process_view(Req, CalendarId) ->
|
||||
Qs = cowboy_req:parse_qs(Req),
|
||||
case lists:keyfind(<<"month">>, 1, Qs) of
|
||||
{<<"month">>, MonthBin} ->
|
||||
case binary:split(MonthBin, <<"-">>) of
|
||||
[YearStr, MonthStr] ->
|
||||
Year = binary_to_integer(YearStr),
|
||||
Month = binary_to_integer(MonthStr),
|
||||
Events = fetch_events(CalendarId, Year, Month),
|
||||
Html = calendar_html_renderer:render_month(Year, Month, Events),
|
||||
Headers = #{
|
||||
<<"content-type">> => <<"text/html">>,
|
||||
<<"cache-control">> => <<"public, max-age=86400">>
|
||||
},
|
||||
cowboy_req:reply(200, Headers, Html, Req),
|
||||
{ok, Req, undefined};
|
||||
_ ->
|
||||
handler_utils:send_error(Req, 400, <<"Invalid 'month' format. Use YYYY-MM">>)
|
||||
end;
|
||||
false ->
|
||||
handler_utils:send_error(Req, 400, <<"Missing 'month' parameter">>)
|
||||
end.
|
||||
|
||||
%% @private Извлекает события для указанного месяца календаря.
|
||||
-spec fetch_events(binary(), integer(), integer()) -> list(#event{}).
|
||||
fetch_events(CalendarId, Year, Month) ->
|
||||
case is_hot(Year, Month) of
|
||||
true -> fetch_hot_events(CalendarId, Year, Month);
|
||||
false -> fetch_archive_events(CalendarId, Year, Month)
|
||||
end.
|
||||
|
||||
%% @private Определяет, является ли месяц "горячим" (в пределах 30 дней от текущей даты).
|
||||
-spec is_hot(integer(), integer()) -> boolean().
|
||||
is_hot(Year, Month) ->
|
||||
Current = calendar:local_time(),
|
||||
Target = {{Year, Month, 1}, {0, 0, 0}},
|
||||
calendar:datetime_to_gregorian_seconds(Current) -
|
||||
calendar:datetime_to_gregorian_seconds(Target) < 30 * 86400.
|
||||
|
||||
%% @private Извлекает "горячие" события из Mnesia.
|
||||
-spec fetch_hot_events(binary(), integer(), integer()) -> list(#event{}).
|
||||
fetch_hot_events(CalendarId, Year, Month) ->
|
||||
Start = {{Year, Month, 1}, {0, 0, 0}},
|
||||
End = {{Year, Month, calendar:last_day_of_the_month(Year, Month)}, {23, 59, 59}},
|
||||
mnesia:dirty_select(event, [
|
||||
{#event{calendar_id = CalendarId, start_time = '$1', _ = '_'},
|
||||
[{'>=', '$1', {const, Start}}, {'=<', '$1', {const, End}}],
|
||||
['$_']}
|
||||
]).
|
||||
|
||||
%% @private Извлекает архивные события через RPC на архивный узел.
|
||||
%% При недоступности архива возвращает события из основной Mnesia.
|
||||
-spec fetch_archive_events(binary(), integer(), integer()) -> list(#event{}).
|
||||
fetch_archive_events(CalendarId, Year, Month) ->
|
||||
DayStr = lists:flatten(io_lib:format("~4..0B~2..0B", [Year, Month])),
|
||||
case safe_get_archive_node(DayStr) of
|
||||
{ok, Node} ->
|
||||
case rpc:call(Node, archive_fetcher, fetch, [CalendarId, Year, Month],
|
||||
?ARCHIVE_CALL_TIMEOUT) of
|
||||
Events when is_list(Events) -> Events;
|
||||
_ -> fetch_hot_events(CalendarId, Year, Month)
|
||||
end;
|
||||
{error, _} ->
|
||||
fetch_hot_events(CalendarId, Year, Month)
|
||||
end.
|
||||
|
||||
-spec safe_get_archive_node(string()) -> {ok, node()} | {error, term()}.
|
||||
safe_get_archive_node(Day) ->
|
||||
try gen_server:call(archive_manager, {get_node, Day}, ?ARCHIVE_CALL_TIMEOUT) of
|
||||
{ok, Node} when is_atom(Node) -> {ok, Node};
|
||||
{error, Reason} -> {error, Reason};
|
||||
Other -> {error, Other}
|
||||
catch
|
||||
exit:{timeout, _} -> {error, timeout};
|
||||
exit:{noproc, _} -> {error, noproc}
|
||||
end.
|
||||
@@ -186,6 +186,8 @@ update_event(Req) ->
|
||||
handler_utils:send_error(Req2, 404, <<"Event not found">>);
|
||||
{error, event_in_past} ->
|
||||
handler_utils:send_error(Req2, 400, <<"Event cannot be in the past">>);
|
||||
{error, archived} ->
|
||||
handler_utils:send_error(Req2, 409, <<"Month is archived">>);
|
||||
{error, {content_banned, _}} ->
|
||||
handler_utils:send_error(Req2, 400, <<"Content contains banned words">>);
|
||||
{error, invalid_specialist} ->
|
||||
@@ -215,6 +217,8 @@ delete_event(Req) ->
|
||||
handler_utils:send_error(Req1, 403, <<"Access denied">>);
|
||||
{error, not_found} ->
|
||||
handler_utils:send_error(Req1, 404, <<"Event not found">>);
|
||||
{error, archived} ->
|
||||
handler_utils:send_error(Req1, 409, <<"Month is archived">>);
|
||||
{error, _} ->
|
||||
handler_utils:send_error(Req1, 500, <<"Internal server error">>)
|
||||
end;
|
||||
|
||||
@@ -184,6 +184,8 @@ create_event(Req) ->
|
||||
handler_utils:send_error(Req2, 404, <<"Calendar not found">>);
|
||||
{error, event_in_past} ->
|
||||
handler_utils:send_error(Req2, 400, <<"Event cannot be in the past">>);
|
||||
{error, archived} ->
|
||||
handler_utils:send_error(Req2, 409, <<"Month is archived">>);
|
||||
{error, {content_banned, _}} ->
|
||||
handler_utils:send_error(Req2, 400, <<"Content contains banned words">>);
|
||||
{error, _} ->
|
||||
@@ -201,6 +203,8 @@ create_event(Req) ->
|
||||
handler_utils:send_error(Req2, 404, <<"Calendar not found">>);
|
||||
{error, event_in_past} ->
|
||||
handler_utils:send_error(Req2, 400, <<"Event cannot be in the past">>);
|
||||
{error, archived} ->
|
||||
handler_utils:send_error(Req2, 409, <<"Month is archived">>);
|
||||
{error, {content_banned, _}} ->
|
||||
handler_utils:send_error(Req2, 400, <<"Content contains banned words">>);
|
||||
{error, _} ->
|
||||
@@ -239,7 +243,10 @@ list_events(Req) ->
|
||||
{FromStr, ToStr} ->
|
||||
FromDt = parse_datetime_binary(FromStr),
|
||||
ToDt = parse_datetime_binary(ToStr),
|
||||
expand_recurring_events(UserId, Events, FromDt, ToDt)
|
||||
HotJson = expand_recurring_events(UserId, Events, FromDt, ToDt),
|
||||
SnapJson = logic_month_archive:events_json_in_range(
|
||||
CalendarId, FromDt, ToDt),
|
||||
merge_event_json(HotJson, SnapJson)
|
||||
end,
|
||||
handler_utils:send_json(Req1, 200, Response);
|
||||
{error, access_denied} ->
|
||||
@@ -308,24 +315,36 @@ expand_recurring_events(UserId, Events, From, To) ->
|
||||
lists:flatmap(fun(Event) ->
|
||||
case Event#event.event_type of
|
||||
single ->
|
||||
case is_in_range(Event#event.start_time, From, To) of
|
||||
true -> [handler_utils:event_to_json(Event)];
|
||||
false -> []
|
||||
case logic_month_archive:month_is_closed(Event#event.start_time) of
|
||||
true -> [];
|
||||
false ->
|
||||
case is_in_range(Event#event.start_time, From, To) of
|
||||
true -> [handler_utils:event_to_json(Event)];
|
||||
false -> []
|
||||
end
|
||||
end;
|
||||
recurring ->
|
||||
case logic_event:get_occurrences(UserId, Event#event.id, To) of
|
||||
{ok, Occurrences} ->
|
||||
lists:filtermap(
|
||||
fun({virtual, Occ}) ->
|
||||
case is_in_range(Occ, From, To) of
|
||||
true -> {true, occurrence_to_json(Event, Occ)};
|
||||
false -> false
|
||||
case logic_month_archive:month_is_closed(Occ) of
|
||||
true -> false;
|
||||
false ->
|
||||
case is_in_range(Occ, From, To) of
|
||||
true -> {true, occurrence_to_json(Event, Occ)};
|
||||
false -> false
|
||||
end
|
||||
end;
|
||||
({materialized, Instance}) ->
|
||||
case is_in_range(Instance#event.start_time, From, To) of
|
||||
true -> {true, handler_utils:event_to_json(Instance)};
|
||||
false -> false
|
||||
end
|
||||
case logic_month_archive:month_is_closed(Instance#event.start_time) of
|
||||
true -> false;
|
||||
false ->
|
||||
case is_in_range(Instance#event.start_time, From, To) of
|
||||
true -> {true, handler_utils:event_to_json(Instance)};
|
||||
false -> false
|
||||
end
|
||||
end
|
||||
end, Occurrences);
|
||||
_ -> []
|
||||
end
|
||||
@@ -334,6 +353,16 @@ expand_recurring_events(UserId, Events, From, To) ->
|
||||
|
||||
is_in_range(Time, From, To) -> Time >= From andalso Time =< To.
|
||||
|
||||
merge_event_json(Hot, Snap) ->
|
||||
Ids = maps:from_list(
|
||||
[{maps:get(<<"id">>, M, maps:get(id, M, undefined)), true} || M <- Hot]),
|
||||
Extra = [M || M <- Snap,
|
||||
begin
|
||||
Id = maps:get(<<"id">>, M, maps:get(id, M, undefined)),
|
||||
Id =:= undefined orelse not maps:is_key(Id, Ids)
|
||||
end],
|
||||
Hot ++ Extra.
|
||||
|
||||
parse_datetime_binary(Str) ->
|
||||
{ok, Dt} = handler_utils:parse_datetime(Str),
|
||||
Dt.
|
||||
|
||||
Reference in New Issue
Block a user