All files / src/entities/container_registry regex.ts

100% Statements 128/128
100% Branches 45/45
100% Functions 26/26
100% Lines 108/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 24922x   22x 22x 22x     22x 22x       22x                                                                               58x             58x         58x 139x 138x 138x 6x 132x 138x   58x 58x 58x         58x 58x   58x   52x   6x   58x       135x   135x 9x 9x 9x       150x 147x 147x   1x         147x         37x       92x 92x 89x 89x   1x     92x       61x 61x       47x 47x       59x 59x         22x 19x 38x 19x         38x 38x   4x 3x 3x 3x 3x 3x   3x           22x   48x 48x 23x 44x 23x       22x 23x 23x 23x 21x 21x 2x 1x           7x 7x 7x 6x 6x 6x 6x       22x         60x       2x 58x   53x 55x 53x 52x 52x 52x 52x 51x 51x 50x 42x 42x 37x 37x   37x       52x 52x 52x   52x   8x 8x 8x          
import { Worker } from 'node:worker_threads';
 
const REGEX_TIMEOUT_MS = 1000;
const MAX_ACTIVE_MATCHERS = 2;
export const MAX_REGISTRY_PATTERN_LENGTH = 500;
// Per-process compute admission only, not account or session state shared across replicas.
type MatcherSlot = { matcher: TagMatcher; ready: Promise<number[]> };
const matcherSlots: MatcherSlot[] = [];
let poolOpen = true;
let poolClosure: Promise<void> | undefined;
 
// Untrusted patterns and names are data, never interpolated into executable source.
const MATCHER_SOURCE = `
const { parentPort, workerData } = require('node:worker_threads');
const { RE2JS } = require(workerData.library);
let remove = null;
let keep = null;
function compile(pattern) {
  const compiled = RE2JS.compile(pattern);
  if (compiled.programSize() > 1000) throw new Error('Registry regex exceeds 1000 instructions. Use smaller repetitions.');
  return compiled;
}
parentPort.postMessage({ indices: [] });
parentPort.on('message', message => {
  try {
    if (message.action === 'compile') {
      remove = compile(message.remove);
      keep = message.keep ? compile(message.keep) : null;
      parentPort.postMessage({ indices: [] });
    } else {
      const selected = [];
      if (message.action === 'match') {
        for (let i = 0; i < message.names.length; i++) {
          if (remove.test(message.names[i]) && !keep?.test(message.names[i])) selected.push(i);
        }
      }
      remove = null;
      keep = null;
      parentPort.postMessage({ indices: selected });
    }
  } catch (error) {
    remove = null;
    keep = null;
    parentPort.postMessage({ error: error.message });
  }
});
`;
 
/** A request leases one worker exclusively; the process pool owns its lifetime. */
class TagMatcher {
  private readonly worker: Worker;
  failure?: Error;
  busy = false;
  private pending?: {
    resolve: (indices: number[]) => void;
    reject: (error: Error) => void;
    timer: ReturnType<typeof setTimeout>;
  };
  private constructor() {
    this.worker = new Worker(MATCHER_SOURCE, {
      eval: true,
      workerData: { library: require.resolve('re2js') },
      resourceLimits: { maxOldGenerationSizeMb: 32, maxYoungGenerationSizeMb: 8, stackSizeMb: 2 },
    });
    this.worker.on('message', (message: { indices: number[] } | { error: string }) => {
      if (!this.pending) return;
      clearTimeout(this.pending.timer);
      if ('error' in message)
        this.pending.reject(new Error(`Invalid RE2 registry regex: ${message.error}`));
      else this.pending.resolve(message.indices);
      this.pending = undefined;
    });
    this.worker.on('error', (error) => this.fail(error));
    this.worker.on('exit', (code) =>
      this.fail(new Error(`Registry regex worker exited (${code})`)),
    );
  }
 
  static create(): MatcherSlot {
    const matcher = new TagMatcher();
    const ready = matcher.wait();
    // An idle prewarmed worker must not keep CLI commands or test processes alive.
    ready.then(
      () => {
        if (!matcher.busy) matcher.worker.unref();
      },
      (error: unknown) => matcher.fail(error),
    );
    return { matcher, ready };
  }
 
  private fail(error: unknown): void {
    this.failure =
      error instanceof Error ? error : new Error('Registry regex worker failed', { cause: error });
    if (!this.pending) return;
    clearTimeout(this.pending.timer);
    this.pending.reject(this.failure);
    this.pending = undefined;
  }
 
  private wait(): Promise<number[]> {
    if (this.failure) return Promise.reject(this.failure);
    return new Promise((resolve, reject) => {
      const timer = setTimeout(
        () =>
          this.fail(
            new Error('Registry regex exceeded the 1000 ms time limit. Use a simpler pattern.'),
          ),
        REGEX_TIMEOUT_MS,
      );
      this.pending = { resolve, reject, timer };
    });
  }
 
  match(names: string[]): Promise<number[]> {
    return this.send({ action: 'match', names });
  }
 
  send(message: object): Promise<number[]> {
    const result = this.wait();
    if (!this.failure) {
      try {
        this.worker.postMessage(message);
      } catch (error) {
        this.fail(error);
      }
    }
    return result;
  }
 
  lease(): void {
    this.busy = true;
    this.worker.ref();
  }
 
  release(): void {
    this.busy = false;
    this.worker.unref();
  }
 
  async close(): Promise<void> {
    this.fail(new Error('Registry regex worker closed'));
    await this.worker.terminate();
  }
}
 
/** Preload a bounded process-local compute pool without retaining caller context. */
export async function warmTagMatchers(): Promise<void> {
  if (!poolOpen) await resetTagMatchers();
  while (matcherSlots.length < MAX_ACTIVE_MATCHERS) matcherSlots.push(TagMatcher.create());
  await Promise.all(matcherSlots.map(warmMatcherSlot));
}
 
/** Repair a transient startup failure once, without an unbounded restart loop. */
async function warmMatcherSlot(slot: MatcherSlot): Promise<void> {
  try {
    await slot.ready;
  } catch (error) {
    if (slot.matcher.busy) throw error;
    slot.matcher.lease();
    let owned = slot;
    try {
      owned = await replaceMatcherSlot(slot);
      await owned.ready;
    } finally {
      owned.matcher.release();
    }
  }
}
 
/** Terminate idle and active compute workers during server shutdown. */
export function closeTagMatchers(): Promise<void> {
  // Close admission before draining so termination cannot race with new leases.
  poolOpen = false;
  if (poolClosure) return poolClosure;
  const owned = matcherSlots.splice(0);
  poolClosure = Promise.all(owned.map((slot) => slot.matcher.close())).then(() => undefined);
  return poolClosure;
}
 
/** Explicit recovery may reopen admission only after the previous pool has fully terminated. */
export async function resetTagMatchers(): Promise<void> {
  const closing = closeTagMatchers();
  await closing;
  if (poolClosure === closing) {
    poolClosure = undefined;
    poolOpen = true;
  } else if (!poolOpen) {
    throw new Error('Registry regex pool closed');
  }
}
 
/** Keep the slot reserved until termination completes, including across concurrent calls. */
async function replaceMatcherSlot(slot: MatcherSlot): Promise<MatcherSlot> {
  await slot.matcher.close();
  const index = matcherSlots.indexOf(slot);
  if (index === -1) throw new Error('Registry regex pool closed');
  const replacement = TagMatcher.create();
  replacement.matcher.lease();
  matcherSlots[index] = replacement;
  return replacement;
}
 
/** Bound both compilation and matching before permitting any destructive operation. */
export async function withTagMatcher<T>(
  remove: string,
  keep: string | undefined,
  operation: (match: (names: string[]) => Promise<number[]>) => Promise<T>,
): Promise<T> {
  if (
    remove.length > MAX_REGISTRY_PATTERN_LENGTH ||
    (keep !== undefined && keep.length > MAX_REGISTRY_PATTERN_LENGTH)
  )
    throw new Error('Registry regex exceeds 500 characters.');
  if (!poolOpen) throw new Error('Registry regex pool closed');
  // Do not await warming before leasing: simultaneous requests must reserve distinct workers.
  while (matcherSlots.length < MAX_ACTIVE_MATCHERS) matcherSlots.push(TagMatcher.create());
  let slot = matcherSlots.find((candidate) => !candidate.matcher.busy);
  if (!slot) throw new Error('Registry regex matching is at capacity. Retry shortly.');
  slot.matcher.lease();
  let resetRequired = false;
  try {
    if (slot.matcher.failure) slot = await replaceMatcherSlot(slot);
    const { matcher } = slot;
    await slot.ready;
    await matcher.send({ action: 'compile', remove, keep });
    resetRequired = true;
    return await operation(async (names) => {
      try {
        return await matcher.match(names);
      } finally {
        resetRequired = false;
      }
    });
  } finally {
    const { matcher } = slot;
    try {
      if (!matcher.failure && resetRequired) await matcher.send({ action: 'reset' });
    } finally {
      if (!matcher.failure) matcher.release();
      else {
        await matcher.close();
        const index = matcherSlots.indexOf(slot);
        if (index !== -1) matcherSlots.splice(index, 1, TagMatcher.create());
      }
    }
  }
}