Flake: random worker id

This commit is contained in:
href 2019-01-27 16:04:36 +01:00
parent 6383fa3a5d
commit e0e0cc5ab0
No known key found for this signature in database
GPG Key ID: EE8296C1A152C325
1 changed files with 3 additions and 18 deletions

View File

@ -90,7 +90,7 @@ def start_link do
@impl GenServer @impl GenServer
def init([]) do def init([]) do
{:ok, %FlakeId{node: mac(), time: time()}} {:ok, %FlakeId{node: worker_id(), time: time()}}
end end
@impl GenServer @impl GenServer
@ -161,23 +161,8 @@ defp time do
1_000_000_000 * mega_seconds + seconds * 1000 + :erlang.trunc(micro_seconds / 1000) 1_000_000_000 * mega_seconds + seconds * 1000 + :erlang.trunc(micro_seconds / 1000)
end end
def mac do defp worker_id() do
{:ok, addresses} = :inet.getifaddrs() <<worker::integer-size(48)>> = :crypto.strong_rand_bytes(6)
macids =
Enum.reduce(addresses, [], fn {_iface, attrs}, acc ->
case attrs[:hwaddr] do
[0, 0, 0 | _] -> acc
mac when is_list(mac) -> [mac_to_worker_id(mac) | acc]
_ -> acc
end
end)
List.first(macids)
end
def mac_to_worker_id(mac) do
<<worker::integer-size(48)>> = :binary.list_to_bin(mac)
worker worker
end end
end end