aboutsummaryrefslogtreecommitdiffstats
path: root/lib/lkn/core/instance.ex
blob: ef16d96cf87f2731e0275764321ab9c82833b5af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
#
# lkn.core: an entity-component-system (ecs) implementation for lyxan
# Copyright (C) 2017 Thomas Letan <contact@thomasletan.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
defmodule Lkn.Core.Instance.Supervisor do
  @moduledoc false

  use Supervisor

  alias Lkn.Core.Name

  def start_link(map_key) do
    Supervisor.start_link(__MODULE__, map_key, name: Name.instance_sup(map_key))
  end

  def init(map_key) do
    children = [
      worker(Lkn.Core.Instance, [map_key])
    ]
    supervise(children, strategy: :simple_one_for_one)
  end
end

defmodule Lkn.Core.Instance do
  @moduledoc """
  A Process to arbitrate the Systems of a given Map.

  There are two things to remember about Instances:

  1. There can be several Instances of a single Map
  2. They are dynamically created by the `Lkn.Core.Pool` of a Map when required

  In other words, it is not the developer job to spawn an Instance.  You can see
  an instance as the entry point of a game scene. It acts as a proxy between
  `Lkn.Core.Puppeteer`s and `Lkn.Core.System`s.

  An Instance will stay alive as long as it hosts at least one
  `Lkn.Core.Puppeteer`. Once it has became empty, it warns its `Lkn.Core.Pool`
  so that the Pool can kill it.
  """
  use Lkn.Prelude

  alias Lkn.Core.Entity
  alias Lkn.Core.Puppet
  alias Lkn.Core, as: L
  alias Lkn.Core.Name
  alias Lkn.Core.Pool
  alias Lkn.Core.Puppeteer
  alias Lkn.Core.System

  @typedoc """
  A key to identify and reach an Instance.
  """
  @type k :: any

  defmodule State do
    @moduledoc false

    defstruct [
      :locked,
      :mode,
      :map_key,
      :instance_key,
      :puppeteers,
    ]

    @type mode :: :running|{:zombie, Option.t(Beacon.t)}

    @type t :: %State {
      locked: boolean,
      mode: mode,
      map_key: L.Map.k,
      instance_key: Instance.k,
      puppeteers: %{Puppeteer.k => Puppeteer.m},
    }

    @spec new(L.Map.k, Instance.k) :: t
    def new(map_key, instance_key) do
      %State{
        locked:       false,
        mode:         :running,
        map_key:      map_key,
        instance_key: instance_key,
        puppeteers:   Map.new(),
      }
    end

    @spec lock(t) :: t
    def lock(state) do
      %State{state|locked: true}
    end

    @spec kick_all(t) :: :ok
    def kick_all(state) do
      Enum.map(state.puppeteers, fn {key, _mod} ->
        Lkn.Core.Puppeteer.leave_instance(key, state.instance_key)
      end)

      :ok
    end

    @spec zombify(t) :: t
    def zombify(state) do
      if Map.size(state.puppeteers) == 0 do
        case Entity.read(state.map_key, :delay) do
          Option.some(delay) ->
            if !state.locked do
              {:ok, timer} = Beacon.start_link(state.map_key)

              timer
              |> Beacon.set_duration(delay,
                                     &(Pool.kill_request(&1, state.instance_key)))
              |> Beacon.enable

              %State{state|mode: {:zombie, Option.some(timer)}}
            else
              # we have been locked so nobody will be able to join the instance again,
              # there is no need to wait.
              Pool.kill_request(state.map_key, state.instance_key)

              %State{state|mode: {:zombie, Option.nothing()}}
            end
          Option.nothing() ->
            # there is no specified delay, so we can die right now
            Pool.kill_request(state.map_key, state.instance_key)

            %State{state|mode: {:zombie, Option.nothing()}}
        end
      else
        state
      end
    end

    @spec closed?(t) :: boolean
    def closed?(state) do
      state.locked || case Entity.read(state.map_key, :limit) do
                        Option.some(limit) -> Map.size(state.puppeteers) == limit
                        Option.nothing() -> false
                      end
    end

    @spec register_puppeteer(t, Puppeteer.k, Puppeteer.m) :: t
    def register_puppeteer(state, puppeteer_key, puppeteer_module) do
      state =  %State{state|puppeteers: Map.put(state.puppeteers, puppeteer_key, puppeteer_module)}
      case state.mode do
        {:zombie, Option.some(timer)} ->
            Beacon.cancel(timer)
            %State{state|mode: :running}
        _ -> state
      end
    end

    @spec unregister_puppeteer(t, Puppeteer.k) :: t
    def unregister_puppeteer(state, puppeteer_key) do
      %State{state|puppeteers: Map.delete(state.puppeteers, puppeteer_key)}
      |> zombify
    end
  end

  use GenServer

  @doc false
  @spec start_link(L.Map.k, k) :: GenServer.on_start
  def start_link(map_key, instance_key) do
    GenServer.start_link(__MODULE__, [map: map_key, instance: instance_key], name: Name.instance(instance_key))
  end

  @doc false
  @spec spawn_instance(L.Map.k, k) :: Supervisor.on_start
  def spawn_instance(map_key, instance_key) do
    Supervisor.start_child(Name.instance_sup(map_key), [instance_key])
  end

  def init(map: map_key, instance: instance_key) do
    sys_map = Entity.systems(map_key)

    _ = Enum.map(sys_map, fn sys ->
      {:ok, _} = System.start_link(sys, instance_key, map_key)
    end)

    {:ok, State.new(map_key, instance_key)}
  end

  @doc """
  Insert a new Puppet into an Instance.

  This function can be used by a `Lkn.Core.Puppeteer` to insert a new Puppet
  into an Instance. There is no notion of Puppet owner, from an Instance point
  of view. Therefore, any Puppeteer can send a command “on behalf of a given
  Puppet. This Puppeteer will have the obligation to unregister it.

  Under the hood, this function dispatches the register event to each system the
  Puppet has a Component for.
  """
  @spec register_puppet(k, Puppet.k) :: :ok
  def register_puppet(instance_key, puppet_key) do
    # get a digest of the puppet and send it to the puppeteer
    notify_puppeteers(instance_key, &Lkn.Core.Puppeteer.puppet_enter(
          &1,
          instance_key,
          puppet_key,
          Lkn.Core.Entity.digest(puppet_key)
        )
    )

    # try registering the puppet to each system
    sys_map = Entity.systems(puppet_key)

    _ = Enum.map(sys_map, fn sys ->
      try do
        Lkn.Core.System.register_puppet(instance_key, sys, puppet_key)
      rescue
        _ -> nil
      end
    end)

    :ok
  end

  @doc """
  Remove a Puppet from an Instance.

  This function can be used by a `Lkn.Core.Puppeteer` to an Instance. An
  Instance will never do it by itself, so it needs to be done by the Puppeteer
  owner, e.g. before it registers istelf. Note that, if the Puppeteer forgets to
  unregister one of its Puppets, this Puppets will stay in this Instance as long
  as at least one Puppeteer stays registered (and it will probably do nothing at
  all).
  """
  @spec unregister_puppet(k, Puppet.k) :: :ok
  def unregister_puppet(instance_key, puppet_key) do
    # unregister the pupet from each systems
    sys_map = Entity.systems(puppet_key)

    _ = Enum.map(sys_map, fn sys ->
      try do
        Lkn.Core.System.unregister_puppet(instance_key, sys, puppet_key)
      rescue
        _ -> nil
      end
    end)

    # notify the puppeteers
    notify_puppeteers(instance_key, &Lkn.Core.Puppeteer.puppet_leave(
          &1,
          instance_key,
          puppet_key
        )
    )

    :ok
  end

  @doc false
  @spec register_puppeteer(k, Puppeteer.k, Puppeteer.m) :: boolean
  def register_puppeteer(instance_key, puppeteer_key, puppeteer_module) do
    GenServer.call(Name.instance(instance_key), {:register_puppeteer, puppeteer_key, puppeteer_module})
  end

  @doc false
  @spec lock(k) :: :ok
  def lock(instance_key) do
    GenServer.call(Name.instance(instance_key), :lock)
    :ok
  end

  @doc false
  @spec kick_all(k) :: :ok
  def kick_all(instance_key) do
    GenServer.cast(Name.instance(instance_key), :kick_all)
  end

  @doc false
  @spec kill(k) :: boolean
  def kill(instance_key) do
    GenServer.call(Name.instance(instance_key), :killme)
  end

  @doc """
  Notify an Instance that a given Puppeteer is leaving.

  This function needs to be used by a Puppeteer, __after__ it has removed all of
  its Puppets. Right now, a Puppeteer cannot choose its Instance to join, and
  the `Lkn.Core.Pool.register_puppeteer` is the function to use to join the
  Instance of a given Map.
  """
  @spec unregister_puppeteer(k, Puppeteer.k) :: :ok
  def unregister_puppeteer(instance_key, puppeteer_key) do
    GenServer.cast(Name.instance(instance_key), {:unregister_puppeteer, puppeteer_key})

    Registry.unregister(Lkn.Core.Notifier, Name.notify_group(instance_key))
  end

  def handle_call(:lock, _from, state) do
    {:reply, :ok, State.lock(state)}
  end
  def handle_call({:register_puppeteer, puppeteer_key, puppeteer_module}, _from, state) do
    if !State.closed?(state) do
      {:reply, true, State.register_puppeteer(state, puppeteer_key, puppeteer_module)}
    else
      {:reply, false, state}
    end
  end
  def handle_call(:killme, _from, state) do
    case state.mode do
      :running -> {:reply, false, state}
      {:zombie, _} -> {:stop, :normal, true, state}
    end
  end

  def handle_cast(:kick_all, state) do
    State.kick_all(state)
    {:noreply, state}
  end
  def handle_cast({:unregister_puppeteer, puppeteer_key}, state) do
    {:noreply, State.unregister_puppeteer(state, puppeteer_key)}
  end

  def notify_puppeteers(instance_key, notif) do
    Registry.dispatch(Lkn.Core.Notifier, Name.notify_group(instance_key), fn entries ->
      for {_, key} <- entries do
        notif.(key)
      end
    end)
  end
end