All files / sheaves/src sheafify.ts

99.04% Statements 104/105
97.43% Branches 38/39
100% Functions 20/20
99.03% Lines 103/104

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 316 317 318 319 320 321 322 323                                                                        3x 99x 1x   98x 1x   97x 64x 2x   62x 2x   60x 1x   59x 1x     91x                       3x 74x 74x 2x   72x 27x 99x 72x                   3x     35x 35x 35x 74x 74x 71x 71x     35x                   3x           32x   32x 32x     32x 32x 45x 45x 90x 90x   45x 2x       32x 68x 68x 95x 91x     68x     32x                     3x 55x 55x 55x 1x   54x               3x           32x 32x 32x 32x 36x 36x 30x 30x   6x 6x     2x         3x                 44x 79x         44x                 44x   44x           44x       53x 53x 91x         53x   1x   17x           35x 35x 3x           32x 32x 68x         32x         36x 36x 1x             35x               44x 44x 53x     44x                 44x     44x           42x   44x               2x   44x          
/**
 * Sheafify a set of providers into an authority manager.
 *
 * `sheafify({ name, providers })` returns a `Sheaf` — an immutable object
 * that produces dispatch sections over a fixed set of providers.
 *
 * Each dispatch through a granted section:
 *   1. Filters to providers whose guard covers the point (getMatchingProviders)
 *   2. Collapses equivalent candidates (same metadata → one representative)
 *   3. Decomposes metadata into constraints + options
 *   4. Invokes the policy on the distinguished options
 *   5. Dispatches to some element of the chosen candidate
 */
 
import { makeExo } from '@endo/exo';
import { M } from '@endo/patterns';
import type { InterfaceGuard } from '@endo/patterns';
import type { MethodSchema } from '@metamask/kernel-utils';
import { makeDiscoverableExo } from '@metamask/kernel-utils';
import { stringify } from '@metamask/kernel-utils';
 
import { asyncifyMethodGuards } from './guard.ts';
import { getMatchingProviders } from './match.ts';
import { evaluateMetadata } from './metadata.ts';
import type {
  Candidate,
  MetadataSpec,
  Section,
  Policy,
  PolicyContext,
  Provider,
  Sheaf,
} from './types.ts';
 
type EncodedEntry = [key: string, type: string, value: unknown];
 
const encodeMetadataEntry = (key: string, value: unknown): EncodedEntry => {
  if (value === undefined) {
    return [key, 'undefined', null];
  }
  if (typeof value === 'bigint') {
    return [key, 'bigint', String(value)];
  }
  if (typeof value === 'number') {
    if (Number.isNaN(value)) {
      return [key, 'NaN', null];
    }
    if (value === Infinity) {
      return [key, '+Infinity', null];
    }
    if (value === -Infinity) {
      return [key, '-Infinity', null];
    }
    if (Object.is(value, -0)) {
      return [key, '-0', null];
    }
  }
  return [key, typeof value, value];
};
 
/**
 * Serialize metadata for equivalence-class keying (collapse step).
 *
 * Uses type-tagged encoding so that values JSON.stringify conflates
 * (undefined, null, NaN, Infinity, -Infinity) produce distinct keys.
 *
 * @param metadata - The metadata value to serialize.
 * @returns A string key for equivalence comparison.
 */
const metadataKey = (metadata: Record<string, unknown>): string => {
  const keys = Object.keys(metadata);
  if (keys.length === 0) {
    return 'null';
  }
  const entries = Object.entries(metadata)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([key, val]) => encodeMetadataEntry(key, val));
  return JSON.stringify(entries);
};
 
/**
 * Collapse candidates into equivalence classes by metadata identity.
 * Returns one representative per class; the choice within a class is arbitrary.
 *
 * @param candidates - The candidates to collapse.
 * @returns One representative per equivalence class.
 */
const collapseEquivalent = <MetaData extends Record<string, unknown>>(
  candidates: Candidate<MetaData>[],
): Candidate<MetaData>[] => {
  const seen = new Set<string>();
  const representatives: Candidate<MetaData>[] = [];
  for (const entry of candidates) {
    const key = metadataKey(entry.metadata);
    if (!seen.has(key)) {
      seen.add(key);
      representatives.push(entry);
    }
  }
  return representatives;
};
 
/**
 * Decompose candidate metadata into constraints (shared by all) and
 * stripped candidates (carrying only distinguishing keys).
 *
 * @param candidates - The collapsed candidates.
 * @returns Constraints and stripped candidates.
 */
const decomposeMetadata = <MetaData extends Record<string, unknown>>(
  candidates: Candidate<MetaData>[],
): {
  constraints: Partial<MetaData>;
  stripped: Candidate<Partial<MetaData>>[];
} => {
  const constraints: Record<string, unknown> = {};
 
  const head = candidates[0];
  Iif (head === undefined) {
    return { constraints: {} as Partial<MetaData>, stripped: [] };
  }
  const first = head.metadata;
  for (const key of Object.keys(first)) {
    const val = first[key];
    const shared = candidates.every((entry) => {
      const meta = entry.metadata;
      return Object.hasOwn(meta, key) && Object.is(meta[key], val);
    });
    if (shared) {
      constraints[key] = val;
    }
  }
 
  const stripped = candidates.map((entry) => {
    const remaining: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(entry.metadata)) {
      if (!Object.hasOwn(constraints, key)) {
        remaining[key] = val;
      }
    }
    return { exo: entry.exo, metadata: remaining as Partial<MetaData> };
  });
 
  return { constraints: constraints as Partial<MetaData>, stripped };
};
 
/**
 * Invoke a method on a section exo, throwing if the handler is missing.
 *
 * @param exo - The section exo to invoke.
 * @param method - The method name to call.
 * @param args - The positional arguments.
 * @returns The synchronous return value of the method (typically a Promise).
 */
const invokeExo = (exo: Section, method: string, args: unknown[]): unknown => {
  const obj = exo as Record<string, (...a: unknown[]) => unknown>;
  const fn = obj[method];
  if (fn === undefined) {
    throw new Error(`Section has guard for '${method}' but no handler`);
  }
  return fn.call(obj, ...args);
};
 
type ResolvedProvider<M extends Record<string, unknown>> = {
  exo: Section;
  spec: MetadataSpec<M> | undefined;
};
 
const drivePolicy = async <M extends Record<string, unknown>>(
  policy: Policy<M>,
  candidates: Candidate<Partial<M>>[],
  context: PolicyContext<M>,
  invoke: (candidate: Candidate<Partial<M>>) => Promise<unknown>,
): Promise<unknown> => {
  const errors: unknown[] = [];
  const gen = policy(candidates, context);
  let next = await gen.next([...errors]);
  while (!next.done) {
    try {
      const result = await invoke(next.value);
      await gen.return(undefined);
      return result;
    } catch (error) {
      errors.push(error);
      next = await gen.next([...errors]);
    }
  }
  throw new Error(`No viable section for ${context.method}`, {
    cause: errors,
  });
};
 
export const sheafify = <
  MetaData extends Record<string, unknown> = Record<string, unknown>,
>({
  name,
  providers,
}: {
  name: string;
  providers: Provider<MetaData>[];
}): Sheaf<MetaData> => {
  const frozenProviders: readonly ResolvedProvider<MetaData>[] = harden(
    providers.map((provider) => ({
      exo: provider.exo,
      spec: provider.metadata,
    })),
  );
  const buildSection = ({
    guard,
    policy,
    schema,
  }: {
    guard: InterfaceGuard;
    policy: Policy<MetaData>;
    schema?: Record<string, MethodSchema>;
  }): object => {
    const asyncMethodGuards = asyncifyMethodGuards(guard);
    const asyncGuard =
      schema === undefined
        ? M.interface(`${name}:section`, asyncMethodGuards)
        : M.interface(`${name}:section`, asyncMethodGuards, {
            defaultGuards: 'passable',
          });
 
    const dispatch = async (
      method: string,
      args: unknown[],
    ): Promise<unknown> => {
      const candidates = getMatchingProviders(frozenProviders, method, args);
      const evaluatedCandidates: Candidate<MetaData>[] = candidates.map(
        (provider) => ({
          exo: provider.exo,
          metadata: evaluateMetadata(provider.spec, args),
        }),
      );
      switch (evaluatedCandidates.length) {
        case 0:
          throw new Error(`No section covers ${method}(${stringify(args, 0)})`);
        case 1:
          return invokeExo(
            (evaluatedCandidates[0] as Candidate<MetaData>).exo,
            method,
            args,
          );
        default: {
          const collapsed = collapseEquivalent(evaluatedCandidates);
          if (collapsed.length === 1) {
            return invokeExo(
              (collapsed[0] as Candidate<MetaData>).exo,
              method,
              args,
            );
          }
          const { constraints, stripped } = decomposeMetadata(collapsed);
          const strippedToCollapsed = new Map(
            stripped.map((strippedCandidate, i) => [
              strippedCandidate,
              collapsed[i] as Candidate<MetaData>,
            ]),
          );
          return drivePolicy(
            policy,
            stripped,
            { method, args, constraints },
            async (candidate) => {
              const resolved = strippedToCollapsed.get(candidate);
              if (resolved === undefined) {
                throw new Error(
                  `Policy yielded an unrecognized candidate for '${method}'. ` +
                    `The yielded value must be one of the Candidate objects ` +
                    `passed into the policy (object identity, not structural equality). ` +
                    `Did the policy construct a new object instead of yielding from the candidates array?`,
                );
              }
              return invokeExo(resolved.exo, method, args);
            },
          );
        }
      }
    };
 
    const handlers: Record<string, (...args: unknown[]) => Promise<unknown>> =
      {};
    for (const method of Object.keys(asyncMethodGuards)) {
      handlers[method] = async (...args: unknown[]) => dispatch(method, args);
    }
 
    const exo = (schema === undefined
      ? makeExo(`${name}:section`, asyncGuard, handlers)
      : makeDiscoverableExo(
          `${name}:section`,
          handlers,
          schema,
          asyncGuard,
        )) as unknown as Section;
 
    return exo;
  };
 
  const getSection = ({
    guard,
    policy,
  }: {
    guard: InterfaceGuard;
    policy: Policy<MetaData>;
  }): object => buildSection({ guard, policy });
 
  const getDiscoverableSection = ({
    guard,
    policy,
    schema,
  }: {
    guard: InterfaceGuard;
    policy: Policy<MetaData>;
    schema: Record<string, MethodSchema>;
  }): object => buildSection({ guard, policy, schema });
 
  return harden({
    getSection,
    getDiscoverableSection,
  });
};