# `MishkaInstaller.Event.Hook`
[🔗](https://github.com/mishka-group/mishka_installer/blob/v0.1.14/lib/event/hook.ex#L1)

The `MishkaInstaller.Event.Hook` module provides a set of functionalities to manage event hooks
within the Mishka Installer system.

It leverages `GenServer` to handle asynchronous event-driven operations and offers a set of
macros and functions for registering, starting, stopping, and managing hooks dynamically.

In addition to being one of the most significant modules of the MishkaInstaller library,
the Hook module gives you the ability to make the library as a whole,
as well as the projects that make use of this library, more modular.

It is essential to comprehend that you may treat any action performed independently
as an event and register an unlimited number of plugins for that event.

You can do this by considering that action to be done separately.
Each plugin has the potential to have its own individual inputs and outputs,
and depending on the architecture of the area that you want to use Hook in,
you may even be able to change the output and send it to other plugins.

Throughout all of the many parts that have been built for this module,
it has been attempted to have a flexible approach to dealing with errors
and to provide the programmer with a wide variety of options.

With the additional functions at her disposal, the programmer can actually create a
gateway in their projects, where the data flow must pass through several gates,
whether it changes or remains unchanged, and a series of operations are performed.

For illustration's sake, let's suppose you want the registration system to allow users
to sign up for social networks on Twitter and Google.

When you use this library, it is conceivable that you can quickly display HTML
or even operate in the background before registering after registering.

This is a significant improvement over the standard practice,
in which you are required to modify the primary codes of your project. Create a separate plugin.

It is interesting to notice that these facilities are quite basic and convenient for the admin user.

If this opportunity is provided, the management can manage its own plugins in different ways
if it has a dashboard.

It is crucial to highlight that each plugin is its own `GenServer`; in addition,
it is dynamically supervised, and the information is stored in the database as well as in Mnesia.

Furthermore, this section is very useful even if the programmer wants to perform many tasks
that are not associated with Perform defined functions.

The fact that the programmers have to introduce each plugin to the system based on a specific
behavior is one of the exciting aspects of using this section. Additionally,
the system has prepared some default behaviors to force the programmers
to introduce the plugins in the order specified by the system.

The use of custom behaviors on the part of the programmer and MishkaInstaller itself makes debugging easier;
however, this library does not leave the programmer to fend for themselves in this significant matter;
rather, a straightforward error storage system is prepared based on the particular activities being performed.

Should prevent any unpredictable behavior at any costs.

---

## Build purpose
---

Imagine you are going to make an application that will have many plugins built for it in the future.
But the fact that many manipulations will be made on your source code makes it
difficult to maintain the application.

For example, you present a content management system for your users, and now they need to
activate a section for registration and SMS; the system allows you to present your desired
`input/output` absolutely plugin oriented to your users and makes it possible for the
developers to write their required applications beyond the core source code.

---

The library categorizes your whole software design structure into many parts;
and has an appropriate dependency that is optional with `GenServer`;
it considers a monitoring branch for each of your plugins, which results in fewer errors and `downtime`.

The considered part:

1. Behaviors and events
2. Recalling or `Hook` with priority
3. `State` management and links to the database (`Mnesia` support)

> Most of the sections mentioned can be fully customized to suit your needs.
> This library offers a range of predefined strategies for public use, which might
> be sufficient for your requirements.

In Mishka Elixir Plugin Management Library, a series of action or `hook` functions are given
to the developer of the main plugin or software, which helps build plugins outside the system
and convert software sections into separate `events`.

Some of the functions of this module include the following:

- `config/0` - Retrieves the merged configuration for the hook module.
- `config/1` - Retrieves a specific configuration value by key.
- `register/0` - Register a plugin for a specific event.
- `start/0` - Start a plugin of a specific event.
- `restart/0` - Restart a plugin of a specific event.
- `stop/0` - Stop (disable) a plugin of a specific event.
- `enable/0` - Re-enable a plugin that was stopped.
- `unregister/0` - Unregister a plugin of a specific event.
- `get/0` - Retrieves a Plugin `GenServer` state.

### Example:

```elixir
defmodule RegisterEmailSender do
  use MishkaInstaller.Event.Hook, event: "after_success_login"

  def call(entries) do
    {:reply, entries}
  end
end
```

If you want to change a series of default information, do this:

```elixir
use MishkaInstaller.Event.Hook,
  event: "after_success_login",
  initial: %{depends: [SomeEvent], priority: 20}
```

> There should be one main functions in each plugin, namely `call`. In this function,
> whenever the action function calls this special event for which the plugin is written,
> based on priority. This plugin is also called. But what is important is the final output
> of the `call` function.
> This output may be the input of other plugins with higher priorities.
> The order of the plugins is from small to large, and if several plugins are registered for a number,
> it is sorted by name in the second parameter. And it should be noted that in any case,
> if you did not want this `state` to go to other plugins and the last output is returned in the same plugin,
> and you can replace `{:reply, :halt, new_state}` with `{:reply, new_state}`.

**Note: If you want your plugin to execute automatically,
all you need to do is send the name of the module in which you utilized
the `MishkaInstaller.Event.Hook` to the Application module.***

> On every boot the plugin adopts its stored status, with one self-heal: a record still in
> `:registered` (it was written, but its very first `start` never completed — an interrupted
> boot, an early Mnesia hiccup) is started again automatically. A `:stopped` or `:held`
> record is never auto-started — that is the operator's switch and it survives restarts.
>
> Registration is an upsert on the plugin name, so the fields you declare in `initial`
> (`:priority`, `:extra`, `:depends`) are re-applied on every boot and reach installs that
> registered with an older version of your plugin; the stored status is left alone.

```elixir
children = [
  ...
  RegisterEmailSender
]

...
opts = [strategy: :one_for_one, name: SomeModule.Supervisor]
Supervisor.start_link(children, opts)
```

#### You can call all plugins of an event:

```elixir
alias MishkaInstaller.Event.Hook

# Normal call an event plugins
Hook.call("after_success_login", params)

# If you want certain entries not to change
Hook.call("after_success_login", params, [private: something_based_on_your_data])

# If you want the initial entry to be displayed at the end
Hook.call("after_success_login", params, [return: true])

# If you want another answer than `params` when a plugin of the event is not loaded
Hook.call("after_success_login", params, [cannot_run: {:error, :refused}])
```

> #### Use cases information {: .tip}
>
> Module `MishkaInstaller.Event.Event` has all of the preset functionalities, and it is
> simple for you to build and implement your own strategy because of this.
>
> You can override these functions:
> `register: 0`, `start: 0`, `restart: 0`, `stop: 0`, `enable: 0`, `unregister: 0`, `get: 0`

### Statuses, and what `depends` does

A plugin is in exactly one of five statuses, and only two of them are decisions someone made:

| Status | Meaning |
| --- | --- |
| `:registered` | stored, never started yet |
| `:started` / `:restarted` | running, and part of its event's compiled chain |
| `:stopped` | **an operator switched it off** — survives restarts and dependency changes |
| `:held` | **its dependencies are not all active** — restored automatically when they are |

`depends: [OtherPlugin]` means "do not run me unless `OtherPlugin` runs". Stopping, unregistering
or holding `OtherPlugin` therefore holds this plugin too, transitively, across events, and drops it
from its compiled chain within the same call; switching `OtherPlugin` back on releases everything it
was holding. All of a plugin's dependencies must be active for it to run, and nothing anywhere keeps
a list of "children" — the reverse edges are read from the stored `depends` (see
`MishkaInstaller.Event.Event.dependents/1` and `MishkaInstaller.Event.Event.sync_dependents/2`).

The two decisions never override each other: releasing a dependency never re-enables a plugin an
operator stopped, and `restart/0` refuses a `:stopped` plugin — only `enable/0` switches it back on.
A `:held` plugin can still be stopped, since "blocked by a dependency" and "switched off" are
different things.

### Consideration:

It should be brought to your attention that the output of the `call` function has a few trade-offs.
These trade-offs do not restrict your ability to customize the outcome of the `call` function;
nevertheless, they do cause you to move away from the foreseen and planned structure that is the
approach that this library takes.

In situations when you have access to a `:private` key, it is preferable for your data to be in the
form of a `Map` or a `Keyword`. This allows you to perform an accurate match prior to the
output of the data.
With the exception of these two circumstances, we do not collect any other data.

---

The list below is all the outputs that are checked in the form of different wrist patterns:

```elixir
{:ok, data} when is_list(data) # It can be merged with the `:private` key
{:ok, data} when is_map(data) # It can be merged with the `:private` key
# If you have :private, we do not recommend to use this pattern
{:ok, data} # It can not be merged with the `:private` key
{:error, _errors} # It does not need to be merged
data when is_list(data) # It can be merged with the `:private` key
data when is_map(data) # It can be merged with the `:private` key
data # Any other state, such as `{:noreply, socket}`: it comes back as the plugins left it
```

### For example:

We do not recommend these the data or error data; they should have `Map` or `Keyword` format.

```elixir
def call(entries) do
  {:reply, :halt, {:ok, "Message is sent!"}}
end

def call(entries) do
  {:reply, entries}
end
```

But it is recommended to use these.

```elixir
def call(entries) do
  {:reply, :halt, {:ok, %{name: "mishka"}}
end

def call(entries) do
  {:reply, {:ok, [name: "mishka"]}
end

def call(entries) do
  {:reply, {:error, any_data}
end
```

> #### Use cases information {: .tip}
>
> Take note that you have the ability to set the `queue` of a plugin to `false` while
> you are defining it. This will ensure that the implementation and build of
> the event state module are not **queued**.
>
> For projects that require a significant amount of time to compile their events module,
> this possibility has been implemented. Additionally, these projects may have created a
> series of conditions in order to avoid race conditions from occurring within their system.
>
> It is `true` by default and recommend to set `false` till you get some problem.

##### Example:
```elixir
use MishkaInstaller.Event.Hook, event: "after_success_login", queue: false
```

[![Run in Livebook](https://livebook.dev/badge/v1/pink.svg)](https://livebook.dev/run?url=https%3A%2F%2Fgithub.com%2Fmishka-group%2Fmishka_installer%2Fblob%2Fmaster%2Fguidance%2Fevent%2Fhook.livemd)

# `error_return`

```elixir
@type error_return() ::
  {:error, [%{action: atom(), field: atom(), message: String.t()}]}
```

# `okey_return`

```elixir
@type okey_return() :: {:ok, struct() | map() | module() | [any()]}
```

# `call`
*optional* 

```elixir
@callback call(any()) :: any()
```

# `call`
*optional* 

```elixir
@callback call(any(), meta :: any()) :: any()
```

# `enable`
*optional* 

```elixir
@callback enable() :: okey_return() | error_return()
```

# `get`
*optional* 

```elixir
@callback get() :: keyword()
```

# `health_check`
*optional* 

```elixir
@callback health_check() :: :ok | {:degraded, term()} | {:error, term()}
```

# `on_dependency_error`
*optional* 

```elixir
@callback on_dependency_error(term()) :: term()
```

# `register`
*optional* 

```elixir
@callback register() :: okey_return() | error_return()
```

# `restart`
*optional* 

```elixir
@callback restart() :: okey_return() | error_return()
```

# `start`
*optional* 

```elixir
@callback start() :: okey_return() | error_return()
```

# `stop`
*optional* 

```elixir
@callback stop() :: okey_return() | error_return()
```

# `unregister`
*optional* 

```elixir
@callback unregister() :: okey_return() | error_return()
```

# `call`

```elixir
@spec call(String.t(), any(), keyword()) :: any()
```

Invokes the `call/2` function of the specified event module.

## Parameters
- `event` (String.t()): The name of the event.
- `data` (any()): The data to be passed to the event module.
- `args` (keyword()): Additional arguments for the call:
  - `private` — merged into a list or map result, untouched by the plugins.
  - `return` — when set, the plugins run and `data` is returned as it was given.
  - `meta` — read-only side context handed to plugins that opt in with `call/2`; unlike `private`
    it is never merged into the result.
  - `cannot_run` — the answer when the event cannot run: one of its plugins is started but not
    loaded, so none of them runs. Without it that event answers `data`. An event whose plugins
    all run ignores it.

## Returns
- `any()`: The result of the event module's `call/2` function; `data` when the event is not
  compiled (it has no plugins); the `cannot_run` answer, or `data`, when it cannot run.

## Examples
```elixir
MishkaInstaller.Event.Hook.call("my_event", %{}, [])

# A decision the plugins take part in refuses when they cannot run
MishkaInstaller.Event.Hook.call("auth:gate:check", gate, cannot_run: %{gate | allowed?: false})
```

# `call!`

```elixir
@spec call!(String.t(), any(), keyword()) :: any()
```

The only difference between this function and the `call/3` function is that the former
does not check in a single step whether the required event has been compiled or not.
When you are 100% certain that the event you want is present in the system,
using it is the best option.

It takes the same `args`, `cannot_run` included: an event that cannot run answers it, or `data`.

# `event_health`

```elixir
@spec event_health(String.t(), timeout()) :: map()
```

Health report for an event: whether its module is compiled, its `mode` (`:error` means it has
plugins that are started but not loaded — see issue #1), and a report for each plugin in the
chain. Plugin probes run concurrently and time-boxed. `healthy?` is the overall verdict.

# `health`

```elixir
@spec health(timeout()) :: [map()]
```

Health report for every event in the system. See `event_health/2`.

# `plugin_health`

```elixir
@spec plugin_health(module(), timeout()) :: map()
```

Health report for a single plugin. Combines built-in checks — process `alive?`, module
`callable?`, registry `status` — with the plugin's optional `c:health_check/0` probe (run in a
time-boxed process, so it never blocks the plugin or the caller).

`probe` is `:ok | {:degraded, reason} | {:error, reason}` (with `{:error, :timeout}`,
`{:error, :no_health_check}`, `{:error, {:raised, _}}` ... for the failure variants). `healthy?`
is the overall verdict.

# `profile`

```elixir
@spec profile(String.t(), any()) :: {:ok, [map()]} | {:error, :not_compiled}
```

Profiles an event's compiled plugin chain: runs each plugin once with `state` and returns how long
each took, in microseconds, in execution order.

This is a **development/debugging** helper. It runs the same plugins as `call/3` but is a separate,
off-the-hot-path function, so production dispatch keeps zero profiling overhead. For a visual flame
graph, add [`flame_on`](https://hexdocs.pm/flame_on) to your host app's `LiveDashboard` and profile
`MishkaInstaller.Event.Hook.call/3`.

Returns `{:ok, [%{plugin: module(), microseconds: non_neg_integer()}]}` or `{:error, :not_compiled}`.

# `run_health`

```elixir
@spec run_health(module(), timeout()) :: :ok | {:degraded, term()} | {:error, term()}
```

Runs a plugin's `c:health_check/0` probe in a short-lived monitored process, bounded by `timeout`.
Never blocks the plugin's `GenServer` and never crashes the caller: a slow probe yields
`{:error, :timeout}`, a raising/exiting one `{:error, {:raised | :exit, _}}`, a non-conforming
return `{:error, {:bad_return, _}}`, and a plugin without the callback `{:error, :no_health_check}`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
