I’m working with setting up an API in Julia. It requires tokens, which periodically expire. I currently have my tokens saved in “tokens.json” file, which I read when initializing the code. However, I wanted to create a function that automatically updates the tokens when necessary.
I’m new to Julia, and I haven’t really used threading before, so I was wondering if this was a possibility to safely access the tokens. I.e, what’s the best way to have another process that runs in the background and automatically updates these tokens. Is it safe to load the json file in another thread, check/update, and then write back to that json file? And then how would it work to access the updated json file in other parts of my code where I’m using the tokens.
I tried Threads.Atomic but it wouldn’t let me store complex objects like Dict(). Should I do something with Threads.@spawn? Thanks.
When writing the json file to not end up with a partially written file.
You can do something like:
# safely update the json file `file_name` in `dir_name` directory
mktemp(dir_name) do temp_path, temp_out
nb = write(temp_out, data)
if nb != length(data)
error("short write of $(repr(file_name)) data")
end
close(temp_out)
mv(temp_path, joinpath(dir_name, file_name); force=true)
end
Though this may throw an error on Windows sometimes.
I would also recommend storing a checksum in the json file so you can detect if you are reading invalid data.
That’s exactly what I’m trying to avoid. Is there a way to safely access it across multiple threads in a way that doesn’t throw an error? I.e. there’s a threading process that updates but pushes to a “safe” latest version which the other parts access.
If you need to use a JSON file, you could try to write a temp file, then rename it to the original file, and if that fails because the original file is open, write a tokens-v2.json file. Then when reading, always try and read the latest version of the file, using readdir(dir_name) to see the available versions of the JSON file.