Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cache precision per device #104

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 27 additions & 19 deletions lib/mtime-precision.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,48 @@
const cacheSymbol = Symbol();

function probe(file, fs, callback) {
const cachedPrecision = fs[cacheSymbol];
let cachedPrecisions = fs[cacheSymbol];
if (cachedPrecisions === undefined) {
cachedPrecisions = new Map();

if (cachedPrecision) {
return fs.stat(file, (err, stat) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

callback(null, stat.mtime, cachedPrecision);
});
// Cache the precisions in a non-enumerable way
Object.defineProperty(fs, cacheSymbol, { value: cachedPrecisions });
}

// Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);

fs.utimes(file, mtime, mtime, (err) => {
return fs.stat(file, (err, stat) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

fs.stat(file, (err, stat) => {
const dev = stat.dev;

// Precisions are cached by device, see #103
const precision = cachedPrecisions.get(dev);
if (precision !== undefined) {
return callback(null, stat.mtime, precision);
}

// Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);

fs.utimes(file, mtime, mtime, (err) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
fs.stat(file, (err, stat) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

// Cache the precision in a non-enumerable way
Object.defineProperty(fs, cacheSymbol, { value: precision });
const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
cachedPrecisions.set(dev, precision);

callback(null, stat.mtime, precision);
callback(null, stat.mtime, precision);
});
});
});
}
Expand Down