In LiveViewTest’s implementation of open_browser, it creates a temp file. To name that, it implements a function that generates a bunch of random bytes which is used to make a filename that looks like: "phx-#{random_id}". The function looks like this:
def random_id do
"phx-"
|> Kernel.<>(random_encoded_bytes())
|> String.replace(["/", "+"], "-")
end
and random_encoded_bytes looks like this:
defp random_encoded_bytes do
binary = <<
System.system_time(:nanosecond)::64,
:erlang.phash2({node(), self()})::16,
:erlang.unique_integer()::16
>>
Base.url_encode64(binary)
end
My question is not about the implementation of these functions but rather: what’s wrong with simply using "phx#{System.unique_integer()"? I’ve thought on it a bunch but can’t come up with an answer.
Thanks!
mods: I wasn’t exactly sure where to put this. I mention LiveView but the question isn’t really about Phoenix but it’s also not even really about Elixir specifically! Apologies if it needs moving.
Though to remove that last 0.01% chance of collision I’d do it only slightly differently, like so:
def random_id do
"phx-"
|> Kernel.<>(random_encoded_bytes())
|> String.replace(["/", "+"], "-")
end
defp random_encoded_bytes do
8
|> :crypto.strong_rand_bytes()
|> Base.url_encode64()
end
Or you can use only System.unique_integer but with the :monotonic modifier as well.
I didn’t think so, but then why the extra ceremony? The only reason I’ve got then is that they already have Phoenix.LiveView.Utils.random_id so may as well use it! Unsure. Anyway, it’s a bit curious though, like, not the most interesting mystery in the world I’m porting over some of that code, though, so it’s still gonna bug me. I’ll accept your answer… for now
Not sure why it would be useful, but the more-complicated approach has some additional properties:
leading with system_time means that a temp file that sorts later in lexicographic order was created later
using phash2 means that it’s possible to spot temp files that were made by the same process (though 8-bytes into a base64 value is going to be hard to spot visually)
I think our wires may be getting crossed! That :crypto. strong_rand_bytes code is in LiveView. I was assuming by your response about crypto that System.unique_integer wraps a crypto function.
Oh man, LOL. Of course, I’m laughing because it’s such a familiar experience. Just like the classic “Who the *%&$ wrote this crap… git blame… oh, 6-months ago me ”