Renaming over other files does not properly free space
OC version: 1.7.7.2-GTNH
To "atomically" replace the contents of files, I want to use something like the following:
function calledEveryFewSeconds()
local f = fs.open("output.json.new", "wb")
f:write(someData)
f:close()
fs.rename("output.json.new", "output.json") -- this should free any space used by the previous file
end
However, I observe that instead of constant disk usage, the disk used increases over time until the disk is full and creating the new file fails. When I remove the hard disk and reinsert it, rebooting the OC computer, the usage is correctly recalculated back to the (much) lower level.
For now, I'm working around it by explicitly removing the existing file before renaming, however this is unfortunate because I'd like to host a webserver on the same box that serves up the file for a pretty web ui. I'd like the webserver to never see the file missing -- and this 'rename' technique is the easiest way to get that.
I'm think the issue is that only delete() is overridden at https://github.com/MightyPirates/OpenComputers/blob/master-MC1.7.10/src/main/scala/li/cil/oc/server/fs/Capacity.scala#L26, and rename() should also be overridden since it can result in a file being deleted.
Broadly speaking, OpenComputers does not allow usage of fs.rename in this manner - the fact it works at all is due to bufferChanges in the GT:NH fork being set to false, which is a non-default option.
This is especially tricky as the usage you're trying to perform with bufferChanges being set to false would work on Linux, but not on Windows, whose filesystem rename() call will not succeed if the target file exists, rather than overwrite it. I'm really not sure what the best way to solve this inconsistency is...
I'm of the opinion OpenComputers should break this usecase, as it is impossible to make it work consistently in a cross-platform manner (on Windows, we'd need to quietly delete the file first anyway).
I'm not sure how feasible calling Win32 functions is, but MoveFileEXW()1 can do it:
MoveFileEXW(L"replacement.txt", L"destination.txt", MOVEFILE_REPLACE_EXISTING)
Alternatively, the C++17 standard library function2 has POSIX semantics (overwrite):
#include <filesystem>
void foo() {
std::filesystem::rename("oldfile", "newfile");
}
I did a quick test (Windows 11), there's a REPLACE_EXISTING option for Files.move that appears to do the trick. Test program:
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class RenameTest {
public static void main(String[] args) throws Throwable {
var fs = FileSystems.getDefault();
Files.move(fs.getPath("a.txt"), fs.getPath("b.txt"), StandardCopyOption.REPLACE_EXISTING);
}
}
So going with rename = replace should be feasible in a consistent fashion?