All files / omnium-gatherum/src/controllers/caplet caplet-controller.ts

100% Statements 50/50
100% Branches 12/12
100% Functions 16/16
100% Lines 50/50

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 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                                                                                                                                                                                                                      28x                                                 28x 28x 28x 28x 28x                             28x     28x       28x             28x                 28x   18x     7x     7x     9x     5x                               18x 18x     18x 1x     17x 2x     15x 1x   14x   14x                 14x   14x   13x 13x               13x     13x   14x                   7x   7x 7x 2x     5x   4x 4x     4x                 7x                   9x                   5x 5x 2x     3x 1x       2x     2x  
import { makeDefaultExo } from '@metamask/kernel-utils/exo';
import type { Logger } from '@metamask/logger';
import type { ClusterConfig } from '@metamask/ocap-kernel';
 
import type {
  CapletId,
  CapletManifest,
  InstalledCaplet,
  InstallResult,
  LaunchResult,
} from './types.ts';
import { isCapletManifest } from './types.ts';
import { Controller } from '../base-controller.ts';
import type { ControllerConfig } from '../base-controller.ts';
import { ControllerStorage } from '../storage/controller-storage.ts';
import type { StorageAdapter } from '../storage/types.ts';
 
/**
 * Caplet controller persistent state.
 * This is the shape of the state managed by the CapletController
 * through the ControllerStorage abstraction.
 */
export type CapletControllerState = {
  /** Installed caplets keyed by caplet ID */
  caplets: Record<CapletId, InstalledCaplet>;
};
 
/**
 * Methods exposed by the CapletController.
 */
export type CapletControllerFacet = {
  /**
   * Install a caplet.
   *
   * @param manifest - The caplet manifest.
   * @returns The installation result.
   * @example
   * ```typescript
   * const result = await omnium.caplet.install({
   *   id: 'com.example.test',
   *   name: 'Test Caplet',
   *   version: '1.0.0',
   *   bundleSpec: '/path/to/bundle.json',
   * });
   * ```
   */
  install: (manifest: CapletManifest) => Promise<InstallResult>;
 
  /**
   * Uninstall a caplet.
   *
   * @param capletId - The ID of the caplet to uninstall.
   */
  uninstall: (capletId: CapletId) => Promise<void>;
 
  /**
   * List all installed caplets.
   *
   * @returns Array of installed caplets.
   */
  list: () => InstalledCaplet[];
 
  /**
   * Get a specific installed caplet.
   *
   * @param capletId - The caplet ID.
   * @returns The installed caplet or undefined if not found.
   */
  get: (capletId: CapletId) => InstalledCaplet | undefined;
 
  /**
   * Get the root object presence for a caplet.
   *
   * @param capletId - The caplet ID.
   * @returns A promise for the caplet's root object (as a CapTP presence).
   */
  getCapletRoot: (capletId: CapletId) => Promise<unknown>;
};
 
/**
 * Dependencies for the CapletController.
 * These are attenuated - only the methods needed are provided.
 */
export type CapletControllerDeps = {
  /** Storage adapter for creating controller storage */
  adapter: StorageAdapter;
  /** Launch a subcluster for a caplet */
  launchSubcluster: (config: ClusterConfig) => Promise<LaunchResult>;
  /** Terminate a caplet's subcluster */
  terminateSubcluster: (subclusterId: string) => Promise<void>;
  /** Get the root object for a vat by kref string */
  getVatRoot: (krefString: string) => Promise<unknown>;
};
 
/**
 * Controller for managing caplet lifecycle.
 *
 * The CapletController manages:
 * - Installing caplets (validating manifest, launching subcluster, storing metadata)
 * - Uninstalling caplets (terminating subcluster, removing metadata)
 * - Querying installed caplets
 */
export class CapletController extends Controller<
  'CapletController',
  CapletControllerState,
  CapletControllerFacet
> {
  readonly #pendingInstalls: Set<CapletId> = new Set();
 
  readonly #launchSubcluster: (config: ClusterConfig) => Promise<LaunchResult>;
 
  readonly #terminateSubcluster: (subclusterId: string) => Promise<void>;
 
  readonly #getVatRoot: (krefString: string) => Promise<unknown>;
 
  /**
   * Private constructor - use static create() method.
   *
   * @param storage - ControllerStorage for caplet state.
   * @param logger - Logger instance.
   * @param launchSubcluster - Function to launch a subcluster.
   * @param terminateSubcluster - Function to terminate a subcluster.
   * @param getVatRoot - Function to get a vat's root object as a presence.
   */
  // eslint-disable-next-line no-restricted-syntax -- TypeScript doesn't support # for constructors
  private constructor(
    storage: ControllerStorage<CapletControllerState>,
    logger: Logger,
    launchSubcluster: (config: ClusterConfig) => Promise<LaunchResult>,
    terminateSubcluster: (subclusterId: string) => Promise<void>,
    getVatRoot: (krefString: string) => Promise<unknown>,
  ) {
    super('CapletController', storage, logger);
    this.#launchSubcluster = launchSubcluster;
    this.#terminateSubcluster = terminateSubcluster;
    this.#getVatRoot = getVatRoot;
    harden(this);
  }
 
  /**
   * Create a CapletController and return its public methods.
   *
   * @param config - Controller configuration.
   * @param deps - Controller dependencies (attenuated for POLA).
   * @returns A hardened CapletController exo.
   */
  static async make(
    config: ControllerConfig,
    deps: CapletControllerDeps,
  ): Promise<CapletControllerFacet> {
    // Create storage internally
    const storage = await ControllerStorage.make({
      namespace: 'caplet',
      adapter: deps.adapter,
      makeDefaultState: () => ({ caplets: {} }),
      logger: config.logger.subLogger({ tags: ['storage'] }),
    });
 
    const controller = new CapletController(
      storage,
      config.logger,
      deps.launchSubcluster,
      deps.terminateSubcluster,
      deps.getVatRoot,
    );
    return controller.makeFacet();
  }
 
  /**
   * Returns the hardened exo with public methods.
   *
   * @returns A hardened exo object with the controller's public methods.
   */
  makeFacet(): CapletControllerFacet {
    return makeDefaultExo('CapletController', {
      install: async (manifest: CapletManifest): Promise<InstallResult> => {
        return this.#install(manifest);
      },
      uninstall: async (capletId: CapletId): Promise<void> => {
        return this.#uninstall(capletId);
      },
      list: (): InstalledCaplet[] => {
        return this.#list();
      },
      get: (capletId: CapletId): InstalledCaplet | undefined => {
        return this.#get(capletId);
      },
      getCapletRoot: async (capletId: CapletId): Promise<unknown> => {
        return this.#getCapletRoot(capletId);
      },
    });
  }
 
  /**
   * Install a caplet.
   *
   * @param manifest - The caplet manifest.
   * @param _bundle - The caplet bundle (currently unused).
   * @returns The installation result.
   */
  async #install(
    manifest: CapletManifest,
    _bundle?: unknown,
  ): Promise<InstallResult> {
    const { id } = manifest;
    this.logger.info(`Installing caplet: ${id}`);
 
    // TODO: Move this validation in front of the controller.
    if (!isCapletManifest(manifest)) {
      throw new Error(`Invalid caplet manifest for ${id}`);
    }
 
    if (this.state.caplets[id] !== undefined) {
      throw new Error(`Caplet ${id} is already installed`);
    }
 
    if (this.#pendingInstalls.has(id)) {
      throw new Error(`Caplet ${id} is already being installed`);
    }
    this.#pendingInstalls.add(id);
 
    const clusterConfig: ClusterConfig = {
      bootstrap: id,
      vats: {
        [id]: {
          bundleSpec: manifest.bundleSpec,
        },
      },
    };
 
    try {
      const { subclusterId, rootKref } =
        await this.#launchSubcluster(clusterConfig);
 
      this.update((draft) => {
        draft.caplets[id] = {
          manifest,
          subclusterId,
          rootKref,
          installedAt: Date.now(),
        };
      });
 
      this.logger.info(
        `Caplet ${id} installed with subcluster ${subclusterId}`,
      );
      return { capletId: id, subclusterId };
    } finally {
      this.#pendingInstalls.delete(id);
    }
  }
 
  /**
   * Uninstall a caplet.
   *
   * @param capletId - The ID of the caplet to uninstall.
   */
  async #uninstall(capletId: CapletId): Promise<void> {
    this.logger.info(`Uninstalling caplet: ${capletId}`);
 
    const caplet = this.state.caplets[capletId];
    if (caplet === undefined) {
      throw new Error(`Caplet ${capletId} not found`);
    }
 
    await this.#terminateSubcluster(caplet.subclusterId);
 
    this.update((draft) => {
      delete draft.caplets[capletId];
    });
 
    this.logger.info(`Caplet ${capletId} uninstalled`);
  }
 
  /**
   * Get all installed caplets.
   *
   * @returns Array of all installed caplets.
   */
  #list(): InstalledCaplet[] {
    return Object.values(this.state.caplets);
  }
 
  /**
   * Get an installed caplet by ID.
   *
   * @param capletId - The caplet ID to retrieve.
   * @returns The installed caplet or undefined if not found.
   */
  #get(capletId: CapletId): InstalledCaplet | undefined {
    return this.state.caplets[capletId];
  }
 
  /**
   * Get the root object presence for a caplet.
   *
   * @param capletId - The caplet ID.
   * @returns A promise for the caplet's root object (as a CapTP presence).
   */
  async #getCapletRoot(capletId: CapletId): Promise<unknown> {
    const caplet = this.state.caplets[capletId];
    if (!caplet) {
      throw new Error(`Caplet ${capletId} not found`);
    }
 
    if (!caplet.rootKref) {
      throw new Error(`Caplet ${capletId} has no root object`);
    }
 
    // Convert the stored kref string to a presence using the kernel facade
    return this.#getVatRoot(caplet.rootKref);
  }
}
harden(CapletController);