All files / app flow-pairing.service.ts

11.97% Statements 17/142
0% Branches 0/46
8.88% Functions 4/45
13.7% Lines 17/124

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                1x         1x       1x       1x         1x         1x   1x 1x 1x     1x 1x 1x 1x                                                                                                                                 1x 1x                                                                                                                                   1x                                                                     1x                                                                                                                                                  
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ModelDiffDataService } from './model-diff-data.service';
import { Entry, isResultTag, removeResultTagsFrom } from './types';
 
@Injectable({
  providedIn: 'root'
})
export class FlowPairingService {
 
  /**
   * The pairs of flows that we can match automatically - they have the same metadata
   */
  private automatic: Set<Pair> = new Set();
  /**
   * The pairs of flows we've had to add manually - metadata has changed.
   */
  private manualPairs: Set<Pair> = new Set();
  /**
   * The pairs of flows we've manually unpaired
   */
  private manualUnpairs: Set<Pair> = new Set();
  /**
   * Indices on the left that we haven't matched up yet.
   * These will show as deleted flows.
   */
  private leftUnpaired: Set<IndexedEntry> = new Set();
  /**
   * Indices on the right that we haven't matched up yet.
   * These will show as newly-added flows
   */
  private rightUnpaired: Set<IndexedEntry> = new Set();
 
  private unpairListeners: Set<((p: Pair) => void)> = new Set();
  private pairListeners: Set<((p: Pair) => void)> = new Set();
  private rebuildListeners: Set<(() => void)> = new Set();
 
  constructor(
    private mdds: ModelDiffDataService,
    private route: ActivatedRoute) {
    mdds.onIndex("from", l => this.rebuild());
    mdds.onIndex("to", l => this.rebuild());
  }
 
  buildQuery(usp: URLSearchParams): void {
    this.manualUnpairs.forEach(p => usp.append("u", p.left.index + "-" + p.right.index));
    this.manualPairs.forEach(p => usp.append("p", p.left.index + "-" + p.right.index));
  }
 
  private rebuild(): void {
    this.automatic.clear();
    this.manualPairs.clear();
    this.manualUnpairs.clear();
    this.leftUnpaired.clear();
    this.rightUnpaired.clear();
 
    // work out automatic pairs
    let left: Entry[] | null = this.mdds.index("from")?.index?.entries ?? null;
    let right: Entry[] | null = this.mdds.index("to")?.index?.entries ?? null;
    Iif (left !== null && right != null) {
      left.forEach((e, i) => this.leftUnpaired.add({ index: i, entry: e }));
      right.forEach((e, i) => this.rightUnpaired.add({ index: i, entry: e }));
 
 
      this.leftUnpaired.forEach(l => {
        this.rightUnpaired.forEach(r => {
 
          Iif (this.matches(l.entry, r.entry)) {
            this.automatic.add({
              left: l,
              right: r
            });
            this.rightUnpaired.delete(r);
            this.leftUnpaired.delete(l);
            return;
          }
        });
      });
    }
 
    // apply unpairs and pairs from URL
    this.route.snapshot.queryParamMap.getAll("u")
      .forEach(v => {
        let [li, ri] = v.split("-").map(s => Number.parseInt(s));
        let auto = Array.from(this.automatic.values())
          .find(p => p.left.index === li && p.right.index == ri);
        Iif (auto != undefined) {
          this.quietlyUnpair(auto);
        }
      });
    this.route.snapshot.queryParamMap.getAll("p")
      .forEach(v => {
        let [li, ri] = v.split("-").map(s => Number.parseInt(s));
        let le = Array.from(this.leftUnpaired.values())
          .find(p => p.index === li);
        let re = Array.from(this.rightUnpaired.values())
          .find(p => p.index === ri);
        Iif (le != undefined && re !== undefined) {
          this.quietlyPair(le, re);
        }
      });
 
    this.rebuildListeners.forEach(cb => cb());
  }
 
  onRebuild(cb: () => void): void {
    cb();
    this.rebuildListeners.add(cb);
  }
 
  matches(left: Entry, right: Entry): boolean {
    let match: boolean = left !== null && right !== null;
    Iif (match) {
      match = left.description === right.description;
    }
    Iif (match) {
      let lt: Set<string> = new Set(left.tags);
      let rt: Set<string> = new Set(right.tags);
      removeResultTagsFrom(lt, rt);
      match = setEq(lt, rt);
    }
    return match;
  }
 
  naturallyPaired(): Pair[] {
    return Array.from(this.automatic.values());
  }
 
  manuallyPaired(): Pair[] {
    return Array.from(this.manualPairs.values());
  }
 
  /**
   * @returns Paired index entries
   */
  paired(): Pair[] {
    let pairs: Pair[] = [];
 
    let le = this.mdds.index("from")?.index?.entries ?? null;
    let re = this.mdds.index("to")?.index?.entries ?? null;
    Iif (le !== null && re !== null) {
      this.automatic.forEach(p => pairs.push(p));
      this.manualPairs.forEach(p => pairs.push(p));
    }
 
    pairs.sort((a, b) => this.sortPair(a, b));
    return pairs;
  }
 
  private quietlyUnpair(pair: Pair): boolean {
    let removed = this.automatic.delete(pair);
    Iif (removed) {
      this.manualUnpairs.add(pair);
    }
    Iif (!removed) {
      removed = this.manualPairs.delete(pair);
    }
    Iif (removed) {
      this.leftUnpaired.add(pair.left);
      this.rightUnpaired.add(pair.right);
 
      return true;
    }
    return false;
  }
 
  unpair(pair: Pair): void {
    Iif (this.quietlyUnpair(pair)) {
      this.unpairListeners.forEach(upl => upl(pair));
    }
  }
 
  onUnpair(cb: (p: Pair) => void) {
    this.unpairListeners.add(cb);
  }
 
  private quietlyPair(left: IndexedEntry, right: IndexedEntry): Pair | undefined {
    Iif (
      this.leftUnpaired.delete(left) &&
      this.rightUnpaired.delete(right)) {
      let pair = { left: left, right: right };
      if (this.matches(left.entry, right.entry)) {
        this.automatic.add(pair);
 
        let original = Array.from(this.manualUnpairs.values())
          .find(p => p.left.entry.detail === left.entry.detail
            && p.right.entry.detail === right.entry.detail);
        Iif (original !== undefined) {
          this.manualUnpairs.delete(original);
        }
      }
      else {
        this.manualPairs.add(pair);
      }
 
      return pair;
    }
    return undefined;
  }
 
  pair(left: IndexedEntry, right: IndexedEntry): void {
    let p = this.quietlyPair(left, right);
    Iif (p !== undefined) {
      this.pairListeners.forEach(upl => upl(p!));
    }
  }
 
  onPair(cb: (p: Pair) => void) {
    this.pairListeners.add(cb);
  }
 
  /**
   * @returns Unpaired index entries on the left
   */
  unpairedLeftEntries(): IndexedEntry[] {
    let lup: IndexedEntry[] = Array.from(this.leftUnpaired);
    lup.sort((a, b) => this.sortEntry(a.entry, b.entry));
    return lup;
  }
 
  /**
   * @returns Unpaired index entries on the right
   */
  unpairedRightEntries(): IndexedEntry[] {
    let rup: IndexedEntry[] = Array.from(this.rightUnpaired);
    rup.sort((a, b) => this.sortEntry(a.entry, b.entry));
    return rup;
  }
 
  private sortPair(
    a: Pair,
    b: Pair): number {
    let d = this.sortEntry(a.left.entry, b.left.entry);
    Iif (d === 0) {
      d = this.sortEntry(a.right.entry, b.right.entry);
    }
    return d;
  }
 
  private sortEntry(a: Entry, b: Entry): number {
    let d = 0;
    // tags form most of the identity, so sort on that first, ignoring result tags
    let at = a.tags.filter(t => !isResultTag(t));
    let bt = b.tags.filter(t => !isResultTag(t));
    let idx = 0;
    while (d === 0 && idx < at.length && idx < bt.length) {
      d = at[idx].localeCompare(bt[idx]);
      idx++;
    }
    Iif (d === 0) {
      d = at.length - bt.length;
    }
 
    // tags are the same, fall back to the description
    Iif (d === 0) {
      d = a.description.localeCompare(b.description);
    }
    return d;
  }
}
 
function setEq(a: Set<string>, b: Set<string>): boolean {
  Iif (a.size != b.size) {
    return false;
  }
  for (var v of a) {
    Iif (!b.has(v)) {
      return false;
    }
  }
  return true;
}
 
export interface Pair {
  left: IndexedEntry,
  right: IndexedEntry
}
 
export interface IndexedEntry {
  index: number,
  entry: Entry
}