All files / src/internal/holder unified-storage.mts

90.76% Statements 59/65
84.61% Branches 33/39
100% Functions 14/14
90.76% Lines 59/65

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                                          474x         474x     474x       2129x   2129x 979x       1150x   1x           18x             1131x               822x   822x 14x         561x 561x   559x   561x                     479x   479x                           479x       309x 309x 2x           307x                                         3x               353x       348x 504x         24x 51x 21x     3x       18x 18x                       61x 66x 10x 10x         61x 61x   7x 7x 8x   7x 7x       61x 9x                                       14x 17x 17x 15x 15x   17x                     559x 3x 3x 3x 3x 3x            
import type { OnServiceDestroy } from '../../interfaces/index.mjs'
import type {
  HolderGetResult,
  IHolderStorage,
} from './holder-storage.interface.mjs'
import type { InstanceHolder } from './instance-holder.mjs'
 
import { InjectableScope, InjectableType } from '../../enums/index.mjs'
import { DIError } from '../../errors/index.mjs'
import { InstanceStatus } from './instance-holder.mjs'
 
/**
 * Unified storage implementation that works the same way regardless of scope.
 * Replaces RequestContext, HolderManager, SingletonStorage, RequestStorage.
 *
 * Scope is just metadata - storage operations are identical for all scopes.
 * Different storage instances are just isolated storage spaces.
 */
export class UnifiedStorage implements IHolderStorage {
  readonly scope: InjectableScope
 
  private readonly holders = new Map<string, InstanceHolder>()
  /**
   * Reverse dependency index: maps a dependency name to the set of holder names that depend on it.
   * This allows O(1) lookup of dependents instead of O(n) iteration.
   */
  private readonly dependents = new Map<string, Set<string>>()
 
  constructor(scope: InjectableScope = InjectableScope.Singleton) {
    this.scope = scope
  }
 
  get<T = unknown>(instanceName: string): HolderGetResult<T> {
    const holder = this.holders.get(instanceName)
 
    if (!holder) {
      return null
    }
 
    // Check holder status for error states
    switch (holder.status) {
      case InstanceStatus.Destroying:
        return [
          DIError.instanceDestroying(instanceName),
          holder as InstanceHolder<T>,
        ]
 
      case InstanceStatus.Error:
        return [
          holder.instance as unknown as DIError,
          holder as InstanceHolder<T>,
        ]
 
      case InstanceStatus.Creating:
      case InstanceStatus.Created:
        return [undefined, holder as InstanceHolder<T>]
 
      default:
        return null
    }
  }
 
  set(instanceName: string, holder: InstanceHolder): void {
    this.holders.set(instanceName, holder)
    // Register dependencies in reverse index
    if (holder.deps.size > 0) {
      this.registerDependencies(instanceName, holder.deps)
    }
  }
 
  delete(instanceName: string): boolean {
    const holder = this.holders.get(instanceName)
    if (holder) {
      // Remove this holder from the reverse index for all its dependencies
      this.removeFromDependentsIndex(instanceName, holder.deps)
    }
    return this.holders.delete(instanceName)
  }
 
  createHolder<T>(
    instanceName: string,
    type: InjectableType,
    deps: Set<string>,
  ): [
    ReturnType<typeof Promise.withResolvers<[undefined, T]>>,
    InstanceHolder<T>,
  ] {
    const deferred = Promise.withResolvers<[undefined, T]>()
 
    const holder: InstanceHolder<T> = {
      status: InstanceStatus.Creating,
      name: instanceName,
      instance: null,
      creationPromise: deferred.promise,
      destroyPromise: null,
      type,
      scope: this.scope,
      deps,
      destroyListeners: [],
      createdAt: Date.now(),
      waitingFor: new Set(),
    }
 
    return [deferred, holder]
  }
 
  storeInstance(instanceName: string, instance: unknown): void {
    const holder = this.holders.get(instanceName)
    if (holder) {
      throw DIError.storageError(
        'Instance already stored',
        'storeInstance',
        instanceName,
      )
    }
    this.set(instanceName, {
      status: InstanceStatus.Created,
      name: instanceName,
      instance,
      creationPromise: null,
      destroyPromise: null,
      type: InjectableType.Class,
      scope: this.scope,
      deps: new Set(),
      destroyListeners:
        typeof instance === 'object' &&
        instance !== null &&
        'onServiceDestroy' in instance
          ? [(instance as OnServiceDestroy).onServiceDestroy]
          : [],
      createdAt: Date.now(),
      waitingFor: new Set(),
    })
  }
 
  handles(scope: InjectableScope): boolean {
    return scope === this.scope
  }
 
  // ============================================================================
  // ITERATION AND QUERY
  // ============================================================================
 
  getAllNames(): string[] {
    return Array.from(this.holders.keys())
  }
 
  forEach(callback: (name: string, holder: InstanceHolder) => void): void {
    for (const [name, holder] of this.holders) {
      callback(name, holder)
    }
  }
 
  findByInstance(instance: unknown): InstanceHolder | null {
    for (const holder of this.holders.values()) {
      if (holder.instance === instance) {
        return holder
      }
    }
    return null
  }
 
  findDependents(instanceName: string): string[] {
    const dependents = this.dependents.get(instanceName)
    return dependents ? Array.from(dependents) : []
  }
 
  /**
   * Updates dependency references when instance names change.
   * Used during scope upgrades when instance names are regenerated with requestId.
   *
   * @param oldName The old instance name
   * @param newName The new instance name
   */
  updateDependencyReference(oldName: string, newName: string): void {
    // Update all holders that reference oldName in their deps Set
    for (const holder of this.holders.values()) {
      if (holder.deps.has(oldName)) {
        holder.deps.delete(oldName)
        holder.deps.add(newName)
      }
    }
 
    // Update reverse dependency index
    const oldDependents = this.dependents.get(oldName)
    if (oldDependents) {
      // Move dependents from old name to new name
      const newDependents = this.dependents.get(newName) || new Set<string>()
      for (const dependent of oldDependents) {
        newDependents.add(dependent)
      }
      this.dependents.set(newName, newDependents)
      this.dependents.delete(oldName)
    }
 
    // Update reverse index entries - if oldName was a dependency, update all holders that depend on it
    for (const [depName, dependents] of this.dependents.entries()) {
      Iif (depName === oldName) {
        // This shouldn't happen, but handle it just in case
        const newDependents = this.dependents.get(newName) || new Set<string>()
        for (const dependent of dependents) {
          newDependents.add(dependent)
        }
        this.dependents.set(newName, newDependents)
        this.dependents.delete(oldName)
      }
    }
  }
 
  // ============================================================================
  // INTERNAL HELPERS
  // ============================================================================
 
  /**
   * Registers a holder's dependencies in the reverse index.
   */
  private registerDependencies(holderName: string, deps: Set<string>): void {
    for (const dep of deps) {
      let dependents = this.dependents.get(dep)
      if (!dependents) {
        dependents = new Set()
        this.dependents.set(dep, dependents)
      }
      dependents.add(holderName)
    }
  }
 
  /**
   * Removes a holder from the reverse dependency index.
   */
  private removeFromDependentsIndex(
    holderName: string,
    deps: Set<string>,
  ): void {
    for (const dep of deps) {
      const dependents = this.dependents.get(dep)
      Eif (dependents) {
        dependents.delete(holderName)
        Eif (dependents.size === 0) {
          this.dependents.delete(dep)
        }
      }
    }
  }
}