SPB Git

Repository Public

worker-pool.ts 9.3 KB 283 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : KA Maps Engine8 * File             : sdk/web/src/worker-pool.ts9 * Module           : sdk10 * Repository       : https://git.spboucher.ai/ka-maps-engine11 * Created          : 2026-12-0112 * Last Modified    : 2026-12-0113 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Groupe de Web Workers pour la construction des tuiles (analyse MVT + tessellation).43//44// - taille déduite de `navigator.hardwareConcurrency` ;45// - le même module wasm que le fil principal, déjà compilé, est remis à chaque worker ;46// - même origine : `new Worker(url)` sans `blob:` ; autre origine (actifs servis par47//   maps.spboucher.ai) : un amorçage `blob:` + `importScripts` est inévitable (règle du navigateur) ;48// - si les workers ne démarrent pas (CSP, fichier absent), les travaux retombent sur le fil principal.4950export interface BuildJob {51  job: number;52  z: number;53  x: number;54  y: number;55  rev: number;56  bytes: Uint8Array;57}5859export interface BuildSink {60  buildDone(job: number, bytes: Uint8Array): void;61  buildFailed(job: number, message: string): void;62  /** Document de style d'une révision (remis une fois par worker) ; `undefined` si la révision est périmée. */63  styleDocument(rev: number): string | undefined;64  /** Construction sur le fil principal (repli). */65  buildLocal(job: BuildJob): void;66}6768interface Slot {69  worker: Worker;70  ready: boolean;71  dead: boolean;72  load: number;73  rev: number;74  jobs: Map<number, BuildJob>;75}7677const EMPTY = new Uint8Array(0);7879export interface PoolStats {80  workers: number;81  alive: number;82  built: number;83  failed: number;84  local: number;85  /** Travaux retirés de la file avant d'être construits (tuile devenue inutile). */86  cancelled: number;87  pending: number;88  buildMs: number;89  mode: 'workers' | 'main' | 'starting';90  blobBootstrap: boolean;91}9293export function defaultWorkerCount(): number {94  const hc = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 4 : 4;95  return Math.max(1, Math.min(4, hc - 2));96}9798const MAX_PER_WORKER = 2;99100export class WorkerPool {101  private slots: Slot[] = [];102  private queue: BuildJob[] = [];103  private destroyed = false;104  private blobUrl?: string;105  readonly stats: PoolStats = { workers: 0, alive: 0, built: 0, failed: 0, local: 0, cancelled: 0, pending: 0, buildMs: 0, mode: 'starting', blobBootstrap: false };106107  constructor(108    private sink: BuildSink,109    private module: WebAssembly.Module,110    workerUrl: string,111    count: number,112  ) {113    this.stats.workers = count;114    let url = workerUrl;115    try {116      const abs = new URL(workerUrl, location.href);117      if (abs.origin !== location.origin) {118        // Un worker ne peut pas être créé depuis une autre origine : amorçage par blob.119        this.blobUrl = URL.createObjectURL(new Blob([`importScripts(${JSON.stringify(abs.href)});`], { type: 'text/javascript' }));120        url = this.blobUrl;121        this.stats.blobBootstrap = true;122      } else {123        url = abs.href;124      }125    } catch {126      /* adresse relative conservée telle quelle */127    }128    for (let i = 0; i < count; i++) this.spawn(url, i);129    if (count === 0) this.stats.mode = 'main';130  }131132  private spawn(url: string, i: number): void {133    let worker: Worker;134    try {135      worker = new Worker(url, { name: `ka-maps-${i}` });136    } catch {137      this.stats.workers--;138      this.onDead(undefined);139      return;140    }141    const slot: Slot = { worker, ready: false, dead: false, load: 0, rev: -1, jobs: new Map() };142    this.slots.push(slot);143    worker.onmessage = (e: MessageEvent) => {144      const m = e.data as { t: string; job?: number; bytes?: Uint8Array; message?: string; ms?: number };145      if (m.t === 'ready') {146        slot.ready = true;147        this.stats.alive++;148        this.stats.mode = 'workers';149        this.drain();150      } else if (m.t === 'built' && m.job !== undefined && m.bytes) {151        slot.jobs.delete(m.job);152        slot.load--;153        this.stats.built++;154        this.stats.buildMs += m.ms ?? 0;155        if (!this.destroyed) this.sink.buildDone(m.job, m.bytes);156        this.drain();157      } else if (m.t === 'failed' && m.job !== undefined) {158        slot.jobs.delete(m.job);159        slot.load--;160        this.stats.failed++;161        if (!this.destroyed) this.sink.buildFailed(m.job, m.message ?? 'construction impossible');162        this.drain();163      } else if (m.t === 'error') {164        this.onDead(slot);165      }166    };167    worker.onerror = (e) => {168      e.preventDefault?.();169      this.onDead(slot);170    };171    try {172      worker.postMessage({ t: 'init', module: this.module });173    } catch {174      this.onDead(slot);175    }176  }177178  private onDead(slot: Slot | undefined): void {179    if (slot) {180      if (slot.dead) return;181      slot.dead = true;182      if (slot.ready) this.stats.alive--;183      slot.ready = false;184      try {185        slot.worker.terminate();186      } catch {187        /* déjà arrêté */188      }189      // Ses travaux en cours sont perdus (leurs octets lui avaient été transférés, sans copie) :190      // le moteur redemandera ces tuiles quand elles reviendront dans la vue.191      for (const j of slot.jobs.keys()) {192        this.stats.failed++;193        if (!this.destroyed) this.sink.buildFailed(j, 'worker arrêté');194      }195      slot.jobs.clear();196    }197    if (this.slots.every((s) => s.dead)) this.stats.mode = 'main';198    this.drain();199  }200201  /** Vrai tant qu'au moins un worker est vivant ou en démarrage. */202  get usable(): boolean {203    return this.slots.some((s) => !s.dead);204  }205206  submit(job: BuildJob): void {207    if (this.destroyed) return;208    this.queue.push(job);209    this.drain();210  }211212  /** Travail devenu inutile : retiré s'il attend encore ; s'il est déjà dans un worker, il se termine et le moteur l'ignore. */213  cancel(job: number): void {214    const i = this.queue.findIndex((j) => j.job === job);215    if (i >= 0) {216      this.queue.splice(i, 1);217      this.stats.cancelled++;218      this.stats.pending = this.queue.length + this.slots.reduce((n, s) => n + s.jobs.size, 0);219    }220  }221222  private drain(): void {223    if (this.destroyed) return;224    if (!this.usable) {225      // Repli : fil principal, un travail par tâche pour ne pas figer l'interface.226      const next = this.queue.shift();227      if (next) {228        this.stats.local++;229        this.sink.buildLocal(next);230        if (this.queue.length) setTimeout(() => this.drain(), 0);231      }232      this.stats.pending = this.queue.length;233      return;234    }235    while (this.queue.length > 0) {236      let best: Slot | undefined;237      for (const s of this.slots) {238        if (s.ready && !s.dead && s.load < MAX_PER_WORKER && (!best || s.load < best.load)) best = s;239      }240      if (!best) break;241      const job = this.queue.shift()!;242      try {243        if (best.rev !== job.rev) {244          const document = this.sink.styleDocument(job.rev);245          if (document === undefined) {246            // Thème changé pendant l'attente : le moteur écarterait le résultat, inutile de construire.247            this.sink.buildFailed(job.job, 'style périmé');248            continue;249          }250          best.worker.postMessage({ t: 'style', rev: job.rev, document });251          best.rev = job.rev;252        }253        best.jobs.set(job.job, job);254        best.load++;255        // Transfert du tampon (aucune copie) : `job.bytes` est détaché après l'envoi.256        const bytes = job.bytes;257        best.worker.postMessage({ t: 'build', job: job.job, rev: job.rev, z: job.z, x: job.x, y: job.y, bytes }, [bytes.buffer]);258        job.bytes = EMPTY;259      } catch {260        // Envoi impossible : le worker est perdu ; onDead signale l'échec de ses travaux (dont celui-ci).261        if (!best.jobs.has(job.job)) this.sink.buildFailed(job.job, 'worker injoignable');262        this.onDead(best);263        return;264      }265    }266    this.stats.pending = this.queue.length + this.slots.reduce((n, s) => n + s.jobs.size, 0);267  }268269  destroy(): void {270    this.destroyed = true;271    for (const s of this.slots) {272      try {273        s.worker.terminate();274      } catch {275        /* rien */276      }277    }278    this.slots.length = 0;279    this.queue.length = 0;280    if (this.blobUrl) URL.revokeObjectURL(this.blobUrl);281  }282}283
Files main
Menu

Theme