github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/ui/app/services/stats-trackers-registry.js (about)

     1  import { computed } from '@ember/object';
     2  import Service, { inject as service } from '@ember/service';
     3  import { LRUMap } from 'lru_map';
     4  import NodeStatsTracker from 'nomad-ui/utils/classes/node-stats-tracker';
     5  import AllocationStatsTracker from 'nomad-ui/utils/classes/allocation-stats-tracker';
     6  
     7  // An unbounded number of stat trackers is a great way to gobble up all the memory
     8  // on a machine. This max number is unscientific, but aims to balance losing
     9  // stat trackers a user is likely to return to with preventing gc from freeing
    10  // memory occupied by stat trackers a user is likely to no longer care about
    11  const MAX_STAT_TRACKERS = 10;
    12  let registry;
    13  
    14  const exists = (tracker, prop) =>
    15    tracker.get(prop) && !tracker.get(prop).isDestroyed && !tracker.get(prop).isDestroying;
    16  
    17  export default class StatsTrackersRegistryService extends Service {
    18    @service token;
    19  
    20    constructor() {
    21      super(...arguments);
    22  
    23      // The LRUMap limits the number of trackers tracked by making room for
    24      // new entries beyond the limit by removing the least recently used entry.
    25      registry = new LRUMap(MAX_STAT_TRACKERS);
    26    }
    27  
    28    // A read-only way of getting a reference to the registry.
    29    // Since this could be overwritten by a bad actor, it isn't
    30    // used in getTracker
    31    @computed
    32    get registryRef() {
    33      return registry;
    34    }
    35  
    36    getTracker(resource) {
    37      if (!resource) return;
    38  
    39      const type = resource && resource.constructor.modelName;
    40      const key = `${type}:${resource.get('id')}`;
    41      const Constructor = type === 'node' ? NodeStatsTracker : AllocationStatsTracker;
    42      const resourceProp = type === 'node' ? 'node' : 'allocation';
    43  
    44      const cachedTracker = registry.get(key);
    45      if (cachedTracker) {
    46        // It's possible for the resource on a cachedTracker to have been
    47        // deleted. Rebind it if that's the case.
    48        if (!exists(cachedTracker, resourceProp)) cachedTracker.set(resourceProp, resource);
    49        return cachedTracker;
    50      }
    51  
    52      const tracker = Constructor.create({
    53        fetch: url => this.token.authorizedRequest(url),
    54        [resourceProp]: resource,
    55      });
    56  
    57      registry.set(key, tracker);
    58  
    59      return tracker;
    60    }
    61  }