All files / lib/metadata storage.ts

95.86% Statements 116/121
91.56% Branches 76/83
100% Functions 15/15
95.65% Lines 110/115

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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368                                            19x 15x 15x   4x                       25x 25x 31x                                                                                                           25x 1x     24x 1x 1x     24x 25x                 4x 1x     1x     4x           25x 4x     25x   25x 23x 22x 1x   21x 25x 21x 21x 21x   24x   21x 25x 1x 1x       1x 20x 17x 17x 1x   17x 3x 1x 1x     1x 2x 1x 2x                           1x     20x   25x               20x 1x   1x           1x       1x 1x         1x   1x                           20x 19x                                   8x 8x 8x   12x   8x 1x   7x 8x 8x   1x     8x     7x 7x 5x 5x 5x 2x 1x 1x 1x 1x 1x 2x                       7x                                                     11x 11x 11x 11x   14x   11x 1x   10x 10x 6x 6x 4x 1x 1x 3x 2x 2x 2x 1x 2x                     1x 1x 2x                     10x   10x    
import { computeCascades } from '$lib/cascades.js';
import type * as DB from '$lib/database.js';
import type { DatabaseHandle, ReactiveTableNames } from '$lib/idb.svelte.js';
import {
	ensureNamespacedMetadataId,
	MetadataError,
	namespacedMetadataId,
	namespaceOfMetadataId,
	type RuntimeValue
} from '$lib/schemas/metadata.js';
 
import { serializeMetadataValue } from './serializing.js';
 
/**
 *
 * @param protocolId
 * @param metadataId null to get options of all metadata of the protocol
 */
export function metadataOptionsKeyRange(
	protocolId: string,
	metadataId: string | null
): IDBKeyRange {
	if (metadataId) {
		const fullMetadataId = ensureNamespacedMetadataId(metadataId, protocolId);
		return IDBKeyRange.bound(fullMetadataId + ':', fullMetadataId + ':\uffff');
	} else {
		return IDBKeyRange.bound(
			namespacedMetadataId('', protocolId),
			namespacedMetadataId('\uffff', protocolId)
		);
	}
}
 
/**
 * Refresh the specified table. Does nothing if we can't import idb.svelte.js.
 * We do it this way so that this file can be imported in the web worker.
 */
async function refreshTables(sessionId: string, ...tableNames: ReactiveTableNames[]) {
	try {
		const idb = await import('$lib/idb.svelte.js');
		await Promise.all(tableNames.map((name) => idb.tables[name].refresh(sessionId)));
	} catch (error) {
		console.warn(`Cannot refresh tables ${tableNames}:`, error);
	}
}
 
/**
 *
 * @param options
 * @param options.subjectId id de l'image, l'observation ou la session
 * @param options.metadataId id de la métadonnée
 * @param options.type le type de données pour la métadonnée, sert à éviter des problèmes de typages
 * @param options.value la valeur de la métadonnée
 * @param options.manuallyModified si la valeur a été modifiée manuellement
 * @param options.confidence la confiance dans la valeur (proba que ce soit la bonne valeur)
 * @param options.confirmed si la valeur a été confirmée manuellement comme correcte
 * @param options.clearErrors effacer tout les metadataErrors associés à cette métadonnée. True par défaut.
 * @param options.db BDD à modifier
 * @param options.alternatives les autres valeurs possibles
 * @param options.cascadedFrom ID des métadonnées dont celle-ci est dérivée, pour éviter les boucles infinies (cf "cascade" dans MetadataEnumVariant)
 * @param options.abortSignal signal d'abandon pour annuler la requête
 * @param options.sessionId id de la session en cours, important pour refresh le state réactif des tables
 */
export async function storeMetadataValue<Type extends DB.MetadataType>({
	db,
	subjectId,
	metadataId,
	type,
	value,
	confidence = 1,
	confirmed = false,
	alternatives = [],
	manuallyModified = false,
	clearErrors = true,
	cascadedFrom = [],
	sessionId,
	abortSignal
}: {
	subjectId: string;
	metadataId: string;
	type?: Type;
	value: RuntimeValue<Type>;
	manuallyModified?: boolean;
	confidence?: number;
	confirmed?: boolean;
	clearErrors?: boolean;
	db: DatabaseHandle;
	alternatives?:
		| DB.MetadataValue['alternatives']
		| Array<{ value: RuntimeValue<Type>; confidence: number }>;
	cascadedFrom?: string[];
	abortSignal?: AbortSignal | undefined;
	sessionId?: string | undefined;
}) {
	if (!namespaceOfMetadataId(metadataId)) {
		throw new Error(`Le metadataId ${metadataId} n'est pas namespacé`);
	}
 
	if (confidence > 1) {
		console.warn(`Confidence ${confidence} is greater than 1, capping to 1`);
		confidence = 1;
	}
 
	abortSignal?.throwIfAborted();
	const newValue = {
		value: serializeMetadataValue(value),
		confidence,
		confirmed,
		manuallyModified,
		alternatives: !Array.isArray(alternatives)
			? alternatives
			: Object.fromEntries(
					alternatives.map(({ value, confidence }) => {
						if (confidence > 1) {
							console.warn(
								`Confidence ${confidence} of alternative ${value} is greater than 1, capping to 1`
							);
							confidence = 1;
						}
 
						return [serializeMetadataValue(value), confidence];
					})
				)
	};
 
	// Make sure the alternatives does not contain the value itself
	newValue.alternatives = Object.fromEntries(
		Object.entries(newValue.alternatives).filter(([key]) => key !== newValue.value)
	);
 
	console.debug(`Store metadata ${metadataId} = `, value, ` in ${subjectId}`, newValue);
 
	const metadata = await db.get('Metadata', metadataId);
	if (!metadata) throw new Error(`Métadonnée inconnue avec l'ID ${metadataId}`);
	if (type && metadata.type !== type)
		throw new Error(`Type de métadonnée incorrect: ${metadata.type} !== ${type}`);
 
	abortSignal?.throwIfAborted();
	const image = await db.get('Image', subjectId);
	const observation = await db.get('Observation', subjectId);
	const session = await db.get('Session', subjectId);
	const imagesFromImageFile = await db
		.getAll('Image')
		.then((imgs) => imgs.filter(({ fileId }) => fileId === subjectId));
 
	abortSignal?.throwIfAborted();
	if (session) {
		if (session.metadata) {
			session.metadata[metadataId] = newValue;
		} else E{
			session.metadata = { [metadataId]: newValue };
		}
		db.put('Session', session);
	} else if (image) {
		image.metadata[metadataId] = newValue;
		if (clearErrors && image.metadataErrors?.[metadataId]) {
			delete image.metadataErrors[metadataId];
		}
		db.put('Image', image);
	} else if (observation) {
		observation.metadataOverrides[metadataId] = newValue;
		Iif (clearErrors && observation.metadataErrors?.[metadataId]) {
			delete observation.metadataErrors[metadataId];
		}
		db.put('Observation', observation);
	} else if (imagesFromImageFile.length > 0) {
		for (const { id } of imagesFromImageFile) {
			await storeMetadataValue({
				db,
				sessionId,
				subjectId: id,
				metadataId,
				value,
				confidence,
				confirmed,
				manuallyModified,
				clearErrors,
				abortSignal
			});
		}
	} else {
		throw new Error(`Aucune image ou observation avec l'ID ${subjectId}`);
	}
 
	abortSignal?.throwIfAborted();
 
	const cascades = await computeCascades({
		db,
		metadataId,
		value,
		confidence,
		alternatives
	});
 
	for (const cascade of cascades) {
		abortSignal?.throwIfAborted();
 
		Iif (cascadedFrom.includes(cascade.metadataId)) {
			throw new Error(
				`Boucle infinie de cascade détectée pour ${cascade.metadataId} avec ${cascade.value}: ${cascadedFrom.join(' -> ')} -> ${metadataId} -> ${cascade.metadataId}`
			);
		}
 
		console.info(
			`Cascading metadata ${metadataId} @ ${value} -> ${cascade.metadataId}  = ${cascade.value}`
		);
 
		const metadataNamespace = namespaceOfMetadataId(metadataId);
		Iif (!metadataNamespace)
			throw new Error(
				`Metadata ${metadataId} is not namespaced, cannot cascade onto ${cascade.metadataId}`
			);
 
		cascade.metadataId = ensureNamespacedMetadataId(cascade.metadataId, metadataNamespace);
 
		await storeMetadataValue({
			db,
			sessionId,
			subjectId,
			manuallyModified,
			confirmed,
			cascadedFrom: [...cascadedFrom, metadataId],
			abortSignal,
			clearErrors,
			...cascade
		});
	}
 
	// Only refresh table state once everything has been cascaded, meaning not inside recursive calls
	if (cascadedFrom.length === 0 && sessionId) {
		await refreshTables(sessionId, image ? 'Image' : 'Observation');
	}
}
 
export async function storeMetadataErrors(
	{
		db,
		subjectId,
		sessionId,
		metadataId
	}: {
		db: DatabaseHandle;
		subjectId: string;
		sessionId: string;
		metadataId: string;
	},
	...errors: Array<typeof DB.Schemas.MetadataError.inferIn>
) {
	const image = await db.get('Image', subjectId);
	const observation = await db.get('Observation', subjectId);
	const imagesFromImageFile = await db
		.getAllFromIndex('Image', 'sessionId', sessionId)
		.then((imgs) => imgs.filter(({ fileId }) => fileId === subjectId));
 
	if (!image && !observation && imagesFromImageFile.length === 0)
		throw new Error(`Aucune image ou observation avec l'ID ${subjectId}`);
 
	const serializedErrors = errors.map((error) => {
		try {
			JSON.stringify(error.details);
		} catch {
			error.details = `{{Non-JSONable}} ${String(error.details)}`;
		}
 
		return MetadataError.assert(error);
	});
 
	console.debug(`Store metadata error on ${metadataId} in ${subjectId}:`, errors);
	if (image) {
		image.metadataErrors ??= {};
		image.metadataErrors[metadataId] = serializedErrors;
		db.put('Image', image);
	} else if (observation) {
		observation.metadataErrors ??= {};
		observation.metadataErrors[metadataId] = serializedErrors;
		db.put('Observation', observation);
	E} else if (imagesFromImageFile) {
		for (const { id } of imagesFromImageFile) {
			await storeMetadataErrors(
				{
					db,
					sessionId,
					subjectId: id,
					metadataId
				},
				...errors
			);
		}
	}
 
	return;
}
/**
 *
 * @param options
 * @param options.subjectId id de l'image ou l'observation
 * @param options.metadataId id de la métadonnée
 * @param options.recursive si true, supprime la métadonnée de toutes les images composant l'observation
 * @param options.db BDD à modifier
 * @param options.reactive refresh reactive table state if possible
 * @param options.sessionId current session, used to refresh reactive tables
 */
export async function deleteMetadataValue({
	db,
	subjectId,
	metadataId,
	recursive = false,
	reactive = true,
	sessionId
}: {
	subjectId: string;
	metadataId: string;
	recursive?: boolean;
	db: DatabaseHandle;
	reactive?: boolean;
	sessionId?: string | undefined;
}) {
	const image = await db.get('Image', subjectId);
	const observation = await db.get('Observation', subjectId);
	const session = await db.get('Session', subjectId);
	const imagesFromImageFile = await db
		.getAllFromIndex('Image', 'sessionId', sessionId)
		.then((imgs) => imgs.filter(({ fileId }) => fileId === subjectId));
 
	if (!image && !observation && !session && imagesFromImageFile.length === 0)
		throw new Error(`Aucune image, observation ou session avec l'ID ${subjectId}`);
 
	console.debug(`Delete metadata ${metadataId} in ${subjectId}`);
	if (image) {
		delete image.metadata[metadataId];
		db.put('Image', image);
	} else if (session) {
		delete session.metadata[metadataId];
		db.put('Session', session);
	} else if (observation) {
		delete observation.metadataOverrides[metadataId];
		db.put('Observation', observation);
		if (recursive) {
			for (const imageId of observation.images) {
				await deleteMetadataValue({
					db,
					sessionId,
					subjectId: imageId,
					recursive: false,
					metadataId,
					// Don't refresh table state on recursive calls, we just have to do it once
					reactive: false
				});
			}
		}
	E} else if (imagesFromImageFile) {
		for (const { id } of imagesFromImageFile) {
			await deleteMetadataValue({
				db,
				sessionId,
				subjectId: id,
				recursive: false,
				metadataId,
				reactive: false
			});
		}
	}
 
	if (reactive && sessionId) await refreshTables(sessionId, 'Image', 'Observation');
 
	return;
}