All files / lib/internal/fs watchers.js

89.42% Statements 338/378
78.79% Branches 52/66
81.82% Functions 18/22
89.42% Lines 338/378

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 37918x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 12x 12x 12x 18x 14x 14x 14x 14x 14x 14x 14x 14x 14x 18x 18x 18x 9x 9x 9x 9x 9x     9x 9x 9x 9x 9x 18x 18x 18x 18x 18x 18x 18x 18x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x                 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 14x 14x 12x 12x 12x 12x 12x 12x 12x 18x 18x 18x 18x 12x 1x 1x 1x 12x 2x 2x 2x 11x 9x 9x 9x 9x 9x 18x 18x 18x 3x 3x 3x 3x 3x 2x 18x 18x 18x 7x 7x 7x 7x 5x 18x 18x 18x 30x 30x 30x 30x 30x 30x 30x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 11x 11x 30x 30x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 31x 31x 31x 31x     31x 31x     30x 30x 30x 30x 30x 30x 30x 31x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 20x 5x 5x 15x 20x     14x 14x 14x 18x 18x 18x 1x 1x 18x 18x 18x 2x 2x 18x 18x 14x 14x 14x 18x 18x 18x 18x 18x 18x 18x 18x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 3x 9x 9x 3x 3x 3x 3x 1x 1x 3x 3x 3x 9x 9x 2x                     2x 2x 9x 9x 9x 9x                       3x 9x 3x       9x 3x 3x 3x 9x 18x 18x 18x 18x 18x 18x 18x 18x 18x  
'use strict';
 
const {
  FunctionPrototypeCall,
  ObjectDefineProperty,
  ObjectSetPrototypeOf,
  Symbol,
} = primordials;
 
const {
  AbortError,
  uvException,
  codes: {
    ERR_INVALID_ARG_VALUE,
  },
} = require('internal/errors');
const { createDeferredPromise } = require('internal/util');
 
const {
  kFsStatsFieldsNumber,
  StatWatcher: _StatWatcher
} = internalBinding('fs');
 
const { FSEvent } = internalBinding('fs_event_wrap');
const { UV_ENOSPC } = internalBinding('uv');
const { EventEmitter } = require('events');
 
const {
  getStatsFromBinding,
  getValidatedPath
} = require('internal/fs/utils');
 
const {
  defaultTriggerAsyncIdScope,
  symbols: { owner_symbol }
} = require('internal/async_hooks');
 
const { toNamespacedPath } = require('path');
 
const {
  validateAbortSignal,
  validateBoolean,
  validateObject,
  validateUint32,
} = require('internal/validators');
 
const {
  Buffer: {
    isEncoding,
  },
} = require('buffer');
 
const assert = require('internal/assert');
 
const kOldStatus = Symbol('kOldStatus');
const kUseBigint = Symbol('kUseBigint');
 
const kFSWatchStart = Symbol('kFSWatchStart');
const kFSStatWatcherStart = Symbol('kFSStatWatcherStart');
const KFSStatWatcherRefCount = Symbol('KFSStatWatcherRefCount');
const KFSStatWatcherMaxRefCount = Symbol('KFSStatWatcherMaxRefCount');
const kFSStatWatcherAddOrCleanRef = Symbol('kFSStatWatcherAddOrCleanRef');
 
function emitStop(self) {
  self.emit('stop');
}
 
function StatWatcher(bigint) {
  FunctionPrototypeCall(EventEmitter, this);
 
  this._handle = null;
  this[kOldStatus] = -1;
  this[kUseBigint] = bigint;
  this[KFSStatWatcherRefCount] = 1;
  this[KFSStatWatcherMaxRefCount] = 1;
}
ObjectSetPrototypeOf(StatWatcher.prototype, EventEmitter.prototype);
ObjectSetPrototypeOf(StatWatcher, EventEmitter);
 
function onchange(newStatus, stats) {
  const self = this[owner_symbol];
  if (self[kOldStatus] === -1 &&
      newStatus === -1 &&
      stats[2/* new nlink */] === stats[16/* old nlink */]) {
    return;
  }
 
  self[kOldStatus] = newStatus;
  self.emit('change', getStatsFromBinding(stats),
            getStatsFromBinding(stats, kFsStatsFieldsNumber));
}
 
// At the moment if filename is undefined, we
// 1. Throw an Error if it's the first
//    time Symbol('kFSStatWatcherStart') is called
// 2. Return silently if Symbol('kFSStatWatcherStart') has already been called
//    on a valid filename and the wrap has been initialized
// This method is a noop if the watcher has already been started.
StatWatcher.prototype[kFSStatWatcherStart] = function(filename,
                                                      persistent,
                                                      interval) {
  if (this._handle !== null)
    return;
 
  this._handle = new _StatWatcher(this[kUseBigint]);
  this._handle[owner_symbol] = this;
  this._handle.onchange = onchange;
  if (!persistent)
    this.unref();
 
  // uv_fs_poll is a little more powerful than ev_stat but we curb it for
  // the sake of backwards compatibility.
  this[kOldStatus] = -1;
 
  filename = getValidatedPath(filename, 'filename');
  validateUint32(interval, 'interval');
  const err = this._handle.start(toNamespacedPath(filename), interval);
  if (err) {
    const error = uvException({
      errno: err,
      syscall: 'watch',
      path: filename
    });
    error.filename = filename;
    throw error;
  }
};
 
// To maximize backward-compatibility for the end user,
// a no-op stub method has been added instead of
// totally removing StatWatcher.prototype.start.
// This should not be documented.
StatWatcher.prototype.start = () => {};
 
// FIXME(joyeecheung): this method is not documented while there is
// another documented fs.unwatchFile(). The counterpart in
// FSWatcher is .close()
// This method is a noop if the watcher has not been started.
StatWatcher.prototype.stop = function() {
  if (this._handle === null)
    return;
 
  defaultTriggerAsyncIdScope(this._handle.getAsyncId(),
                             process.nextTick,
                             emitStop,
                             this);
  this._handle.close();
  this._handle = null;
};
 
// Clean up or add ref counters.
StatWatcher.prototype[kFSStatWatcherAddOrCleanRef] = function(operate) {
  if (operate === 'add') {
    // Add a Ref
    this[KFSStatWatcherRefCount]++;
    this[KFSStatWatcherMaxRefCount]++;
  } else if (operate === 'clean') {
    // Clean up a single
    this[KFSStatWatcherMaxRefCount]--;
    this.unref();
  } else if (operate === 'cleanAll') {
    // Clean up all
    this[KFSStatWatcherMaxRefCount] = 0;
    this[KFSStatWatcherRefCount] = 0;
    this._handle?.unref();
  }
};
 
StatWatcher.prototype.ref = function() {
  // Avoid refCount calling ref multiple times causing unref to have no effect.
  if (this[KFSStatWatcherRefCount] === this[KFSStatWatcherMaxRefCount])
    return this;
  if (this._handle && this[KFSStatWatcherRefCount]++ === 0)
    this._handle.ref();
  return this;
};
 
StatWatcher.prototype.unref = function() {
  // Avoid refCount calling unref multiple times causing ref to have no effect.
  if (this[KFSStatWatcherRefCount] === 0) return this;
  if (this._handle && --this[KFSStatWatcherRefCount] === 0)
    this._handle.unref();
  return this;
};
 
 
function FSWatcher() {
  FunctionPrototypeCall(EventEmitter, this);
 
  this._handle = new FSEvent();
  this._handle[owner_symbol] = this;
 
  this._handle.onchange = (status, eventType, filename) => {
    // TODO(joyeecheung): we may check self._handle.initialized here
    // and return if that is false. This allows us to avoid firing the event
    // after the handle is closed, and to fire both UV_RENAME and UV_CHANGE
    // if they are set by libuv at the same time.
    if (status < 0) {
      if (this._handle !== null) {
        // We don't use this.close() here to avoid firing the close event.
        this._handle.close();
        this._handle = null;  // Make the handle garbage collectable.
      }
      const error = uvException({
        errno: status,
        syscall: 'watch',
        path: filename
      });
      error.filename = filename;
      this.emit('error', error);
    } else {
      this.emit('change', eventType, filename);
    }
  };
}
ObjectSetPrototypeOf(FSWatcher.prototype, EventEmitter.prototype);
ObjectSetPrototypeOf(FSWatcher, EventEmitter);
 
// At the moment if filename is undefined, we
// 1. Throw an Error if it's the first time Symbol('kFSWatchStart') is called
// 2. Return silently if Symbol('kFSWatchStart') has already been called
//    on a valid filename and the wrap has been initialized
// 3. Return silently if the watcher has already been closed
// This method is a noop if the watcher has already been started.
FSWatcher.prototype[kFSWatchStart] = function(filename,
                                              persistent,
                                              recursive,
                                              encoding) {
  if (this._handle === null) {  // closed
    return;
  }
  assert(this._handle instanceof FSEvent, 'handle must be a FSEvent');
  if (this._handle.initialized) {  // already started
    return;
  }
 
  filename = getValidatedPath(filename, 'filename');
 
  const err = this._handle.start(toNamespacedPath(filename),
                                 persistent,
                                 recursive,
                                 encoding);
  if (err) {
    const error = uvException({
      errno: err,
      syscall: 'watch',
      path: filename,
      message: err === UV_ENOSPC ?
        'System limit for number of file watchers reached' : ''
    });
    error.filename = filename;
    throw error;
  }
};
 
// To maximize backward-compatibility for the end user,
// a no-op stub method has been added instead of
// totally removing FSWatcher.prototype.start.
// This should not be documented.
FSWatcher.prototype.start = () => {};
 
// This method is a noop if the watcher has not been started or
// has already been closed.
FSWatcher.prototype.close = function() {
  if (this._handle === null) {  // closed
    return;
  }
  assert(this._handle instanceof FSEvent, 'handle must be a FSEvent');
  if (!this._handle.initialized) {  // not started
    return;
  }
  this._handle.close();
  this._handle = null;  // Make the handle garbage collectable.
  process.nextTick(emitCloseNT, this);
};
 
FSWatcher.prototype.ref = function() {
  if (this._handle) this._handle.ref();
  return this;
};
 
FSWatcher.prototype.unref = function() {
  if (this._handle) this._handle.unref();
  return this;
};
 
function emitCloseNT(self) {
  self.emit('close');
}
 
// Legacy alias on the C++ wrapper object. This is not public API, so we may
// want to runtime-deprecate it at some point. There's no hurry, though.
ObjectDefineProperty(FSEvent.prototype, 'owner', {
  get() { return this[owner_symbol]; },
  set(v) { return this[owner_symbol] = v; }
});
 
async function* watch(filename, options = {}) {
  const path = toNamespacedPath(getValidatedPath(filename));
  validateObject(options, 'options');
 
  const {
    persistent = true,
    recursive = false,
    encoding = 'utf8',
    signal,
  } = options;
 
  validateBoolean(persistent, 'options.persistent');
  validateBoolean(recursive, 'options.recursive');
  validateAbortSignal(signal, 'options.signal');
 
  if (encoding && !isEncoding(encoding)) {
    const reason = 'is invalid encoding';
    throw new ERR_INVALID_ARG_VALUE(encoding, 'encoding', reason);
  }
 
  if (signal?.aborted)
    throw new AbortError();
 
  const handle = new FSEvent();
  let { promise, resolve, reject } = createDeferredPromise();
  const oncancel = () => {
    handle.close();
    reject(new AbortError());
  };
 
  try {
    signal?.addEventListener('abort', oncancel, { once: true });
    handle.onchange = (status, eventType, filename) => {
      if (status < 0) {
        const error = uvException({
          errno: status,
          syscall: 'watch',
          path: filename
        });
        error.filename = filename;
        handle.close();
        reject(error);
        return;
      }
 
      resolve({ eventType, filename });
    };
 
    const err = handle.start(path, persistent, recursive, encoding);
    if (err) {
      const error = uvException({
        errno: err,
        syscall: 'watch',
        path: filename,
        message: err === UV_ENOSPC ?
          'System limit for number of file watchers reached' : ''
      });
      error.filename = filename;
      handle.close();
      throw error;
    }
 
    while (!signal?.aborted) {
      yield await promise;
      ({ promise, resolve, reject } = createDeferredPromise());
    }
    throw new AbortError();
  } finally {
    handle.close();
    signal?.removeEventListener('abort', oncancel);
  }
}
 
module.exports = {
  FSWatcher,
  StatWatcher,
  kFSWatchStart,
  kFSStatWatcherStart,
  kFSStatWatcherAddOrCleanRef,
  watch,
};