<commit_before>%%
%% Copyright (c) 2015 <NAME>
%%
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), to deal
%% in the Software without restriction, including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%% copies of the Software, and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in all
%% copies or substantial portions of the Software.
%%
%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
%% SOFTWARE.
%%

-module(erwa_invocation).
-behaviour(gen_server).

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.


%% API
-export([yield/4]).
-export([error/5]).

-export([start/1]).
-export([start_link/1]).
-export([stop/1]).

%% gen_server
-export([init/1]).
-export([handle_call/3]).
-export([handle_cast/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).


-record(state, {
                procedure_id = unknown,
                call_req_id = none,
                caller_pid = none,
                call_options = [],
                call_arguments = undefined,
                call_argumentskw = undefined,

                invocation_id = none,
                callee_pids = [],
                results = []
                }).

start(Args) ->
  gen_server:start(?MODULE, Args, []).

start_link(Args) ->
  gen_server:start_link(?MODULE, Args, []).

stop(Pid) ->
  gen_server:call(Pid, stop).

  %% gen_server.


yield(Pid,Options,Arguments,ArgumentsKw) ->
  gen_server:cast(Pid,{yield,Options,Arguments,ArgumentsKw}).

error(Pid,Details,ErrorUri,Arguments,ArgumentsKw) ->
  gen_server:cast(Pid,{error,Details,ErrorUri,Arguments,ArgumentsKw}).

init(Args) ->
  case check_and_create_state(Args) of
    {ok, #state{callee_pids=Callees,
                procedure_id=ProcedureId,
                call_arguments=Arguments,
                call_argumentskw=ArgumentsKw} = State} ->
      send_message_to({invocation,set_request_id,ProcedureId,[{invocation_pid,self()}],Arguments,ArgumentsKw},Callees),
      {ok, State};
    {error,Reason} ->
      {stop,Reason}
  end.


handle_call(stop, _From, State) ->
	{stop,normal,{ok,stopped},State};
handle_call(_Request, _From, State) ->
	{reply, ignored, State}.


handle_cast({yield,_Options,Arguments,ArgumentsKw}, #state{caller_pid=Pid,call_req_id=RequestId}=State) ->
  %% TODO: implement advanced stuff
  send_message_to({result, RequestId, [], Arguments, ArgumentsKw},Pid),
  {stop,normal,State};
handle_cast({error,Details,ErrorUri,Arguments,ArgumentsKw},#state{caller_pid=Pid,call_req_id=RequestId}=State) ->
  %% TODO: implement advanced stuff
  send_message_to({error, call, RequestId, Details, ErrorUri, Arguments, ArgumentsKw},Pid),
  {stop,normal,State};
handle_cast(_Request, State) ->
	{noreply, State}.



handle_info(_Info, State) ->
	{noreply, State}.

terminate(_Reason, _State) ->
	ok.

code_change(_OldVsn, State, _Extra) ->
	{ok, State}.


check_and_create_state(Args) ->
  try
    #{procedure_id := ProcedureId,
      caller_pid := CallerPid,
      call_req_id := RequestId,<commit_msg>Keep track of callees and handle cancel by caller.<commit_after>%%
%% Copyright (c) 2015 <NAME>
%%
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), to deal
%% in the Software without restriction, including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
%% copies of the Software, and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in all
%% copies or substantial portions of the Software.
%%
%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
%% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
%% SOFTWARE.
%%

-module(erwa_invocation).
-behaviour(gen_server).

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.


%% API
-export([cancel/2]).
-export([yield/4]).
-export([error/5]).

-export([start/1]).
-export([start_link/1]).
-export([stop/1]).

%% gen_server
-export([init/1]).
-export([handle_call/3]).
-export([handle_cast/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).


-record(state, {
                procedure_id = unknown,
                call_req_id = none,
                caller_pid = none,
                call_options = [],
                call_arguments = undefined,
                call_argumentskw = undefined,

                invocation_id = none,
                callee_pids = [],
                results = [],
                canceled = false
                }).

start(Args) ->
  gen_server:start(?MODULE, Args, []).

start_link(Args) ->
  gen_server:start_link(?MODULE, Args, []).

stop(Pid) ->
  gen_server:call(Pid, stop).

  %% gen_server.


cancel(Pid,Options) ->
  gen_server:call(Pid,{cancel,Options}).

yield(Pid,Options,Arguments,ArgumentsKw) ->
  gen_server:cast(Pid,{yield,Options,Arguments,ArgumentsKw,self()}).

error(Pid,Details,ErrorUri,Arguments,ArgumentsKw) ->
  gen_server:cast(Pid,{error,Details,ErrorUri,Arguments,ArgumentsKw,self()}).

init(Args) ->
  case check_and_create_state(Args) of
    {ok, #state{callee_pids=Callees,
                procedure_id=ProcedureId,
                call_arguments=Arguments,
                call_argumentskw=ArgumentsKw} = State} ->
      send_message_to({invocation,set_request_id,ProcedureId,[{invocation_pid,self()}],Arguments,ArgumentsKw},Callees),
      {ok, State};
    {error,Reason} ->
      {stop,Reason}
  end.


handle_call({cancel,_Options},_From, #state{canceled=false, callee_pids=Callees}=State) ->
  send_message_to({interrupt,set_request_id,[{invocation_pid,self()}]},Callees),
  {reply,ok,State#state{canceled=true}};
handle_call(stop, _From, State) ->
	{stop,normal,{ok,stopped},State};
handle_call(_Request, _From, State) ->
	{reply, ignored, State}.



handle_cast({yield,Options,Arguments,ArgumentsKw,CalleePid}, #state{caller_pid=Pid,call_req_id=RequestId,callee_pids=Callees}=State) ->
  case lists:keyfind(progress,1,Options) of
    {progress,true} ->
      send_message_to({result, RequestId, [{progress,true}], Arguments, ArgumentsKw},Pid),
      {noreply,State};
    _ ->
      send_message_to({result, RequestId, [], Arguments, ArgumentsKw},Pid),
      case lists:delete(CalleePid,Callees) of
        [] ->
          {stop,normal,State#state{callee_pids=[]}};
        NewCallees ->
          {noreply,State#state{callee_pids=NewCallees}}
      end
  end;
handle_cast({error,Details,ErrorUri,Arguments,ArgumentsKw,CalleePid},#state{caller_pid=Pid,call_req_id=RequestId, callee_pids=Callees}=State) ->
  send_message_to({error, call, RequestId, Details, ErrorUri, Arguments, ArgumentsKw},Pid),
  case lists:delete(CalleePid,Callees) of
    [] ->
      {stop,normal,State#state{callee_pids=[]}};
    NewCallees ->
      {noreply,State#state{callee_pids=NewCallees}}
  end;
handle_cast(_Request, State) ->
	{noreply, State}.



handle_info(_Info, State) ->
	{noreply, State}.

terminate(_Reason, _State) ->
	ok.

code_change(_OldVsn, State, _Extra) ->
	{ok, State}.


check_and_create_state(Args) ->
  try
    #{procedure_id := ProcedureId,
      caller_pid := CallerPid,
      call_req_id := RequestId,
{'fraction_non_alphanumeric': 0.13611811307166005, 'fraction_numerical': 0.003841075501140319, 'mean_word_length': 4.001200480192077, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3272440', 'n_tokens_mistral': 2747, 'n_tokens_neox': 2623, 'n_words': 611}