* Try `O_WRONLY | O_CREAT | O_EXCL` to create the lock file with the contents. * Returns true on success, false on EEXIST. Throws on any other fs error.
(path: string, contents: LockContents)
| 162 | * Returns true on success, false on EEXIST. Throws on any other fs error. |
| 163 | */ |
| 164 | function tryExclusiveCreate(path: string, contents: LockContents): boolean { |
| 165 | let fd: number | undefined; |
| 166 | try { |
| 167 | // 0o100 (O_CREAT) | 0o200 (O_EXCL) | 0o2 (O_RDWR) — but `openSync` accepts the |
| 168 | // string flag form which is portable. Mode 0o600 so the lock file (which |
| 169 | // lives next to the per-pid token file) is not world/group readable |
| 170 | // (ROADMAP M5.2). |
| 171 | fd = openSync(path, 'wx', 0o600); |
| 172 | writeFileSync(fd, JSON.stringify(contents)); |
| 173 | return true; |
| 174 | } catch (err) { |
| 175 | if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false; |
| 176 | throw err; |
| 177 | } finally { |
| 178 | if (fd !== undefined) { |
| 179 | try { |
| 180 | closeSync(fd); |
| 181 | } catch { |
| 182 | // already closed by writeFileSync in some Node versions — ignore. |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * Acquire an exclusive lock for this server instance. Throws `ServerLockedError` |