All files / src/impl Contracts.impl.ts

98.19% Statements 109/111
92.1% Branches 35/38
96.96% Functions 32/33
98.14% Lines 106/108

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 28925x   25x   25x   25x 25x 25x       25x 25x 25x 25x 25x 25x               25x 165x                                         166x             230x 230x 228x   228x 225x   3x               165x 164x 162x   2x             115x 115x 114x 114x             1245x 1245x 1244x 1244x   1244x             2x       165x       165x 165x       142x 142x   142x         2x       142x 142x   142x 140x 140x                 1244x 1238x   4x         1244x   1244x 9x   1235x             9x 1x     8x   3x 1x   2x   1x     4x               1238x   1238x 1238x 1238x 3x   1238x 1238x 1063x 1063x                     2045x 2045x   2045x         2045x 1060x         2824x       282x 282x 982x 982x   282x       70x       3x 2x 2x 1x       2x       67x 2x   65x       2x       2x       165x 165x   165x 165x   2x     165x 165x       165x 165x 165x 165x 165x 165x                
import { AUTO_CLOSE_NONE, AutoClose, AutoCloseType, inlineAutoClose } from "@jonloucks/contracts-ts/api/AutoClose";
import { AutoOpen } from "@jonloucks/contracts-ts/api/AutoOpen";
import { BindStrategy, BindStrategyType, resolveBindStrategy } from "@jonloucks/contracts-ts/api/BindStrategy";
import { Contract } from "@jonloucks/contracts-ts/api/Contract";
import { ContractException } from "@jonloucks/contracts-ts/api/ContractException";
import { Config, Contracts } from "@jonloucks/contracts-ts/api/Contracts";
import { Promisor, PromisorType, typeToPromisor } from "@jonloucks/contracts-ts/api/Promisor";
import { OptionalType, RequiredType, isPresent } from "@jonloucks/contracts-ts/api/Types";
import { configCheck, contractCheck, presentCheck } from "@jonloucks/contracts-ts/auxiliary/Checks";
import { Idempotent } from "@jonloucks/contracts-ts/auxiliary/Idempotent";
import { AtomicBoolean } from "@jonloucks/contracts-ts/auxiliary/AtomicBoolean";
 
import { AutoCloseMany, create as createAutoCloseMany } from "./AutoCloseMany.impl";
import { create as createIdempotent } from "./Idempotent.impl";
import { create as createAtomicBoolean } from "./AtomicBoolean.impl";
import { Events, create as createEvents } from "./Events.impl";
import { Internal } from "./Internal.impl";
import { Policy, create as createPolicy } from "./Policy.impl";
 
/**
 * Factory method to create Contracts instance.
 * 
 * @param config the configuration for the Contracts instance
 * @returns the Contracts implementation
 */
export function create(config: Config): RequiredType<Contracts> {
  return ContractsImpl.internalCreate(config);
}
 
// ---- Implementation details below ----
 
/**
 * Contracts implementation.
 */
class ContractsImpl implements Contracts, AutoOpen {
 
  /**
   * AutoOpen.autoOpen override.
   */
  autoOpen(): AutoClose {
    return this.open();
  }
 
  /**
   * Open.open override.
   */
  open(): AutoClose {
    return this.#idempotent.open();
  }
 
  /**
   * Contracts.claim override.
   */
  claim<T>(contract: Contract<T>): OptionalType<T> {
    const validContract: Contract<T> = contractCheck(contract);
    this.#policy.checkContract(validContract);
    const promisor: OptionalType<Promisor<T>> = this.getFromPromisorMap(validContract);
 
    if (isPresent(promisor)) {
      return validContract.cast(promisor.demand());
    } else {
      return this.claimFromPartners(validContract);
    }
  }
 
  /**
   * Contracts.enforce override.
   */
  enforce<T>(contract: Contract<T>): RequiredType<T> {
    const deliverable: OptionalType<T> = this.claim(contract);
    if (isPresent(deliverable)) {
      return deliverable;
    }
    throw new ContractException("Contract " + contract + " enforcement failed: No value present.");
  }
 
  /**
   * Contracts.isBound override.
   */
  isBound<T>(contract: Contract<T>): boolean {
    const validContract: Contract<T> = contractCheck(contract);
    this.#policy.checkContract(validContract);
    const promisor: OptionalType<Promisor<T>> = this.getFromPromisorMap(validContract);
    return isPresent(promisor) || this.isAnyPartnerBound(contract);
  }
 
  /**
   * Contracts.bind override.
   */
  bind<T>(contract: Contract<T>, promisor: PromisorType<T>, bindStrategy?: BindStrategyType): AutoClose {
    const validContract: Contract<T> = contractCheck(contract);
    this.#policy.checkContract(validContract);
    const validPromisor: Promisor<T> = typeToPromisor<T>(promisor);
    const validBindStrategy: BindStrategy = resolveBindStrategy(bindStrategy);
 
    return this.maybeBind(validContract, validPromisor, validBindStrategy);
  }
 
  /**
   * Object.toString override.
   */
  toString(): string {
    return `Contracts[size: ${this.#promisorMap.size}]`;
  }
 
  static internalCreate(config: Config): RequiredType<Contracts> {
    return new ContractsImpl(config);
  }
 
  private firstOpen(): AutoCloseType {
    this.#closeMany.add(this.#events.open());
    return () => this.closeFirstOpen();
  }
 
  private closeFirstOpen(): void {
    try {
      this.attemptToCloseBindings();
    } finally {
      this.#closeMany.close();
    }
  }
 
  private shutdown(): void {
    this.closeFirstOpen();
  }
 
  private attemptToCloseBindings(): void {
    const MAX_RETRIES = 6;
    let iterations = 0;
 
    while (this.breakAllBindings() > 0) {
      iterations++;
      Iif (iterations >= MAX_RETRIES) {
        throw new ContractException(
          `Failed to break all bindings after ${MAX_RETRIES} attempts`
        );
      }
    }
  }
 
  private maybeBind<T>(contract: Contract<T>, newPromisor: Promisor<T>, bindStrategy: BindStrategy): AutoClose {
    if (this.checkBind(contract, newPromisor, bindStrategy)) {
      return this.doBind(contract, newPromisor);
    } else {
      return AUTO_CLOSE_NONE;
    }
  }
 
  private checkBind<T>(contract: Contract<T>, newPromisor: Promisor<T>, bindStrategy: BindStrategy): boolean {
    const optionalCurrent: OptionalType<Promisor<T>> = this.getFromPromisorMap(contract);
 
    if (isPresent(optionalCurrent)) {
      return this.checkReplacement(contract, newPromisor, bindStrategy, optionalCurrent);
    } else {
      return true;
    }
  }
 
  private checkReplacement<T>(contract: Contract<T>, newPromisor: Promisor<T>, bindStrategy: BindStrategy, currentPromisor: Promisor<T>): boolean {
    // Double bind of same promisor, do not rebind
    // Review unwrapping if needed in future
    if (currentPromisor === newPromisor) {
      return false;
    }
 
    switch (bindStrategy) {
      case "ALWAYS":
        if (contract.replaceable) {
          return true;
        }
        this.throwContractNotReplaceableException(contract);
      case "IF_NOT_BOUND":
        return false;
      case "IF_ALLOWED":
      default:
        return contract.replaceable;
    }
  }
 
  private doBind<T>(contract: Contract<T>, promisor: Promisor<T>): AutoClose {
    // Since ReentrantReadWriteLock does not support lock upgrade, there are opportunities
    // for changes by other threads between the reads and writes.
    // This is mitigated by always incrementing the new value and decrementing the old value.
    promisor.incrementUsage();
 
    const previousPromisor: OptionalType<Promisor<T>> = this.getFromPromisorMap(contract);
    this.#promisorMap.set(contract, promisor);
    if (isPresent(previousPromisor)) {
      previousPromisor.decrementUsage();
    }
    const breakBindingOnce: AtomicBoolean = createAtomicBoolean(true);
    return inlineAutoClose(() => {
      Eif (breakBindingOnce.compareAndSet(true, false)) {
        this.breakBinding(contract, promisor);
      }
    });
  }
 
  private breakBinding<T>(contract: Contract<T>, promisor: Promisor<T>): void {
    // it is possible the Contract has already been removed or updated with a new Promisor
    // Checking the removed promisor is required to avoid:
    //   1. Calling decrementUsage twice on Promisors already removed
    //   2. Not calling decrementUsage enough times
    // decrementing usage too many times.
    try {
      this.removeFromPromisorMap(contract, promisor);
    } finally {
      promisor.decrementUsage();
    }
  }
 
  private removeFromPromisorMap<T>(contract: Contract<T>, promisor: Promisor<T>): void {
    if (this.#promisorMap.get(contract) === promisor) {
      this.#promisorMap.delete(contract);
    }
  }
 
  private getFromPromisorMap<T>(contract: Contract<T>): OptionalType<Promisor<T>> {
    return (this.#promisorMap.get(contract) as OptionalType<Promisor<T>>);
  }
 
  private breakAllBindings(): number {
    let contractCount: number = 0;
    Internal.mapForEachReversed(this.#promisorMap, (contract, promisor) => {
      this.breakBinding(contract, promisor);
      contractCount++;
    });
    return contractCount;
  }
 
  private hasPartners(): boolean {
    return this.#partners.length > 0;
  }
 
  private claimFromPartners<T>(contract: Contract<T>): OptionalType<T> {
    if (this.hasPartners()) {
      for (const partner of this.#partners) {
        if (partner.isBound(contract)) {
          return partner.claim(contract);
        }
      }
    }
    this.throwContractNotPromisedException(contract);
  }
 
  private isAnyPartnerBound<T>(contract: Contract<T>): boolean {
    if (this.hasPartners()) {
      return this.#partners.some(partner => partner.isBound(contract));
    }
    return false;
  }
 
  private throwContractNotPromisedException<T>(contract: Contract<T>): never {
    throw new ContractException("Contract " + contract + " was not promised.");
  }
 
  private throwContractNotReplaceableException<T>(contract: Contract<T>): never {
    throw new ContractException("Contract " + contract + " is not replaceable.");
  }
 
  private constructor(config: Config) {
    const validConfig = configCheck(config);
    const validPartners = presentCheck(validConfig?.partners ?? [], "Partners must be present.");
 
    this.#policy = createPolicy(validConfig);
    this.#events = createEvents({
      names: validConfig?.shutdownEvents ?? [],
      callback: () => this.shutdown()
    });
 
    Eif (isPresent(validPartners)) {
      this.#partners.push(...validPartners);
    }
  }
 
  readonly #closeMany: AutoCloseMany = createAutoCloseMany();
  readonly #idempotent: Idempotent = createIdempotent({ open: () => this.firstOpen() });
  readonly #promisorMap = new Map<Contract<unknown>, Promisor<unknown>>();
  readonly #partners: Contracts[] = [];
  readonly #policy: Policy;
  readonly #events: Events;
}