summaryrefslogtreecommitdiffstats
path: root/devtools/client/memory/actions/snapshot.js
blob: 63885be251f4df960a4dd1e1b2df6eded9c854fa (plain)
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

const {
  assert,
  reportException,
  isSet,
} = require("resource://devtools/shared/DevToolsUtils.js");
const {
  censusIsUpToDate,
  getSnapshot,
  createSnapshot,
  dominatorTreeIsComputed,
} = require("resource://devtools/client/memory/utils.js");
const {
  actions,
  snapshotState: states,
  viewState,
  censusState,
  treeMapState,
  dominatorTreeState,
  individualsState,
} = require("resource://devtools/client/memory/constants.js");
const view = require("resource://devtools/client/memory/actions/view.js");
const refresh = require("resource://devtools/client/memory/actions/refresh.js");
const diffing = require("resource://devtools/client/memory/actions/diffing.js");
const TaskCache = require("resource://devtools/client/memory/actions/task-cache.js");

/**
 * A series of actions are fired from this task to save, read and generate the
 * initial census from a snapshot.
 *
 * @param {MemoryFront}
 * @param {HeapAnalysesClient}
 * @param {Object}
 */
exports.takeSnapshotAndCensus = function (front, heapWorker) {
  return async function ({ dispatch, getState }) {
    const id = await dispatch(takeSnapshot(front));
    if (id === null) {
      return;
    }

    await dispatch(readSnapshot(heapWorker, id));
    if (getSnapshot(getState(), id).state !== states.READ) {
      return;
    }

    await dispatch(computeSnapshotData(heapWorker, id));
  };
};

/**
 * Create the census for the snapshot with the provided snapshot id. If the
 * current view is the DOMINATOR_TREE view, create the dominator tree for this
 * snapshot as well.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {snapshotId} id
 */
const computeSnapshotData = (exports.computeSnapshotData = function (
  heapWorker,
  id
) {
  return async function ({ dispatch, getState }) {
    if (getSnapshot(getState(), id).state !== states.READ) {
      return;
    }

    // Decide which type of census to take.
    const censusTaker = getCurrentCensusTaker(getState().view.state);
    await dispatch(censusTaker(heapWorker, id));

    if (
      getState().view.state === viewState.DOMINATOR_TREE &&
      !getSnapshot(getState(), id).dominatorTree
    ) {
      await dispatch(computeAndFetchDominatorTree(heapWorker, id));
    }
  };
});

/**
 * Selects a snapshot and if the snapshot's census is using a different
 * display, take a new census.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {snapshotId} id
 */
exports.selectSnapshotAndRefresh = function (heapWorker, id) {
  return async function ({ dispatch, getState }) {
    if (getState().diffing || getState().individuals) {
      dispatch(view.changeView(viewState.CENSUS));
    }

    dispatch(selectSnapshot(id));
    await dispatch(refresh.refresh(heapWorker));
  };
};

/**
 * Take a snapshot and return its id on success, or null on failure.
 *
 * @param {MemoryFront} front
 * @returns {Number|null}
 */
const takeSnapshot = (exports.takeSnapshot = function (front) {
  return async function ({ dispatch, getState }) {
    if (getState().diffing || getState().individuals) {
      dispatch(view.changeView(viewState.CENSUS));
    }

    const snapshot = createSnapshot(getState());
    const id = snapshot.id;
    dispatch({ type: actions.TAKE_SNAPSHOT_START, snapshot });
    dispatch(selectSnapshot(id));

    let path;
    try {
      path = await front.saveHeapSnapshot();
    } catch (error) {
      reportException("takeSnapshot", error);
      dispatch({ type: actions.SNAPSHOT_ERROR, id, error });
      return null;
    }

    dispatch({ type: actions.TAKE_SNAPSHOT_END, id, path });
    return snapshot.id;
  };
});

/**
 * Reads a snapshot into memory; necessary to do before taking
 * a census on the snapshot. May only be called once per snapshot.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {snapshotId} id
 */
const readSnapshot = (exports.readSnapshot = TaskCache.declareCacheableTask({
  getCacheKey(_, id) {
    return id;
  },

  async task(heapWorker, id, removeFromCache, dispatch, getState) {
    const snapshot = getSnapshot(getState(), id);
    assert(
      [states.SAVED, states.IMPORTING].includes(snapshot.state),
      `Should only read a snapshot once. Found snapshot in state ${snapshot.state}`
    );

    let creationTime;

    dispatch({ type: actions.READ_SNAPSHOT_START, id });
    try {
      await heapWorker.readHeapSnapshot(snapshot.path);
      creationTime = await heapWorker.getCreationTime(snapshot.path);
    } catch (error) {
      removeFromCache();
      reportException("readSnapshot", error);
      dispatch({ type: actions.SNAPSHOT_ERROR, id, error });
      return;
    }

    removeFromCache();
    dispatch({ type: actions.READ_SNAPSHOT_END, id, creationTime });
  },
}));

let takeCensusTaskCounter = 0;

/**
 * Census and tree maps both require snapshots. This function shares the logic
 * of creating snapshots, but is configurable with specific actions for the
 * individual census types.
 *
 * @param {getDisplay} Get the display object from the state.
 * @param {getCensus} Get the census from the snapshot.
 * @param {beginAction} Action to send at the beginning of a heap snapshot.
 * @param {endAction} Action to send at the end of a heap snapshot.
 * @param {errorAction} Action to send if a snapshot has an error.
 */
function makeTakeCensusTask({
  getDisplay,
  getFilter,
  getCensus,
  beginAction,
  endAction,
  errorAction,
  canTakeCensus,
}) {
  /**
   * @param {HeapAnalysesClient} heapWorker
   * @param {snapshotId} id
   *
   * @see {Snapshot} model defined in devtools/client/memory/models.js
   * @see `devtools/shared/heapsnapshot/HeapAnalysesClient.js`
   * @see `js/src/doc/Debugger/Debugger.Memory.md` for breakdown details
   */
  const thisTakeCensusTaskId = ++takeCensusTaskCounter;
  return TaskCache.declareCacheableTask({
    getCacheKey(_, id) {
      return `take-census-task-${thisTakeCensusTaskId}-${id}`;
    },

    async task(heapWorker, id, removeFromCache, dispatch, getState) {
      const snapshot = getSnapshot(getState(), id);
      if (!snapshot) {
        removeFromCache();
        return;
      }

      // Assert that snapshot is in a valid state
      assert(
        canTakeCensus(snapshot),
        "Attempting to take a census when the snapshot is not in a ready state. " +
          `snapshot.state = ${snapshot.state}, ` +
          `census.state = ${(getCensus(snapshot) || { state: null }).state}`
      );

      let report, parentMap;
      let display = getDisplay(getState());
      let filter = getFilter(getState());

      // If display, filter and inversion haven't changed, don't do anything.
      if (censusIsUpToDate(filter, display, getCensus(snapshot))) {
        removeFromCache();
        return;
      }

      // Keep taking a census if the display changes while our request is in
      // flight. Recheck that the display used for the census is the same as the
      // state's display.
      do {
        display = getDisplay(getState());
        filter = getState().filter;

        dispatch({
          type: beginAction,
          id,
          filter,
          display,
        });

        const opts = display.inverted
          ? { asInvertedTreeNode: true }
          : { asTreeNode: true };

        opts.filter = filter || null;

        try {
          ({ report, parentMap } = await heapWorker.takeCensus(
            snapshot.path,
            { breakdown: display.breakdown },
            opts
          ));
        } catch (error) {
          removeFromCache();
          reportException("takeCensus", error);
          dispatch({ type: errorAction, id, error });
          return;
        }
      } while (
        filter !== getState().filter ||
        display !== getDisplay(getState())
      );

      removeFromCache();
      dispatch({
        type: endAction,
        id,
        display,
        filter,
        report,
        parentMap,
      });
    },
  });
}

/**
 * Take a census.
 */
const takeCensus = (exports.takeCensus = makeTakeCensusTask({
  getDisplay: state => state.censusDisplay,
  getFilter: state => state.filter,
  getCensus: snapshot => snapshot.census,
  beginAction: actions.TAKE_CENSUS_START,
  endAction: actions.TAKE_CENSUS_END,
  errorAction: actions.TAKE_CENSUS_ERROR,
  canTakeCensus: snapshot =>
    snapshot.state === states.READ &&
    (!snapshot.census || snapshot.census.state === censusState.SAVED),
}));

/**
 * Take a census for the treemap.
 */
const takeTreeMap = (exports.takeTreeMap = makeTakeCensusTask({
  getDisplay: state => state.treeMapDisplay,
  getFilter: () => null,
  getCensus: snapshot => snapshot.treeMap,
  beginAction: actions.TAKE_TREE_MAP_START,
  endAction: actions.TAKE_TREE_MAP_END,
  errorAction: actions.TAKE_TREE_MAP_ERROR,
  canTakeCensus: snapshot =>
    snapshot.state === states.READ &&
    (!snapshot.treeMap || snapshot.treeMap.state === treeMapState.SAVED),
}));

/**
 * Define what should be the default mode for taking a census based on the
 * default view of the tool.
 */
const defaultCensusTaker = takeTreeMap;

/**
 * Pick the default census taker when taking a snapshot. This should be
 * determined by the current view. If the view doesn't include a census, then
 * use the default one defined above. Some census information is always needed
 * to display some basic information about a snapshot.
 *
 * @param {string} value from viewState
 */
const getCurrentCensusTaker = (exports.getCurrentCensusTaker = function (
  currentView
) {
  switch (currentView) {
    case viewState.TREE_MAP:
      return takeTreeMap;
    case viewState.CENSUS:
      return takeCensus;
    default:
      return defaultCensusTaker;
  }
});

/**
 * Focus the given node in the individuals view.
 *
 * @param {DominatorTreeNode} node.
 */
exports.focusIndividual = function (node) {
  return {
    type: actions.FOCUS_INDIVIDUAL,
    node,
  };
};

/**
 * Fetch the individual `DominatorTreeNodes` for the census group specified by
 * `censusBreakdown` and `reportLeafIndex`.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {SnapshotId} id
 * @param {Object} censusBreakdown
 * @param {Set<Number> | Number} reportLeafIndex
 */
const fetchIndividuals = (exports.fetchIndividuals = function (
  heapWorker,
  id,
  censusBreakdown,
  reportLeafIndex
) {
  return async function ({ dispatch, getState }) {
    if (getState().view.state !== viewState.INDIVIDUALS) {
      dispatch(view.changeView(viewState.INDIVIDUALS));
    }

    const snapshot = getSnapshot(getState(), id);
    assert(
      snapshot && snapshot.state === states.READ,
      "The snapshot should already be read into memory"
    );

    if (!dominatorTreeIsComputed(snapshot)) {
      await dispatch(computeAndFetchDominatorTree(heapWorker, id));
    }

    const snapshot_ = getSnapshot(getState(), id);
    assert(
      snapshot_.dominatorTree?.root,
      "Should have a dominator tree with a root."
    );

    const dominatorTreeId = snapshot_.dominatorTree.dominatorTreeId;

    const indices = isSet(reportLeafIndex)
      ? reportLeafIndex
      : new Set([reportLeafIndex]);

    let labelDisplay;
    let nodes;
    do {
      labelDisplay = getState().labelDisplay;
      assert(
        labelDisplay?.breakdown?.by,
        `Should have a breakdown to label nodes with, got: ${JSON.stringify(
          labelDisplay
        )}`
      );

      if (getState().view.state !== viewState.INDIVIDUALS) {
        // We switched views while in the process of fetching individuals -- any
        // further work is useless.
        return;
      }

      dispatch({ type: actions.FETCH_INDIVIDUALS_START });

      try {
        ({ nodes } = await heapWorker.getCensusIndividuals({
          dominatorTreeId,
          indices,
          censusBreakdown,
          labelBreakdown: labelDisplay.breakdown,
          maxRetainingPaths: Services.prefs.getIntPref(
            "devtools.memory.max-retaining-paths"
          ),
          maxIndividuals: Services.prefs.getIntPref(
            "devtools.memory.max-individuals"
          ),
        }));
      } catch (error) {
        reportException("actions/snapshot/fetchIndividuals", error);
        dispatch({ type: actions.INDIVIDUALS_ERROR, error });
        return;
      }
    } while (labelDisplay !== getState().labelDisplay);

    dispatch({
      type: actions.FETCH_INDIVIDUALS_END,
      id,
      censusBreakdown,
      indices,
      labelDisplay,
      nodes,
      dominatorTree: snapshot_.dominatorTree,
    });
  };
});

/**
 * Refresh the current individuals view.
 *
 * @param {HeapAnalysesClient} heapWorker
 */
exports.refreshIndividuals = function (heapWorker) {
  return async function ({ dispatch, getState }) {
    assert(
      getState().view.state === viewState.INDIVIDUALS,
      "Should be in INDIVIDUALS view."
    );

    const { individuals } = getState();

    switch (individuals.state) {
      case individualsState.COMPUTING_DOMINATOR_TREE:
      case individualsState.FETCHING:
        // Nothing to do here.
        return;

      case individualsState.FETCHED:
        if (getState().individuals.labelDisplay === getState().labelDisplay) {
          return;
        }
        break;

      case individualsState.ERROR:
        // Doesn't hurt to retry: maybe we won't get an error this time around?
        break;

      default:
        assert(false, `Unexpected individuals state: ${individuals.state}`);
        return;
    }

    await dispatch(
      fetchIndividuals(
        heapWorker,
        individuals.id,
        individuals.censusBreakdown,
        individuals.indices
      )
    );
  };
};

/**
 * Refresh the selected snapshot's census data, if need be (for example,
 * display configuration changed).
 *
 * @param {HeapAnalysesClient} heapWorker
 */
exports.refreshSelectedCensus = function (heapWorker) {
  return async function ({ dispatch, getState }) {
    const snapshot = getState().snapshots.find(s => s.selected);
    if (!snapshot || snapshot.state !== states.READ) {
      return;
    }

    // Intermediate snapshot states will get handled by the task action that is
    // orchestrating them. For example, if the snapshot census's state is
    // SAVING, then the takeCensus action will keep taking a census until
    // the inverted property matches the inverted state. If the snapshot is
    // still in the process of being saved or read, the takeSnapshotAndCensus
    // task action will follow through and ensure that a census is taken.
    if (
      (snapshot.census && snapshot.census.state === censusState.SAVED) ||
      !snapshot.census
    ) {
      await dispatch(takeCensus(heapWorker, snapshot.id));
    }
  };
};

/**
 * Refresh the selected snapshot's tree map data, if need be (for example,
 * display configuration changed).
 *
 * @param {HeapAnalysesClient} heapWorker
 */
exports.refreshSelectedTreeMap = function (heapWorker) {
  return async function ({ dispatch, getState }) {
    const snapshot = getState().snapshots.find(s => s.selected);
    if (!snapshot || snapshot.state !== states.READ) {
      return;
    }

    // Intermediate snapshot states will get handled by the task action that is
    // orchestrating them. For example, if the snapshot census's state is
    // SAVING, then the takeCensus action will keep taking a census until
    // the inverted property matches the inverted state. If the snapshot is
    // still in the process of being saved or read, the takeSnapshotAndCensus
    // task action will follow through and ensure that a census is taken.
    if (
      (snapshot.treeMap && snapshot.treeMap.state === treeMapState.SAVED) ||
      !snapshot.treeMap
    ) {
      await dispatch(takeTreeMap(heapWorker, snapshot.id));
    }
  };
};

/**
 * Request that the `HeapAnalysesWorker` compute the dominator tree for the
 * snapshot with the given `id`.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {SnapshotId} id
 *
 * @returns {Promise<DominatorTreeId>}
 */
const computeDominatorTree = (exports.computeDominatorTree =
  TaskCache.declareCacheableTask({
    getCacheKey(_, id) {
      return id;
    },

    async task(heapWorker, id, removeFromCache, dispatch, getState) {
      const snapshot = getSnapshot(getState(), id);
      assert(
        !snapshot.dominatorTree?.dominatorTreeId,
        "Should not re-compute dominator trees"
      );

      dispatch({ type: actions.COMPUTE_DOMINATOR_TREE_START, id });

      let dominatorTreeId;
      try {
        dominatorTreeId = await heapWorker.computeDominatorTree(snapshot.path);
      } catch (error) {
        removeFromCache();
        reportException("actions/snapshot/computeDominatorTree", error);
        dispatch({ type: actions.DOMINATOR_TREE_ERROR, id, error });
        return null;
      }

      removeFromCache();
      dispatch({
        type: actions.COMPUTE_DOMINATOR_TREE_END,
        id,
        dominatorTreeId,
      });
      return dominatorTreeId;
    },
  }));

/**
 * Get the partial subtree, starting from the root, of the
 * snapshot-with-the-given-id's dominator tree.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {SnapshotId} id
 *
 * @returns {Promise<DominatorTreeNode>}
 */
const fetchDominatorTree = (exports.fetchDominatorTree =
  TaskCache.declareCacheableTask({
    getCacheKey(_, id) {
      return id;
    },

    async task(heapWorker, id, removeFromCache, dispatch, getState) {
      const snapshot = getSnapshot(getState(), id);
      assert(
        dominatorTreeIsComputed(snapshot),
        "Should have dominator tree model and it should be computed"
      );

      let display;
      let root;
      do {
        display = getState().labelDisplay;
        assert(
          display?.breakdown,
          `Should have a breakdown to describe nodes with, got: ${JSON.stringify(
            display
          )}`
        );

        dispatch({ type: actions.FETCH_DOMINATOR_TREE_START, id, display });

        try {
          root = await heapWorker.getDominatorTree({
            dominatorTreeId: snapshot.dominatorTree.dominatorTreeId,
            breakdown: display.breakdown,
            maxRetainingPaths: Services.prefs.getIntPref(
              "devtools.memory.max-retaining-paths"
            ),
          });
        } catch (error) {
          removeFromCache();
          reportException("actions/snapshot/fetchDominatorTree", error);
          dispatch({ type: actions.DOMINATOR_TREE_ERROR, id, error });
          return null;
        }
      } while (display !== getState().labelDisplay);

      removeFromCache();
      dispatch({ type: actions.FETCH_DOMINATOR_TREE_END, id, root });
      return root;
    },
  }));

/**
 * Fetch the immediately dominated children represented by the placeholder
 * `lazyChildren` from snapshot-with-the-given-id's dominator tree.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {SnapshotId} id
 * @param {DominatorTreeLazyChildren} lazyChildren
 */
exports.fetchImmediatelyDominated = TaskCache.declareCacheableTask({
  getCacheKey(_, id, lazyChildren) {
    return `${id}-${lazyChildren.key()}`;
  },

  async task(
    heapWorker,
    id,
    lazyChildren,
    removeFromCache,
    dispatch,
    getState
  ) {
    const snapshot = getSnapshot(getState(), id);
    assert(snapshot.dominatorTree, "Should have dominator tree model");
    assert(
      snapshot.dominatorTree.state === dominatorTreeState.LOADED ||
        snapshot.dominatorTree.state ===
          dominatorTreeState.INCREMENTAL_FETCHING,
      "Cannot fetch immediately dominated nodes in a dominator tree unless " +
        " the dominator tree has already been computed"
    );

    let display;
    let response;
    do {
      display = getState().labelDisplay;
      assert(display, "Should have a display to describe nodes with.");

      dispatch({ type: actions.FETCH_IMMEDIATELY_DOMINATED_START, id });

      try {
        response = await heapWorker.getImmediatelyDominated({
          dominatorTreeId: snapshot.dominatorTree.dominatorTreeId,
          breakdown: display.breakdown,
          nodeId: lazyChildren.parentNodeId(),
          startIndex: lazyChildren.siblingIndex(),
          maxRetainingPaths: Services.prefs.getIntPref(
            "devtools.memory.max-retaining-paths"
          ),
        });
      } catch (error) {
        removeFromCache();
        reportException("actions/snapshot/fetchImmediatelyDominated", error);
        dispatch({ type: actions.DOMINATOR_TREE_ERROR, id, error });
        return;
      }
    } while (display !== getState().labelDisplay);

    removeFromCache();
    dispatch({
      type: actions.FETCH_IMMEDIATELY_DOMINATED_END,
      id,
      path: response.path,
      nodes: response.nodes,
      moreChildrenAvailable: response.moreChildrenAvailable,
    });
  },
});

/**
 * Compute and then fetch the dominator tree of the snapshot with the given
 * `id`.
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {SnapshotId} id
 *
 * @returns {Promise<DominatorTreeNode>}
 */
const computeAndFetchDominatorTree = (exports.computeAndFetchDominatorTree =
  TaskCache.declareCacheableTask({
    getCacheKey(_, id) {
      return id;
    },

    async task(heapWorker, id, removeFromCache, dispatch, getState) {
      const dominatorTreeId = await dispatch(
        computeDominatorTree(heapWorker, id)
      );
      if (dominatorTreeId === null) {
        removeFromCache();
        return null;
      }

      const root = await dispatch(fetchDominatorTree(heapWorker, id));
      removeFromCache();

      if (!root) {
        return null;
      }

      return root;
    },
  }));

/**
 * Update the currently selected snapshot's dominator tree.
 *
 * @param {HeapAnalysesClient} heapWorker
 */
exports.refreshSelectedDominatorTree = function (heapWorker) {
  return async function ({ dispatch, getState }) {
    const snapshot = getState().snapshots.find(s => s.selected);
    if (!snapshot) {
      return;
    }

    if (
      snapshot.dominatorTree &&
      !(
        snapshot.dominatorTree.state === dominatorTreeState.COMPUTED ||
        snapshot.dominatorTree.state === dominatorTreeState.LOADED ||
        snapshot.dominatorTree.state === dominatorTreeState.INCREMENTAL_FETCHING
      )
    ) {
      return;
    }

    // We need to check for the snapshot state because if there was an error,
    // we can't continue and if we are still saving or reading the snapshot,
    // then takeSnapshotAndCensus will finish the job for us
    if (snapshot.state === states.READ) {
      if (snapshot.dominatorTree) {
        await dispatch(fetchDominatorTree(heapWorker, snapshot.id));
      } else {
        await dispatch(computeAndFetchDominatorTree(heapWorker, snapshot.id));
      }
    }
  };
};

/**
 * Select the snapshot with the given id.
 *
 * @param {snapshotId} id
 * @see {Snapshot} model defined in devtools/client/memory/models.js
 */
const selectSnapshot = (exports.selectSnapshot = function (id) {
  return {
    type: actions.SELECT_SNAPSHOT,
    id,
  };
});

/**
 * Delete all snapshots that are in the READ or ERROR state
 *
 * @param {HeapAnalysesClient} heapWorker
 */
exports.clearSnapshots = function (heapWorker) {
  return async function ({ dispatch, getState }) {
    const snapshots = getState().snapshots.filter(s => {
      const snapshotReady = s.state === states.READ || s.state === states.ERROR;
      const censusReady =
        (s.treeMap && s.treeMap.state === treeMapState.SAVED) ||
        (s.census && s.census.state === censusState.SAVED);

      return snapshotReady && censusReady;
    });

    const ids = snapshots.map(s => s.id);

    dispatch({ type: actions.DELETE_SNAPSHOTS_START, ids });

    if (getState().diffing) {
      dispatch(diffing.toggleDiffing());
    }
    if (getState().individuals) {
      dispatch(view.popView());
    }

    await Promise.all(
      snapshots.map(snapshot => {
        return heapWorker.deleteHeapSnapshot(snapshot.path).catch(error => {
          reportException("clearSnapshots", error);
          dispatch({ type: actions.SNAPSHOT_ERROR, id: snapshot.id, error });
        });
      })
    );

    dispatch({ type: actions.DELETE_SNAPSHOTS_END, ids });
  };
};

/**
 * Delete a snapshot
 *
 * @param {HeapAnalysesClient} heapWorker
 * @param {snapshotModel} snapshot
 */
exports.deleteSnapshot = function (heapWorker, snapshot) {
  return async function ({ dispatch, getState }) {
    dispatch({ type: actions.DELETE_SNAPSHOTS_START, ids: [snapshot.id] });

    try {
      await heapWorker.deleteHeapSnapshot(snapshot.path);
    } catch (error) {
      reportException("deleteSnapshot", error);
      dispatch({ type: actions.SNAPSHOT_ERROR, id: snapshot.id, error });
    }

    dispatch({ type: actions.DELETE_SNAPSHOTS_END, ids: [snapshot.id] });
  };
};

/**
 * Expand the given node in the snapshot's census report.
 *
 * @param {CensusTreeNode} node
 */
exports.expandCensusNode = function (id, node) {
  return {
    type: actions.EXPAND_CENSUS_NODE,
    id,
    node,
  };
};

/**
 * Collapse the given node in the snapshot's census report.
 *
 * @param {CensusTreeNode} node
 */
exports.collapseCensusNode = function (id, node) {
  return {
    type: actions.COLLAPSE_CENSUS_NODE,
    id,
    node,
  };
};

/**
 * Focus the given node in the snapshot's census's report.
 *
 * @param {SnapshotId} id
 * @param {DominatorTreeNode} node
 */
exports.focusCensusNode = function (id, node) {
  return {
    type: actions.FOCUS_CENSUS_NODE,
    id,
    node,
  };
};

/**
 * Expand the given node in the snapshot's dominator tree.
 *
 * @param {DominatorTreeTreeNode} node
 */
exports.expandDominatorTreeNode = function (id, node) {
  return {
    type: actions.EXPAND_DOMINATOR_TREE_NODE,
    id,
    node,
  };
};

/**
 * Collapse the given node in the snapshot's dominator tree.
 *
 * @param {DominatorTreeTreeNode} node
 */
exports.collapseDominatorTreeNode = function (id, node) {
  return {
    type: actions.COLLAPSE_DOMINATOR_TREE_NODE,
    id,
    node,
  };
};

/**
 * Focus the given node in the snapshot's dominator tree.
 *
 * @param {SnapshotId} id
 * @param {DominatorTreeNode} node
 */
exports.focusDominatorTreeNode = function (id, node) {
  return {
    type: actions.FOCUS_DOMINATOR_TREE_NODE,
    id,
    node,
  };
};