All files / src/impl Waitable.impl.ts

100% Statements 106/106
96.87% Branches 31/32
100% Functions 28/28
100% Lines 106/106

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 24112x     12x 12x 12x 12x 12x 12x     12x 12x             12x 266x                 12x         111x 110x 105x 104x       1x           90x       90x         4x 4x 4x 2x   2x           5x 1x     4x 4x 4x 4x 4x     4x   25x 3x 3x       1x 1x           4x         4x 4x 4x         118x         2x 2x 2x 2x 1x 1x 1x   1x           4x 1x     3x 3x 3x 3x 3x 3x   3x 2x     3x   6x 2x 2x 2x 2x       1x 1x       3x         3x 3x   3x         5x   4x 4x 4x 4x 4x 4x   4x   19x 8x   11x     5x 4x 4x         4x 4x 4x 4x         266x       266x   266x       9x       121x 121x 111x         111x 39x         104x 3x         5x 1x       266x 266x 266x  
import { ConcurrencyException } from "@jonloucks/concurrency-ts/api/ConcurrencyException";
import { Duration, OptionalType, RequiredType } from "@jonloucks/concurrency-ts/api/Types";
import { Config, Waitable } from "@jonloucks/concurrency-ts/api/Waitable";
import { Consumer, fromType as consumerFromType, Type as ConsumerType } from "@jonloucks/concurrency-ts/auxiliary/Consumer";
import { Predicate, fromType as predicateFromType, Type as PredicateType } from "@jonloucks/concurrency-ts/auxiliary/Predicate";
import { Supplier, fromType as supplierFromType, Type as SupplierType } from "@jonloucks/concurrency-ts/auxiliary/Supplier";
import { AtomicBoolean, AtomicReference, createAtomicBoolean, createAtomicReference } from "@jonloucks/contracts-ts/auxiliary/Convenience";
import { IllegalStateException } from "@jonloucks/contracts-ts/auxiliary/IllegalStateException";
import { AutoClose, AUTO_CLOSE_NONE, Close, inlineAutoClose } from "@jonloucks/contracts-ts/api/AutoClose";
 
import { ExposedPromise } from "./ExposedPromise";
import { create as createExposedPromise } from "./ExposedPromise.impl";
import { Internal } from "./Internal.impl";
 
/**
 * Create a new Waitable
 *
 * @return the new Waitable
 */
export function create<T>(config?: Config<T>): Waitable<T> {
  return WaitableImpl.internalCreate(config);
}
 
// ---- Implementation details below ----
 
interface ValueObserver<T> extends Close {
  observeValue(value: OptionalType<T>): void;
};
 
const CLOSED_EXCEPTION: ConcurrencyException = new ConcurrencyException("Waitable is closed.");
 
class WaitableImpl<T> implements Waitable<T> {
 
  open(): AutoClose {
    if (this.#isOpen.compareAndSet(false, true)) {
      return inlineAutoClose((): void => {
        if (this.#isOpen.compareAndSet(true, false)) {
          this.closeAllListeners();
        }
      });
    } else {
      return AUTO_CLOSE_NONE;
    }
  };
 
  // WaitableSupplier.supply implementations
  supply(): T {
    const value = this.#reference.get();
    // if (value === undefined || value === null) {
    //   throw new IllegalStateException("No value is currently available in Waitable.");
    // }
    return value as T;
  }
 
  // WaitableSupplier.supplyIf implementation
  supplyIf(predicate: PredicateType<T>): OptionalType<T> {
    const validPredicate: Predicate<OptionalType<T>> = predicateFromType(predicate);
    const currentValue: OptionalType<T> = this.#reference.get();
    if (validPredicate.test(currentValue)) {
      return currentValue;
    } else {
      return undefined;
    }
  }
 
  // WaitableSupplier.supplyWhen implementation
  async supplyWhen(predicate: RequiredType<PredicateType<T>>, timeout?: Duration): Promise<T> {
    if (!this.isOpen()) {
      return Promise.reject(CLOSED_EXCEPTION);
    }
 
    const validPredicate: Predicate<OptionalType<T>> = predicateFromType(predicate);
    const firstNotify: AtomicBoolean = createAtomicBoolean(true);
    const exposedPromise: ExposedPromise<T> = createExposedPromise();
    const removeListener = (v: ValueObserver<T>): void => {
      this.#valueObservers.delete(v);
    };
 
    const valueObserver: ValueObserver<T> = {
      observeValue: function (value: T): void {
        if (validPredicate.test(value) && firstNotify.getAndSet(false)) {
          removeListener(this);
          exposedPromise.resolve(value);
        }
      },
      close: function (): void {
        removeListener(this);
        exposedPromise.reject(CLOSED_EXCEPTION);
      }
    };
 
    // maybe have the timeout delete the observer as well
 
    const returnPromise: Promise<T> = Internal.wrapPromiseWithTimeout<T>(
      exposedPromise.getPromise(),
      timeout
    );
 
    this.#valueObservers.add(valueObserver);
    valueObserver.observeValue(this.supply());
    return returnPromise;
  }
 
  // WaitableConsumer.consume implementations
  consume(value: SupplierType<T>): void {
    this.setValue(supplierFromType(value).supply());
  }
 
  // WaitableConsumer.consumeIf implementation
  consumeIf(predicate: RequiredType<PredicateType<T>>, value: SupplierType<T>): OptionalType<T> {
    const validPredicate: Predicate<OptionalType<T>> = predicateFromType(predicate);
    const validValueSupplier: Supplier<T> = supplierFromType(value);
    const currentValue: OptionalType<T> = this.#reference.get();
    if (validPredicate.test(currentValue)) {
      const newValue: T = validValueSupplier.supply();
      this.setValue(newValue);
      return newValue;
    } else {
      return undefined;
    }
  }
 
  // WaitableConsumer.consumeWhen implementation
  async consumeWhen(predicate: RequiredType<PredicateType<T>>, value: SupplierType<T>, timeout?: Duration): Promise<OptionalType<T>> {
    if (!this.isOpen()) {
      return Promise.reject(CLOSED_EXCEPTION);
    }
 
    const validPredicate: Predicate<OptionalType<T>> = predicateFromType(predicate);
    const validValueSupplier: Supplier<T> = supplierFromType(value);
    const firstNotify: AtomicBoolean = createAtomicBoolean(true);
    const exposedPromise: ExposedPromise<OptionalType<T>> = createExposedPromise();
    const removeListener = (v: ValueObserver<T>): void => {
      this.#valueObservers.delete(v);
    };
    const setTheValue: (T: OptionalType<T>) => void = (v: OptionalType<T>): void => {
      this.setValue(v);
    };
 
    const valueObserver: ValueObserver<T> = {
      observeValue: function (value: T): void {
        if (validPredicate.test(value) && firstNotify.getAndSet(false)) {
          const suppliedValue: OptionalType<T> = validValueSupplier.supply();
          setTheValue(suppliedValue);
          removeListener(this);
          exposedPromise.resolve(suppliedValue);
        }
      },
      close: function (): void {
        removeListener(this);
        exposedPromise.reject(CLOSED_EXCEPTION);
      }
    };
 
    const returnPromise: Promise<OptionalType<T>> = Internal.wrapPromiseWithTimeout<OptionalType<T>>(
      exposedPromise.getPromise(),
      timeout
    );
 
    this.#valueObservers.add(valueObserver);
    valueObserver.observeValue(this.supply());
 
    return returnPromise;
  }
 
  // WaitableNotify.notifyWhile implementation
  notifyWhile(predicate: RequiredType<PredicateType<T>>, listener: RequiredType<ConsumerType<T>>): RequiredType<AutoClose> {
    this.assertOpen();
 
    const validPredicate: Predicate<OptionalType<T>> = predicateFromType(predicate);
    const notifyCallback: Consumer<T> = consumerFromType(listener);
    const firstClose: AtomicBoolean = createAtomicBoolean(true);
    const isLive: AtomicBoolean = createAtomicBoolean(true);
    const removeListener = (v: ValueObserver<T>): void => {
      this.#valueObservers.delete(v);
    };
    const valueObserver: ValueObserver<T> = {
      observeValue: function (value: T): void {
        if (!isLive.get() || !validPredicate.test(value)) {
          return;
        }
        notifyCallback.consume(value);
      },
      close: function (): void {
        if (firstClose.compareAndSet(true, false)) {
          isLive.set(false);
          removeListener(this);
        }
      }
    };
 
    this.#valueObservers.add(valueObserver);
    valueObserver.observeValue(this.supply());
    return inlineAutoClose((): void => {
      valueObserver.close();
    });
  }
 
  static internalCreate<T>(config?: RequiredType<Config<T>>): RequiredType<Waitable<T>> {
    return new WaitableImpl(config);
  }
 
  private constructor(config?: Config<T>) {
    const actualConfig = config ? config : {};
 
    this.#reference = createAtomicReference<OptionalType<T>>(actualConfig.initialValue);
  }
 
  private isOpen(): boolean {
    return this.#isOpen.get();
  }
 
  private setValue(newValue: OptionalType<T>): void {
    const oldValue: OptionalType<T> = this.#reference.getAndSet(newValue);
    if (oldValue !== newValue) {
      this.notifyListeners(newValue);
    }
  }
 
  private notifyListeners(newValue: OptionalType<T>): void {
    for (const valueObserver of this.#valueObservers) {
      valueObserver.observeValue(newValue);
    }
  }
 
  private closeAllListeners(): void {
    for (const valueObserver of this.#valueObservers) {
      valueObserver.close();
    }
  }
 
  private assertOpen(): void {
    if (!this.#isOpen.get()) {
      throw new IllegalStateException("Waitable must be open.");
    }
  }
 
  readonly #isOpen: AtomicBoolean = createAtomicBoolean(false)
  readonly #reference: AtomicReference<OptionalType<T>>;
  readonly #valueObservers: Set<ValueObserver<unknown>> = new Set<ValueObserver<unknown>>();
}