Kotlin / kotlinx-io

Kotlin multiplatform I/O library
Apache License 2.0
1.29k stars 59 forks source link

Add support for atomic file creation #369

Open zx96 opened 3 months ago

zx96 commented 3 months ago

FileSystem.sink has no ability to create new files atomically (POSIX O_CREAT | O_EXCL, Win32 CREATE_NEW, Java StandardOpenOption.CREATE_NEW). This feels like fairly fundamental functionality for a file I/O library, and is currently the sole reason I am unable to use kotlinx.io over java.nio in an application.

I would propose adding another keyword argument to FileSystem.sink to specify whether an existing file should be overwritten. This parameter would allow the implementation to use an appropriate set of flags when creating the file to ensure the file is created atomically, or could throw an exception if atomic creation is unsupported on a given platform. This parameter could default to true in order to preserve existing behavior in the API, or default to false to provide a safer default behavior:

abstract fun sink(path: Path, append: Boolean = false, overwrite: Boolean = true): RawSink

This change would allow files to be created without risk of a race condition causing files to be overwritten unexpectedly.