Repository Public
1// @vitest-environment happy-dom2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : KA Maps Engine9 * File : sdk/web/tests/unit/workers.test.ts10 * Module : sdk11 * Repository : https://git.spboucher.ai/ka-maps-engine12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';44import { defaultWorkerCount, WorkerPool, type BuildJob, type BuildSink } from '../../src/worker-pool.js';4546/** Worker simulé : mémorise les messages, laisse l'essai répondre à la main. */47class FakeWorker {48 static all: FakeWorker[] = [];49 static failConstruct = false;50 onmessage: ((e: { data: unknown }) => void) | null = null;51 onerror: ((e: { preventDefault(): void }) => void) | null = null;52 messages: { msg: any; transfer?: Transferable[] }[] = [];53 terminated = false;54 constructor(55 public url: string,56 public opts?: { name?: string },57 ) {58 if (FakeWorker.failConstruct) throw new Error('worker-src');59 FakeWorker.all.push(this);60 }61 postMessage(msg: unknown, transfer?: Transferable[]) {62 this.messages.push({ msg, transfer });63 }64 terminate() {65 this.terminated = true;66 }67 reply(data: unknown) {68 this.onmessage?.({ data });69 }70 builds() {71 return this.messages.filter((m) => m.msg.t === 'build').map((m) => m.msg);72 }73}7475function sink(currentRev = 1) {76 const s = {77 done: [] as number[],78 failed: [] as [number, string][],79 local: [] as number[],80 rev: currentRev,81 buildDone: (job: number) => void s.done.push(job),82 buildFailed: (job: number, message: string) => void s.failed.push([job, message]),83 styleDocument: (rev: number) => (rev === s.rev ? `{"rev":${rev}}` : undefined),84 buildLocal: (job: BuildJob) => void s.local.push(job.job),85 };86 return s as typeof s & BuildSink;87}8889const job = (n: number, rev = 1): BuildJob => ({ job: n, z: 14, x: n, y: 1, rev, bytes: new Uint8Array([n, n, n]) });90const mod = {} as WebAssembly.Module;9192beforeEach(() => {93 FakeWorker.all = [];94 FakeWorker.failConstruct = false;95 vi.stubGlobal('Worker', FakeWorker);96});97afterEach(() => vi.unstubAllGlobals());9899describe('groupe de workers', () => {100 it('taille par défaut bornée entre 1 et 4', () => {101 const n = defaultWorkerCount();102 expect(n).toBeGreaterThanOrEqual(1);103 expect(n).toBeLessThanOrEqual(4);104 });105106 it('même origine : pas de blob ; le module compilé est remis à chaque worker', () => {107 const s = sink();108 const pool = new WorkerPool(s, mod, '/ka-maps/0.1.0/ka-maps-worker.js', 2);109 expect(FakeWorker.all).toHaveLength(2);110 expect(FakeWorker.all[0].url).toBe(`${location.origin}/ka-maps/0.1.0/ka-maps-worker.js`);111 expect(FakeWorker.all[0].messages[0].msg).toEqual({ t: 'init', module: mod });112 expect(pool.stats).toMatchObject({ blobBootstrap: false, mode: 'starting', workers: 2 });113 pool.destroy();114 expect(FakeWorker.all.every((w) => w.terminated)).toBe(true);115 });116117 it('autre origine : amorçage par blob + importScripts', () => {118 const created: string[] = [];119 const orig = URL.createObjectURL;120 URL.createObjectURL = ((b: Blob) => (created.push(String(b.size)), 'blob:essai')) as typeof URL.createObjectURL;121 const pool = new WorkerPool(sink(), mod, 'https://maps.spboucher.ai/sdk/0.1.0/ka-maps-worker.js', 1);122 URL.createObjectURL = orig;123 expect(FakeWorker.all[0].url).toBe('blob:essai');124 expect(created).toHaveLength(1);125 expect(pool.stats.blobBootstrap).toBe(true);126 pool.destroy();127 });128129 it('attend « ready », envoie le style une fois par révision, transfère les octets, répartit la charge', () => {130 const s = sink();131 const pool = new WorkerPool(s, mod, '/w.js', 2);132 const [a, b] = FakeWorker.all;133 const jobs = [1, 2, 3, 4, 5].map((n) => job(n));134 const buffers = jobs.map((j) => j.bytes.buffer);135 for (const j of jobs) pool.submit(j);136 expect(a.builds()).toHaveLength(0); // pas encore prêts137 a.reply({ t: 'ready' });138 b.reply({ t: 'ready' });139 expect(pool.stats.mode).toBe('workers');140 // Deux travaux au plus par worker ; le cinquième attend.141 expect(a.builds().map((m) => m.job).sort()).toHaveLength(2);142 expect(b.builds().map((m) => m.job).sort()).toHaveLength(2);143 expect(a.messages.filter((m) => m.msg.t === 'style')).toHaveLength(1);144 expect(a.messages.find((m) => m.msg.t === 'style')!.msg).toEqual({ t: 'style', rev: 1, document: '{"rev":1}' });145 // Transfert sans copie : le tampon d'origine part tel quel dans la liste de transfert.146 const sent = [...a.messages, ...b.messages].filter((m) => m.msg.t === 'build');147 for (const m of sent) expect(buffers).toContain(m.transfer![0]);148 expect(pool.stats.pending).toBe(5);149 const first = a.builds()[0].job;150 a.reply({ t: 'built', job: first, bytes: new Uint8Array(4), ms: 3 });151 expect(s.done).toEqual([first]);152 expect(a.builds()).toHaveLength(3); // le cinquième est parti sur le worker libéré153 expect(pool.stats).toMatchObject({ built: 1, buildMs: 3 });154 pool.destroy();155 });156157 it('révision périmée : échec immédiat sans construire ; nouvelle révision : nouveau style', () => {158 const s = sink(2);159 const pool = new WorkerPool(s, mod, '/w.js', 1);160 const [w] = FakeWorker.all;161 w.reply({ t: 'ready' });162 pool.submit(job(1, 1)); // le thème a changé entre-temps163 expect(s.failed).toEqual([[1, 'style périmé']]);164 expect(w.builds()).toHaveLength(0);165 pool.submit(job(2, 2));166 expect(w.messages.filter((m) => m.msg.t === 'style').map((m) => m.msg.rev)).toEqual([2]);167 s.rev = 3;168 pool.submit(job(3, 3));169 expect(w.messages.filter((m) => m.msg.t === 'style').map((m) => m.msg.rev)).toEqual([2, 3]);170 pool.destroy();171 });172173 it('annulation : un travail encore en file est retiré, un travail déjà parti se termine', () => {174 const s = sink();175 const pool = new WorkerPool(s, mod, '/w.js', 1);176 const [w] = FakeWorker.all;177 w.reply({ t: 'ready' });178 for (const n of [1, 2, 3, 4]) pool.submit(job(n)); // 1 et 2 partent, 3 et 4 attendent179 pool.cancel(3);180 pool.cancel(1); // déjà dans le worker : sans effet181 pool.cancel(99);182 expect(pool.stats.cancelled).toBe(1);183 w.reply({ t: 'built', job: 1, bytes: new Uint8Array(1) });184 w.reply({ t: 'built', job: 2, bytes: new Uint8Array(1) });185 expect(w.builds().map((m) => m.job)).toEqual([1, 2, 4]);186 expect(s.done).toEqual([1, 2]);187 pool.destroy();188 });189190 it('échec d’une construction transmis au moteur', () => {191 const s = sink();192 const pool = new WorkerPool(s, mod, '/w.js', 1);193 const [w] = FakeWorker.all;194 w.reply({ t: 'ready' });195 pool.submit(job(9));196 w.reply({ t: 'failed', job: 9, message: 'tuile illisible' });197 expect(s.failed).toEqual([[9, 'tuile illisible']]);198 expect(pool.stats.failed).toBe(1);199 pool.destroy();200 });201202 it('workers qui ne démarrent pas (CSP, fichier absent) : tout retombe sur le fil principal', async () => {203 const s = sink();204 const pool = new WorkerPool(s, mod, '/w.js', 2);205 pool.submit(job(1));206 pool.submit(job(2));207 for (const w of FakeWorker.all) w.onerror?.({ preventDefault() {} });208 expect(pool.usable).toBe(false);209 expect(pool.stats.mode).toBe('main');210 await new Promise((r) => setTimeout(r, 10));211 expect(s.local).toEqual([1, 2]);212 pool.submit(job(3));213 expect(s.local).toEqual([1, 2, 3]);214 pool.destroy();215 });216217 it('construction du Worker refusée : repli immédiat', () => {218 FakeWorker.failConstruct = true;219 const s = sink();220 const pool = new WorkerPool(s, mod, '/w.js', 2);221 expect(pool.usable).toBe(false);222 pool.submit(job(1));223 expect(s.local).toEqual([1]);224 pool.destroy();225 });226227 it('worker qui meurt en cours de route : ses travaux sont déclarés perdus, les autres continuent', () => {228 const s = sink();229 const pool = new WorkerPool(s, mod, '/w.js', 2);230 const [a, b] = FakeWorker.all;231 a.reply({ t: 'ready' });232 b.reply({ t: 'ready' });233 for (const n of [1, 2, 3, 4]) pool.submit(job(n));234 const lost = a.builds().map((m) => m.job);235 a.onerror?.({ preventDefault() {} });236 expect(s.failed.map((f) => f[0]).sort()).toEqual(lost.sort());237 expect(a.terminated).toBe(true);238 expect(pool.usable).toBe(true);239 pool.submit(job(5));240 for (const m of b.builds()) b.reply({ t: 'built', job: m.job, bytes: new Uint8Array(1) });241 expect(b.builds().map((m) => m.job)).toContain(5);242 pool.destroy();243 });244});245